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:
How to parse through script tag using python and beautifulsoup
I am trying to extract the attributes of a frame tag which is inside document.write function on a page as follows:
<script language="javascript">
.
.
.
document.write('<frame name="nav" src="/nav/index_nav.html" marginwidth="0" marginheight="0" scrolling="no" frameborder="0" border = "no" noresize>');
if (anchor != "") {
document.write('<frame name="body" src="http://content.members.fidelity.com/mfl/summary/0,,' + cusip + ',00.html?' + anchor + '" marginwidth="0" marginheight="0" scrolling="auto" frameborder="0" noresize>');
} else {
document.write('<frame name="body" src="http://content.members.fidelity.com/mfl/summary/0,,' + cusip + ',00.html" marginwidth="0" marginheight="0" scrolling="auto" frameborder="0" noresize>');
}
document.write('</frameset>');
// end hiding -->
</script>
findAll('frame') method didn't help. Is there a way to read the contents of frame tag?
I am using python 2.5 and BeautifulSoup 3.0.8.
I am also open to using python 3.1 with BeautifulSoup 3.1
so long as i am able to get the results.
Thanks
A:
You can't do it with BeautifulSoup alone. BeautifulSoup parses HTML as it would arrive to the browser (before any rewriting or DOM manipulation), and it does not parse (let alone execute) Javascript.
You might want to use a simple regular expression in this special case.
A:
Pyparsing might help you bridge this mix of JS and HTML. This parser looks for document.write statements containing a quoted string or a string expression of several quoted strings and identifiers, quasi-evaluates the string expression, parses it for an embedded <frame> tag, and returns the frame attributes as a pyparsing ParseResults object, which gives you access to the named attributes as if they were object attributes or dict keys (your preference).
jssrc = """
<script language="javascript">
.
.
.
document.write('<frame name="nav" src="/nav/index_nav.html" marginwidth="0" marginheight="0" scrolling="no" frameborder="0" border = "no" noresize>');
if (anchor != "")
{ document.write('<frame name="body" src="http://content.members.fidelity.com/mfl/summary/0,,' + cusip + ',00.html?' + anchor + '" marginwidth="0" marginheight="0" scrolling="auto" frameborder="0" noresize>'); }
else
{ document.write('<frame name="body" src="http://content.members.fidelity.com/mfl/summary/0,,' + cusip + ',00.html" marginwidth="0" marginheight="0" scrolling="auto" frameborder="0" noresize>'); }
document.write('</frameset>');
// end hiding -->
</script>"""
from pyparsing import *
# define some basic punctuation, and quoted string
LPAR,RPAR,PLUS = map(Suppress,"()+")
qs = QuotedString("'")
# use pyparsing helper to define an expression for opening <frame>
# tags, which includes support for attributes also
frameTag = makeHTMLTags("frame")[0]
# some of our document.write statements contain not a sting literal,
# but an expression of strings and vars added together; define
# an identifier expression, and add a parse action that converts
# a var name to a likely value
ident = Word(alphas).setParseAction(lambda toks: evalvars[toks[0]])
evalvars = { 'cusip' : "CUSIP", 'anchor' : "ANCHOR" }
# now define the string expression itself, as a quoted string,
# optionally followed by identifiers and quoted strings added
# together; identifiers will get translated to their defined values
# as they are parsed; the first parse action on stringExpr concatenates
# all the tokens; then the second parse action actually parses the
# body of the string as a <frame> tag and returns the results of parsing
# the tag and its attributes; if the parse fails (that is, if the
# string contains something that is not a <frame> tag), the second
# parse action will throw an exception, which will cause the stringExpr
# expression to fail
stringExpr = qs + ZeroOrMore( PLUS + (ident | qs))
stringExpr.setParseAction(lambda toks : ''.join(toks))
stringExpr.addParseAction(lambda toks:
frameTag.parseString(toks[0],parseAll=True))
# finally, define the overall document.write(...) expression
docWrite = "document.write" + LPAR + stringExpr + RPAR
# scan through the source looking for document.write commands containing
# <frame> tags using scanString; print the original source fragment,
# then access some of the attributes extracted from the <frame> tag
# in the quoted string, using either object-attribute notation or
# dict index notation
for dw,locstart,locend in docWrite.scanString(jssrc):
print jssrc[locstart:locend]
print dw.name
print dw["src"]
print
Prints:
document.write('<frame name="nav" src="/nav/index_nav.html" marginwidth="0" marginheight="0" scrolling="no" frameborder="0" border = "no" noresize>')
nav
/nav/index_nav.html
document.write('<frame name="body" src="http://content.members.fidelity.com/mfl/summary/0,,' + cusip + ',00.html?' + anchor + '" marginwidth="0" marginheight="0" scrolling="auto" frameborder="0" noresize>')
body
http://content.members.fidelity.com/mfl/summary/0,,CUSIP,00.html?ANCHOR
document.write('<frame name="body" src="http://content.members.fidelity.com/mfl/summary/0,,' + cusip + ',00.html" marginwidth="0" marginheight="0" scrolling="auto" frameborder="0" noresize>')
body
http://content.members.fidelity.com/mfl/summary/0,,CUSIP,00.html
|
How to parse through script tag using python and beautifulsoup
|
I am trying to extract the attributes of a frame tag which is inside document.write function on a page as follows:
<script language="javascript">
.
.
.
document.write('<frame name="nav" src="/nav/index_nav.html" marginwidth="0" marginheight="0" scrolling="no" frameborder="0" border = "no" noresize>');
if (anchor != "") {
document.write('<frame name="body" src="http://content.members.fidelity.com/mfl/summary/0,,' + cusip + ',00.html?' + anchor + '" marginwidth="0" marginheight="0" scrolling="auto" frameborder="0" noresize>');
} else {
document.write('<frame name="body" src="http://content.members.fidelity.com/mfl/summary/0,,' + cusip + ',00.html" marginwidth="0" marginheight="0" scrolling="auto" frameborder="0" noresize>');
}
document.write('</frameset>');
// end hiding -->
</script>
findAll('frame') method didn't help. Is there a way to read the contents of frame tag?
I am using python 2.5 and BeautifulSoup 3.0.8.
I am also open to using python 3.1 with BeautifulSoup 3.1
so long as i am able to get the results.
Thanks
|
[
"You can't do it with BeautifulSoup alone. BeautifulSoup parses HTML as it would arrive to the browser (before any rewriting or DOM manipulation), and it does not parse (let alone execute) Javascript. \nYou might want to use a simple regular expression in this special case.\n",
"Pyparsing might help you bridge this mix of JS and HTML. This parser looks for document.write statements containing a quoted string or a string expression of several quoted strings and identifiers, quasi-evaluates the string expression, parses it for an embedded <frame> tag, and returns the frame attributes as a pyparsing ParseResults object, which gives you access to the named attributes as if they were object attributes or dict keys (your preference).\njssrc = \"\"\"\n<script language=\"javascript\">\n.\n.\n.\ndocument.write('<frame name=\"nav\" src=\"/nav/index_nav.html\" marginwidth=\"0\" marginheight=\"0\" scrolling=\"no\" frameborder=\"0\" border = \"no\" noresize>'); \nif (anchor != \"\") \n{ document.write('<frame name=\"body\" src=\"http://content.members.fidelity.com/mfl/summary/0,,' + cusip + ',00.html?' + anchor + '\" marginwidth=\"0\" marginheight=\"0\" scrolling=\"auto\" frameborder=\"0\" noresize>'); } \nelse \n{ document.write('<frame name=\"body\" src=\"http://content.members.fidelity.com/mfl/summary/0,,' + cusip + ',00.html\" marginwidth=\"0\" marginheight=\"0\" scrolling=\"auto\" frameborder=\"0\" noresize>'); } \ndocument.write('</frameset>');\n // end hiding -->\n </script>\"\"\"\n\nfrom pyparsing import *\n\n# define some basic punctuation, and quoted string\nLPAR,RPAR,PLUS = map(Suppress,\"()+\")\nqs = QuotedString(\"'\")\n\n# use pyparsing helper to define an expression for opening <frame> \n# tags, which includes support for attributes also\nframeTag = makeHTMLTags(\"frame\")[0]\n\n# some of our document.write statements contain not a sting literal,\n# but an expression of strings and vars added together; define\n# an identifier expression, and add a parse action that converts\n# a var name to a likely value\nident = Word(alphas).setParseAction(lambda toks: evalvars[toks[0]])\nevalvars = { 'cusip' : \"CUSIP\", 'anchor' : \"ANCHOR\" }\n\n# now define the string expression itself, as a quoted string,\n# optionally followed by identifiers and quoted strings added\n# together; identifiers will get translated to their defined values\n# as they are parsed; the first parse action on stringExpr concatenates\n# all the tokens; then the second parse action actually parses the\n# body of the string as a <frame> tag and returns the results of parsing\n# the tag and its attributes; if the parse fails (that is, if the\n# string contains something that is not a <frame> tag), the second\n# parse action will throw an exception, which will cause the stringExpr\n# expression to fail\nstringExpr = qs + ZeroOrMore( PLUS + (ident | qs))\nstringExpr.setParseAction(lambda toks : ''.join(toks))\nstringExpr.addParseAction(lambda toks: \n frameTag.parseString(toks[0],parseAll=True))\n\n# finally, define the overall document.write(...) expression\ndocWrite = \"document.write\" + LPAR + stringExpr + RPAR\n\n# scan through the source looking for document.write commands containing\n# <frame> tags using scanString; print the original source fragment, \n# then access some of the attributes extracted from the <frame> tag\n# in the quoted string, using either object-attribute notation or \n# dict index notation\nfor dw,locstart,locend in docWrite.scanString(jssrc):\n print jssrc[locstart:locend]\n print dw.name\n print dw[\"src\"]\n print\n\nPrints:\ndocument.write('<frame name=\"nav\" src=\"/nav/index_nav.html\" marginwidth=\"0\" marginheight=\"0\" scrolling=\"no\" frameborder=\"0\" border = \"no\" noresize>')\nnav\n/nav/index_nav.html\n\ndocument.write('<frame name=\"body\" src=\"http://content.members.fidelity.com/mfl/summary/0,,' + cusip + ',00.html?' + anchor + '\" marginwidth=\"0\" marginheight=\"0\" scrolling=\"auto\" frameborder=\"0\" noresize>')\nbody\nhttp://content.members.fidelity.com/mfl/summary/0,,CUSIP,00.html?ANCHOR\n\ndocument.write('<frame name=\"body\" src=\"http://content.members.fidelity.com/mfl/summary/0,,' + cusip + ',00.html\" marginwidth=\"0\" marginheight=\"0\" scrolling=\"auto\" frameborder=\"0\" noresize>')\nbody\nhttp://content.members.fidelity.com/mfl/summary/0,,CUSIP,00.html\n\n"
] |
[
2,
1
] |
[] |
[] |
[
"beautifulsoup",
"python"
] |
stackoverflow_0001883273_beautifulsoup_python.txt
|
Q:
How could I get a Frame with a scrollbar in Tkinter?
I'd like to have a Frame, where the user could add as many textfields as needed by the application.
The application starts with a textfield, and a button below that textfield. When the user presses the button, a new text entry will be added below the first one ( this may be repeated countless times ). In the middle of the window, there will be a Text widget, used to display text :)
However, I noticed this in the documentation:
This widget is used to implement scrolled listboxes, canvases, and text fields.
Is there a way to use the Scrollbar with a Frame?
A:
If you can use Tix, there is the ScrolledWindow widget which has a window Frame and one or two Scrollbar widgets:
import Tix as tk
r= tk.Tk()
r.title("test scrolled window")
sw= tk.ScrolledWindow(r, scrollbar=tk.Y) # just the vertical scrollbar
sw.pack(fill=tk.BOTH, expand=1)
for i in xrange(10):
e= tk.Entry(sw.window)
e.pack()
r.mainloop()
Change the size of the root window. You will want to add code to the focus_get event of the Entry widgets to scroll the ScrolledWindow when tabbing through the keyboard.
Otherwise, you will have to use a Canvas widget (you can add Label, Entry and Text subwidgets) and write a lot more code yourself to implement your required functionality.
A:
The following is an example of auto hiding scrollbars that only works if you just use the grid geometry manager, taken from the effbot.org documentation:
from tkinter import *
class AutoScrollbar(Scrollbar):
# A scrollbar that hides itself if it's not needed.
# Only works if you use the grid geometry manager!
def set(self, lo, hi):
if float(lo) <= 0.0 and float(hi) >= 1.0:
# grid_remove is currently missing from Tkinter!
self.tk.call("grid", "remove", self)
else:
self.grid()
Scrollbar.set(self, lo, hi)
def pack(self, **kw):
raise TclError("cannot use pack with this widget")
def place(self, **kw):
raise TclError("cannot use place with this widget")
# create scrolled canvas
root = Tk()
vscrollbar = AutoScrollbar(root)
vscrollbar.grid(row=0, column=1, sticky=N+S)
hscrollbar = AutoScrollbar(root, orient=HORIZONTAL)
hscrollbar.grid(row=1, column=0, sticky=E+W)
canvas = Canvas(root, yscrollcommand=vscrollbar.set, xscrollcommand=hscrollbar.set)
canvas.grid(row=0, column=0, sticky=N+S+E+W)
vscrollbar.config(command=canvas.yview)
hscrollbar.config(command=canvas.xview)
# make the canvas expandable
root.grid_rowconfigure(0, weight=1)
root.grid_columnconfigure(0, weight=1)
# create canvas contents
frame = Frame(canvas)
frame.rowconfigure(1, weight=1)
frame.columnconfigure(1, weight=1)
rows = 5
for i in range(1, rows):
for j in range(1, 10):
button = Button(frame, text="%d, %d" % (i,j))
button.grid(row=i, column=j, sticky='news')
canvas.create_window(0, 0, anchor=NW, window=frame)
frame.update_idletasks()
canvas.config(scrollregion=canvas.bbox("all"))
root.mainloop()
|
How could I get a Frame with a scrollbar in Tkinter?
|
I'd like to have a Frame, where the user could add as many textfields as needed by the application.
The application starts with a textfield, and a button below that textfield. When the user presses the button, a new text entry will be added below the first one ( this may be repeated countless times ). In the middle of the window, there will be a Text widget, used to display text :)
However, I noticed this in the documentation:
This widget is used to implement scrolled listboxes, canvases, and text fields.
Is there a way to use the Scrollbar with a Frame?
|
[
"If you can use Tix, there is the ScrolledWindow widget which has a window Frame and one or two Scrollbar widgets:\nimport Tix as tk\n\nr= tk.Tk()\nr.title(\"test scrolled window\")\nsw= tk.ScrolledWindow(r, scrollbar=tk.Y) # just the vertical scrollbar\nsw.pack(fill=tk.BOTH, expand=1)\nfor i in xrange(10):\n e= tk.Entry(sw.window)\n e.pack()\nr.mainloop()\n\nChange the size of the root window. You will want to add code to the focus_get event of the Entry widgets to scroll the ScrolledWindow when tabbing through the keyboard.\nOtherwise, you will have to use a Canvas widget (you can add Label, Entry and Text subwidgets) and write a lot more code yourself to implement your required functionality.\n",
"The following is an example of auto hiding scrollbars that only works if you just use the grid geometry manager, taken from the effbot.org documentation:\nfrom tkinter import *\n\n\nclass AutoScrollbar(Scrollbar):\n # A scrollbar that hides itself if it's not needed.\n # Only works if you use the grid geometry manager!\n def set(self, lo, hi):\n if float(lo) <= 0.0 and float(hi) >= 1.0:\n # grid_remove is currently missing from Tkinter!\n self.tk.call(\"grid\", \"remove\", self)\n else:\n self.grid()\n Scrollbar.set(self, lo, hi)\n def pack(self, **kw):\n raise TclError(\"cannot use pack with this widget\")\n def place(self, **kw):\n raise TclError(\"cannot use place with this widget\")\n\n\n# create scrolled canvas\n\nroot = Tk()\n\nvscrollbar = AutoScrollbar(root)\nvscrollbar.grid(row=0, column=1, sticky=N+S)\nhscrollbar = AutoScrollbar(root, orient=HORIZONTAL)\nhscrollbar.grid(row=1, column=0, sticky=E+W)\n\ncanvas = Canvas(root, yscrollcommand=vscrollbar.set, xscrollcommand=hscrollbar.set)\ncanvas.grid(row=0, column=0, sticky=N+S+E+W)\n\nvscrollbar.config(command=canvas.yview)\nhscrollbar.config(command=canvas.xview)\n\n# make the canvas expandable\nroot.grid_rowconfigure(0, weight=1)\nroot.grid_columnconfigure(0, weight=1)\n\n# create canvas contents\nframe = Frame(canvas)\nframe.rowconfigure(1, weight=1)\nframe.columnconfigure(1, weight=1)\n\nrows = 5\nfor i in range(1, rows):\n for j in range(1, 10):\n button = Button(frame, text=\"%d, %d\" % (i,j))\n button.grid(row=i, column=j, sticky='news')\n\ncanvas.create_window(0, 0, anchor=NW, window=frame)\nframe.update_idletasks()\ncanvas.config(scrollregion=canvas.bbox(\"all\"))\n\nroot.mainloop()\n\n"
] |
[
8,
7
] |
[] |
[] |
[
"frame",
"python",
"scrollbar",
"tkinter"
] |
stackoverflow_0001873575_frame_python_scrollbar_tkinter.txt
|
Q:
Named parameters with Python C API?
How can I simulate the following Python function using the Python C API?
def foo(bar, baz="something or other"):
print bar, baz
(i.e., so that it is possible to call it via:
>>> foo("hello")
hello something or other
>>> foo("hello", baz="world!")
hello world!
>>> foo("hello", "world!")
hello, world!
)
A:
See the docs: you want to use PyArg_ParseTupleAndKeywords, documented at the URL I gave.
So for example:
def foo(bar, baz="something or other"):
print bar, baz
becomes (roughly -- haven't tested it!):
#include "Python.h"
static PyObject *
themodule_foo(PyObject *self, PyObject *args, PyObject *keywds)
{
char *bar;
char *baz = "something or other";
static char *kwlist[] = {"bar", "baz", NULL};
if (!PyArg_ParseTupleAndKeywords(args, keywds, "s|s", kwlist,
&bar, &baz))
return NULL;
printf("%s %s\n", bar, baz);
Py_INCREF(Py_None);
return Py_None;
}
static PyMethodDef themodule_methods[] = {
{"foo", (PyCFunction)themodule_foo, METH_VARARGS | METH_KEYWORDS,
"Print some greeting to standard output."},
{NULL, NULL, 0, NULL} /* sentinel */
};
void
initthemodule(void)
{
Py_InitModule("themodule", themodule_methods);
}
|
Named parameters with Python C API?
|
How can I simulate the following Python function using the Python C API?
def foo(bar, baz="something or other"):
print bar, baz
(i.e., so that it is possible to call it via:
>>> foo("hello")
hello something or other
>>> foo("hello", baz="world!")
hello world!
>>> foo("hello", "world!")
hello, world!
)
|
[
"See the docs: you want to use PyArg_ParseTupleAndKeywords, documented at the URL I gave.\nSo for example:\ndef foo(bar, baz=\"something or other\"):\n print bar, baz\n\nbecomes (roughly -- haven't tested it!):\n#include \"Python.h\"\n\nstatic PyObject *\nthemodule_foo(PyObject *self, PyObject *args, PyObject *keywds)\n{\n char *bar;\n char *baz = \"something or other\";\n\n static char *kwlist[] = {\"bar\", \"baz\", NULL};\n\n if (!PyArg_ParseTupleAndKeywords(args, keywds, \"s|s\", kwlist,\n &bar, &baz))\n return NULL;\n\n printf(\"%s %s\\n\", bar, baz);\n\n Py_INCREF(Py_None);\n return Py_None;\n}\n\nstatic PyMethodDef themodule_methods[] = {\n {\"foo\", (PyCFunction)themodule_foo, METH_VARARGS | METH_KEYWORDS,\n \"Print some greeting to standard output.\"},\n {NULL, NULL, 0, NULL} /* sentinel */\n};\n\nvoid\ninitthemodule(void)\n{\n Py_InitModule(\"themodule\", themodule_methods);\n}\n\n"
] |
[
12
] |
[] |
[] |
[
"c",
"named_parameters",
"python",
"python_c_api"
] |
stackoverflow_0001884327_c_named_parameters_python_python_c_api.txt
|
Q:
AJAX URLs and GET requests
Ok, a great example of what I am trying to achieve is at Google Translate. The URL: http://translate.google.com/#en|es|this is what I am trying to do makes a GET request using this URL: http://translate.google.com/translate_a/t?client=t&text=this%20is%20what%20I%20am%20trying%20to%20do&sl=en&tl=es&otf=1&pc=0
I'm not trying to do the real-time aspect. Right now I have the basic AJAX stuff working (using jQuery and .getJSON()), makes a GET request, Python function does stuff and returns JSON data, the callback function in .getJSON handles it and updates the page dynamically.
So how would I
Make a customized URL that will contain the information from form elements that I would need in processing.
Make this URL, when clicked on or put in an address bar, make the appropriate GET request.
Have the function that is returning JSON, be able to return it and have the content updated dynamically on the page.
edit: Ok, I guess an easier way of asking this is, the server side Python function I have handles the GET requests. It returns the data back as JSON, this works ok if the request is made by .getJSON() because it has the callback to handle updating the HTML on the page. But, say I want to link to a certain query, ex: http://mysite.com/q?s=hello&r=3 if that URL is put in the address bar, the GET request will be made and it will return JSON (as it should), but since the .getJSON() didn't make that request, the callback doesn't fire.
So how would I have it so I could use that link but have it handle it as if the .getJSON() had requested it?
A:
What you're looking for is JQuery's Serialization functionality.
A:
Hey, you can make a customized URL by getting the values of the input fields you wish and then just concatenate this with you url.
$.getJSON("http://translate?lang=" + $(".lang").attr("value") + "&text=bla");
i just simplized here the usage to show you how it works. if this don't helps you, it would be great if you provide additional information.
for the other things like events (clicking on a button) please read the jQuery documentation.
A:
Please see http://whiffdoc.appspot.com/docs/W1100_1400.calc for a tutorial that describes how to do stuff like this.
|
AJAX URLs and GET requests
|
Ok, a great example of what I am trying to achieve is at Google Translate. The URL: http://translate.google.com/#en|es|this is what I am trying to do makes a GET request using this URL: http://translate.google.com/translate_a/t?client=t&text=this%20is%20what%20I%20am%20trying%20to%20do&sl=en&tl=es&otf=1&pc=0
I'm not trying to do the real-time aspect. Right now I have the basic AJAX stuff working (using jQuery and .getJSON()), makes a GET request, Python function does stuff and returns JSON data, the callback function in .getJSON handles it and updates the page dynamically.
So how would I
Make a customized URL that will contain the information from form elements that I would need in processing.
Make this URL, when clicked on or put in an address bar, make the appropriate GET request.
Have the function that is returning JSON, be able to return it and have the content updated dynamically on the page.
edit: Ok, I guess an easier way of asking this is, the server side Python function I have handles the GET requests. It returns the data back as JSON, this works ok if the request is made by .getJSON() because it has the callback to handle updating the HTML on the page. But, say I want to link to a certain query, ex: http://mysite.com/q?s=hello&r=3 if that URL is put in the address bar, the GET request will be made and it will return JSON (as it should), but since the .getJSON() didn't make that request, the callback doesn't fire.
So how would I have it so I could use that link but have it handle it as if the .getJSON() had requested it?
|
[
"What you're looking for is JQuery's Serialization functionality.\n",
"Hey, you can make a customized URL by getting the values of the input fields you wish and then just concatenate this with you url.\n$.getJSON(\"http://translate?lang=\" + $(\".lang\").attr(\"value\") + \"&text=bla\");\n\ni just simplized here the usage to show you how it works. if this don't helps you, it would be great if you provide additional information.\nfor the other things like events (clicking on a button) please read the jQuery documentation.\n",
"Please see http://whiffdoc.appspot.com/docs/W1100_1400.calc for a tutorial that describes how to do stuff like this.\n"
] |
[
1,
0,
0
] |
[] |
[] |
[
"ajax",
"jquery",
"python",
"url"
] |
stackoverflow_0001883626_ajax_jquery_python_url.txt
|
Q:
Handling UTF-16 in a Django uploaded file
In my Django webapp, in one location users can upload a text file where each line contains a string which will be operated on - the file isn't being stored on the server or anything like that.
My code looks like this:
roFile = request.FILES['uploadFileName']
ros = roFile.read().strip()
ros = ros.split('\n')
ros = [t.strip() for t in ros]
To date, this has worked AOK. Today I had a user uploading a file which was causing issues. Using these strings in Django generates the following error:
ProgrammingError: ERROR: invalid byte sequence for encoding "UTF8":0xff
The user has told me that he saved the file as UTF-16.
Within python proper, I can do the following:
import codecs
from django.utils.encoding import *
fo = codecs.open('filename', 'r', 'utf-16')
zz = fo.readlines()
and then the values seem to be manageable, but not with the file upload.
What is the appropriate way to deal with the data in request.FILES in order to handle the differing character set?
A:
This first part doesn't answer your question (I know nothing about django); I'd just like to point out that when you supply code that you say works or doesn't work, you should copy/past the actual code that you ran,; don't type it from memory.
This code:
import codecs
from django.utils.encoding
f = codecs.open('filename', 'r', 'utf-16')
zz = fo.readlines()
has 2 problems and looks like it should be:
import codecs from django.utils.encoding
fo = codecs.open('filename', 'r', 'utf-16')
zz = fo.readlines()
To your question: google("django request files") seems to give some useful clues; have you investigated them, including this? One of the clues was that file uploads seem to have been improved in later versions of django; what version are you using?
|
Handling UTF-16 in a Django uploaded file
|
In my Django webapp, in one location users can upload a text file where each line contains a string which will be operated on - the file isn't being stored on the server or anything like that.
My code looks like this:
roFile = request.FILES['uploadFileName']
ros = roFile.read().strip()
ros = ros.split('\n')
ros = [t.strip() for t in ros]
To date, this has worked AOK. Today I had a user uploading a file which was causing issues. Using these strings in Django generates the following error:
ProgrammingError: ERROR: invalid byte sequence for encoding "UTF8":0xff
The user has told me that he saved the file as UTF-16.
Within python proper, I can do the following:
import codecs
from django.utils.encoding import *
fo = codecs.open('filename', 'r', 'utf-16')
zz = fo.readlines()
and then the values seem to be manageable, but not with the file upload.
What is the appropriate way to deal with the data in request.FILES in order to handle the differing character set?
|
[
"This first part doesn't answer your question (I know nothing about django); I'd just like to point out that when you supply code that you say works or doesn't work, you should copy/past the actual code that you ran,; don't type it from memory.\nThis code:\nimport codecs\nfrom django.utils.encoding\nf = codecs.open('filename', 'r', 'utf-16')\nzz = fo.readlines()\n\nhas 2 problems and looks like it should be:\nimport codecs from django.utils.encoding\nfo = codecs.open('filename', 'r', 'utf-16')\nzz = fo.readlines()\n\nTo your question: google(\"django request files\") seems to give some useful clues; have you investigated them, including this? One of the clues was that file uploads seem to have been improved in later versions of django; what version are you using?\n"
] |
[
1
] |
[] |
[] |
[
"django",
"python",
"utf_8"
] |
stackoverflow_0001884399_django_python_utf_8.txt
|
Q:
How to transfer a file between two FTP servers?
I have two ftp servers with fxp enabled on both, I'm just wondering how I would transfer a file between the two servers in Python?
I was told curl wouldnt do it, but maybe ftplib will do.
so, the file (file.txt) is in '/personal/' FTP1 and I want to transfer that to FTP2 also to the same place, '/personal/'
Any ideas on how to do this?
A:
You should use ftplib (http://docs.python.org/library/ftplib.html)
A:
The simplest thing to is call the shell from within python, and then scp your file from one computer to the other. It shouldn't be very costly, almost nothing compared with the transfer costs, so don't worry about performance.
Just try
os.system('scp myfile othermachine.jack.com:/transfers')
Or something of the sort. See the documentation of scp. On Windows, you'll need CYGWIN for this.
Of course you can also go for ftp-style copies. Just set up an Apache on the target machine where you can write. But I'd go for the scp solution :)
|
How to transfer a file between two FTP servers?
|
I have two ftp servers with fxp enabled on both, I'm just wondering how I would transfer a file between the two servers in Python?
I was told curl wouldnt do it, but maybe ftplib will do.
so, the file (file.txt) is in '/personal/' FTP1 and I want to transfer that to FTP2 also to the same place, '/personal/'
Any ideas on how to do this?
|
[
"You should use ftplib (http://docs.python.org/library/ftplib.html)\n",
"The simplest thing to is call the shell from within python, and then scp your file from one computer to the other. It shouldn't be very costly, almost nothing compared with the transfer costs, so don't worry about performance. \nJust try \nos.system('scp myfile othermachine.jack.com:/transfers')\n\nOr something of the sort. See the documentation of scp. On Windows, you'll need CYGWIN for this.\nOf course you can also go for ftp-style copies. Just set up an Apache on the target machine where you can write. But I'd go for the scp solution :)\n"
] |
[
2,
0
] |
[] |
[] |
[
"ftp",
"ftplib",
"python"
] |
stackoverflow_0001881752_ftp_ftplib_python.txt
|
Q:
Removing custom widget from QVBoxLayout
I've got a QFrame with a QVBoxLayout and I'm adding my own custom widgets to the layout
to simulate a QListWidget but with more information/functionality in the items. I add the widget to the layout and keep a reference in a member variable (this is Python):
self.sv_widgets[purchase.id] = widget
self.vl_seatView.addWidget(widget)
Then when I'm done with an item I want to remove it from the screen and clean up the reference:
self.vl_seatView.removeWidget(self.sv_widgets[purchase.id])
del self.sv_widgets[purchase.id]
Unfortunately, the widget is still being displayed on the screen! I've checked and I'm only adding it to the layout once (and indeed only one copy is displayed), tried manually calling update() on the layout, but to no avail. What's the right way to do this?
A:
You can do this:
import sip # you'll need this import (no worries, it ships with your pyqt install)
sip.delete(self.sv_widgets[purchase.id])
sip.delete(obj) explicitely calls the destructor on the corresponding C++ object. removeWidget does not cause this destructor to be called (it still has a parent at that point) and del only marks the Python object for garbage collection.
You can achieve the same by doing (propably cleaner):
self.vl_seatView.removeWidget(self.sv_widgets[purchase.id])
self.sv_widgets[purchase.id].setParent(None)
del self.sv_widgets[purchase.id]
A:
You can also use self.sv_widgets[purchase.id].deleteLater()
|
Removing custom widget from QVBoxLayout
|
I've got a QFrame with a QVBoxLayout and I'm adding my own custom widgets to the layout
to simulate a QListWidget but with more information/functionality in the items. I add the widget to the layout and keep a reference in a member variable (this is Python):
self.sv_widgets[purchase.id] = widget
self.vl_seatView.addWidget(widget)
Then when I'm done with an item I want to remove it from the screen and clean up the reference:
self.vl_seatView.removeWidget(self.sv_widgets[purchase.id])
del self.sv_widgets[purchase.id]
Unfortunately, the widget is still being displayed on the screen! I've checked and I'm only adding it to the layout once (and indeed only one copy is displayed), tried manually calling update() on the layout, but to no avail. What's the right way to do this?
|
[
"You can do this:\nimport sip # you'll need this import (no worries, it ships with your pyqt install)\nsip.delete(self.sv_widgets[purchase.id])\n\nsip.delete(obj) explicitely calls the destructor on the corresponding C++ object. removeWidget does not cause this destructor to be called (it still has a parent at that point) and del only marks the Python object for garbage collection.\nYou can achieve the same by doing (propably cleaner):\nself.vl_seatView.removeWidget(self.sv_widgets[purchase.id])\nself.sv_widgets[purchase.id].setParent(None)\ndel self.sv_widgets[purchase.id]\n\n",
"You can also use self.sv_widgets[purchase.id].deleteLater()\n"
] |
[
6,
1
] |
[] |
[] |
[
"layout",
"pyqt",
"python",
"qt"
] |
stackoverflow_0001869034_layout_pyqt_python_qt.txt
|
Q:
When are property validations run in Google App Engine (GAE)?
So I was reading the following documentation on defining your own property types in GAE. I noticed that I could also include a .validate() method when extending a new Property. This validate method will be called "when an assignment is made to a property to make sure that it is compatible with your assigned attributes". Fair enough, but when exactly is that?
My question is, when exactly is this validate method called? Specifically, is it called before or after it is put? If I create this entity in a transaction, is validate called within the transaction or before the transaction?
I am aware that optimally, every Property should be "self contained" or at most, it should only deal with the state of the entity is resides in. But, what would happen if you performed a Query in the validate method? Would it blow up if you did a Query within validate that was in a different entity group than your current transactions entity group?
A:
Before put, and during the transaction, respectively (it may abort the transaction if validation fails of course). "When an assignment is made" to a property of your entity is when you write theentity.theproperty = somevalue (or when you perform it implicitly).
I believe that queries of unrelated entities during a transaction (in validate or otherwise) are non-transactional (and thus very iffy practice), but not forbidden -- but on this last point I'm not sure.
|
When are property validations run in Google App Engine (GAE)?
|
So I was reading the following documentation on defining your own property types in GAE. I noticed that I could also include a .validate() method when extending a new Property. This validate method will be called "when an assignment is made to a property to make sure that it is compatible with your assigned attributes". Fair enough, but when exactly is that?
My question is, when exactly is this validate method called? Specifically, is it called before or after it is put? If I create this entity in a transaction, is validate called within the transaction or before the transaction?
I am aware that optimally, every Property should be "self contained" or at most, it should only deal with the state of the entity is resides in. But, what would happen if you performed a Query in the validate method? Would it blow up if you did a Query within validate that was in a different entity group than your current transactions entity group?
|
[
"Before put, and during the transaction, respectively (it may abort the transaction if validation fails of course). \"When an assignment is made\" to a property of your entity is when you write theentity.theproperty = somevalue (or when you perform it implicitly).\nI believe that queries of unrelated entities during a transaction (in validate or otherwise) are non-transactional (and thus very iffy practice), but not forbidden -- but on this last point I'm not sure.\n"
] |
[
2
] |
[] |
[] |
[
"google_app_engine",
"python"
] |
stackoverflow_0001884635_google_app_engine_python.txt
|
Q:
An Exercise: map or reduce a map in Python without list comprehensions?
When I started writing this question, I didn't think of the easy solution with nested lists, but now anyway want to find one.
Here's an ugly code:
fun0(
fun1(fun2(fun3(arg1))),
fun1(fun2(fun3(arg4))),
fun1(fun2(fun3(arg4))),
fun1(fun2(fun3(arg4))))
Ouch! Names are given for examples. In the real application, their names have no pattern like this.
I played a bit with map(map ...) and reduce(map ...) getting wrong results or TypeErrors, before going here and writing this. The simple solution, of course, came while writing the question: use list comprehensions. Something like this (haven't tested yet):
fun0([i(j) for i in (fun1, fun2, fun3) for j in (arg1, arg2, arg3, arg4)])
Still, I'd like to know how is it possible to achieve the same with functional programming tools only?
fun0(map(fun1, map(fun2, map(fun3,
(arg1, arg2, arg3, arg4)))))
There's still a pattern that I think can be removed. I tried map(map, (fun1, ...), (arg1, ...)) but this way Python tried to iterate over each argument and raised errors.
A:
your 3 examples do 3 different things.
your original is the same as
fun0(map(lambda x:fun1(fun2(fun3(x))), [arg1,arg2,arg3,arg4])
your second example, if you absolutely want a functional form, is probably something like
fun0(map(apply, itertools.product([fun1,fun2,fun3],[arg1,arg2,arg3,arg4])))
A:
def composed(x): return fun1(fun2(fun3(x)))
fun0(*map(composed, (arg1, arg2, arg3, arg4)))
You could use a lambda, of course, instead of naming intermediate function composed, but I find this way more readable.
Note that the * is crucial, otherwise you're calling fun0 with a single argument, a list, instead of calling it with four arguments!-)
|
An Exercise: map or reduce a map in Python without list comprehensions?
|
When I started writing this question, I didn't think of the easy solution with nested lists, but now anyway want to find one.
Here's an ugly code:
fun0(
fun1(fun2(fun3(arg1))),
fun1(fun2(fun3(arg4))),
fun1(fun2(fun3(arg4))),
fun1(fun2(fun3(arg4))))
Ouch! Names are given for examples. In the real application, their names have no pattern like this.
I played a bit with map(map ...) and reduce(map ...) getting wrong results or TypeErrors, before going here and writing this. The simple solution, of course, came while writing the question: use list comprehensions. Something like this (haven't tested yet):
fun0([i(j) for i in (fun1, fun2, fun3) for j in (arg1, arg2, arg3, arg4)])
Still, I'd like to know how is it possible to achieve the same with functional programming tools only?
fun0(map(fun1, map(fun2, map(fun3,
(arg1, arg2, arg3, arg4)))))
There's still a pattern that I think can be removed. I tried map(map, (fun1, ...), (arg1, ...)) but this way Python tried to iterate over each argument and raised errors.
|
[
"your 3 examples do 3 different things.\nyour original is the same as\nfun0(map(lambda x:fun1(fun2(fun3(x))), [arg1,arg2,arg3,arg4])\n\nyour second example, if you absolutely want a functional form, is probably something like\nfun0(map(apply, itertools.product([fun1,fun2,fun3],[arg1,arg2,arg3,arg4])))\n\n",
"def composed(x): return fun1(fun2(fun3(x)))\n\nfun0(*map(composed, (arg1, arg2, arg3, arg4)))\n\nYou could use a lambda, of course, instead of naming intermediate function composed, but I find this way more readable.\nNote that the * is crucial, otherwise you're calling fun0 with a single argument, a list, instead of calling it with four arguments!-)\n"
] |
[
2,
1
] |
[
"The most functional way to rewrite your first code block would be to compose the three functions, map the composed function over the list of arguments, then apply fun0 to the list. Python doesn't really have a natural way to do function composition, so something like Jimmy's solution is where you'll end up.\nPython style tends to discourage lambdas, though, so I'd probably write it as a list comprehension instead of a map:\nfun0(*[fun1(fun2(fun3(x))) for x in [arg1, arg2, arg3, arg4]])\n\nEDIT: Missed that fun0 needs separate arguments, not a list; adding * as per Alex Martelli's post.\n"
] |
[
-1
] |
[
"functional_programming",
"map",
"python"
] |
stackoverflow_0001884682_functional_programming_map_python.txt
|
Q:
Pinging first available host in network subnets
I've written a small script in Python that pings all subnets of my school's wireless network and prints out the IP addresses and hostnames of computers that are connected to each subnet of the network. My current setup is that I'm relying on creating threads to handle each of the ping requests.
from threading import Thread
import subprocess
from Queue import Queue
import time
import socket
#wraps system ping command
def ping(i, q):
"""Pings address"""
while True:
ip = q.get()
#print "Thread %s: Pinging %s" % (i, ip)
result = subprocess.call("ping -n 1 %s" % ip, shell=True, stdout=subprocess.PIPE, stderr=subprocess.STDOUT)
#Avoid flooding the network with ping requests
time.sleep(3)
if result == 0:
try:
hostname=socket.gethostbyaddr(ip)
print "%s (%s): alive" % (ip,hostname[0])
except:
print "%s: alive"%ip
q.task_done()
num_threads = 100
queue = Queue()
addresses=[]
#Append all possible IP addresses from all subnets on wireless network
for i in range(1,255):
for j in range(1,254):
addresses.append('128.119.%s.%s'%(str(i),str(j)))
#Spawn thread pool
for i in range(num_threads):
worker = Thread(target=ping, args=(i, queue))
worker.setDaemon(True)
worker.start()
#Place work in queue
for ip in addresses:
queue.put(ip)
#Wait until worker threads are done to exit
queue.join()
However, I want to modify my script so that it only seeks out the first available host in the subnet. What that means is that suppose I have the following subnet (128.119.177.0/24) and the first available host is 128.119.177.20. I want my script to stop pinging the remaining hosts in the 128.119.177.0/24 after I successfully contact 128.119.177.20. I want to repeat that for every subnet on my network (128.119.0.1 - 128.119.255.254). Given my current setup, what would be the best course of action to make this change? I was thinking of doing something like a list of Queues (where each Queue holds 255 IP addresses for one of the subnets) and having one thread process each queue (unless there is a limitation on how many threads I can spawn in Python on Windows).
EDIT: I have played around with nmap (and Angry IP scanner) for this task, but I was interested in pursuing writing my own script.
A:
Simplest thing would be to have a thread work through a whole subnet and exit when it finds a host.
UNTESTED
from Queue import Queue
import time
import socket
#wraps system ping command
def ping(i, q):
"""Pings address"""
while True:
subnet = q.get()
# each IP addresse in subnet
for ip in (subnet=str(x) for x in range(1,254)):
#print "Thread %s: Pinging %s" % (i, ip)
result = subprocess.call("ping -n 1 %s" % ip, shell=True, stdout=subprocess.PIPE, stderr=subprocess.STDOUT)
#Avoid flooding the network with ping requests
time.sleep(3)
if result == 0:
try:
hostname=socket.gethostbyaddr(ip)
print "%s (%s): alive" % (ip,hostname[0]
except:
print "%s: alive"%ip
break
q.task_done()
num_threads = 100
queue = Queue()
#Put all possible subnets on wireless network into a queue
for i in range(1,255):
queue.put('128.119.%s.'%i)
#Spawn thread pool
for i in range(num_threads):
worker = Thread(target=ping, args=(i, queue))
worker.setDaemon(True)
worker.start()
#Wait until worker threads are done to exit
queue.join()
A:
Since you know how many threads you got in the beginning of the run, you could periodically check the current number of threads running to see if nowThreadCount < startThreadCount. If it's true terminate the current thread.
PS: Easiest way would be to just clear the queue object too, but I can't find that in the docs.
|
Pinging first available host in network subnets
|
I've written a small script in Python that pings all subnets of my school's wireless network and prints out the IP addresses and hostnames of computers that are connected to each subnet of the network. My current setup is that I'm relying on creating threads to handle each of the ping requests.
from threading import Thread
import subprocess
from Queue import Queue
import time
import socket
#wraps system ping command
def ping(i, q):
"""Pings address"""
while True:
ip = q.get()
#print "Thread %s: Pinging %s" % (i, ip)
result = subprocess.call("ping -n 1 %s" % ip, shell=True, stdout=subprocess.PIPE, stderr=subprocess.STDOUT)
#Avoid flooding the network with ping requests
time.sleep(3)
if result == 0:
try:
hostname=socket.gethostbyaddr(ip)
print "%s (%s): alive" % (ip,hostname[0])
except:
print "%s: alive"%ip
q.task_done()
num_threads = 100
queue = Queue()
addresses=[]
#Append all possible IP addresses from all subnets on wireless network
for i in range(1,255):
for j in range(1,254):
addresses.append('128.119.%s.%s'%(str(i),str(j)))
#Spawn thread pool
for i in range(num_threads):
worker = Thread(target=ping, args=(i, queue))
worker.setDaemon(True)
worker.start()
#Place work in queue
for ip in addresses:
queue.put(ip)
#Wait until worker threads are done to exit
queue.join()
However, I want to modify my script so that it only seeks out the first available host in the subnet. What that means is that suppose I have the following subnet (128.119.177.0/24) and the first available host is 128.119.177.20. I want my script to stop pinging the remaining hosts in the 128.119.177.0/24 after I successfully contact 128.119.177.20. I want to repeat that for every subnet on my network (128.119.0.1 - 128.119.255.254). Given my current setup, what would be the best course of action to make this change? I was thinking of doing something like a list of Queues (where each Queue holds 255 IP addresses for one of the subnets) and having one thread process each queue (unless there is a limitation on how many threads I can spawn in Python on Windows).
EDIT: I have played around with nmap (and Angry IP scanner) for this task, but I was interested in pursuing writing my own script.
|
[
"Simplest thing would be to have a thread work through a whole subnet and exit when it finds a host.\nUNTESTED\nfrom Queue import Queue\nimport time\nimport socket\n\n#wraps system ping command\ndef ping(i, q):\n \"\"\"Pings address\"\"\"\n while True:\n subnet = q.get()\n # each IP addresse in subnet \n for ip in (subnet=str(x) for x in range(1,254)):\n #print \"Thread %s: Pinging %s\" % (i, ip)\n result = subprocess.call(\"ping -n 1 %s\" % ip, shell=True, stdout=subprocess.PIPE, stderr=subprocess.STDOUT)\n #Avoid flooding the network with ping requests\n time.sleep(3)\n if result == 0:\n\n try:\n hostname=socket.gethostbyaddr(ip)\n print \"%s (%s): alive\" % (ip,hostname[0] \n except:\n print \"%s: alive\"%ip\n break\n q.task_done()\n\nnum_threads = 100\nqueue = Queue()\n\n#Put all possible subnets on wireless network into a queue\nfor i in range(1,255):\n queue.put('128.119.%s.'%i)\n\n#Spawn thread pool\nfor i in range(num_threads):\n worker = Thread(target=ping, args=(i, queue))\n worker.setDaemon(True)\n worker.start()\n\n#Wait until worker threads are done to exit \nqueue.join()\n\n",
"Since you know how many threads you got in the beginning of the run, you could periodically check the current number of threads running to see if nowThreadCount < startThreadCount. If it's true terminate the current thread.\nPS: Easiest way would be to just clear the queue object too, but I can't find that in the docs.\n"
] |
[
1,
0
] |
[] |
[] |
[
"networking",
"python",
"subnet"
] |
stackoverflow_0001883136_networking_python_subnet.txt
|
Q:
Should I take a Python CS class using Windows or Mac?
I'll be taking a Python-based computer science class next semester using my MacBook Pro. It will be centered around a custom-designed package for this class. The problem is that this package is being sponsored by Microsoft Research, so it was obviously designed with Windows in mind. Supposedly, it runs on Mac OS and Linux too, but they say they don't officially support Snow Leopard whatsoever.
My concern is that there will be some sort of miniscule differences between the Python code on a Mac and on a PC. The homework is submitted online, and is graded for results. Apparently, they don't actually look at the code itself.
Is this a concern? Should I install Windows in a VM/partition and be done with it? Or should I stay where I feel most comfortable? After all, switching back and forth constantly would be a huge hassle. Thanks for your help!
A:
If the class expects the code to run on Windows then I would install a VM with Windows on it since it is possible that some things may not work quite the same way (especially if you are doing system-specific things like file-system access or executing OS commands).
Classwork/homework always goes smoother when you have the exact same environment as the professor and the rest of the class.
A:
Definitely start with Mac. If it turns out that it really does need Windows, you can switch once you're sure. But Python development is definitely more natural on a Unix-based machine.
Most online graders will let you submit multiple times, and the first assignment is usually easy, so you should know pretty quickly if using a Mac is causing you problems. In the meantime though, you'll have a much smoother ride doing Python on a Mac than on Windows.
A:
If they will be testing your code on windows then you really need to be targeting that platform. However if you feel more comfortable on the Mac, do your dev there but also run a virtual win machine so you can test on the target platform. I would suggest the excellent VirtualBox. You can share local folders with the VM, which reduces the pain of switching back and forth, once the VM has python setup you can just hop in and and run the code direct from the directory on the Mac you developed in.
A:
From their site it looks like Mac is fully supported (up to 10.5 -- it's true that 10.6 is different enough to give occasional problems... I haven't upgraded yet even though I did buy a family pack of 10.5 to 10.6 upgrades, as I'm not looking for trouble right now). If you can use a Macbook with 10.5, I'd say to go for it -- the familiarity and extra productivity are worth the miniscule risk that despite all their claims of support something goes wrong (and you can in fact download and start testing right now!). If your Mac options are limited to 10.6, then I'd go for a VMWare or Parallels VM with a Windows (not sure if Windows 7 is fully supported yet, maybe XP is a more prudent option) installation instead.
A:
Develop and test on a Mac. If it works on the Mac, then test it on Windows before submitting. Done this tons of times with my own programming courses, albeit with a different set of languages and technologies.
A:
Go Mac and never go back.
More seriously, a Mac offers UNIX environment, and Windows offers blue screens.
|
Should I take a Python CS class using Windows or Mac?
|
I'll be taking a Python-based computer science class next semester using my MacBook Pro. It will be centered around a custom-designed package for this class. The problem is that this package is being sponsored by Microsoft Research, so it was obviously designed with Windows in mind. Supposedly, it runs on Mac OS and Linux too, but they say they don't officially support Snow Leopard whatsoever.
My concern is that there will be some sort of miniscule differences between the Python code on a Mac and on a PC. The homework is submitted online, and is graded for results. Apparently, they don't actually look at the code itself.
Is this a concern? Should I install Windows in a VM/partition and be done with it? Or should I stay where I feel most comfortable? After all, switching back and forth constantly would be a huge hassle. Thanks for your help!
|
[
"If the class expects the code to run on Windows then I would install a VM with Windows on it since it is possible that some things may not work quite the same way (especially if you are doing system-specific things like file-system access or executing OS commands).\nClasswork/homework always goes smoother when you have the exact same environment as the professor and the rest of the class.\n",
"Definitely start with Mac. If it turns out that it really does need Windows, you can switch once you're sure. But Python development is definitely more natural on a Unix-based machine.\nMost online graders will let you submit multiple times, and the first assignment is usually easy, so you should know pretty quickly if using a Mac is causing you problems. In the meantime though, you'll have a much smoother ride doing Python on a Mac than on Windows.\n",
"If they will be testing your code on windows then you really need to be targeting that platform. However if you feel more comfortable on the Mac, do your dev there but also run a virtual win machine so you can test on the target platform. I would suggest the excellent VirtualBox. You can share local folders with the VM, which reduces the pain of switching back and forth, once the VM has python setup you can just hop in and and run the code direct from the directory on the Mac you developed in.\n",
"From their site it looks like Mac is fully supported (up to 10.5 -- it's true that 10.6 is different enough to give occasional problems... I haven't upgraded yet even though I did buy a family pack of 10.5 to 10.6 upgrades, as I'm not looking for trouble right now). If you can use a Macbook with 10.5, I'd say to go for it -- the familiarity and extra productivity are worth the miniscule risk that despite all their claims of support something goes wrong (and you can in fact download and start testing right now!). If your Mac options are limited to 10.6, then I'd go for a VMWare or Parallels VM with a Windows (not sure if Windows 7 is fully supported yet, maybe XP is a more prudent option) installation instead.\n",
"Develop and test on a Mac. If it works on the Mac, then test it on Windows before submitting. Done this tons of times with my own programming courses, albeit with a different set of languages and technologies.\n",
"Go Mac and never go back.\nMore seriously, a Mac offers UNIX environment, and Windows offers blue screens.\n"
] |
[
9,
4,
3,
3,
2,
0
] |
[] |
[] |
[
"compatibility",
"macos",
"python",
"windows"
] |
stackoverflow_0001878904_compatibility_macos_python_windows.txt
|
Q:
Django loaddata error
I created a "fixtures" folder in the app directory and put data1.json in there.
This is what is in the file:
[{"firm_url": "http://www.graychase.com/kadam", "firm_name": "Gray & Chase", "first": " Karin ", "last": "Adam", "school": "Ernst Moritz Arndt University Greifswald", "year_graduated": " 2004"} ]
In the command line I cd to the app directory and
django-admin.py loaddata data1.json
but I get this error
Installing json fixture 'data1' from
'C:\Users\A\Documents\Projects\Django\sw2\wkw2\fixtures'.
Problem installing fixture
'C:\Users\A\Documents\Projects\Django\sw2\wkw2\fixtures\data1.json': Traceback (most recent call last):
File "C:\Python26\Lib\site-packages\django\core\management\commands\loaddata.py", line 150, in handle for obj in objects:
File "C:\Python26\lib\site-packages\django\core\serializers\json.py", line 41, in Deserializer for obj in PythonDeserializer(simplejson.load(stream)):
File "C:\Python26\lib\site-packages\django\core\serializers\python.py", line 76, in Deserializer
Model = _get_model(d["model"])
KeyError: 'model'
What am I doing wrong?
Edit:
I fixed the json format:
[
{
"pk": 1,
"model": "wkw2.Lawyer",
"fields": {
"school": "The George Washington University Law School",
"last": "Babas",
"firm_url": "http://www.graychase.com/babbas",
"year_graduated": "2005",
"firm_name": "Gray & Chase",
"first": "Amr A"
}
}
]
But now I get ValidationError: This value must be an integer. Is there a way to find out from the line numbers what causes the error? Only "pk" is an integer.
Problem installing fixture 'C:\~\sw2\wkw2\fixtures\csvtest1.csv.json': Traceback (most recent call last):
File "C:\Python26\Lib\site-packages\django\core\management\commands\loaddata.py", line 150, in handle for obj in objects:
File "C:\Python26\lib\site-packages\django\core\serializers\json.py", line 41, in Deserializer for obj in PythonDeserializer(simplejson.load(stream)):
File "C:\Python26\lib\site-packages\django\core\serializers\python.py", line 95, in Deserializer data[field.attname] = field.rel.to._meta.get_field(field.rel.field_name).to_python(field_value)
File "C:\Python26\lib\site-packages\django\db\models\fields\__init__.py", line 356, in to_python_("This value must be an integer."))
ValidationError: This value must be an integer.
A:
it looks like you are not defining your fixtures properly. Take a look at the Django Documentation. You need to define the model that you are loading, then define the fields like this
[
{
"model": "myapp.person",
"pk": 1,
"fields": {
"first_name": "John",
"last_name": "Lennon"
}
},
{
"model": "myapp.person",
"pk": 2,
"fields": {
"first_name": "Paul",
"last_name": "McCartney"
}
}
]
A:
It looks like the problem is within the fixture you've created. The following might cause problems:
Changing the database schema after creating a fixture, then loading the fixture into your new schema
Manually fiddling with the contents of the fixture.
Did you create the fixture using manage.py dumpdata?
|
Django loaddata error
|
I created a "fixtures" folder in the app directory and put data1.json in there.
This is what is in the file:
[{"firm_url": "http://www.graychase.com/kadam", "firm_name": "Gray & Chase", "first": " Karin ", "last": "Adam", "school": "Ernst Moritz Arndt University Greifswald", "year_graduated": " 2004"} ]
In the command line I cd to the app directory and
django-admin.py loaddata data1.json
but I get this error
Installing json fixture 'data1' from
'C:\Users\A\Documents\Projects\Django\sw2\wkw2\fixtures'.
Problem installing fixture
'C:\Users\A\Documents\Projects\Django\sw2\wkw2\fixtures\data1.json': Traceback (most recent call last):
File "C:\Python26\Lib\site-packages\django\core\management\commands\loaddata.py", line 150, in handle for obj in objects:
File "C:\Python26\lib\site-packages\django\core\serializers\json.py", line 41, in Deserializer for obj in PythonDeserializer(simplejson.load(stream)):
File "C:\Python26\lib\site-packages\django\core\serializers\python.py", line 76, in Deserializer
Model = _get_model(d["model"])
KeyError: 'model'
What am I doing wrong?
Edit:
I fixed the json format:
[
{
"pk": 1,
"model": "wkw2.Lawyer",
"fields": {
"school": "The George Washington University Law School",
"last": "Babas",
"firm_url": "http://www.graychase.com/babbas",
"year_graduated": "2005",
"firm_name": "Gray & Chase",
"first": "Amr A"
}
}
]
But now I get ValidationError: This value must be an integer. Is there a way to find out from the line numbers what causes the error? Only "pk" is an integer.
Problem installing fixture 'C:\~\sw2\wkw2\fixtures\csvtest1.csv.json': Traceback (most recent call last):
File "C:\Python26\Lib\site-packages\django\core\management\commands\loaddata.py", line 150, in handle for obj in objects:
File "C:\Python26\lib\site-packages\django\core\serializers\json.py", line 41, in Deserializer for obj in PythonDeserializer(simplejson.load(stream)):
File "C:\Python26\lib\site-packages\django\core\serializers\python.py", line 95, in Deserializer data[field.attname] = field.rel.to._meta.get_field(field.rel.field_name).to_python(field_value)
File "C:\Python26\lib\site-packages\django\db\models\fields\__init__.py", line 356, in to_python_("This value must be an integer."))
ValidationError: This value must be an integer.
|
[
"it looks like you are not defining your fixtures properly. Take a look at the Django Documentation. You need to define the model that you are loading, then define the fields like this \n [\n {\n \"model\": \"myapp.person\",\n \"pk\": 1,\n \"fields\": {\n \"first_name\": \"John\",\n \"last_name\": \"Lennon\"\n }\n },\n {\n \"model\": \"myapp.person\",\n \"pk\": 2,\n \"fields\": {\n \"first_name\": \"Paul\",\n \"last_name\": \"McCartney\"\n }\n }\n]\n\n",
"It looks like the problem is within the fixture you've created. The following might cause problems:\n\nChanging the database schema after creating a fixture, then loading the fixture into your new schema\nManually fiddling with the contents of the fixture.\n\nDid you create the fixture using manage.py dumpdata?\n"
] |
[
11,
3
] |
[] |
[] |
[
"django",
"python"
] |
stackoverflow_0001884827_django_python.txt
|
Q:
Liteweight CGI Server to use on local machine to serve KML to Google Earth via Python or similar?
Greetings,
I want to write a script that handles simple http requests from Google Earth and sends back KML to display map tiles that are stored locally. I would LIKE to use Python but any language is fine. I have not ever done anything with CGI, but I think this is the simplest way to accomplish my task. This is what the Google KML docs use, is Python CGI scripts to talk to Google Earth. Is there a CGI server that I can download (and run on Windows 7, or if absolutely necessary I could build a VM running linux) that I can just drop my Python script onto and go?
Basically, as I move around the screen in Google Earth, it will send a request to my server, which will tell Google Earth what to show on the screen. Simple.
Background:
I am doing a lot of driving with my laptop beside me, with a USB GPS receiver that updates my location in realtime on Google Earth. But, since I am OFFLINE, I cannot dynamically download map tiles from Google Maps so that I can see street names and such. I have been downloading the map tiles and patching them together as one big PNG to cover the city I will be driving in, and then importing those images as an Overlay in Google Earth, but I would like to build a server that runs locally, taps into a database of map tiles stored on the machine, and serves up the KML to display those tiles as an overlay instead of having to do all that work ahead of time each time I make a trip.
A:
If I were you I'd use MapServer and Tilecache to do exactly that (serving up georeferenced raster imagery over http / python mapscript bindings available).
If you want plain cgi you can probably use lighthttpd or nxginx or similar.
Also note that scraping the google map tiles is very likely infringing their terms of use.
A:
CGIHTTPServer in the standard library.
# current directory containing cgi-bin directory with scripts in
# subclass CGIHTTPRequestHandler and override cgi_directories to change this
#
os.chdir('/path/to/htdocs')
BaseHTTPServer.HTTPServer(('',80), CGIHTTPServer.CGIHTTPRequestHandler).serve_forever()
It ain't fast, it's pretty limited (you can't return anything but 200 OK responses, for one) and it probably ain't wholly secure, but for this sort of local job it's fine.
|
Liteweight CGI Server to use on local machine to serve KML to Google Earth via Python or similar?
|
Greetings,
I want to write a script that handles simple http requests from Google Earth and sends back KML to display map tiles that are stored locally. I would LIKE to use Python but any language is fine. I have not ever done anything with CGI, but I think this is the simplest way to accomplish my task. This is what the Google KML docs use, is Python CGI scripts to talk to Google Earth. Is there a CGI server that I can download (and run on Windows 7, or if absolutely necessary I could build a VM running linux) that I can just drop my Python script onto and go?
Basically, as I move around the screen in Google Earth, it will send a request to my server, which will tell Google Earth what to show on the screen. Simple.
Background:
I am doing a lot of driving with my laptop beside me, with a USB GPS receiver that updates my location in realtime on Google Earth. But, since I am OFFLINE, I cannot dynamically download map tiles from Google Maps so that I can see street names and such. I have been downloading the map tiles and patching them together as one big PNG to cover the city I will be driving in, and then importing those images as an Overlay in Google Earth, but I would like to build a server that runs locally, taps into a database of map tiles stored on the machine, and serves up the KML to display those tiles as an overlay instead of having to do all that work ahead of time each time I make a trip.
|
[
"If I were you I'd use MapServer and Tilecache to do exactly that (serving up georeferenced raster imagery over http / python mapscript bindings available).\nIf you want plain cgi you can probably use lighthttpd or nxginx or similar.\nAlso note that scraping the google map tiles is very likely infringing their terms of use.\n",
"CGIHTTPServer in the standard library.\n# current directory containing cgi-bin directory with scripts in\n# subclass CGIHTTPRequestHandler and override cgi_directories to change this\n#\nos.chdir('/path/to/htdocs')\n\nBaseHTTPServer.HTTPServer(('',80), CGIHTTPServer.CGIHTTPRequestHandler).serve_forever()\n\nIt ain't fast, it's pretty limited (you can't return anything but 200 OK responses, for one) and it probably ain't wholly secure, but for this sort of local job it's fine.\n"
] |
[
1,
1
] |
[] |
[] |
[
"cgi",
"google_earth",
"kml",
"python"
] |
stackoverflow_0001885113_cgi_google_earth_kml_python.txt
|
Q:
Use Python's easy_install in intranet
Increasingly I found myself using tools based upon python, particularly that use installation processes involving easy_install. The trouble for me is that I am
On an intranet with no internet access
On windows (which always complicates things a little!)
Any advice on how to setup easy_install on my intranet to make using python based tools a bit easier?
A:
I think you can use .egg files with easy_install, you could host those on your intranet and point easy_install to it. See http://peak.telecommunity.com/DevCenter/EasyInstall#using-easy-install for a good reference.
|
Use Python's easy_install in intranet
|
Increasingly I found myself using tools based upon python, particularly that use installation processes involving easy_install. The trouble for me is that I am
On an intranet with no internet access
On windows (which always complicates things a little!)
Any advice on how to setup easy_install on my intranet to make using python based tools a bit easier?
|
[
"I think you can use .egg files with easy_install, you could host those on your intranet and point easy_install to it. See http://peak.telecommunity.com/DevCenter/EasyInstall#using-easy-install for a good reference.\n"
] |
[
3
] |
[] |
[] |
[
"easy_install",
"python"
] |
stackoverflow_0001884791_easy_install_python.txt
|
Q:
How slow are Python/django exceptions?
is python exception slow?
I'm kind using python exceptions to structure programm follow in my web application, and I'm wondering how throwing exceptions will affect performance of my application. what is your thoughts?
which one of the following statements is less expensive in terms of memory and cpu?
try:
artist = Artist.objects.get(id=id)
except:
raise Http404
artist = Artist.objects.filter(id=id)
if not artist:
return HttpResponse('404')
A:
Handling exceptions will be the least of your worries with regards to performance. I would suggest, however, that you use a shortcut provided by Django for you:
from django.shortcuts import get_object_or_404
artist = get_object_or_404(Artist, id=id)
Which either assigns the object to artist or returns a 404. It's win-win!
Also, you should check out the django-debug-toolbar, which provides rendering/cpu time, context switches, and all kinds of other helpful tidbits of data for developers and might be just the tool you need.
A:
To really understand the performance of your system, you'll have to profile it. But Python is a language that encourages using exceptions like this, so they don't have an unusual overhead as they do in some other languages.
For example, sometimes people debate this choice:
if hasattr(obj, "attr"):
use(obj.attr)
else:
some_other(obj)
or:
try:
use(obj.attr)
except AttributeError:
some_other(obj)
The people who say you should use the first to avoid the exception need to understand that internally, hasattr is implemented by accessing the attribute and returning False if an AttributeError is raised. So in fact, both code chunks use exceptions.
A:
This guy did a nice little writeup of testing try/except speed with dicts, I sure it would have some analogue in your case. Either way, doing a nice profile will give you the best info.
|
How slow are Python/django exceptions?
|
is python exception slow?
I'm kind using python exceptions to structure programm follow in my web application, and I'm wondering how throwing exceptions will affect performance of my application. what is your thoughts?
which one of the following statements is less expensive in terms of memory and cpu?
try:
artist = Artist.objects.get(id=id)
except:
raise Http404
artist = Artist.objects.filter(id=id)
if not artist:
return HttpResponse('404')
|
[
"Handling exceptions will be the least of your worries with regards to performance. I would suggest, however, that you use a shortcut provided by Django for you:\nfrom django.shortcuts import get_object_or_404\nartist = get_object_or_404(Artist, id=id)\n\nWhich either assigns the object to artist or returns a 404. It's win-win!\nAlso, you should check out the django-debug-toolbar, which provides rendering/cpu time, context switches, and all kinds of other helpful tidbits of data for developers and might be just the tool you need.\n",
"To really understand the performance of your system, you'll have to profile it. But Python is a language that encourages using exceptions like this, so they don't have an unusual overhead as they do in some other languages.\nFor example, sometimes people debate this choice:\nif hasattr(obj, \"attr\"):\n use(obj.attr)\nelse:\n some_other(obj)\n\nor:\ntry:\n use(obj.attr)\nexcept AttributeError:\n some_other(obj)\n\nThe people who say you should use the first to avoid the exception need to understand that internally, hasattr is implemented by accessing the attribute and returning False if an AttributeError is raised. So in fact, both code chunks use exceptions.\n",
"This guy did a nice little writeup of testing try/except speed with dicts, I sure it would have some analogue in your case. Either way, doing a nice profile will give you the best info.\n"
] |
[
15,
10,
8
] |
[] |
[] |
[
"django",
"exception",
"python"
] |
stackoverflow_0001885292_django_exception_python.txt
|
Q:
How to populate a Django sqlite3 database
My plan is to collect lawyer biography data from websites in batches and convert each batch into a .csv file, then to json, and then load each into a Django database.
Please let me know how to achieve this task the best way.
A:
Just load the database directly. Collect data from websites in batches, loading the SQlite3 directly. Just write simple batch applications that use the Django ORM. Collect data from websites and load SQLite3 immediately. Do not create CSV. Do not create JSON. Do not create intermediate results. Do not do any extra work.
Edit.
from myapp.models import MyModel
import urllib2
with open("sourceListOfURLs.txt", "r" ) as source:
for aLine in source:
for this, the, the_other in someGenerator( aLine ):
object= MyModel.objects.create( field1=this, field2=that, field3=the_other )
object.save()
def someGenerator( url ):
# open the URL with urllib2
# parse the data with BeautifulSoup
yield this, that, the_other
|
How to populate a Django sqlite3 database
|
My plan is to collect lawyer biography data from websites in batches and convert each batch into a .csv file, then to json, and then load each into a Django database.
Please let me know how to achieve this task the best way.
|
[
"Just load the database directly. Collect data from websites in batches, loading the SQlite3 directly. Just write simple batch applications that use the Django ORM. Collect data from websites and load SQLite3 immediately. Do not create CSV. Do not create JSON. Do not create intermediate results. Do not do any extra work.\n\nEdit.\nfrom myapp.models import MyModel\nimport urllib2\n\nwith open(\"sourceListOfURLs.txt\", \"r\" ) as source:\n for aLine in source:\n for this, the, the_other in someGenerator( aLine ):\n object= MyModel.objects.create( field1=this, field2=that, field3=the_other )\n object.save()\n\ndef someGenerator( url ):\n # open the URL with urllib2\n # parse the data with BeautifulSoup\n yield this, that, the_other \n\n"
] |
[
7
] |
[] |
[] |
[
"csv",
"django",
"json",
"python"
] |
stackoverflow_0001884694_csv_django_json_python.txt
|
Q:
Parsing multilevel text list
I need to parse text lists:
1 List name
1 item
2 item
3 item
2 List name
1 item
2 item
3 item
3 List name
1 item
2 item
3 item
I was trying to use regular expression to split first level list:
import re
def re_show(pat, s):
print re.compile(pat, re.S).sub("{\g<0>}", s),'\n'
s = '''
1 List name
1 item
2 item
3 item
2 List name
1 item
2 item
3 item
3 List name
1 item
2 item
3 item
'''
re_show('\n\d+.*?(?=\n\n\d+.*?\n\n)', s)
But it doesn't work. Instead of this:
{
1 List name
1 item
2 item
3 item}
{
2 List name
1 item
2 item
3 item}
{
3 List name
1 item
2 item
3 item}
I've got this:
{
1 List name}
{
1 item
2 item
3 item}
{
2 List name}
{
1 item
2 item
3 item}
3 List name
1 item
2 item
3 item
What would you recommend to solve this task?
Thanks for your answers. I've learned many new features of Python.
I think, I will use "state machine" approach as described here
A:
Do you have control over the list format? With just a little editing, you could turn that into config file format, and use the ConfigParser module.
Otherwise, how about with a little recursion?
from collections import defaultdict
def fill_data(data, key, sequence, pred):
"""Recursively fill the data dictionary"""
for item in sequence:
# if the pred is true, add it to the list
if pred(item):
data[key].append(item)
# otherwise recurse, with item as key
else:
return fill_data(data, item, sequence, pred)
return data
# a key->list dictionary
data = defaultdict(list)
# Get the text as a sequence of non-empty lines
lines = (l for l in s.splitlines() if l.strip())
def is_data_line(line):
"""Is this line a data line (i.e. two items)?"""
return len(line.split()) == 2
result = fill_data(data, None, lines, is_data_line )
print dict(result)
Output (prettified):
{'2 List name':
['1 item', '2 item', '3 item'],
'3 List name':
['1 item', '2 item', '3 item'],
'1 List name':
['1 item', '2 item', '3 item']}
A:
here's one way using dictionary
f=open("myfile")
d={}
e=0
for line in f:
line=line.rstrip()
if "List" in line:
e=e+1
d.setdefault(e,[])
d[e].append(line)
f.close()
for i ,j in d.iteritems():
print i,j
A:
class ListParser:
def __init__(self, s):
self.str = s.split("\n")
print self.str
self.answer = []
def parse(self):
self.nextLine()
self.topList()
return
def topList(self):
while(len(self.str) > 0):
self.topListItem()
def topListItem(self):
l = self.nextLine()
print "TOP: " + l
l = self.nextLine()
if l != '':
raise Exception("expected blank line but found '%s'" % l)
sub = self.sublist()
def nextLine(self):
return self.str.pop(0)
def sublist(self):
while True:
l = self.nextLine()
if l == '':
return # end of sublist marked by blank line
else:
print "SUB: " + l
parser = ListParser(s)
parser.parse()
print "done"
prints
TOP: 1 List name
SUB: 1 item
SUB: 2 item
SUB: 3 item
TOP: 2 List name
SUB: 1 item
SUB: 2 item
SUB: 3 item
TOP: 3 List name
SUB: 1 item
SUB: 2 item
SUB: 3 item
done
A:
I suspect I'm missing the point, but isn't this simply a question of looking for List?
|
Parsing multilevel text list
|
I need to parse text lists:
1 List name
1 item
2 item
3 item
2 List name
1 item
2 item
3 item
3 List name
1 item
2 item
3 item
I was trying to use regular expression to split first level list:
import re
def re_show(pat, s):
print re.compile(pat, re.S).sub("{\g<0>}", s),'\n'
s = '''
1 List name
1 item
2 item
3 item
2 List name
1 item
2 item
3 item
3 List name
1 item
2 item
3 item
'''
re_show('\n\d+.*?(?=\n\n\d+.*?\n\n)', s)
But it doesn't work. Instead of this:
{
1 List name
1 item
2 item
3 item}
{
2 List name
1 item
2 item
3 item}
{
3 List name
1 item
2 item
3 item}
I've got this:
{
1 List name}
{
1 item
2 item
3 item}
{
2 List name}
{
1 item
2 item
3 item}
3 List name
1 item
2 item
3 item
What would you recommend to solve this task?
Thanks for your answers. I've learned many new features of Python.
I think, I will use "state machine" approach as described here
|
[
"Do you have control over the list format? With just a little editing, you could turn that into config file format, and use the ConfigParser module.\nOtherwise, how about with a little recursion?\nfrom collections import defaultdict\n\ndef fill_data(data, key, sequence, pred):\n \"\"\"Recursively fill the data dictionary\"\"\"\n for item in sequence:\n # if the pred is true, add it to the list\n if pred(item):\n data[key].append(item)\n # otherwise recurse, with item as key\n else:\n return fill_data(data, item, sequence, pred)\n return data\n\n# a key->list dictionary\ndata = defaultdict(list)\n# Get the text as a sequence of non-empty lines\nlines = (l for l in s.splitlines() if l.strip())\n\ndef is_data_line(line):\n \"\"\"Is this line a data line (i.e. two items)?\"\"\"\n return len(line.split()) == 2\n\nresult = fill_data(data, None, lines, is_data_line )\n\nprint dict(result)\n\nOutput (prettified):\n{'2 List name': \n ['1 item', '2 item', '3 item'], \n '3 List name': \n ['1 item', '2 item', '3 item'], \n '1 List name': \n ['1 item', '2 item', '3 item']}\n\n",
"here's one way using dictionary\nf=open(\"myfile\")\nd={}\ne=0\nfor line in f:\n line=line.rstrip()\n if \"List\" in line:\n e=e+1\n d.setdefault(e,[])\n d[e].append(line)\nf.close()\nfor i ,j in d.iteritems():\n print i,j\n\n",
"class ListParser:\n\n def __init__(self, s):\n self.str = s.split(\"\\n\")\n print self.str\n self.answer = []\n\n def parse(self):\n self.nextLine()\n self.topList()\n return\n\n def topList(self):\n while(len(self.str) > 0):\n self.topListItem()\n\n def topListItem(self):\n l = self.nextLine()\n print \"TOP: \" + l\n l = self.nextLine()\n if l != '':\n raise Exception(\"expected blank line but found '%s'\" % l)\n sub = self.sublist()\n\n def nextLine(self):\n return self.str.pop(0)\n\n def sublist(self):\n while True:\n l = self.nextLine()\n if l == '':\n return # end of sublist marked by blank line\n else:\n print \"SUB: \" + l\n\nparser = ListParser(s)\nparser.parse() \nprint \"done\"\n\nprints\nTOP: 1 List name\nSUB: 1 item\nSUB: 2 item\nSUB: 3 item\nTOP: 2 List name\nSUB: 1 item\nSUB: 2 item\nSUB: 3 item\nTOP: 3 List name\nSUB: 1 item\nSUB: 2 item\nSUB: 3 item\ndone\n\n",
"I suspect I'm missing the point, but isn't this simply a question of looking for List?\n"
] |
[
2,
1,
1,
0
] |
[] |
[] |
[
"parsing",
"python",
"regex"
] |
stackoverflow_0001885314_parsing_python_regex.txt
|
Q:
Python 2.6: reading data from a Windows Console application. (os.system?)
I have a Windows console application that returns some text. I want to read that text in a Python script. I have tried reading it by using os.system, but it is not working properly.
import os
foo = os.system('test.exe')
Assuming that test.exe returns "bar", I want the variable foo to be set to "bar". But what happens is, it prints "bar" on the console and the variable foo is set to 0.
What do I need to do to get the behavior I want?
A:
Please use subprocess
import subprocess
foo = subprocess.Popen('test.exe',stdout=subprocess.PIPE,stderr=subprocess.PIPE)
http://docs.python.org/library/subprocess.html#module-subprocess
A:
WARNING: This only works on UNIX systems.
I find that subprocess is overkill when all you want is output to be captured. I recommend the use of commands.getoutput():
>>> import commands
>>> foo = commands.getoutput('bar')
Technically it's just doing a popen() on your behalf, but it's a lot simpler for this basic purpose.
BTW, os.system() does not return the output of the command, it only returns the exit status, which is why it is not working for you.
Alternatively, if you require both the exit status and the command output, use commands.getstatusoutput(), which returns a 2-tuple of (status, output):
>>> foo = commands.getstatusoutput('bar')
>>> foo
(32512, 'sh: bar: command not found')
|
Python 2.6: reading data from a Windows Console application. (os.system?)
|
I have a Windows console application that returns some text. I want to read that text in a Python script. I have tried reading it by using os.system, but it is not working properly.
import os
foo = os.system('test.exe')
Assuming that test.exe returns "bar", I want the variable foo to be set to "bar". But what happens is, it prints "bar" on the console and the variable foo is set to 0.
What do I need to do to get the behavior I want?
|
[
"Please use subprocess\nimport subprocess\nfoo = subprocess.Popen('test.exe',stdout=subprocess.PIPE,stderr=subprocess.PIPE)\n\nhttp://docs.python.org/library/subprocess.html#module-subprocess\n",
"WARNING: This only works on UNIX systems.\nI find that subprocess is overkill when all you want is output to be captured. I recommend the use of commands.getoutput():\n>>> import commands\n>>> foo = commands.getoutput('bar')\n\nTechnically it's just doing a popen() on your behalf, but it's a lot simpler for this basic purpose. \nBTW, os.system() does not return the output of the command, it only returns the exit status, which is why it is not working for you.\nAlternatively, if you require both the exit status and the command output, use commands.getstatusoutput(), which returns a 2-tuple of (status, output):\n>>> foo = commands.getstatusoutput('bar')\n>>> foo\n(32512, 'sh: bar: command not found')\n\n"
] |
[
8,
2
] |
[] |
[] |
[
"console",
"exe",
"python",
"windows"
] |
stackoverflow_0001885776_console_exe_python_windows.txt
|
Q:
Converting a list of lists to a tuple in Python
I have a list of lists (generated with a simple list comprehension):
>>> base_lists = [[a, b] for a in range(1, 3) for b in range(1, 6)]
>>> base_lists
[[1,1],[1,2],[1,3],[1,4],[1,5],[2,1],[2,2],[2,3],[2,4],[2,5]]
I want to turn this entire list into a tuple containing all of the values in the lists, i.e.:
resulting_tuple = (1,1,1,2,1,3,1,4,1,5,2,1,2,2,2,3,2,4,2,5)
What would the most effective way to do this be? (A way to generate this same tuple with list comprehension would also be an acceptable answer.) I've looked at answers here and in the Python documentation, however I have been unable to find a suitable one.
EDIT:
Many thanks to all who answered!
A:
tuple(x for sublist in base_lists for x in sublist)
Edit: note that, with base_lists so short, the genexp (with unlimited memory available) is slow. Consider the following file tu.py:
base_lists = [[a, b] for a in range(1, 3) for b in range(1, 6)]
def genexp():
return tuple(x for sublist in base_lists for x in sublist)
def listcomp():
return tuple([x for sublist in base_lists for x in sublist])
def withsum():
return tuple(sum(base_lists,[]))
import itertools as it
def withit():
return tuple(it.chain(*base_lists))
Now:
$ python -mtimeit -s'import tu' 'tu.genexp()'
100000 loops, best of 3: 7.86 usec per loop
$ python -mtimeit -s'import tu' 'tu.withsum()'
100000 loops, best of 3: 5.79 usec per loop
$ python -mtimeit -s'import tu' 'tu.withit()'
100000 loops, best of 3: 5.17 usec per loop
$ python -mtimeit -s'import tu' 'tu.listcomp()'
100000 loops, best of 3: 5.33 usec per loop
When lists are longer (i.e., when performance really matters) things are a bit different. E.g., putting a 100 * on the RHS defining base_lists:
$ python -mtimeit -s'import tu' 'tu.genexp()'
1000 loops, best of 3: 408 usec per loop
$ python -mtimeit -s'import tu' 'tu.withsum()'
100 loops, best of 3: 5.07 msec per loop
$ python -mtimeit -s'import tu' 'tu.withit()'
10000 loops, best of 3: 148 usec per loop
$ python -mtimeit -s'import tu' 'tu.listcomp()'
1000 loops, best of 3: 278 usec per loop
so for long lists only withsum is a performance disaster -- the others are in the same ballpark, although clearly itertools has the edge, and list comprehensions (when abundant memory is available, as it always will be in microbenchmarks;-) are faster than genexps.
Using 1000 *, genexp slows down by about 10 times (wrt the 100 *), withit and listcomp by about 12 times, and withsum by about 180 times (withsum is O(N squared), plus it's starting to suffer from serious heap fragmentation at that size).
A:
from itertools import chain
base_lists = [[a, b] for a in range(1, 3) for b in range(1, 6)]
print tuple(chain(*base_lists))
A:
>>> sum(base_lists,[])
[1, 1, 1, 2, 1, 3, 1, 4, 1, 5, 2, 1, 2, 2, 2, 3, 2, 4, 2, 5]
>>> tuple(sum(base_lists,[]))
(1, 1, 1, 2, 1, 3, 1, 4, 1, 5, 2, 1, 2, 2, 2, 3, 2, 4, 2, 5)
A:
resulting_tuple = tuple(item for l in base_lists for item in l)
A:
>>> arr=[]
>>> base_lists = [[a, b] for a in range(1, 3) for b in range(1, 6)]
>>> [ arr.extend(i) for i in base_lists ]
[None, None, None, None, None, None, None, None, None, None]
>>> arr
[1, 1, 1, 2, 1, 3, 1, 4, 1, 5, 2, 1, 2, 2, 2, 3, 2, 4, 2, 5]
>>> tuple(arr)
(1, 1, 1, 2, 1, 3, 1, 4, 1, 5, 2, 1, 2, 2, 2, 3, 2, 4, 2, 5)
|
Converting a list of lists to a tuple in Python
|
I have a list of lists (generated with a simple list comprehension):
>>> base_lists = [[a, b] for a in range(1, 3) for b in range(1, 6)]
>>> base_lists
[[1,1],[1,2],[1,3],[1,4],[1,5],[2,1],[2,2],[2,3],[2,4],[2,5]]
I want to turn this entire list into a tuple containing all of the values in the lists, i.e.:
resulting_tuple = (1,1,1,2,1,3,1,4,1,5,2,1,2,2,2,3,2,4,2,5)
What would the most effective way to do this be? (A way to generate this same tuple with list comprehension would also be an acceptable answer.) I've looked at answers here and in the Python documentation, however I have been unable to find a suitable one.
EDIT:
Many thanks to all who answered!
|
[
"tuple(x for sublist in base_lists for x in sublist)\n\nEdit: note that, with base_lists so short, the genexp (with unlimited memory available) is slow. Consider the following file tu.py:\nbase_lists = [[a, b] for a in range(1, 3) for b in range(1, 6)]\n\ndef genexp():\n return tuple(x for sublist in base_lists for x in sublist)\n\ndef listcomp():\n return tuple([x for sublist in base_lists for x in sublist])\n\ndef withsum():\n return tuple(sum(base_lists,[]))\n\nimport itertools as it\n\ndef withit():\n return tuple(it.chain(*base_lists))\n\nNow:\n$ python -mtimeit -s'import tu' 'tu.genexp()'\n100000 loops, best of 3: 7.86 usec per loop\n$ python -mtimeit -s'import tu' 'tu.withsum()'\n100000 loops, best of 3: 5.79 usec per loop\n$ python -mtimeit -s'import tu' 'tu.withit()'\n100000 loops, best of 3: 5.17 usec per loop\n$ python -mtimeit -s'import tu' 'tu.listcomp()'\n100000 loops, best of 3: 5.33 usec per loop\n\nWhen lists are longer (i.e., when performance really matters) things are a bit different. E.g., putting a 100 * on the RHS defining base_lists:\n$ python -mtimeit -s'import tu' 'tu.genexp()'\n1000 loops, best of 3: 408 usec per loop\n$ python -mtimeit -s'import tu' 'tu.withsum()'\n100 loops, best of 3: 5.07 msec per loop\n$ python -mtimeit -s'import tu' 'tu.withit()'\n10000 loops, best of 3: 148 usec per loop\n$ python -mtimeit -s'import tu' 'tu.listcomp()'\n1000 loops, best of 3: 278 usec per loop\n\nso for long lists only withsum is a performance disaster -- the others are in the same ballpark, although clearly itertools has the edge, and list comprehensions (when abundant memory is available, as it always will be in microbenchmarks;-) are faster than genexps.\nUsing 1000 *, genexp slows down by about 10 times (wrt the 100 *), withit and listcomp by about 12 times, and withsum by about 180 times (withsum is O(N squared), plus it's starting to suffer from serious heap fragmentation at that size).\n",
"from itertools import chain\nbase_lists = [[a, b] for a in range(1, 3) for b in range(1, 6)]\n\nprint tuple(chain(*base_lists))\n\n",
">>> sum(base_lists,[])\n[1, 1, 1, 2, 1, 3, 1, 4, 1, 5, 2, 1, 2, 2, 2, 3, 2, 4, 2, 5]\n>>> tuple(sum(base_lists,[]))\n(1, 1, 1, 2, 1, 3, 1, 4, 1, 5, 2, 1, 2, 2, 2, 3, 2, 4, 2, 5)\n\n",
"resulting_tuple = tuple(item for l in base_lists for item in l)\n",
">>> arr=[]\n>>> base_lists = [[a, b] for a in range(1, 3) for b in range(1, 6)]\n>>> [ arr.extend(i) for i in base_lists ]\n[None, None, None, None, None, None, None, None, None, None]\n>>> arr\n[1, 1, 1, 2, 1, 3, 1, 4, 1, 5, 2, 1, 2, 2, 2, 3, 2, 4, 2, 5]\n>>> tuple(arr)\n(1, 1, 1, 2, 1, 3, 1, 4, 1, 5, 2, 1, 2, 2, 2, 3, 2, 4, 2, 5)\n\n"
] |
[
11,
5,
3,
2,
0
] |
[] |
[] |
[
"list_comprehension",
"python",
"python_itertools",
"tuple_packing"
] |
stackoverflow_0001884323_list_comprehension_python_python_itertools_tuple_packing.txt
|
Q:
Use pyExcelerator to generate dynamic Excel file with Django. Ensure unique temporary filename
I'd like to generate a dynamic Excel file on request from Django. The library pyExcelerator does this, but I haven't found any way to use the contents of the Excel file without generating a server-side temporary Excel file, reading it, using its contents and deleting it.
The problem is that pyExcelerator only way to extract the contents of the Excel file is saving it via:
workbook = pyExcelerator.Workbook()
workbook.save("tmp_filename")
And then read the temporary file contents. I can't use the standard library "tempfile" because it doesn't accept a file, just a filename. How can I ensure that the filename is unique and that the file is deleted once it has been used?
A:
pyExcelerator is unmaintained, but it has a fork, xlwt, which is maintained and has more features, including allowing you to save to any file-like object. This includes saving straight to a Django HttpResponse:
from django.http import HttpResponse
import xlwt
def my_view(request):
response = HttpResponse(mimetype="application/ms-excel")
response['Content-Disposition'] = 'attachment; filename="foo.xls"'
wb = xlwt.Workbook()
wb.save(response)
return response
A:
Why can you not use the tempfile module?
How about:
import tempfile
fd, filename = tempfile.mkstemp()
fd.close()
workbook.save(filename)
|
Use pyExcelerator to generate dynamic Excel file with Django. Ensure unique temporary filename
|
I'd like to generate a dynamic Excel file on request from Django. The library pyExcelerator does this, but I haven't found any way to use the contents of the Excel file without generating a server-side temporary Excel file, reading it, using its contents and deleting it.
The problem is that pyExcelerator only way to extract the contents of the Excel file is saving it via:
workbook = pyExcelerator.Workbook()
workbook.save("tmp_filename")
And then read the temporary file contents. I can't use the standard library "tempfile" because it doesn't accept a file, just a filename. How can I ensure that the filename is unique and that the file is deleted once it has been used?
|
[
"pyExcelerator is unmaintained, but it has a fork, xlwt, which is maintained and has more features, including allowing you to save to any file-like object. This includes saving straight to a Django HttpResponse:\nfrom django.http import HttpResponse\nimport xlwt\n\ndef my_view(request):\n response = HttpResponse(mimetype=\"application/ms-excel\")\n response['Content-Disposition'] = 'attachment; filename=\"foo.xls\"'\n wb = xlwt.Workbook()\n wb.save(response)\n return response\n\n",
"Why can you not use the tempfile module?\nHow about:\nimport tempfile\nfd, filename = tempfile.mkstemp()\nfd.close()\nworkbook.save(filename)\n\n"
] |
[
11,
3
] |
[] |
[] |
[
"django",
"excel",
"pyexcelerator",
"python",
"temporary_files"
] |
stackoverflow_0001886744_django_excel_pyexcelerator_python_temporary_files.txt
|
Q:
Unicode filenames on python 2.6 under Mac OS X
I'm using os.walk to create a list of all music files under a folder. Some of these filenames are non-ascii, for example:
01 空即是色.mp3
I'm using the mutagen library to parse metadata for this file, and it professes complete unicode support. The filename is being retrieved as unicode, and can be printed as unicode. However, no matter what I do (including normalising the unicode beforehand, or encoding it as utf-8 beforehand), mutagen attempts to open()
01 \xe7\xa9\xba\xe5\x8d\xb3\xe6\x98\xaf\xe8\x89\xb2.mp3
or
01 \u7a7a\u5373\u662f\u8272.mp3
How can I force it to open() the correct filename (the one it is perfectly capable of printing)?
The full code is here.
Note: I am rather new to python and programming in general, any advice you could give in regards to my code would be very much appreciated. Thanks in advance
EDIT: Okay, this is a rather embarrassing error of mine, the problem was not the character encoding, it was the fact that the path was not being appended to the open() call. How do I find the full path for a file found via walk()? The files are 2-3 directories deep.
A:
Note that walk(dir) returns the filename without path. If you want to open the file, you must prepend dir:
for dirpath, dirnames, filenames in os.walk(dir):
for filename in filenames:
path = os.path.join(dirpath, filename)
|
Unicode filenames on python 2.6 under Mac OS X
|
I'm using os.walk to create a list of all music files under a folder. Some of these filenames are non-ascii, for example:
01 空即是色.mp3
I'm using the mutagen library to parse metadata for this file, and it professes complete unicode support. The filename is being retrieved as unicode, and can be printed as unicode. However, no matter what I do (including normalising the unicode beforehand, or encoding it as utf-8 beforehand), mutagen attempts to open()
01 \xe7\xa9\xba\xe5\x8d\xb3\xe6\x98\xaf\xe8\x89\xb2.mp3
or
01 \u7a7a\u5373\u662f\u8272.mp3
How can I force it to open() the correct filename (the one it is perfectly capable of printing)?
The full code is here.
Note: I am rather new to python and programming in general, any advice you could give in regards to my code would be very much appreciated. Thanks in advance
EDIT: Okay, this is a rather embarrassing error of mine, the problem was not the character encoding, it was the fact that the path was not being appended to the open() call. How do I find the full path for a file found via walk()? The files are 2-3 directories deep.
|
[
"Note that walk(dir) returns the filename without path. If you want to open the file, you must prepend dir:\nfor dirpath, dirnames, filenames in os.walk(dir):\n for filename in filenames:\n path = os.path.join(dirpath, filename)\n\n"
] |
[
2
] |
[] |
[] |
[
"python",
"unicode"
] |
stackoverflow_0001887215_python_unicode.txt
|
Q:
IronPython examples
I have heard IronPython for a long time, but never seen a real-life application using it.
Do you provide some examples to see its power?
Thanks.
A:
How did you miss Resolver Systems? Their Rsolver One spreadsheet application is IronPython.
|
IronPython examples
|
I have heard IronPython for a long time, but never seen a real-life application using it.
Do you provide some examples to see its power?
Thanks.
|
[
"How did you miss Resolver Systems? Their Rsolver One spreadsheet application is IronPython.\n"
] |
[
4
] |
[] |
[] |
[
"ironpython",
"python"
] |
stackoverflow_0001887290_ironpython_python.txt
|
Q:
How to compare datetime in Django?
Suppose I have:
ds = datetime.datetime.now
dd = Entry.objects.get(pk=id).pub_date
How to compare 2 objects above? I want to get the time difference between them.
Please help me solve this problem. Thank you very much !
A:
I am assuming that pub_date is a django.db.models.DateField, which means you can treat it as a datetime.date object.
If you convert them to the same type (either datetime.datetime or datetime.date) and subtract one from the other, you will get an instance of datetime.timedelta.
As you are using datetime.datetime.now(), if your pub_date is simply a date rather than a datetime, you may as well use ds = datetime.date.today() instead:
>>> ds = datetime.date.today()
>>> dd = datetime.date(2009, 12, 9)
>>> ds - dd
datetime.timedelta(2) # 2 days ago
|
How to compare datetime in Django?
|
Suppose I have:
ds = datetime.datetime.now
dd = Entry.objects.get(pk=id).pub_date
How to compare 2 objects above? I want to get the time difference between them.
Please help me solve this problem. Thank you very much !
|
[
"I am assuming that pub_date is a django.db.models.DateField, which means you can treat it as a datetime.date object.\nIf you convert them to the same type (either datetime.datetime or datetime.date) and subtract one from the other, you will get an instance of datetime.timedelta.\nAs you are using datetime.datetime.now(), if your pub_date is simply a date rather than a datetime, you may as well use ds = datetime.date.today() instead:\n>>> ds = datetime.date.today()\n>>> dd = datetime.date(2009, 12, 9)\n>>> ds - dd\ndatetime.timedelta(2) # 2 days ago\n\n"
] |
[
19
] |
[] |
[] |
[
"datetime",
"django",
"django_views",
"python"
] |
stackoverflow_0001887354_datetime_django_django_views_python.txt
|
Q:
How to do a string replace in a urlencoded string
I have a string like x = "http://query.yahooapis.com/v1/public/yql?q=select%20owner%2Curls%20from%20flickr.photos.info%20where%20photo_id%3D'%s'&format=json"
If I do x % 10 that fails as there are %20f etc which are being treated as format strings, so I have to do a string conactination. How can I use normal string replacements here.?
A:
urldecode the string, do the formatting, and then urlencode it again:
import urllib
x = "http://query.yahooapis.com/v1/public/yql?q=select%20owner%2Curls%20from%20flickr.photos.info%20where%20photo_id%3D'%s'&format=json"
tmp = urllib.unquote(x)
tmp2 = tmp % (foo, bar)
x = urllib.quote(tmp2)
As one commenter noted, doing formatting using arbitrary user-inputted strings as the format specification is historically dangerous, and is certainly a bad idea.
A:
Otherwise you can use the new-style output formatting (available since v 2.6), which doesn't rely on %:
x = 'http://query.yahooapis.com/v1/public/yql?q=select%20owner%2Curls%20from%20flickr.photos.info%20where%20photo_id%3D{0}&format=json'
x.format(10)
It also has the advance of not being typedependent.
A:
In python string formatting, use %% to output a single % character (docs).
>>> "%d%%" % 50
'50%'
So you could replace all the % with %%, except where you want to substitute during formatting. But @Conrad Meyer's solution is obviously better in this case.
|
How to do a string replace in a urlencoded string
|
I have a string like x = "http://query.yahooapis.com/v1/public/yql?q=select%20owner%2Curls%20from%20flickr.photos.info%20where%20photo_id%3D'%s'&format=json"
If I do x % 10 that fails as there are %20f etc which are being treated as format strings, so I have to do a string conactination. How can I use normal string replacements here.?
|
[
"urldecode the string, do the formatting, and then urlencode it again:\nimport urllib\n\nx = \"http://query.yahooapis.com/v1/public/yql?q=select%20owner%2Curls%20from%20flickr.photos.info%20where%20photo_id%3D'%s'&format=json\"\ntmp = urllib.unquote(x)\ntmp2 = tmp % (foo, bar)\nx = urllib.quote(tmp2)\n\nAs one commenter noted, doing formatting using arbitrary user-inputted strings as the format specification is historically dangerous, and is certainly a bad idea.\n",
"Otherwise you can use the new-style output formatting (available since v 2.6), which doesn't rely on %:\nx = 'http://query.yahooapis.com/v1/public/yql?q=select%20owner%2Curls%20from%20flickr.photos.info%20where%20photo_id%3D{0}&format=json'\nx.format(10)\n\nIt also has the advance of not being typedependent.\n",
"In python string formatting, use %% to output a single % character (docs).\n>>> \"%d%%\" % 50\n'50%'\n\nSo you could replace all the % with %%, except where you want to substitute during formatting. But @Conrad Meyer's solution is obviously better in this case.\n"
] |
[
5,
0,
0
] |
[] |
[] |
[
"python",
"string"
] |
stackoverflow_0001886660_python_string.txt
|
Q:
Access to class attributes by using a variable in Python?
In PHP I can access class attributes like this:
<?php // very simple :)
class TestClass {}
$tc = new TestClass{};
$attribute = 'foo';
$tc->{$attribute} = 'bar';
echo $tc->foo
// should echo 'bar'
How can I do this in Python?
class TestClass()
tc = TestClass
attribute = 'foo'
# here comes the magic?
print tc.foo
# should echo 'bar'
A:
This question has been asked several times. You can use getattr to get the attribute by name:
print getattr(tc, 'foo')
This works for methods as well:
getattr(tc, 'methodname')(arg1, arg2)
To set an attribute by name use setattr
setattr(tc, 'foo', 'bar')
To check if an attribute exists use hasattr
hasattr(tc, 'foo')
A:
class TestClass(object)
pass
tc = TestClass()
setattr(tc, "foo", "bar")
print tc.foo
|
Access to class attributes by using a variable in Python?
|
In PHP I can access class attributes like this:
<?php // very simple :)
class TestClass {}
$tc = new TestClass{};
$attribute = 'foo';
$tc->{$attribute} = 'bar';
echo $tc->foo
// should echo 'bar'
How can I do this in Python?
class TestClass()
tc = TestClass
attribute = 'foo'
# here comes the magic?
print tc.foo
# should echo 'bar'
|
[
"This question has been asked several times. You can use getattr to get the attribute by name:\nprint getattr(tc, 'foo')\n\nThis works for methods as well:\ngetattr(tc, 'methodname')(arg1, arg2)\n\nTo set an attribute by name use setattr\nsetattr(tc, 'foo', 'bar')\n\nTo check if an attribute exists use hasattr\nhasattr(tc, 'foo')\n\n",
"class TestClass(object)\n pass\n\ntc = TestClass()\nsetattr(tc, \"foo\", \"bar\")\nprint tc.foo\n\n"
] |
[
3,
0
] |
[] |
[] |
[
"attributes",
"python"
] |
stackoverflow_0001887509_attributes_python.txt
|
Q:
How to convert string to hexadecimal integer in Python?
hi I get user argv from command line as follows: '0x000aff00'
and I want python to treat it as hex directly...
str = sys.argv[1]
how is it possible? thanks!
A:
Try: i = int(sys.argv[1], 16)
A:
try:
i = int(sys.argv[1], 16)
except Exception,e:
print e
else:
# carry on
|
How to convert string to hexadecimal integer in Python?
|
hi I get user argv from command line as follows: '0x000aff00'
and I want python to treat it as hex directly...
str = sys.argv[1]
how is it possible? thanks!
|
[
"Try: i = int(sys.argv[1], 16)\n",
"try:\n i = int(sys.argv[1], 16)\nexcept Exception,e:\n print e\nelse:\n # carry on\n\n"
] |
[
7,
0
] |
[] |
[] |
[
"hex",
"integer",
"python"
] |
stackoverflow_0001887392_hex_integer_python.txt
|
Q:
Python setuptools custom configuration
I'm packaging up a Python module, and I would like users to be able to build the module with some custom options. Specifically, the package will do some extra magic if you provide it with certain executables that it can use.
Ideally, users would run setup.py install or setup.py install --magic-doer=/path/to/executable. If they used the second option, I’d set a variable somewhere in the code, and go from there.
Is this possible with Python's setuptools? If so, how do I do it?
A:
It seems you can... read this.
Extract from article:
Commands are simple class that derives from setuptools.Command, and define some minimum elements, which are:
description: describe the command
user_options: a list of options
initialize_options(): called at startup
finalize_options(): called at the end
run(): called to run the command
The setuptools doc is still empty about subclassing Command, but a minimal class will look like this:
class MyCommand(Command):
"""setuptools Command"""
description = "run my command"
user_options = tuple()
def initialize_options(self):
"""init options"""
pass
def finalize_options(self):
"""finalize options"""
pass
def run(self):
"""runner"""
XXX DO THE JOB HERE
The class can then be hook as a command, using an entry point in its setup.py file:
setup(
# ...
entry_points = {
"distutils.commands": [
"my_command = mypackage.some_module:MyCommand"]}
|
Python setuptools custom configuration
|
I'm packaging up a Python module, and I would like users to be able to build the module with some custom options. Specifically, the package will do some extra magic if you provide it with certain executables that it can use.
Ideally, users would run setup.py install or setup.py install --magic-doer=/path/to/executable. If they used the second option, I’d set a variable somewhere in the code, and go from there.
Is this possible with Python's setuptools? If so, how do I do it?
|
[
"It seems you can... read this.\nExtract from article:\n\nCommands are simple class that derives from setuptools.Command, and define some minimum elements, which are:\n\ndescription: describe the command\nuser_options: a list of options\ninitialize_options(): called at startup\nfinalize_options(): called at the end\nrun(): called to run the command\n\n\nThe setuptools doc is still empty about subclassing Command, but a minimal class will look like this:\n\n class MyCommand(Command):\n \"\"\"setuptools Command\"\"\"\n description = \"run my command\"\n user_options = tuple()\n def initialize_options(self):\n \"\"\"init options\"\"\"\n pass\n\n def finalize_options(self):\n \"\"\"finalize options\"\"\"\n pass\n\n def run(self):\n \"\"\"runner\"\"\"\n XXX DO THE JOB HERE\n\n\nThe class can then be hook as a command, using an entry point in its setup.py file:\n\n setup(\n # ...\n entry_points = {\n \"distutils.commands\": [\n \"my_command = mypackage.some_module:MyCommand\"]}\n\n"
] |
[
6
] |
[] |
[] |
[
"python",
"setup.py"
] |
stackoverflow_0001887641_python_setup.py.txt
|
Q:
Convert Python byte to "unsigned 8 bit integer"
I am reading in a byte array/list from socket. I want Python to treat the first byte as an "unsigned 8 bit integer". How is it possible to get its integer value as an unsigned 8 bit integer?
A:
Use the struct module.
import struct
value = struct.unpack('B', data[0])[0]
Note that unpack always returns a tuple, even if you're only unpacking one item.
Also, have a look at this SO question.
A:
bytes/bytearray is a sequence of integers. If you just access an element by its index you'll have an integer:
>>> b'abc'
b'abc'
>>> _[0]
97
By their very definition, bytes and bytearrays contain integers in the range(0, 256). So they're "unsigned 8-bit integers".
A:
Another very reasonable and simple option, if you just need the first byte’s integer value, would be something like the following:
value = ord(data[0])
If you want to unpack all of the elements of your received data at once (and they’re not just a homogeneous array), or if you are dealing with multibyte objects like 32-bit integers, then you’ll need to use something like the struct module.
|
Convert Python byte to "unsigned 8 bit integer"
|
I am reading in a byte array/list from socket. I want Python to treat the first byte as an "unsigned 8 bit integer". How is it possible to get its integer value as an unsigned 8 bit integer?
|
[
"Use the struct module.\nimport struct\nvalue = struct.unpack('B', data[0])[0]\n\nNote that unpack always returns a tuple, even if you're only unpacking one item.\nAlso, have a look at this SO question.\n",
"bytes/bytearray is a sequence of integers. If you just access an element by its index you'll have an integer:\n>>> b'abc'\nb'abc'\n>>> _[0]\n97\n\nBy their very definition, bytes and bytearrays contain integers in the range(0, 256). So they're \"unsigned 8-bit integers\".\n",
"Another very reasonable and simple option, if you just need the first byte’s integer value, would be something like the following:\nvalue = ord(data[0])\n\nIf you want to unpack all of the elements of your received data at once (and they’re not just a homogeneous array), or if you are dealing with multibyte objects like 32-bit integers, then you’ll need to use something like the struct module.\n"
] |
[
23,
10,
7
] |
[] |
[] |
[
"python",
"python_3.x"
] |
stackoverflow_0001887506_python_python_3.x.txt
|
Q:
python string as hex terminated with null
I receive strings in their hex format, i.e. s = "0x0ff" or s = "0fd"
how can I check whether the above type of strings are null terminated or not? thanks!
A:
Try
s[-2:] == "00"
A:
Why would you care wether python strings are null terminated?
If you want to check wether the strings start by "0x" you can just use
x.startswith("0x")
as x cannot be located anywhere else in a hexstring.
|
python string as hex terminated with null
|
I receive strings in their hex format, i.e. s = "0x0ff" or s = "0fd"
how can I check whether the above type of strings are null terminated or not? thanks!
|
[
"Try\ns[-2:] == \"00\"\n\n",
"Why would you care wether python strings are null terminated?\nIf you want to check wether the strings start by \"0x\" you can just use\nx.startswith(\"0x\")\n\nas x cannot be located anywhere else in a hexstring.\n"
] |
[
1,
0
] |
[] |
[] |
[
"python",
"python_3.x"
] |
stackoverflow_0001887707_python_python_3.x.txt
|
Q:
How to redirect complete output of a cron script
I have a simple cronjob running every day at 18:35:
05 18 * * * ~/job.sh 2>&1 >> ~/job.log
So the output of ~/job.sh should be written into ~/job.log. In job.sh, there are some echo commands and a few python scripts are executed, e.g.:
echo 'doing xyz'
python doXYZ.py
Now, whatever output the python scripts produce, they are not written into ~/job.log. I only see the echo text in ~/job.log. How can I redirect the complete output of the shell script to ~/job.log?
A:
Arkaitz has the simplest solution. However, to see what's wrong with your snippet we need to go into the bash manual:
Note that the order of redirections is significant. For example, the
command
ls > dirlist 2>&1
directs both standard output and standard error to the file dirlist,
while the command
ls 2>&1 > dirlist
directs only the standard output to file dirlist, because the standard
error was duplicated from the standard output before the standard out‐
put was redirected to dirlist.
So apparently the output redirection only redirects to the target of the other stream, not to the other stream itself. When bash parses your command line it will come upon the 2>&1 clause and redirect stderr to the target of stdout, which at this point is still the console (or whatever is attached to cron's stdout). Only after this will stdout be redirected.
So what you really want is:
05 18 * * * ~/job.sh >>~/job.log 2>&1
A:
Have you tried ~/job.sh &>> ~/job.log ?
A:
You need to redirect the output of the python script. Learning Python 2nd Edition recommends the following:
import sys
sys.stdout = open('log.txt', 'a') # Redirects output to file
...
print x, y, x # shows up in log.txt
and goes on to say:
"Here, we reset sys.stdout to a maually-opened output file object opened in append mode. After the reset, every print statement anywhere in the program will write its text to the end of file log.txt. instead of the original output stream."
A:
I'm quite sure that this should work in a general case. The stdout file descriptor is changed by the OS when you use shell redirection.
However, if your Python script itself directly writes to the screen (perhaps by opening /dev/tty), it won't get captured in your log.txt. Is that the case? Does it fail even for a simple python program that just does a
print "Hello"
?
|
How to redirect complete output of a cron script
|
I have a simple cronjob running every day at 18:35:
05 18 * * * ~/job.sh 2>&1 >> ~/job.log
So the output of ~/job.sh should be written into ~/job.log. In job.sh, there are some echo commands and a few python scripts are executed, e.g.:
echo 'doing xyz'
python doXYZ.py
Now, whatever output the python scripts produce, they are not written into ~/job.log. I only see the echo text in ~/job.log. How can I redirect the complete output of the shell script to ~/job.log?
|
[
"Arkaitz has the simplest solution. However, to see what's wrong with your snippet we need to go into the bash manual:\n\nNote that the order of redirections is significant. For example, the\n command\n ls > dirlist 2>&1\n\ndirects both standard output and standard error to the file dirlist,\n while the command\n ls 2>&1 > dirlist\n\ndirects only the standard output to file dirlist, because the standard\n error was duplicated from the standard output before the standard out‐\n put was redirected to dirlist.\n\nSo apparently the output redirection only redirects to the target of the other stream, not to the other stream itself. When bash parses your command line it will come upon the 2>&1 clause and redirect stderr to the target of stdout, which at this point is still the console (or whatever is attached to cron's stdout). Only after this will stdout be redirected.\nSo what you really want is:\n05 18 * * * ~/job.sh >>~/job.log 2>&1\n\n",
"Have you tried ~/job.sh &>> ~/job.log ?\n",
"You need to redirect the output of the python script. Learning Python 2nd Edition recommends the following:\nimport sys\nsys.stdout = open('log.txt', 'a') # Redirects output to file\n...\nprint x, y, x # shows up in log.txt\n\nand goes on to say:\n\n\"Here, we reset sys.stdout to a maually-opened output file object opened in append mode. After the reset, every print statement anywhere in the program will write its text to the end of file log.txt. instead of the original output stream.\"\n\n",
"I'm quite sure that this should work in a general case. The stdout file descriptor is changed by the OS when you use shell redirection. \nHowever, if your Python script itself directly writes to the screen (perhaps by opening /dev/tty), it won't get captured in your log.txt. Is that the case? Does it fail even for a simple python program that just does a \nprint \"Hello\"\n\n?\n"
] |
[
17,
4,
2,
1
] |
[] |
[] |
[
"cron",
"python",
"shell"
] |
stackoverflow_0001887618_cron_python_shell.txt
|
Q:
Is this control structure a code smell?
This code seems to smell:
result = None
for item in list:
if result is None:
result = item.foo(args)
else:
if ClassFred.objects.get(arg1=result) < ClassFred.objects.get(arg1=item.foo(args)):
result = item.foo(args)
The smelliest part is the utility of 'result'. Would anyone be kind enough sniff it for me?
A:
L = list # 'list' is a poor variable name, use something else
result = min((n.foo(args) for n in L),
key=lambda x: ClassFred.objects.get(arg1=x))
# if you don't have to use arg1 as a named parameter:
result = min((n.foo(args) for n in L), key=ClassFred.objects.get)
The min function compares the given items and returns the minimum one (of course :P). What isn't obvious at first is you can control what value is used to compare them, this is the 'key' parameter.
>>> L = [-2, -1, 3]
>>> min(L)
-2
>>> min(L, key=abs)
-1
The key function computes the "comparison key", and that is what is used to compare. The default key function is identity, where the comparison key for an item is the item itself.
>>> def identity(x):
... return x
>>> min(L, key=identity)
-2
Another example:
>>> min("0000", "11", "222", "3")
"0000" # lexicographical minimum
>>> min("0000", "11", "222", "3", key=len)
"3"
Your code above is using item.foo(args) as values, where item comes from your list; but the result of passing that through ClassFred.objects.get(arg1=..) is used to compare. This means that construct is your key function:
values = (n.foo(args) for n in L) # this is a generator expression
# it is similar to a list comprehension, but doesn't compute or store
# everything immediately
def keyfunc(x):
return ClassFred.objects.get(arg1=x)
result = min(values, key=keyfunc)
My code at the top just puts this together in one statement.
A:
The logic is too complex. It's difficult to read what you are really doing.
Simplify that loop, you are doing too much in there.
This IMHO is already a pretty nasty smell.
A:
The second-to-last line is so long, I lost patience with it. I'd make those two separate variables with meaningful names, so we can figure out what if x < y is supposed to mean.
How about this:
if not list:
return None
def get_thing(bar):
# I don't know what this is, so... here:
return ClassFred.objects.get(arg1=bar.foo(args))
# way less hassle than that if-else stuff
biggest = get_thing(list[0])
for item in list:
current = get_thing(item)
if biggest < current:
biggest = current
A:
So, I agree it seems like it could be refactored from a readability standpoint, but it should work. This would be my take on it:
# using lst instead of list & at least python 2.5
result = lst[0].foo(args) if lst else None
fxn = ClassFred.objects.get
for item in lst[1:]:
if fxn(arg1=result) > fxn(arg1=item.foo(args)):
result = item.foo(args)
A:
This may work, though, I don't think it'll smell better :p
max([ClassFred.objects.get(arg1=item.foo(args)), item.foo(args) for item in list])[1]
|
Is this control structure a code smell?
|
This code seems to smell:
result = None
for item in list:
if result is None:
result = item.foo(args)
else:
if ClassFred.objects.get(arg1=result) < ClassFred.objects.get(arg1=item.foo(args)):
result = item.foo(args)
The smelliest part is the utility of 'result'. Would anyone be kind enough sniff it for me?
|
[
"L = list # 'list' is a poor variable name, use something else\nresult = min((n.foo(args) for n in L),\n key=lambda x: ClassFred.objects.get(arg1=x))\n# if you don't have to use arg1 as a named parameter:\nresult = min((n.foo(args) for n in L), key=ClassFred.objects.get)\n\nThe min function compares the given items and returns the minimum one (of course :P). What isn't obvious at first is you can control what value is used to compare them, this is the 'key' parameter.\n>>> L = [-2, -1, 3]\n>>> min(L)\n-2\n>>> min(L, key=abs)\n-1\n\nThe key function computes the \"comparison key\", and that is what is used to compare. The default key function is identity, where the comparison key for an item is the item itself.\n>>> def identity(x):\n... return x\n>>> min(L, key=identity)\n-2\n\nAnother example:\n>>> min(\"0000\", \"11\", \"222\", \"3\")\n\"0000\" # lexicographical minimum\n>>> min(\"0000\", \"11\", \"222\", \"3\", key=len)\n\"3\"\n\nYour code above is using item.foo(args) as values, where item comes from your list; but the result of passing that through ClassFred.objects.get(arg1=..) is used to compare. This means that construct is your key function:\nvalues = (n.foo(args) for n in L) # this is a generator expression\n# it is similar to a list comprehension, but doesn't compute or store\n# everything immediately\n\ndef keyfunc(x):\n return ClassFred.objects.get(arg1=x)\n\nresult = min(values, key=keyfunc)\n\nMy code at the top just puts this together in one statement.\n",
"The logic is too complex. It's difficult to read what you are really doing.\nSimplify that loop, you are doing too much in there.\nThis IMHO is already a pretty nasty smell.\n",
"The second-to-last line is so long, I lost patience with it. I'd make those two separate variables with meaningful names, so we can figure out what if x < y is supposed to mean.\nHow about this:\nif not list:\n return None\n\ndef get_thing(bar):\n # I don't know what this is, so... here:\n return ClassFred.objects.get(arg1=bar.foo(args))\n\n# way less hassle than that if-else stuff\nbiggest = get_thing(list[0])\nfor item in list:\n current = get_thing(item)\n if biggest < current:\n biggest = current\n\n",
"So, I agree it seems like it could be refactored from a readability standpoint, but it should work. This would be my take on it:\n# using lst instead of list & at least python 2.5\nresult = lst[0].foo(args) if lst else None\nfxn = ClassFred.objects.get\n\nfor item in lst[1:]:\n if fxn(arg1=result) > fxn(arg1=item.foo(args)):\n result = item.foo(args)\n\n",
"This may work, though, I don't think it'll smell better :p\nmax([ClassFred.objects.get(arg1=item.foo(args)), item.foo(args) for item in list])[1]\n\n"
] |
[
3,
1,
1,
1,
0
] |
[] |
[] |
[
"controls",
"python",
"structure"
] |
stackoverflow_0001886002_controls_python_structure.txt
|
Q:
Python hexadecimal comparison
I got a problem I was hoping someone could help me figure out!
I have a string with a hexadecimal number = '0x00000000' which means:
0x01000000 = apple
0x00010000 = orange
0x00000100 = banana
All combinations with those are possible. i.e., 0x01010000 = apple & orange
How can I from my string determine what fruit it is? I made a dictionary with all the combinations and then comparing to that, and it works! But I am wondering about a nicer way of doing it.
A:
Convert your string to an integer, by using the int() built-in function and specifying a base:
>>> int('0x01010000',16)
16842752
Now, you have a standard integer representing a bitset. use &, | and any other bitwise operator to test individual bits.
>>> value = int('0x01010000',16)
>>> apple = 0x01000000
>>> orange = 0x00010000
>>> banana = 0x00000100
>>> bool(value & apple) # tests if apple is part of the value
True
>>> value |= banana # adds the banana flag to the value
>>> value &= ~orange # removes the orange flag from the value
Now, if you need to convert back to your string:
>>> hex(value)
'0x1000100'
A:
You could first of all convert your string to an integer:
s = "0x01010000"
i = int(s, 16) #i = 269484032
then, you could set up a list for the fruits:
fruits = [(0x01000000, "apple"), (0x00010000, "orange"), (0x00000100, "banana")]
for determing what fruits you have that is enough:
s = "0x01010000"
i = int(s, 16)
for fid,fname in fruits:
if i&fid>0:
print "The fruit '%s' is contained in '%s'" % (fname, s)
The output here is:
The fruit 'apple' is contained in '0x01010000'
The fruit 'orange' is contained in '0x01010000'
A:
def WhichFruit(n):
if n & int('0x01000000',16):
print 'apple'
if n & int('0x00010000',16):
print 'orange'
if n & int('0x00000100',16):
print 'banana'
WhichFruit(int('0x01010000',16))
|
Python hexadecimal comparison
|
I got a problem I was hoping someone could help me figure out!
I have a string with a hexadecimal number = '0x00000000' which means:
0x01000000 = apple
0x00010000 = orange
0x00000100 = banana
All combinations with those are possible. i.e., 0x01010000 = apple & orange
How can I from my string determine what fruit it is? I made a dictionary with all the combinations and then comparing to that, and it works! But I am wondering about a nicer way of doing it.
|
[
"Convert your string to an integer, by using the int() built-in function and specifying a base:\n>>> int('0x01010000',16)\n16842752\n\nNow, you have a standard integer representing a bitset. use &, | and any other bitwise operator to test individual bits.\n>>> value = int('0x01010000',16)\n>>> apple = 0x01000000\n>>> orange = 0x00010000\n>>> banana = 0x00000100\n>>> bool(value & apple) # tests if apple is part of the value\nTrue\n>>> value |= banana # adds the banana flag to the value\n>>> value &= ~orange # removes the orange flag from the value\n\nNow, if you need to convert back to your string:\n>>> hex(value)\n'0x1000100'\n\n",
"You could first of all convert your string to an integer:\ns = \"0x01010000\"\ni = int(s, 16) #i = 269484032\n\nthen, you could set up a list for the fruits:\nfruits = [(0x01000000, \"apple\"), (0x00010000, \"orange\"), (0x00000100, \"banana\")]\n\nfor determing what fruits you have that is enough:\ns = \"0x01010000\"\ni = int(s, 16)\nfor fid,fname in fruits:\n if i&fid>0:\n print \"The fruit '%s' is contained in '%s'\" % (fname, s)\n\nThe output here is:\nThe fruit 'apple' is contained in '0x01010000'\nThe fruit 'orange' is contained in '0x01010000'\n\n",
"def WhichFruit(n):\n if n & int('0x01000000',16):\n print 'apple'\n if n & int('0x00010000',16):\n print 'orange'\n if n & int('0x00000100',16):\n print 'banana'\n\nWhichFruit(int('0x01010000',16))\n\n"
] |
[
21,
2,
0
] |
[] |
[] |
[
"hex",
"python"
] |
stackoverflow_0001888114_hex_python.txt
|
Q:
How to join lists element-wise in Python?
l1 = [4, 6, 8]
l2 = [a, b, c]
result = [(4,a),(6,b),(8,c)]
How do I do that?
A:
The zip standard function does this for you:
>>> l1 = [4, 6, 8]
>>> l2 = ["a", "b", "c"]
>>> zip(l1, l2)
[(4, 'a'), (6, 'b'), (8, 'c')]
If you're using Python 3.x, then zip returns a generator and you can convert it to a list using the list() constructor:
>>> list(zip(l1, l2))
[(4, 'a'), (6, 'b'), (8, 'c')]
A:
Use zip.
l1 = [1, 2, 3]
l2 = [4, 5, 6]
>>> zip(l1, l2)
[(1, 4), (2, 5), (3, 6)]
Note that if your lists are of different lengths, the result will be truncated to the length of the shortest input.
>>> print zip([1, 2, 3],[4, 5, 6, 7])
[(1, 4), (2, 5), (3, 6)]
You can also use zip with more than two lists:
>>> zip([1, 2, 3], [4, 5, 6], [7, 8, 9])
[(1, 4, 7), (2, 5, 8), (3, 6, 9)]
If you have a list of lists, you can call zip using an asterisk:
>>> l = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
>>> zip(*l)
[(1, 4, 7), (2, 5, 8), (3, 6, 9)]
A:
>>> l1 = [4, 6, 8]; l2 = ['a', 'b', 'c']
>>> zip(l1, l2)
[(4, 'a'), (6, 'b'), (8, 'c')]
A:
If the lists are the same length, or if you want the length of the list to be the length of the shorter list, then use zip, as other people have pointed out.
If the lists are different lengths, then you can use map with a transformation function of None:
>>> l1 = [1, 2, 3, 4, 5]
>>> l2 = [9, 8, 7]
>>> map(None, l1, l2)
[(1, 9), (2, 8), (3, 7), (4, None), (5, None)]
Note that the 'extra' values get paired with None.
It's also worth noting that both zip and map can be used with any number of iterables:
>>> zip('abc', 'def', 'ghi')
[('a', 'd', 'g'), ('b', 'e', 'h'), ('c', 'f', 'i')]
>>> map(None, 'abc', 'def', 'gh')
[('a', 'd', 'g'), ('b', 'e', 'h'), ('c', 'f', None)]
|
How to join lists element-wise in Python?
|
l1 = [4, 6, 8]
l2 = [a, b, c]
result = [(4,a),(6,b),(8,c)]
How do I do that?
|
[
"The zip standard function does this for you:\n>>> l1 = [4, 6, 8]\n>>> l2 = [\"a\", \"b\", \"c\"]\n>>> zip(l1, l2)\n[(4, 'a'), (6, 'b'), (8, 'c')]\n\nIf you're using Python 3.x, then zip returns a generator and you can convert it to a list using the list() constructor:\n>>> list(zip(l1, l2))\n[(4, 'a'), (6, 'b'), (8, 'c')]\n\n",
"Use zip.\nl1 = [1, 2, 3]\nl2 = [4, 5, 6]\n>>> zip(l1, l2)\n[(1, 4), (2, 5), (3, 6)]\n\nNote that if your lists are of different lengths, the result will be truncated to the length of the shortest input.\n>>> print zip([1, 2, 3],[4, 5, 6, 7])\n[(1, 4), (2, 5), (3, 6)]\n\nYou can also use zip with more than two lists:\n>>> zip([1, 2, 3], [4, 5, 6], [7, 8, 9])\n[(1, 4, 7), (2, 5, 8), (3, 6, 9)]\n\nIf you have a list of lists, you can call zip using an asterisk:\n>>> l = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]\n>>> zip(*l)\n[(1, 4, 7), (2, 5, 8), (3, 6, 9)]\n\n",
">>> l1 = [4, 6, 8]; l2 = ['a', 'b', 'c']\n>>> zip(l1, l2)\n[(4, 'a'), (6, 'b'), (8, 'c')]\n\n",
"If the lists are the same length, or if you want the length of the list to be the length of the shorter list, then use zip, as other people have pointed out.\nIf the lists are different lengths, then you can use map with a transformation function of None:\n>>> l1 = [1, 2, 3, 4, 5]\n>>> l2 = [9, 8, 7]\n>>> map(None, l1, l2)\n[(1, 9), (2, 8), (3, 7), (4, None), (5, None)]\n\nNote that the 'extra' values get paired with None.\nIt's also worth noting that both zip and map can be used with any number of iterables:\n>>> zip('abc', 'def', 'ghi')\n[('a', 'd', 'g'), ('b', 'e', 'h'), ('c', 'f', 'i')]\n>>> map(None, 'abc', 'def', 'gh')\n[('a', 'd', 'g'), ('b', 'e', 'h'), ('c', 'f', None)]\n\n"
] |
[
12,
11,
1,
0
] |
[] |
[] |
[
"list",
"python"
] |
stackoverflow_0001885300_list_python.txt
|
Q:
give an active to class to active link
I am writing a python website built on the back of the django framework, I am looking for a way to highlight the current link the user is on depening on what the URL, I thought doing some thing like this would work.
What I have done is create a new application called nav and built some templatetags, like so,
from django import template
register = template.Library()
URL_PATTERNS = {
'home': (r'^/$',),
}
@register.tag
def nav_selection(parser, token):
try:
tag_name, nav_item = token.split_contents()
except ValueError:
raise template.TemplateSyntaxError, "%r tag requires a single argument" % token.contents.split()[0]
if not (nav_item[0] == nav_item[-1] and nav_item[0] in ('"', "'")):
raise template.TemplateSyntaxError, "%r tag's argument should be in quotes" % tag_name
return NavSelectionNode(nav_item[1:-1])
class NavSelectionNode(template.Node):
def __init__(self, nav_item):
self.nav_item = nav_item
def render(self, context):
if not 'request' in context:
return ""
import re
try:
regs = URL_PATTERNS[self.nav_item]
except KeyError:
return ''
for reg in regs:
if re.match(reg, context['request'].get_full_path()):
return "active"
return ''
In my template I do this
<ul id="navigation">{% load nav %}
<li><a href="{% url views.home %}" class='{% nav_selection "home" %}'>home</a></li>
<li><a href="{% url views.about %}" class='{% nav_selection "about" %}'>about neal & wolf</a></li>
<li><a href="{% url shop.views.home %}" class='{% nav_selection "shop" %}'>our products</a></li>
<li><a href="{% url shop.views.home %}" class='{% nav_selection "shop" %}'>shop</a></li>
<li><a href="{% url views.look %}" class='{% nav_selection "look" %}'>get the look</a></li>
<li><a href="{% url news.views.index %}" class='{% nav_selection "news" %}'>news</a></li>
<li><a href="{% url contact.views.contact %}" class='{% nav_selection "contact" %}'>contact us</a></li>
<li><a href="{% url store_locator.views.index %}" class='{% nav_selection "finder" %}'>salon finder</a></li>
<li><a href="{% url professional.views.index %}" class='{% nav_selection "contact" %}'>neal & wolf professional</a></li>
</ul>
yet the markup I get out in firebug is this in this example I am browsing the index page
<a class="" href="/home/">
So something is obviously failing but I cannot see where, can anyone help me please?
A:
Some things to check:
Is the request object actually in your context? Are you passing it in specifically, or are you using a RequestContext?
Why are you defining regexes in your templatetags, rather than using the built-in reverse function to look them up in the urlconf?
Do the regexes here actually match the ones in the urlconf?
Have you included your home urlconf under the 'home' url somehow?
|
give an active to class to active link
|
I am writing a python website built on the back of the django framework, I am looking for a way to highlight the current link the user is on depening on what the URL, I thought doing some thing like this would work.
What I have done is create a new application called nav and built some templatetags, like so,
from django import template
register = template.Library()
URL_PATTERNS = {
'home': (r'^/$',),
}
@register.tag
def nav_selection(parser, token):
try:
tag_name, nav_item = token.split_contents()
except ValueError:
raise template.TemplateSyntaxError, "%r tag requires a single argument" % token.contents.split()[0]
if not (nav_item[0] == nav_item[-1] and nav_item[0] in ('"', "'")):
raise template.TemplateSyntaxError, "%r tag's argument should be in quotes" % tag_name
return NavSelectionNode(nav_item[1:-1])
class NavSelectionNode(template.Node):
def __init__(self, nav_item):
self.nav_item = nav_item
def render(self, context):
if not 'request' in context:
return ""
import re
try:
regs = URL_PATTERNS[self.nav_item]
except KeyError:
return ''
for reg in regs:
if re.match(reg, context['request'].get_full_path()):
return "active"
return ''
In my template I do this
<ul id="navigation">{% load nav %}
<li><a href="{% url views.home %}" class='{% nav_selection "home" %}'>home</a></li>
<li><a href="{% url views.about %}" class='{% nav_selection "about" %}'>about neal & wolf</a></li>
<li><a href="{% url shop.views.home %}" class='{% nav_selection "shop" %}'>our products</a></li>
<li><a href="{% url shop.views.home %}" class='{% nav_selection "shop" %}'>shop</a></li>
<li><a href="{% url views.look %}" class='{% nav_selection "look" %}'>get the look</a></li>
<li><a href="{% url news.views.index %}" class='{% nav_selection "news" %}'>news</a></li>
<li><a href="{% url contact.views.contact %}" class='{% nav_selection "contact" %}'>contact us</a></li>
<li><a href="{% url store_locator.views.index %}" class='{% nav_selection "finder" %}'>salon finder</a></li>
<li><a href="{% url professional.views.index %}" class='{% nav_selection "contact" %}'>neal & wolf professional</a></li>
</ul>
yet the markup I get out in firebug is this in this example I am browsing the index page
<a class="" href="/home/">
So something is obviously failing but I cannot see where, can anyone help me please?
|
[
"Some things to check:\nIs the request object actually in your context? Are you passing it in specifically, or are you using a RequestContext?\nWhy are you defining regexes in your templatetags, rather than using the built-in reverse function to look them up in the urlconf? \nDo the regexes here actually match the ones in the urlconf?\nHave you included your home urlconf under the 'home' url somehow?\n"
] |
[
0
] |
[] |
[] |
[
"django",
"django_templates",
"python",
"templatetags"
] |
stackoverflow_0001888519_django_django_templates_python_templatetags.txt
|
Q:
Integration Testing for a Web App
I want to do full integration testing for a web application. I want to test many things like AJAX, positioning and presence of certain phrases and HTML elements using several browsers. I'm seeking a tool to do such automated testing.
On the other hand; this is my first time using integration testing. Are there any specific recommendations when doing such testing? Any tutorial as well?
(As a note: My backend code is done using Perl, Python and Django.)
Thanks!
A:
If you need to do full testing including exploiting browser features like AJAX then I would recomend Selenium. Selenium launches a browser and controls it to run the tests.
It supports all the major platforms and browsers. Selenium itself is implemented in Java but that is not really an issue if it is being used to test a web application through its user interface.
Selenium tests are a sequence of commands in an HTML table, the supported commands are in well documented. There is also an IDE implemented as a Firefox plugin that can be used to record and run tests. However the test scripts created in the IDE can be used to drive tests against any of the supported browsers.
A:
Selenium is a good way to go. For using it with Perl then use the Test::WWW::Selenium CPAN module.
Here is one example from its pod:
use WWW::Selenium;
my $sel = WWW::Selenium->new( host => "localhost",
port => 4444,
browser => "*iexplore",
browser_url => "http://www.google.com",
);
$sel->start;
$sel->open("http://www.google.com");
$sel->type("q", "hello world");
$sel->click("btnG");
$sel->wait_for_page_to_load(5000);
print $sel->get_title;
$sel->stop;
And here are some additional links which maybe helpful:
Selenium + Perl wiki
Automating browser activities using Selenium
Using WWW::Selenium To Test Or Automate An Ajax Website
/I3az/
A:
In this article, Noah Gift does a good job presenting three main alternatives for web app integration testing: Windmill, Selenium and Twill. Twill doesn't do Javascript, so that leaves Selenium and Windmill as your main possibilities; Gifts shows enough about what using each of them means, so you can choose.
One thing Gift doesn't mention is that Selenium is much more popular -- that's not obvious if you just web search each of the terms windmill and selenium, but that's because each gets (different numbers of;-) false hits. [windmill javascript] gives 325k hits, [selenium javascript] gives 1.2M hits, and this ratio is more representative. Anyway, the point is that, if you find them both equally easy and powerful enough for your needs, so that you have a hard time choosing one, then picking selenium (i.e., going with the crowd) may have advantages (more experts around, e.g. on SO to answer questions;-) wrt picking the somewhat less popular alternative.
A:
You can also control selenium using Selenium-RC's python binding. For example:
from selenium import selenium
selenium = selenium("localhost", 4444, "*firefox",
"http://www.google.com/")
selenium.start()
selenium.open("/") # open google.com
selenium.type("q", "selenium rc")
selenium.click("btnG")
selenium.wait_for_page_to_load("30000")
selenium.failUnless(selenium.is_text_present("Results * for selenium rc"))
selenium.stop()
A:
Selenium is a very good tool to automate browser testing
Since you mentioned Ruby in your tags, I also recommend Webrat which is a nice in-browser testing solution in Ruby.
A:
Here's another option, all written in Python and cross browsers for running AND recording tests: Windmill
A:
I would also recommend Selenium. It got a really nice Firefox Plugin, that you can use to create your integration tests.
A:
TestPlan is a great tool for general purpose web testing. It provides both a display-less backend and Selenium. The Selenium backend should take care of testing in all the popular browsers. It also has its own scripting language which makes it quick to write and test, though Java can also be used.
For example, this goes to a page and submits a search form and checks that it found the correct result.
GotoURL http://myapp.com/
SubmitForm with
%Params:search% some term
end
Check //div[@id='results'][contains(text(),'some term']
A:
Another great tool for browser testing which is built as Ruby library and uses Ruby for scripting is Watir. There is also a firefox plugin for watir just like selenium called
Firewatir hosted on google code
|
Integration Testing for a Web App
|
I want to do full integration testing for a web application. I want to test many things like AJAX, positioning and presence of certain phrases and HTML elements using several browsers. I'm seeking a tool to do such automated testing.
On the other hand; this is my first time using integration testing. Are there any specific recommendations when doing such testing? Any tutorial as well?
(As a note: My backend code is done using Perl, Python and Django.)
Thanks!
|
[
"If you need to do full testing including exploiting browser features like AJAX then I would recomend Selenium. Selenium launches a browser and controls it to run the tests.\nIt supports all the major platforms and browsers. Selenium itself is implemented in Java but that is not really an issue if it is being used to test a web application through its user interface.\nSelenium tests are a sequence of commands in an HTML table, the supported commands are in well documented. There is also an IDE implemented as a Firefox plugin that can be used to record and run tests. However the test scripts created in the IDE can be used to drive tests against any of the supported browsers.\n",
"Selenium is a good way to go. For using it with Perl then use the Test::WWW::Selenium CPAN module.\nHere is one example from its pod:\nuse WWW::Selenium;\n\nmy $sel = WWW::Selenium->new( host => \"localhost\", \n port => 4444, \n browser => \"*iexplore\", \n browser_url => \"http://www.google.com\",\n );\n\n$sel->start;\n$sel->open(\"http://www.google.com\");\n$sel->type(\"q\", \"hello world\");\n$sel->click(\"btnG\");\n$sel->wait_for_page_to_load(5000);\nprint $sel->get_title;\n$sel->stop;\n\nAnd here are some additional links which maybe helpful:\n\nSelenium + Perl wiki\nAutomating browser activities using Selenium\nUsing WWW::Selenium To Test Or Automate An Ajax Website\n\n/I3az/\n",
"In this article, Noah Gift does a good job presenting three main alternatives for web app integration testing: Windmill, Selenium and Twill. Twill doesn't do Javascript, so that leaves Selenium and Windmill as your main possibilities; Gifts shows enough about what using each of them means, so you can choose.\nOne thing Gift doesn't mention is that Selenium is much more popular -- that's not obvious if you just web search each of the terms windmill and selenium, but that's because each gets (different numbers of;-) false hits. [windmill javascript] gives 325k hits, [selenium javascript] gives 1.2M hits, and this ratio is more representative. Anyway, the point is that, if you find them both equally easy and powerful enough for your needs, so that you have a hard time choosing one, then picking selenium (i.e., going with the crowd) may have advantages (more experts around, e.g. on SO to answer questions;-) wrt picking the somewhat less popular alternative.\n",
"You can also control selenium using Selenium-RC's python binding. For example:\nfrom selenium import selenium\nselenium = selenium(\"localhost\", 4444, \"*firefox\",\n \"http://www.google.com/\")\nselenium.start()\nselenium.open(\"/\") # open google.com\nselenium.type(\"q\", \"selenium rc\")\nselenium.click(\"btnG\")\nselenium.wait_for_page_to_load(\"30000\")\nselenium.failUnless(selenium.is_text_present(\"Results * for selenium rc\"))\nselenium.stop()\n\n",
"Selenium is a very good tool to automate browser testing\nSince you mentioned Ruby in your tags, I also recommend Webrat which is a nice in-browser testing solution in Ruby.\n",
"Here's another option, all written in Python and cross browsers for running AND recording tests: Windmill\n",
"I would also recommend Selenium. It got a really nice Firefox Plugin, that you can use to create your integration tests.\n",
"TestPlan is a great tool for general purpose web testing. It provides both a display-less backend and Selenium. The Selenium backend should take care of testing in all the popular browsers. It also has its own scripting language which makes it quick to write and test, though Java can also be used.\nFor example, this goes to a page and submits a search form and checks that it found the correct result.\nGotoURL http://myapp.com/\n\nSubmitForm with\n %Params:search% some term\nend\n\nCheck //div[@id='results'][contains(text(),'some term']\n\n",
"Another great tool for browser testing which is built as Ruby library and uses Ruby for scripting is Watir. There is also a firefox plugin for watir just like selenium called\nFirewatir hosted on google code\n"
] |
[
12,
12,
6,
4,
2,
2,
1,
1,
0
] |
[] |
[] |
[
"automated_tests",
"integration_testing",
"perl",
"python",
"ruby"
] |
stackoverflow_0001747772_automated_tests_integration_testing_perl_python_ruby.txt
|
Q:
Simplifying small code example
Lets pretend I have the following code.
num1 = 33
num2 = 45
num3 = 76
lst = ['one', 'two', 'three']
for item in lst:
if item == 'one':
print num1
elif item == 'two':
print num2
elif item == 'three':
print num3
Is there a way to make this more elegant when there is no correlation between the list and the print sentence? Meaning, is there a way to get rid of the ifs and elifs?
A:
You can of course use a dictionary, to look up the response:
lst = ['one', 'two', 'three']
resp = { 'one': num1, 'two': num2, 'three': num3 }
for item in lst:
print resp[item]
This is still pretty static, though. Another approach would be object-orienting it, so you get to implement a function in the objects in lst that makes the decision.
A:
>>> tups = ('one', 33), ('two', 45), ('three', 76)
>>> for i, j in tups:
print(j)
33
45
76
A:
Is it intentional that your code ignores objects that are not mentioned in any if/elif clause? If so, use a dictionary with a default value of 'None' if the object is not found:
lst = ['one', 'two', 'three']
d = { 'one': 33, 'two': 45, 'three': 76}
for item in lst:
x = d.get(item)
if x is not None:
print x
A:
the whole logic of your if/else is equivalent to a dictionary's key and value pairs
d = {"one":33, "two":44, "three":76}
this part of your code
if item == 'one':
print num1
is the same as
print d["one"]
like wise for the others
A:
If you have dictionary like this:
d = {"one":33, "two":44, "three":76}
You can print it like this:
for k in d.keys():
print d[k]
This presumes that you do not care about the order.
A:
For your simple example a dictinary lookup poposed in other answers is the best. But sometimes you need to run completely different code for each condition, so the following idiom might be useful too:
class MyClass(object):
def process(self, item):
# Select the method to call based on item value
return getattr(self, 'do_'+item)()
def do_one(self):
# do something here
def do_two(self):
# do something other here
# ... other methods ...
A:
When there's no correlation between the if clause and the prints, you can create a mapping dictionary to store the correlations. You need to be careful to map to the variable of numx, not the current value (thus the use of the eval function):
num1 = 33
num2 = 45
num3 = 76
lst = ['one', 'two', 'three']
map = {'one': 'num1', 'two': 'num2', 'three': 'num3'}
for item in lst:
print item in map and eval(map[item]) or 'Unknown'
If you're sure the item is in the map, the last line can be simplified further to:
print eval(map[item])
|
Simplifying small code example
|
Lets pretend I have the following code.
num1 = 33
num2 = 45
num3 = 76
lst = ['one', 'two', 'three']
for item in lst:
if item == 'one':
print num1
elif item == 'two':
print num2
elif item == 'three':
print num3
Is there a way to make this more elegant when there is no correlation between the list and the print sentence? Meaning, is there a way to get rid of the ifs and elifs?
|
[
"You can of course use a dictionary, to look up the response:\nlst = ['one', 'two', 'three']\nresp = { 'one': num1, 'two': num2, 'three': num3 }\n\nfor item in lst:\n print resp[item]\n\nThis is still pretty static, though. Another approach would be object-orienting it, so you get to implement a function in the objects in lst that makes the decision.\n",
">>> tups = ('one', 33), ('two', 45), ('three', 76)\n>>> for i, j in tups:\n print(j)\n\n\n33\n45\n76\n\n",
"Is it intentional that your code ignores objects that are not mentioned in any if/elif clause? If so, use a dictionary with a default value of 'None' if the object is not found:\nlst = ['one', 'two', 'three'] \nd = { 'one': 33, 'two': 45, 'three': 76}\n\nfor item in lst: \n x = d.get(item)\n if x is not None:\n print x\n\n",
"the whole logic of your if/else is equivalent to a dictionary's key and value pairs\nd = {\"one\":33, \"two\":44, \"three\":76}\n\nthis part of your code\nif item == 'one':\n print num1\n\nis the same as \nprint d[\"one\"]\n\nlike wise for the others\n",
"If you have dictionary like this:\nd = {\"one\":33, \"two\":44, \"three\":76}\n\nYou can print it like this:\nfor k in d.keys():\n print d[k]\n\nThis presumes that you do not care about the order.\n",
"For your simple example a dictinary lookup poposed in other answers is the best. But sometimes you need to run completely different code for each condition, so the following idiom might be useful too:\nclass MyClass(object):\n\n def process(self, item):\n # Select the method to call based on item value\n return getattr(self, 'do_'+item)()\n\n def do_one(self):\n # do something here\n\n def do_two(self):\n # do something other here\n\n # ... other methods ...\n\n",
"When there's no correlation between the if clause and the prints, you can create a mapping dictionary to store the correlations. You need to be careful to map to the variable of numx, not the current value (thus the use of the eval function):\nnum1 = 33\nnum2 = 45\nnum3 = 76\nlst = ['one', 'two', 'three']\n\nmap = {'one': 'num1', 'two': 'num2', 'three': 'num3'} \n\nfor item in lst:\n print item in map and eval(map[item]) or 'Unknown'\n\nIf you're sure the item is in the map, the last line can be simplified further to:\n print eval(map[item])\n\n"
] |
[
5,
5,
4,
2,
1,
1,
1
] |
[] |
[] |
[
"python"
] |
stackoverflow_0001887690_python.txt
|
Q:
Python twisted: where to start
I am trying to start learning twisted for socket servers creation. I want to add some useful features (like auth, and maybe some other). Maybe someone can point me to a good tutorial which will help me to start (+ maybe some other ideas)
A:
Look here: Twisted Web in 60 seconds. That's a group of blog posts describing step by step how to do lots of common stuff with Twisted, all written by Jean-Paul Calderone, the biggest contributor of Twisted. It's really where you should start.
After that, look at the Twisted core documentation then refer to the API and then into the source code.
Have fun!
A:
There's a great tutorial here - it's usually the one I send to new Twisty's :-)
http://krondo.com/blog/?page_id=1327
Its worth remembering that Twisted programming is more of a thinking paradigm than a programming one. Also, it's worth doing away with the client server model too - in Twisted there's just one broker talking in either direction to another.
Take a look here after the above too:
http://twistedmatrix.com/documents/current/core/howto/pb-intro.html
Enjoy :-)
|
Python twisted: where to start
|
I am trying to start learning twisted for socket servers creation. I want to add some useful features (like auth, and maybe some other). Maybe someone can point me to a good tutorial which will help me to start (+ maybe some other ideas)
|
[
"Look here: Twisted Web in 60 seconds. That's a group of blog posts describing step by step how to do lots of common stuff with Twisted, all written by Jean-Paul Calderone, the biggest contributor of Twisted. It's really where you should start.\nAfter that, look at the Twisted core documentation then refer to the API and then into the source code.\nHave fun! \n",
"There's a great tutorial here - it's usually the one I send to new Twisty's :-)\nhttp://krondo.com/blog/?page_id=1327\nIts worth remembering that Twisted programming is more of a thinking paradigm than a programming one. Also, it's worth doing away with the client server model too - in Twisted there's just one broker talking in either direction to another.\nTake a look here after the above too:\nhttp://twistedmatrix.com/documents/current/core/howto/pb-intro.html\nEnjoy :-)\n"
] |
[
73,
70
] |
[] |
[] |
[
"python",
"twisted"
] |
stackoverflow_0001888139_python_twisted.txt
|
Q:
Am I supposed to use PyQT4 for programming cross-platform software in Python?
So a user suggested getting PyQT.
A quick Google gave me this: Link
Is this GUI Library for pay?
If my development environment is Ubuntu Linux, what should I download on that site. I have no idea.
Please provide links if the site I provided is not correct to what I need. Thank you.
A:
You may want to look at PySide which is sponsored by Nokia, who own QT. It's also LGPL, which is a bit better of a license than the PyQT bindings. It's also a bit more pythonic in how it works. Unfortunately, it's new, so there isn't as much documentation. On their download page you can find information about a PPA for Ubuntu which will make it so your bindings automatically stay up to date.
If you want to run PyQT then just use APT and install python-qt3 or python-qt4.
A:
I will answer the question you have stated in title
"Am I supposed to use PyQT4 for programming cross-platform software in Python?"
No.
You can use wxPython (http://www.wxpython.org/), it is a quite decent GUI toolkit base on wxWdigets and many commercial applications are written in wxPython e.g. www.mockupscreens.com
wxpython works on Mac/linux/Windows, has a very good support for custom widgets and provides a native looks on each platform, though you are free to design you own widgets/skins.
PyQT is comparable or may be in some cases better but costly for non GPL applications(http://qt.nokia.com/products/licensing), but wxPython is free as free beer (http://en.wikipedia.org/wiki/WxPython#License).
A:
PyQT is released under multiple licenses: http://www.riverbankcomputing.co.uk/software/pyqt/license
You only need to pay if you don't want to release your product under the GPL.
PyQT isn't the only option for cross platform GUI in Python. There are many others too: http://wiki.python.org/moin/GuiProgramming
A:
Near the top of the page you will find:
Source Packages
This is the latest stable version of PyQt4.
PyQt-x11-gpl-4.6.2.tar.gz Linux, UNIX source
PyQt-win-gpl-4.6.2.zip Windows source
PyQt-mac-gpl-4.6.2.tar.gz MacOS/X source
For Ubuntu, choose the first one.
A:
In Ubuntu Linux, for PyQT try the package python-qt4.
An alternative is wxpython, and in Ubuntu the package is python-wxgtk2.8.
Another possibility to consider, that is considered an integral part of the Python distribution, is Tkinter, a Python interface to the Tk GUI toolkit. Tkinter is not necessarily considered as "good looking" as wxPython or PyQT, but it is definitely cross-platform, and has the blessing of being part of the Python distribution.
A:
You should try pyQt and wxPython both, but You will know which one better when you release your program to public.
you can install wxpython with synaptic easily.
and here is helloworld for wxpython
import wx
app = wx.App()
frame = wx.Frame(None, wx.ID_ANY, "Hello World")
frame.Show(True)
app.MainLoop()
Just my 2 cents, Sorry, If you dont like to use it.
A:
For cross-platform qt is the best option. GTK doesn't look well on windows, wxwidget/wxpython is ok but not so powerful and tkinter is too ugly/basic. Besides, qt4 is LGPL so you can link with it even if your application is not GPL.
|
Am I supposed to use PyQT4 for programming cross-platform software in Python?
|
So a user suggested getting PyQT.
A quick Google gave me this: Link
Is this GUI Library for pay?
If my development environment is Ubuntu Linux, what should I download on that site. I have no idea.
Please provide links if the site I provided is not correct to what I need. Thank you.
|
[
"You may want to look at PySide which is sponsored by Nokia, who own QT. It's also LGPL, which is a bit better of a license than the PyQT bindings. It's also a bit more pythonic in how it works. Unfortunately, it's new, so there isn't as much documentation. On their download page you can find information about a PPA for Ubuntu which will make it so your bindings automatically stay up to date.\nIf you want to run PyQT then just use APT and install python-qt3 or python-qt4.\n",
"I will answer the question you have stated in title\n\"Am I supposed to use PyQT4 for programming cross-platform software in Python?\"\nNo.\nYou can use wxPython (http://www.wxpython.org/), it is a quite decent GUI toolkit base on wxWdigets and many commercial applications are written in wxPython e.g. www.mockupscreens.com\nwxpython works on Mac/linux/Windows, has a very good support for custom widgets and provides a native looks on each platform, though you are free to design you own widgets/skins.\nPyQT is comparable or may be in some cases better but costly for non GPL applications(http://qt.nokia.com/products/licensing), but wxPython is free as free beer (http://en.wikipedia.org/wiki/WxPython#License).\n",
"PyQT is released under multiple licenses: http://www.riverbankcomputing.co.uk/software/pyqt/license\nYou only need to pay if you don't want to release your product under the GPL.\nPyQT isn't the only option for cross platform GUI in Python. There are many others too: http://wiki.python.org/moin/GuiProgramming\n",
"Near the top of the page you will find:\nSource Packages\nThis is the latest stable version of PyQt4.\n\nPyQt-x11-gpl-4.6.2.tar.gz Linux, UNIX source\nPyQt-win-gpl-4.6.2.zip Windows source\nPyQt-mac-gpl-4.6.2.tar.gz MacOS/X source\n\nFor Ubuntu, choose the first one.\n",
"In Ubuntu Linux, for PyQT try the package python-qt4.\nAn alternative is wxpython, and in Ubuntu the package is python-wxgtk2.8.\nAnother possibility to consider, that is considered an integral part of the Python distribution, is Tkinter, a Python interface to the Tk GUI toolkit. Tkinter is not necessarily considered as \"good looking\" as wxPython or PyQT, but it is definitely cross-platform, and has the blessing of being part of the Python distribution.\n",
"You should try pyQt and wxPython both, but You will know which one better when you release your program to public.\nyou can install wxpython with synaptic easily.\nand here is helloworld for wxpython\nimport wx\napp = wx.App()\nframe = wx.Frame(None, wx.ID_ANY, \"Hello World\")\nframe.Show(True)\napp.MainLoop()\n\nJust my 2 cents, Sorry, If you dont like to use it.\n",
"For cross-platform qt is the best option. GTK doesn't look well on windows, wxwidget/wxpython is ok but not so powerful and tkinter is too ugly/basic. Besides, qt4 is LGPL so you can link with it even if your application is not GPL.\n"
] |
[
10,
3,
1,
0,
0,
0,
0
] |
[] |
[] |
[
"cross_platform",
"python",
"qt"
] |
stackoverflow_0001774487_cross_platform_python_qt.txt
|
Q:
Python memchached client library with CAS support
I need to use gets and cas (check and set) commands of memcached from Python application. The only Python client library supporting them I found is Twisted. But Twisted requires quite different design of application, so it's not an option. Is there any other full-featured (not listed on official page) Python library for memcached? Pure Python solution is preferred.
Summary: Thanks to piquadrat there is patch for for python-libmemcached to add support of missing methods. The patch is already applied to trunk in August, but there was no new release yet. Using development branch is OK in many cases, but I'm still looking for stable pure Python solution.
A:
I don't see pylibmc listed there, but I have no idea if it supports those commands you need (edit: it doesn't, sorry).
/edit: if everything else fails, you could perhaps use this patch for python-libmemcached, which adds support for cas and gets.
/edit: The latest git version of pylibmc supports cas and gets
|
Python memchached client library with CAS support
|
I need to use gets and cas (check and set) commands of memcached from Python application. The only Python client library supporting them I found is Twisted. But Twisted requires quite different design of application, so it's not an option. Is there any other full-featured (not listed on official page) Python library for memcached? Pure Python solution is preferred.
Summary: Thanks to piquadrat there is patch for for python-libmemcached to add support of missing methods. The patch is already applied to trunk in August, but there was no new release yet. Using development branch is OK in many cases, but I'm still looking for stable pure Python solution.
|
[
"I don't see pylibmc listed there, but I have no idea if it supports those commands you need (edit: it doesn't, sorry).\n/edit: if everything else fails, you could perhaps use this patch for python-libmemcached, which adds support for cas and gets. \n/edit: The latest git version of pylibmc supports cas and gets\n"
] |
[
2
] |
[] |
[] |
[
"memcached",
"python"
] |
stackoverflow_0001887431_memcached_python.txt
|
Q:
How to Sort Arrays in Dictionary?
I'm currently writing a program in Python to track statistics on video games. An example of the dictionary I'm using to track the scores :
ten = 1
sec = 9
fir = 10
thi5 = 6
sec5 = 8
games = {
'adom': [ten+fir+sec+sec5, "Ancient Domain of Mysteries"],
'nethack': [fir+fir+fir+sec+thi5, "Nethack"]
}
Right now, I'm going about this the hard way, and making a big long list of nested ifs, but I don't think that's the proper way to go about it. I was trying to figure out a way to sort the dictionary, via the arrays, and then, finding a way to display the first ten that pop up... instead of having to work deep in the if statements.
So... basically, my question is : Do you have any ideas that I could use to about making this easier, instead of wayyyy, way harder?
===== EDIT ====
the ten+fir produces numbers. I want to find a way to go about sorting the lists (I lack the knowledge of proper terminology) to go by the number (basically, whichever ones have the highest number in the first part of the array go first.
Here's an example of my current way of going about it (though, it's incomplete, due to it being very tiresome : Example Nests (paste2) (let's try this one?)
==== SECOND EDIT ====
In case someone doesn't see my comment below :
ten, fir, et cetera - these are just variables for scores. Basically, it goes from a top ten list into a variable number.
ten = 1, nin = 2, fir = 10, fir5 = 10, sec5 = 8, sec = 9...
so : 'adom': [ten+fir+sec+sec5, "Ancient Domain of Mysteries"] actually registers as : 'adom': [1+10+9+8, "Ancient Domain of Mysteries"] , which ends up looking like :
'adom': [28, "Ancient Domain of Mysteries"]
So, basically, if I ended up doing the "top two" out of my example, it'd be :
((1)) Nethack (48)
((2)) ADOM (28)
I'd write an actual number, but I'm thinking of changing a few things up, so the numbers might be a touch different, and I wouldn't want to rewrite it.
== THIRD (AND HOPEFULLY THE FINAL) EDIT ==
Fixed my original code example.
A:
How about something like this:
scores = games.items()
scores.sort(key = lambda key, value: value[0])
return scores[:10]
This will return the first 10 items, sorted by the first item in the array.
I'm not sure if this is what you want though, please update the question (and fix the example link) if you need something else...
A:
import heapq
return heapq.nlargest(10, games.iteritems(), key=lambda k, v: v[0])
is the most direct way to get the top ten key / value pairs, sorted by the first item of each "value" list. If you can define more precisely what output you want (just the names, the name / value pairs, or what else?) and the sorting criterion, this is easy to adjust, of course.
A:
Wim's solution is good, but I'd say that you should probably go the extra mile and push this work off onto a database, rather than relying on Python. Python interfaces well with most types of databases, where much of what you're exploring is already a solved problem.
For example, instead of worrying about shifting your dictionaries to various other data types in order to properly sort them, you can simply get all the data for each pertinent entry pre-sorted based on the criteria of your query. There goes the need for convoluted sorting and resorting right there.
While dictionaries are tempting to use, because they give the illusion of database-like abilities to access data based on its attributes, I still think they stumble quite a bit with respect to implementation. I don't really have any numbers to throw at you, but just from personal experience, anything you do on Python when it comes to manipulating large amounts of data, you can do much faster and more efficient both in code and computation with something like MySQL.
I'm not sure what you have planned as far as the structure of your data goes, but along with adding data, changing its structure is a lot easier using a database, too.
|
How to Sort Arrays in Dictionary?
|
I'm currently writing a program in Python to track statistics on video games. An example of the dictionary I'm using to track the scores :
ten = 1
sec = 9
fir = 10
thi5 = 6
sec5 = 8
games = {
'adom': [ten+fir+sec+sec5, "Ancient Domain of Mysteries"],
'nethack': [fir+fir+fir+sec+thi5, "Nethack"]
}
Right now, I'm going about this the hard way, and making a big long list of nested ifs, but I don't think that's the proper way to go about it. I was trying to figure out a way to sort the dictionary, via the arrays, and then, finding a way to display the first ten that pop up... instead of having to work deep in the if statements.
So... basically, my question is : Do you have any ideas that I could use to about making this easier, instead of wayyyy, way harder?
===== EDIT ====
the ten+fir produces numbers. I want to find a way to go about sorting the lists (I lack the knowledge of proper terminology) to go by the number (basically, whichever ones have the highest number in the first part of the array go first.
Here's an example of my current way of going about it (though, it's incomplete, due to it being very tiresome : Example Nests (paste2) (let's try this one?)
==== SECOND EDIT ====
In case someone doesn't see my comment below :
ten, fir, et cetera - these are just variables for scores. Basically, it goes from a top ten list into a variable number.
ten = 1, nin = 2, fir = 10, fir5 = 10, sec5 = 8, sec = 9...
so : 'adom': [ten+fir+sec+sec5, "Ancient Domain of Mysteries"] actually registers as : 'adom': [1+10+9+8, "Ancient Domain of Mysteries"] , which ends up looking like :
'adom': [28, "Ancient Domain of Mysteries"]
So, basically, if I ended up doing the "top two" out of my example, it'd be :
((1)) Nethack (48)
((2)) ADOM (28)
I'd write an actual number, but I'm thinking of changing a few things up, so the numbers might be a touch different, and I wouldn't want to rewrite it.
== THIRD (AND HOPEFULLY THE FINAL) EDIT ==
Fixed my original code example.
|
[
"How about something like this:\nscores = games.items()\nscores.sort(key = lambda key, value: value[0])\nreturn scores[:10]\n\nThis will return the first 10 items, sorted by the first item in the array.\nI'm not sure if this is what you want though, please update the question (and fix the example link) if you need something else...\n",
"import heapq\n\nreturn heapq.nlargest(10, games.iteritems(), key=lambda k, v: v[0])\n\nis the most direct way to get the top ten key / value pairs, sorted by the first item of each \"value\" list. If you can define more precisely what output you want (just the names, the name / value pairs, or what else?) and the sorting criterion, this is easy to adjust, of course.\n",
"Wim's solution is good, but I'd say that you should probably go the extra mile and push this work off onto a database, rather than relying on Python. Python interfaces well with most types of databases, where much of what you're exploring is already a solved problem.\nFor example, instead of worrying about shifting your dictionaries to various other data types in order to properly sort them, you can simply get all the data for each pertinent entry pre-sorted based on the criteria of your query. There goes the need for convoluted sorting and resorting right there. \nWhile dictionaries are tempting to use, because they give the illusion of database-like abilities to access data based on its attributes, I still think they stumble quite a bit with respect to implementation. I don't really have any numbers to throw at you, but just from personal experience, anything you do on Python when it comes to manipulating large amounts of data, you can do much faster and more efficient both in code and computation with something like MySQL.\nI'm not sure what you have planned as far as the structure of your data goes, but along with adding data, changing its structure is a lot easier using a database, too. \n"
] |
[
3,
2,
0
] |
[] |
[] |
[
"arrays",
"dictionary",
"logic",
"python",
"sorting"
] |
stackoverflow_0001888910_arrays_dictionary_logic_python_sorting.txt
|
Q:
IBoutlet with PyObjC and Interface Builder
I'm writing a simple OSX app using Python and PyObjC. I designed the settings dialog using Interface Builder and I use ibtool to compile it, then load it from Python. The problem is how to access the controls I have in this window from the Python code? I played around with iPhone development a bit before and I remember I need to have an IBOutlet in the controller class which will be connected to the UI control in the interface builder. It should look something like this in Python:
class MyClass(NSObject):
my_outlet = objc.IBOutlet('my_outlet')
But since I'm not working in XCode (all I have is a .py file and a .xib file), Interface Builder doesn't know about my outlets. How can I do the binding in this case? Or how else can I access the UI elements from the code?
A:
First, the use of Xcode or not has nothing to do with NIB loading (beyond making it more convenient).
As Ole said, you can use IB to manually add the outlet's you need to file's owner or to the custom object instances that you have in the NIB file. By doing so, it will all "just work".
However, this statement is what prompted my relatively similar answer:
all I have is a .py file and a .xib
file
Are you trying to write a bit of UI code outside of a .app wrapper? If so, that is a wholly unsupported pattern, very difficult to get correct, and quite likely to break across software updates or major releases (as it has many times in the past).
The best way to solve your problem is to use an Xcode project and build a standard application. The templates are no longer shipped with the dev tools. Just download them separately.
If you need to run it from the command line, you can still do so.
A:
I haven't tried this, but you can also define outlets directly in IB. Open the Library panel, select Classes in the segmented control at the top and select your custom class you want to define an outlet for. Let's say you have a NSWindow subclass called MyWindow. Select the NSWindow class in the list, click on the action button at the bottom left, select New Subclass... and name it MyWindow. Now switch to the Outlets tab and create a NSButton outlet for your window. Now you connect a button to the outlet.
I don't know how this will transfer to PyObjC but I'd love to see your results when you try it out.
|
IBoutlet with PyObjC and Interface Builder
|
I'm writing a simple OSX app using Python and PyObjC. I designed the settings dialog using Interface Builder and I use ibtool to compile it, then load it from Python. The problem is how to access the controls I have in this window from the Python code? I played around with iPhone development a bit before and I remember I need to have an IBOutlet in the controller class which will be connected to the UI control in the interface builder. It should look something like this in Python:
class MyClass(NSObject):
my_outlet = objc.IBOutlet('my_outlet')
But since I'm not working in XCode (all I have is a .py file and a .xib file), Interface Builder doesn't know about my outlets. How can I do the binding in this case? Or how else can I access the UI elements from the code?
|
[
"First, the use of Xcode or not has nothing to do with NIB loading (beyond making it more convenient).\nAs Ole said, you can use IB to manually add the outlet's you need to file's owner or to the custom object instances that you have in the NIB file. By doing so, it will all \"just work\".\nHowever, this statement is what prompted my relatively similar answer:\n\nall I have is a .py file and a .xib\n file\n\nAre you trying to write a bit of UI code outside of a .app wrapper? If so, that is a wholly unsupported pattern, very difficult to get correct, and quite likely to break across software updates or major releases (as it has many times in the past).\nThe best way to solve your problem is to use an Xcode project and build a standard application. The templates are no longer shipped with the dev tools. Just download them separately.\nIf you need to run it from the command line, you can still do so.\n",
"I haven't tried this, but you can also define outlets directly in IB. Open the Library panel, select Classes in the segmented control at the top and select your custom class you want to define an outlet for. Let's say you have a NSWindow subclass called MyWindow. Select the NSWindow class in the list, click on the action button at the bottom left, select New Subclass... and name it MyWindow. Now switch to the Outlets tab and create a NSButton outlet for your window. Now you connect a button to the outlet.\nI don't know how this will transfer to PyObjC but I'd love to see your results when you try it out.\n"
] |
[
4,
1
] |
[] |
[] |
[
"cocoa",
"interface_builder",
"pyobjc",
"python"
] |
stackoverflow_0001887102_cocoa_interface_builder_pyobjc_python.txt
|
Q:
numpy : How to convert an array type quickly
I find the astype() method of numpy arrays not very efficient. I have an array containing
3 million of Uint8 point. Multiplying it by a 3x3 matrix takes 2 second, but converting the result from uint16 to uint8 takes another second.
More precisely :
print time.clock()
imgarray = np.dot(imgarray, M)/255
print time.clock()
imgarray = imgarray.clip(0, 255)
print time.clock()
imgarray = imgarray.astype('B')
print time.clock()
dot product and scaling takes 2 sec
clipping takes 200 msec
type conversion takes 1 sec
Given the time taken by the other operations, I would expect astype to be faster.
Is there a faster way to do type conversion, or am I wrong when guesstimating that type conversion should not be that hard ?
Edit : the goal is to save the final 8 bit array to a file
A:
When you use imgarray = imgarray.astype('B'), you get a copy of the array, cast to the specified type. This requires extra memory allocation, even though you immediately flip imgarray to point to the newly allocated array.
If you use imgarray.view('uint8'), then you get a view of the array. This uses the same data except that it is interpreted as uint8 instead of imgarray.dtype.
(np.dot returns a uint32 array, so after the np.dot, imgarray is of type uint32.)
The problem with using view, however, is that a 32-bit integer becomes viewed as 4 8-bit integers, and we only care about the value in the last 8-bits. So we need to skip to every 4th 8-bit integer. We can do that with slicing:
imgarray.view('uint8')[:,::4]
IPython's %timeit command shows there is a significant speed up doing things this way:
In [37]: %timeit imgarray2 = imgarray.astype('B')
10000 loops, best of 3: 107 us per loop
In [39]: %timeit imgarray3 = imgarray.view('B')[:,::4]
100000 loops, best of 3: 3.64 us per loop
|
numpy : How to convert an array type quickly
|
I find the astype() method of numpy arrays not very efficient. I have an array containing
3 million of Uint8 point. Multiplying it by a 3x3 matrix takes 2 second, but converting the result from uint16 to uint8 takes another second.
More precisely :
print time.clock()
imgarray = np.dot(imgarray, M)/255
print time.clock()
imgarray = imgarray.clip(0, 255)
print time.clock()
imgarray = imgarray.astype('B')
print time.clock()
dot product and scaling takes 2 sec
clipping takes 200 msec
type conversion takes 1 sec
Given the time taken by the other operations, I would expect astype to be faster.
Is there a faster way to do type conversion, or am I wrong when guesstimating that type conversion should not be that hard ?
Edit : the goal is to save the final 8 bit array to a file
|
[
"When you use imgarray = imgarray.astype('B'), you get a copy of the array, cast to the specified type. This requires extra memory allocation, even though you immediately flip imgarray to point to the newly allocated array.\nIf you use imgarray.view('uint8'), then you get a view of the array. This uses the same data except that it is interpreted as uint8 instead of imgarray.dtype.\n(np.dot returns a uint32 array, so after the np.dot, imgarray is of type uint32.)\nThe problem with using view, however, is that a 32-bit integer becomes viewed as 4 8-bit integers, and we only care about the value in the last 8-bits. So we need to skip to every 4th 8-bit integer. We can do that with slicing:\nimgarray.view('uint8')[:,::4]\nIPython's %timeit command shows there is a significant speed up doing things this way:\nIn [37]: %timeit imgarray2 = imgarray.astype('B')\n10000 loops, best of 3: 107 us per loop\n\nIn [39]: %timeit imgarray3 = imgarray.view('B')[:,::4]\n100000 loops, best of 3: 3.64 us per loop\n\n"
] |
[
26
] |
[] |
[] |
[
"numpy",
"python"
] |
stackoverflow_0001888870_numpy_python.txt
|
Q:
Sending the variable's content to my mailbox in Python?
I have asked this question here about a Python command that fetches a URL of a web page and stores it in a variable. The first thing that I wanted to know then was whether or not the variable in this code contains the HTML code of a web-page:
from google.appengine.api import urlfetch
url = "http://www.google.com/"
result = urlfetch.fetch(url)
if result.status_code == 200:
doSomethingWithResult(result.content)
The answer that I received was "yes", i.e. the variable "result" in the code did contain the HTML code of a web page, and the programmer who was answering said that I needed to "check the Content-Type header and verify that it's either text/html or application/xhtml+xml". I've looked through several Python tutorials, but couldn't find anything about headers. So my question is where is this Content-Type header located and how can I check it? Could I send the content of that variable directly to my mailbox?
Here is where I got this code. It's on Google App Engines.
A:
for info on sending Content-Type header, see here: http://code.google.com/appengine/docs/python/urlfetch/overview.html#Request_Headers
A:
If you look at the Google App Engine documentation for the response object, the result of urlfetch.fetch() contains the member headers which contains the HTTP response headers, as a mapping of names to values. So, all you probably need to do is:
if result['Content-Type'] in ('text/html', 'application/xhtml+xml'):
# assuming you want to do something with the content
doSomethingWithXHTML(result.content)
else:
# use content for something else
doTheOtherThing(result.content)
As far as emailing the variable's contents, I suggest the Python email module.
|
Sending the variable's content to my mailbox in Python?
|
I have asked this question here about a Python command that fetches a URL of a web page and stores it in a variable. The first thing that I wanted to know then was whether or not the variable in this code contains the HTML code of a web-page:
from google.appengine.api import urlfetch
url = "http://www.google.com/"
result = urlfetch.fetch(url)
if result.status_code == 200:
doSomethingWithResult(result.content)
The answer that I received was "yes", i.e. the variable "result" in the code did contain the HTML code of a web page, and the programmer who was answering said that I needed to "check the Content-Type header and verify that it's either text/html or application/xhtml+xml". I've looked through several Python tutorials, but couldn't find anything about headers. So my question is where is this Content-Type header located and how can I check it? Could I send the content of that variable directly to my mailbox?
Here is where I got this code. It's on Google App Engines.
|
[
"for info on sending Content-Type header, see here: http://code.google.com/appengine/docs/python/urlfetch/overview.html#Request_Headers\n",
"If you look at the Google App Engine documentation for the response object, the result of urlfetch.fetch() contains the member headers which contains the HTTP response headers, as a mapping of names to values. So, all you probably need to do is:\nif result['Content-Type'] in ('text/html', 'application/xhtml+xml'):\n # assuming you want to do something with the content\n doSomethingWithXHTML(result.content)\nelse:\n # use content for something else\n doTheOtherThing(result.content)\n\nAs far as emailing the variable's contents, I suggest the Python email module.\n"
] |
[
1,
1
] |
[] |
[] |
[
"content_type",
"google_app_engine",
"header",
"python",
"url"
] |
stackoverflow_0001889912_content_type_google_app_engine_header_python_url.txt
|
Q:
List of dictionaries, in a dictionary - in Python
I have a case where I need to construct following structure programmatically (yes I am aware of .setdefault and defaultdict but I can not get what I want)
I basically need a dictionary, with a dictionary of dictionaries created within the loop.
At the beginning the structure is completely blank.
structure sample (please note, I want to create an array that has this structure in the code!)
RULE = {
'hard_failure': {
4514 : {
'f_expr' = 'ABC',
'c_expr' = 'XF0',
}
}
}
pseudo code that needs to create this:
...
self.rules = {}
for row in rows:
a = 'hard_failure'
b = row[0] # 4514
c = row[1] # ABC
d = row[2] # XF0
# Universe collapse right after
self.rules = ????
...
The code above is obviously not working since I dont know how to do it!
A:
Example, that you've posted is not a valid python code, I could only imagine that you're trying to do something like this:
self.rules[a] = [{b:{'f_expr': c, 'c_expr': d}}]
this way self.rules is a dictionary of a list of a dictionary of a dictionary. I bet there is more sane way to do this.
A:
rules = {}
failure = 'hard_failure'
rules[failure] = []
for row in rows:
#this is what people are referring to below. You left out the addition of the dictionary structure to the list.
rules[failure][row[0]] = {}
rules[failure][row[0]]['type 1'] = row[1]
rules[failure][row[0]]['type 2'] = row[2]
This is what I created based on how I understood the questions. I wasn't sure what to call the 'f_expr' and 'c_expr' since you never mention where you get those but I assume they are already know column names in a resultset or structure of some sort.
Just keep adding to the structure as you go.
A:
Your example code doesn't seem to be valid Python. It's not clear if the second level element is supposed to be a list or a dictionary.
However, if you're doing what I think you're doing, and it's a dictionary, you could use a tuple as a key in the top-level dictionary instead of nesting dictionaries:
>>> a = 'hard_failure'
>>> b = 4514
>>> c = "ABC"
>>> d = "XF0"
>>> rules = {}
>>> rules[(a,b)] = {'f_expr' : a,'c_expr' : d}
>>> rules
{('hard_failure', 4514): {'c_expr': 'XF0', 'f_expr': 'hard_failure'}}
A:
My favorite way to deal with nested dictionaries & lists of dictionaries is to use PyYAML. See this response for details.
A:
Well, I apologize for the confusion, I never claimed that code actually compiled, hence (pseudo). Arthur Thomas put me on the right track, here is slightly modified version. (Yes, now its a simply nested dictionary, 3 levels down)
RULE_k = 'hard_failure'
self.rules = {}
for row in rows:
self.rules_compiled.setdefault(RULE_k, {})
self.rules_compiled[RULE_k][row[1]] = {}
self.rules_compiled[RULE_k][row[1]]['f_expr'] = row[0]
self.rules_compiled[RULE_k][row[1]]['c_expr'] = row[1]
|
List of dictionaries, in a dictionary - in Python
|
I have a case where I need to construct following structure programmatically (yes I am aware of .setdefault and defaultdict but I can not get what I want)
I basically need a dictionary, with a dictionary of dictionaries created within the loop.
At the beginning the structure is completely blank.
structure sample (please note, I want to create an array that has this structure in the code!)
RULE = {
'hard_failure': {
4514 : {
'f_expr' = 'ABC',
'c_expr' = 'XF0',
}
}
}
pseudo code that needs to create this:
...
self.rules = {}
for row in rows:
a = 'hard_failure'
b = row[0] # 4514
c = row[1] # ABC
d = row[2] # XF0
# Universe collapse right after
self.rules = ????
...
The code above is obviously not working since I dont know how to do it!
|
[
"Example, that you've posted is not a valid python code, I could only imagine that you're trying to do something like this:\nself.rules[a] = [{b:{'f_expr': c, 'c_expr': d}}]\n\nthis way self.rules is a dictionary of a list of a dictionary of a dictionary. I bet there is more sane way to do this.\n",
"rules = {}\nfailure = 'hard_failure'\nrules[failure] = []\nfor row in rows:\n #this is what people are referring to below. You left out the addition of the dictionary structure to the list.\n rules[failure][row[0]] = {} \n rules[failure][row[0]]['type 1'] = row[1]\n rules[failure][row[0]]['type 2'] = row[2]\n\nThis is what I created based on how I understood the questions. I wasn't sure what to call the 'f_expr' and 'c_expr' since you never mention where you get those but I assume they are already know column names in a resultset or structure of some sort.\nJust keep adding to the structure as you go.\n",
"Your example code doesn't seem to be valid Python. It's not clear if the second level element is supposed to be a list or a dictionary.\nHowever, if you're doing what I think you're doing, and it's a dictionary, you could use a tuple as a key in the top-level dictionary instead of nesting dictionaries:\n>>> a = 'hard_failure'\n>>> b = 4514\n>>> c = \"ABC\"\n>>> d = \"XF0\"\n>>> rules = {}\n>>> rules[(a,b)] = {'f_expr' : a,'c_expr' : d}\n>>> rules\n{('hard_failure', 4514): {'c_expr': 'XF0', 'f_expr': 'hard_failure'}}\n\n",
"My favorite way to deal with nested dictionaries & lists of dictionaries is to use PyYAML. See this response for details.\n",
"Well, I apologize for the confusion, I never claimed that code actually compiled, hence (pseudo). Arthur Thomas put me on the right track, here is slightly modified version. (Yes, now its a simply nested dictionary, 3 levels down)\n RULE_k = 'hard_failure'\n self.rules = {}\n for row in rows:\n self.rules_compiled.setdefault(RULE_k, {})\n self.rules_compiled[RULE_k][row[1]] = {}\n self.rules_compiled[RULE_k][row[1]]['f_expr'] = row[0]\n self.rules_compiled[RULE_k][row[1]]['c_expr'] = row[1]\n\n"
] |
[
5,
1,
0,
0,
0
] |
[] |
[] |
[
"dictionary",
"list",
"nested",
"python"
] |
stackoverflow_0001889385_dictionary_list_nested_python.txt
|
Q:
Setting Python path while developing library module
I am developing a library and an application that uses the library in Python 2.6. I've placed a "mylib.pth" file in "site-packages" so that I can import mylib from within my application.
I am using a DVCS so when I want to fix a bug or add a feature to the library I make a branch of the repository and work within that branch. To test my application with the changes I am making to the library I edit the path in "mylib.pth" to point to the new development branch.
This gets a little tedious if I have a few parallel branches of my library going on at one. I have to keep editing the "mylib.pth" file before testing to ensure I am testing against the correct version of my library. Is there a way to use the current path (i.e. the development branch of the library that I am current in) to set the library path when I invoke my application instead of using the "mylib.pth" in the global "site-packages" directory?
A:
Is virtualenv what you're looking for? From the description:
Imagine you have an application that
needs version 1 of LibFoo, but another
application requires version 2. How
can you use both these applications?
If you install everything into
/usr/lib/python2.4/site-packages (or
whatever your platform's standard
location is), it's easy to end up in a
situation where you unintentionally
upgrade an application that shouldn't
be upgraded.
A:
Suggested reading: Tools of the Modern Python Hacker: Virtualenv, Fabric and Pip. It addresses a number of problems with development and deployment of Python apps.
A:
If you use setuptools, then you can say setup.py develop in your working tree, and it will do the .pth file manipulation for you.
A:
Sure, you can alter sys.path to add the current directory (or a subdirectory of it) to the search path. site.addsitedir is a good way to do it. Since you'd be doing this from Python you can have any sort of logic you like for deciding which directory to add; you could base it on os.path.normpathing the current directory if it looks like a branch, or looking for the newest branch on-disc, or something else.
You could put this code in the sitecustomize.py module or other startup-triggered location.
A:
You might also consider using zc.buildout. It allows you to create entry points with customized python paths.
A:
I set my PYTHONPATH to point to the latest-and-greatest version. No editing.
export PYTHONPATH=.:/the/new/version
|
Setting Python path while developing library module
|
I am developing a library and an application that uses the library in Python 2.6. I've placed a "mylib.pth" file in "site-packages" so that I can import mylib from within my application.
I am using a DVCS so when I want to fix a bug or add a feature to the library I make a branch of the repository and work within that branch. To test my application with the changes I am making to the library I edit the path in "mylib.pth" to point to the new development branch.
This gets a little tedious if I have a few parallel branches of my library going on at one. I have to keep editing the "mylib.pth" file before testing to ensure I am testing against the correct version of my library. Is there a way to use the current path (i.e. the development branch of the library that I am current in) to set the library path when I invoke my application instead of using the "mylib.pth" in the global "site-packages" directory?
|
[
"Is virtualenv what you're looking for? From the description:\n\nImagine you have an application that\n needs version 1 of LibFoo, but another\n application requires version 2. How\n can you use both these applications?\n If you install everything into\n /usr/lib/python2.4/site-packages (or\n whatever your platform's standard\n location is), it's easy to end up in a\n situation where you unintentionally\n upgrade an application that shouldn't\n be upgraded.\n\n",
"Suggested reading: Tools of the Modern Python Hacker: Virtualenv, Fabric and Pip. It addresses a number of problems with development and deployment of Python apps.\n",
"If you use setuptools, then you can say setup.py develop in your working tree, and it will do the .pth file manipulation for you.\n",
"Sure, you can alter sys.path to add the current directory (or a subdirectory of it) to the search path. site.addsitedir is a good way to do it. Since you'd be doing this from Python you can have any sort of logic you like for deciding which directory to add; you could base it on os.path.normpathing the current directory if it looks like a branch, or looking for the newest branch on-disc, or something else.\nYou could put this code in the sitecustomize.py module or other startup-triggered location.\n",
"You might also consider using zc.buildout. It allows you to create entry points with customized python paths.\n",
"I set my PYTHONPATH to point to the latest-and-greatest version. No editing.\nexport PYTHONPATH=.:/the/new/version\n\n"
] |
[
4,
4,
2,
1,
1,
1
] |
[] |
[] |
[
"python"
] |
stackoverflow_0001889967_python.txt
|
Q:
Response Code 202, Not a Qualified Error Code
I'm working with an API which I post files to. However, when I receive the response, the HTTP status code is a 202. This is to be expected, but in addition the API will also respond with XML content.
So in my try/except block urllib2.urlopen will result in a raised urllib2.HTTPError and destroying the XML content.
try:
response = urllib2.urlopen(req)
except urllib2.HTTPError, http_e:
if http_e.code == 202:
print 'accepted!'
pass
print response.read() # UnboundLocalError: local variable 'response' referenced before assignment
How can I expect the 202 and keep the response content, but not raise an error?
A:
Edit
Being silly, I forgot to inspect the exception that is returned by urllib2. It features all of the properties I've been waxing on about for httplib. This should do the trick for you:
try:
urllib2.urlopen(req)
except urllib2.HTTPError, e:
print "Response code",e.code # prints 404
print "Response body",e.read() # prints the body of the response...
# ie: your XML
print "Headers",e.headers.headers
Original
In this case, given that you're using HTTP as your transport protocol, you'll probably have more luck with the httplib library:
>>> import httplib
>>> conn = httplib.HTTPConnection("www.stackoverflow.com")
>>> conn.request("GET", "/dlkfjadslkfjdslkfjd.html")
>>> r = conn.getresponse()
>>> r.status
301
>>> r.reason
'Moved Permanently'
>>> r.read()
'<head><title>Document Moved</title></head>\n<body><h1>Object Moved</h1>
This document may be found
<a HREF="http://stackoverflow.com/dlkfjadslkfjdslkfjd.html">here</a></body>'
You can further use r.getheaders() and so forth to inspect other aspects of the response.
|
Response Code 202, Not a Qualified Error Code
|
I'm working with an API which I post files to. However, when I receive the response, the HTTP status code is a 202. This is to be expected, but in addition the API will also respond with XML content.
So in my try/except block urllib2.urlopen will result in a raised urllib2.HTTPError and destroying the XML content.
try:
response = urllib2.urlopen(req)
except urllib2.HTTPError, http_e:
if http_e.code == 202:
print 'accepted!'
pass
print response.read() # UnboundLocalError: local variable 'response' referenced before assignment
How can I expect the 202 and keep the response content, but not raise an error?
|
[
"Edit\nBeing silly, I forgot to inspect the exception that is returned by urllib2. It features all of the properties I've been waxing on about for httplib. This should do the trick for you:\ntry:\n urllib2.urlopen(req)\nexcept urllib2.HTTPError, e:\n print \"Response code\",e.code # prints 404\n print \"Response body\",e.read() # prints the body of the response...\n # ie: your XML\n print \"Headers\",e.headers.headers\n\nOriginal\nIn this case, given that you're using HTTP as your transport protocol, you'll probably have more luck with the httplib library:\n>>> import httplib\n>>> conn = httplib.HTTPConnection(\"www.stackoverflow.com\")\n>>> conn.request(\"GET\", \"/dlkfjadslkfjdslkfjd.html\")\n>>> r = conn.getresponse()\n>>> r.status\n301\n>>> r.reason\n'Moved Permanently'\n>>> r.read()\n'<head><title>Document Moved</title></head>\\n<body><h1>Object Moved</h1>\n This document may be found \n <a HREF=\"http://stackoverflow.com/dlkfjadslkfjdslkfjd.html\">here</a></body>'\n\nYou can further use r.getheaders() and so forth to inspect other aspects of the response.\n"
] |
[
4
] |
[] |
[] |
[
"python"
] |
stackoverflow_0001890216_python.txt
|
Q:
How to replace models.py in Django app in the production server
I have a simple django app that is using only the admin. This is the model as is now in the server:
from django.db import models
class School(models.Model):
school = models.CharField(max_length=200)
def __unicode__(self):
return self.school
class Lawyer(models.Model):
first = models.CharField(max_length=20)
initial = models.CharField(blank=True, max_length=2)
last = models.CharField(max_length=20)
year_graduated = models.IntegerField('Year graduated')
school = models.CharField(max_length=200)
school = models.ForeignKey(School)
class Meta:
ordering = ('last',)
def __unicode__(self):
return self.first
I want to add two new fields, so that the new models.py looks like this:
from django.db import models
class School(models.Model):
school = models.CharField(max_length=300)
def __unicode__(self):
return self.school
class Lawyer(models.Model):
firm_url = models.URLField('Bio', max_length=200)
firm_name = models.CharField('Firm', max_length=100)
first = models.CharField('First Name', max_length=50)
last = models.CharField('Last Name', max_length=50)
year_graduated = models.IntegerField('Year graduated')
school = models.CharField(max_length=300)
school = models.ForeignKey(School)
class Meta:
ordering = ('?',)
def __unicode__(self):
return self.first
Otherwise everything else is the same. Can I just upload this new models.py to the server and expect the application to work the same as before? I also need to clear what is in the database. I am using sqlite3.
I tried to deploy a new app but unfortunately the hosting co is refusing to help. Since I don't need two apps I thought about replacing models.py. This new app works in the django dev server as expected. I would appreciate advice since I will take care of the other outstanding questions after I make this app running. Thanks!
Edit
Thanks for all the answers. Since I want the database clear I will try jcd's solution. So, I will replace the old fields in the models.py
first = models.CharField(max_length=20)
initial = models.CharField(blank=True, max_length=2)
last = models.CharField(max_length=20)
year_graduated = models.IntegerField('Year graduated')
school = models.CharField(max_length=200)
school = models.ForeignKey(School)
with the new fields:
firm_url = models.URLField('Bio', max_length=200)
firm_name = models.CharField('Firm', max_length=100)
first = models.CharField('First Name', max_length=50)
last = models.CharField('Last Name', max_length=50)
year_graduated = models.IntegerField('Year graduated')
school = models.CharField(max_length=300)
school = models.ForeignKey(School)
to have
from django.db import models
class School(models.Model):
school = models.CharField(max_length=200)
def __unicode__(self):
return self.school
class Lawyer(models.Model):
firm_url = models.URLField('Bio', max_length=200)
firm_name = models.CharField('Firm', max_length=100)
first = models.CharField('First Name', max_length=50)
last = models.CharField('Last Name', max_length=50)
year_graduated = models.IntegerField('Year graduated')
school = models.CharField(max_length=300)
school = models.ForeignKey(School)
class Meta:
ordering = ('last',)
def __unicode__(self):
return self.first
and upload this to the server. Then I will run manage.py syncdb.
And when I open the page I will see the admin as it was before except with new fields.
I assume it is no problem to update the admin.py later to add the new fields:
class LawyerAdmin(admin.ModelAdmin):
fieldsets = [
('Name', {'fields': ['first', 'last', 'firm_name', 'firm_url']}),
('School', {'fields': ['school', 'year_graduated']}),
]
list_display = ('first', 'last', 'school', 'year_graduated', 'firm_name', 'firm_url')
list_filter = ['year_graduated']
#search_fields = ['last', 'first']
search_fields = ['school__school']
search_fields = ['school__lawyer__last']
Thanks again!
A:
No, you cannot just replace models.py.
You need some kind of schema migration.
If you don't use a tool like django south, you'll have to do it manually.
Look at http://www.sqlite.org/lang_altertable.html
You can use manage.py sqlall to see which SQL statements you need.
A:
Since you're using a sqlite database, and you want to clear the data anyway, this is dead easy. Add your two fields, move your database to a backup location, and re-run manage.py syncdb. It will set up the new database for you. If you need to keep your old data, you are using a more complex database, or you want to manage your change over time, you should look into a schema migration tool like South.
A:
Run a manage.py sqlall on your project
This will dump the SQL create command
From there, look at the dump for your new columns, and use this to help create your Alter Table statements
Side note, is it kinda weird you have two "school" definitions?
A:
Modifying a model on a live Django environment can be a bit of a hassle, depending on your approach.
If you don't mind losing data, a simple manage.py command will do the trick:
python manage.py reset [app name]
If, however, you want to retain the data that's already in the database, you'll have to execute some SQL manually to modify the schema. This can get messy to keep track of if you're not careful.
What I've done previously is to write a SQL statement for every change to any model, and record that somewhere along with the date. I also record the last time the schema was modified for any database (in my case, development, staging, and production). To update any one database to the correct schema, I just ran all the schema change SQL from dates after that particular database was last updated.
A:
You can use python manage.py sqlall <appname> | grep <column name> to get the SQL definition of a particular column.
Then, you can do something like: ALTER TABLE my_table ADD COLUMN 'column_name' varchar(30);
(In this case, the manage.py line above returned 'column_name varchar(30);')
|
How to replace models.py in Django app in the production server
|
I have a simple django app that is using only the admin. This is the model as is now in the server:
from django.db import models
class School(models.Model):
school = models.CharField(max_length=200)
def __unicode__(self):
return self.school
class Lawyer(models.Model):
first = models.CharField(max_length=20)
initial = models.CharField(blank=True, max_length=2)
last = models.CharField(max_length=20)
year_graduated = models.IntegerField('Year graduated')
school = models.CharField(max_length=200)
school = models.ForeignKey(School)
class Meta:
ordering = ('last',)
def __unicode__(self):
return self.first
I want to add two new fields, so that the new models.py looks like this:
from django.db import models
class School(models.Model):
school = models.CharField(max_length=300)
def __unicode__(self):
return self.school
class Lawyer(models.Model):
firm_url = models.URLField('Bio', max_length=200)
firm_name = models.CharField('Firm', max_length=100)
first = models.CharField('First Name', max_length=50)
last = models.CharField('Last Name', max_length=50)
year_graduated = models.IntegerField('Year graduated')
school = models.CharField(max_length=300)
school = models.ForeignKey(School)
class Meta:
ordering = ('?',)
def __unicode__(self):
return self.first
Otherwise everything else is the same. Can I just upload this new models.py to the server and expect the application to work the same as before? I also need to clear what is in the database. I am using sqlite3.
I tried to deploy a new app but unfortunately the hosting co is refusing to help. Since I don't need two apps I thought about replacing models.py. This new app works in the django dev server as expected. I would appreciate advice since I will take care of the other outstanding questions after I make this app running. Thanks!
Edit
Thanks for all the answers. Since I want the database clear I will try jcd's solution. So, I will replace the old fields in the models.py
first = models.CharField(max_length=20)
initial = models.CharField(blank=True, max_length=2)
last = models.CharField(max_length=20)
year_graduated = models.IntegerField('Year graduated')
school = models.CharField(max_length=200)
school = models.ForeignKey(School)
with the new fields:
firm_url = models.URLField('Bio', max_length=200)
firm_name = models.CharField('Firm', max_length=100)
first = models.CharField('First Name', max_length=50)
last = models.CharField('Last Name', max_length=50)
year_graduated = models.IntegerField('Year graduated')
school = models.CharField(max_length=300)
school = models.ForeignKey(School)
to have
from django.db import models
class School(models.Model):
school = models.CharField(max_length=200)
def __unicode__(self):
return self.school
class Lawyer(models.Model):
firm_url = models.URLField('Bio', max_length=200)
firm_name = models.CharField('Firm', max_length=100)
first = models.CharField('First Name', max_length=50)
last = models.CharField('Last Name', max_length=50)
year_graduated = models.IntegerField('Year graduated')
school = models.CharField(max_length=300)
school = models.ForeignKey(School)
class Meta:
ordering = ('last',)
def __unicode__(self):
return self.first
and upload this to the server. Then I will run manage.py syncdb.
And when I open the page I will see the admin as it was before except with new fields.
I assume it is no problem to update the admin.py later to add the new fields:
class LawyerAdmin(admin.ModelAdmin):
fieldsets = [
('Name', {'fields': ['first', 'last', 'firm_name', 'firm_url']}),
('School', {'fields': ['school', 'year_graduated']}),
]
list_display = ('first', 'last', 'school', 'year_graduated', 'firm_name', 'firm_url')
list_filter = ['year_graduated']
#search_fields = ['last', 'first']
search_fields = ['school__school']
search_fields = ['school__lawyer__last']
Thanks again!
|
[
"No, you cannot just replace models.py.\nYou need some kind of schema migration.\nIf you don't use a tool like django south, you'll have to do it manually.\nLook at http://www.sqlite.org/lang_altertable.html\nYou can use manage.py sqlall to see which SQL statements you need.\n",
"Since you're using a sqlite database, and you want to clear the data anyway, this is dead easy. Add your two fields, move your database to a backup location, and re-run manage.py syncdb. It will set up the new database for you. If you need to keep your old data, you are using a more complex database, or you want to manage your change over time, you should look into a schema migration tool like South.\n",
"Run a manage.py sqlall on your project\nThis will dump the SQL create command\nFrom there, look at the dump for your new columns, and use this to help create your Alter Table statements\nSide note, is it kinda weird you have two \"school\" definitions?\n",
"Modifying a model on a live Django environment can be a bit of a hassle, depending on your approach.\nIf you don't mind losing data, a simple manage.py command will do the trick:\npython manage.py reset [app name]\n\nIf, however, you want to retain the data that's already in the database, you'll have to execute some SQL manually to modify the schema. This can get messy to keep track of if you're not careful.\nWhat I've done previously is to write a SQL statement for every change to any model, and record that somewhere along with the date. I also record the last time the schema was modified for any database (in my case, development, staging, and production). To update any one database to the correct schema, I just ran all the schema change SQL from dates after that particular database was last updated.\n",
"You can use python manage.py sqlall <appname> | grep <column name> to get the SQL definition of a particular column.\nThen, you can do something like: ALTER TABLE my_table ADD COLUMN 'column_name' varchar(30);\n(In this case, the manage.py line above returned 'column_name varchar(30);')\n"
] |
[
0,
0,
0,
0,
0
] |
[] |
[] |
[
"django",
"python",
"sqlite"
] |
stackoverflow_0001889622_django_python_sqlite.txt
|
Q:
Problem creating N*N*N list in Python
I'm trying to create a 3-dimensional NNN list in Python, like such:
n=3
l = [[[0,]*n]*n]*n
Unfortunately, this does not seem to properly "clone" the list, as I thought it would:
>>> l
[[[0, 0, 0], [0, 0, 0], [0, 0, 0]], [[0, 0, 0], [0, 0, 0], [0, 0, 0]], [[0, 0, 0], [0, 0, 0], [0, 0, 0]]]
>>> l[0][0][0]=1
>>> l
[[[1, 0, 0], [1, 0, 0], [1, 0, 0]], [[1, 0, 0], [1, 0, 0], [1, 0, 0]], [[1, 0, 0], [1, 0, 0], [1, 0, 0]]]
What am I doing wrong here?
A:
The problem is that * n does a shallow copy of the list. A solution is to use nested loops, or try the numpy library.
A:
If you want to do numerical processing with 3-d matrix you are better of using numpy. It is quite easy:
>>> import numpy
>>> numpy.zeros((3,3,3), dtype=numpy.int)
array([[[0, 0, 0],
[0, 0, 0],
[0, 0, 0]],
[[0, 0, 0],
[0, 0, 0],
[0, 0, 0]],
[[0, 0, 0],
[0, 0, 0],
[0, 0, 0]]])
>>> _[0,0,0]
0
A:
As others have mentioned, it's building the 2nd and 3rd levels with references, not clones. Try:
>>> n = 3
>>> l = [[[0]*n for _ in xrange(n)] for _ in xrange(n)]
>>> l[0][0][0] = 1
>>> l
[[[1, 0, 0], [0, 0, 0], [0, 0, 0]], [[0, 0, 0], [0, 0, 0], [0, 0, 0]], [[0, 0, 0], [0, 0, 0], [0, 0, 0]]]
Or if you want to type a bit less:
>>> l = [[[0]*n for _ in '.'*n] for _ in '.'*n]
A:
It's not cloning the list. It's inserting a reference to the same list over and over. Try creating the list using a set of nested for loops.
A:
I have to second what leonardo-santagada suggested, with the addition that creating N dimensional arrays/lists is very unpythonic and you should reconsider how you're keeping your data and seeing if it doesn't belong better in a class or a list of dictionaries (or dictionaries of lists).
|
Problem creating N*N*N list in Python
|
I'm trying to create a 3-dimensional NNN list in Python, like such:
n=3
l = [[[0,]*n]*n]*n
Unfortunately, this does not seem to properly "clone" the list, as I thought it would:
>>> l
[[[0, 0, 0], [0, 0, 0], [0, 0, 0]], [[0, 0, 0], [0, 0, 0], [0, 0, 0]], [[0, 0, 0], [0, 0, 0], [0, 0, 0]]]
>>> l[0][0][0]=1
>>> l
[[[1, 0, 0], [1, 0, 0], [1, 0, 0]], [[1, 0, 0], [1, 0, 0], [1, 0, 0]], [[1, 0, 0], [1, 0, 0], [1, 0, 0]]]
What am I doing wrong here?
|
[
"The problem is that * n does a shallow copy of the list. A solution is to use nested loops, or try the numpy library.\n",
"If you want to do numerical processing with 3-d matrix you are better of using numpy. It is quite easy:\n>>> import numpy\n>>> numpy.zeros((3,3,3), dtype=numpy.int)\narray([[[0, 0, 0],\n [0, 0, 0],\n [0, 0, 0]],\n\n [[0, 0, 0],\n [0, 0, 0],\n [0, 0, 0]],\n\n [[0, 0, 0],\n [0, 0, 0],\n [0, 0, 0]]])\n>>> _[0,0,0]\n0\n\n",
"As others have mentioned, it's building the 2nd and 3rd levels with references, not clones. Try:\n>>> n = 3\n\n>>> l = [[[0]*n for _ in xrange(n)] for _ in xrange(n)]\n\n>>> l[0][0][0] = 1\n\n>>> l\n[[[1, 0, 0], [0, 0, 0], [0, 0, 0]], [[0, 0, 0], [0, 0, 0], [0, 0, 0]], [[0, 0, 0], [0, 0, 0], [0, 0, 0]]]\n\nOr if you want to type a bit less:\n>>> l = [[[0]*n for _ in '.'*n] for _ in '.'*n]\n\n",
"It's not cloning the list. It's inserting a reference to the same list over and over. Try creating the list using a set of nested for loops.\n",
"I have to second what leonardo-santagada suggested, with the addition that creating N dimensional arrays/lists is very unpythonic and you should reconsider how you're keeping your data and seeing if it doesn't belong better in a class or a list of dictionaries (or dictionaries of lists). \n"
] |
[
5,
4,
3,
2,
2
] |
[] |
[] |
[
"list",
"mutable",
"python"
] |
stackoverflow_0001889080_list_mutable_python.txt
|
Q:
Having models' declarations at two folders in Django
How can you have model declarations at two different directories in Django?
I have the model at the directory Code which contains "init.py", "models.py" and "admin.py".
It is working properly alone.
I want to have the directory History which has the model of the revisions of the given questions. I have the similar files in the directory.
I need to tell Django to use the model at the directory "History" somehow, since I have a ManyToMany relation in the table Questions to the other directory.
I get the following import error
ImportError at /
cannot import name history
Request Method: GET
Request URL: http://127.0.0.1:8000/
Exception Type: ImportError
Exception Value:
cannot import name history
Exception Location: /home/noa/build/CML/../CML/codes/models.py in <module>, line 2
Python Executable: /usr/bin/python
Python Version: 2.6.2
Python Path: ['/home/noa/build/CML', '/usr/lib/python2.6', '/usr/lib/python2.6/plat-linux2', '/usr/lib/python2.6/lib-tk', '/usr/lib/python2.6/lib-old', '/usr/lib/python2.6/lib-dynload', '/usr/lib/python2.6/dist-packages', '/usr/lib/python2.6/dist-packages/PIL', '/usr/lib/python2.6/dist-packages/gst-0.10', '/var/lib/python-support/python2.6', '/usr/lib/python2.6/dist-packages/gtk-2.0', '/var/lib/python-support/python2.6/gtk-2.0', '/var/lib/python-support/python2.6/pyinotify', '/usr/lib/python2.6/dist-packages/wx-2.8-gtk2-unicode', '/usr/local/lib/python2.6/dist-packages']
Server time: Fri, 11 Dec 2009 15:46:30 -0600
A:
Since it sounds like both of your directories are Django apps, and assuming you've put both of them in your INSTALLED_APPS list in settings.py you can refer to them using a string without having to import:
# in code/models.py
class Questions(models.Model):
histories = models.ManyToManyField('history.MyHistoryModel')
Note that the path is case sensitive... so if you app is truly called 'History' you will need to reference it using 'History.MyHistoryModel'.
A:
Generally people just have one "models" directory, or even sometimes just one models file. If you get to the point that you feel you need 2 full directories for your models, it's probably better to start thinking about breaking your one app, into a couple of small apps instead generally. That being said, there's a number of things that could be potentially wrong just with your setup that we can't see.
Anytime I have an import error though, I drop to a python shell and try to import the item. If it fails, then something is either wrong with the module (you'd be surprised how often I forget __init__.py), or it's not properly in your python path.
A:
If the directory is called History, you should change import history to import History, as python imports are case-sensitive (on my Linux box, at least).
|
Having models' declarations at two folders in Django
|
How can you have model declarations at two different directories in Django?
I have the model at the directory Code which contains "init.py", "models.py" and "admin.py".
It is working properly alone.
I want to have the directory History which has the model of the revisions of the given questions. I have the similar files in the directory.
I need to tell Django to use the model at the directory "History" somehow, since I have a ManyToMany relation in the table Questions to the other directory.
I get the following import error
ImportError at /
cannot import name history
Request Method: GET
Request URL: http://127.0.0.1:8000/
Exception Type: ImportError
Exception Value:
cannot import name history
Exception Location: /home/noa/build/CML/../CML/codes/models.py in <module>, line 2
Python Executable: /usr/bin/python
Python Version: 2.6.2
Python Path: ['/home/noa/build/CML', '/usr/lib/python2.6', '/usr/lib/python2.6/plat-linux2', '/usr/lib/python2.6/lib-tk', '/usr/lib/python2.6/lib-old', '/usr/lib/python2.6/lib-dynload', '/usr/lib/python2.6/dist-packages', '/usr/lib/python2.6/dist-packages/PIL', '/usr/lib/python2.6/dist-packages/gst-0.10', '/var/lib/python-support/python2.6', '/usr/lib/python2.6/dist-packages/gtk-2.0', '/var/lib/python-support/python2.6/gtk-2.0', '/var/lib/python-support/python2.6/pyinotify', '/usr/lib/python2.6/dist-packages/wx-2.8-gtk2-unicode', '/usr/local/lib/python2.6/dist-packages']
Server time: Fri, 11 Dec 2009 15:46:30 -0600
|
[
"Since it sounds like both of your directories are Django apps, and assuming you've put both of them in your INSTALLED_APPS list in settings.py you can refer to them using a string without having to import:\n# in code/models.py\n\nclass Questions(models.Model):\n histories = models.ManyToManyField('history.MyHistoryModel')\n\nNote that the path is case sensitive... so if you app is truly called 'History' you will need to reference it using 'History.MyHistoryModel'.\n",
"Generally people just have one \"models\" directory, or even sometimes just one models file. If you get to the point that you feel you need 2 full directories for your models, it's probably better to start thinking about breaking your one app, into a couple of small apps instead generally. That being said, there's a number of things that could be potentially wrong just with your setup that we can't see.\nAnytime I have an import error though, I drop to a python shell and try to import the item. If it fails, then something is either wrong with the module (you'd be surprised how often I forget __init__.py), or it's not properly in your python path.\n",
"If the directory is called History, you should change import history to import History, as python imports are case-sensitive (on my Linux box, at least).\n"
] |
[
2,
0,
0
] |
[] |
[] |
[
"django",
"import",
"models",
"python"
] |
stackoverflow_0001891139_django_import_models_python.txt
|
Q:
Python Exception Propagation
I'm building a tool where as exceptions propagate upwards, new data about the context of the exception gets added to the exception. The issue is, by the time the exception gets to the top level, all of the extra context data is there, but only the very latest stack trace is shown. Is there an easy way to have an exception show the original stack trace in which it was thrown instead of the last stack trace, or should I do something like grab the original stack trace the first time that the exception propagates?
For example, the following code:
def a():
return UNBOUND
def b():
try:
a()
except Exception as e:
raise e
b()
yields the following exception:
Traceback (most recent call last):
File "test.py", line 8, in <module>
b()
File "test.py", line 7, in b
raise e
NameError: global name 'UNBOUND' is not defined
where, ideally, I'd like to somehow show the user this:
Traceback (most recent call last):
File "test.py", line 8, in <module>
File "test.py", line 2, in a
return UNBOUND
NameError: global name 'UNBOUND' is not defined
As that points the user to the line that the error originally occurred on.
A:
Python exceptions are a bit like java, there is a way to cause the exception to be rethrown without truncating the stack.
Just use raise without an argument. The result it:
Traceback (most recent call last):
File "./exc.py", line 11, in <module>
b()
File "./exc.py", line 7, in b
a()
File "./exc.py", line 4, in a
return UNBOUND
NameError: global name 'UNBOUND' is not defined
You can modify some things about the e object, even if you just raise without that argument - for example:
e.args = ("hi!",)
raise
will actually change the exception message. You can probably change the other options too this way - without destroying the stack.
|
Python Exception Propagation
|
I'm building a tool where as exceptions propagate upwards, new data about the context of the exception gets added to the exception. The issue is, by the time the exception gets to the top level, all of the extra context data is there, but only the very latest stack trace is shown. Is there an easy way to have an exception show the original stack trace in which it was thrown instead of the last stack trace, or should I do something like grab the original stack trace the first time that the exception propagates?
For example, the following code:
def a():
return UNBOUND
def b():
try:
a()
except Exception as e:
raise e
b()
yields the following exception:
Traceback (most recent call last):
File "test.py", line 8, in <module>
b()
File "test.py", line 7, in b
raise e
NameError: global name 'UNBOUND' is not defined
where, ideally, I'd like to somehow show the user this:
Traceback (most recent call last):
File "test.py", line 8, in <module>
File "test.py", line 2, in a
return UNBOUND
NameError: global name 'UNBOUND' is not defined
As that points the user to the line that the error originally occurred on.
|
[
"Python exceptions are a bit like java, there is a way to cause the exception to be rethrown without truncating the stack.\nJust use raise without an argument. The result it:\nTraceback (most recent call last):\n File \"./exc.py\", line 11, in <module>\n b()\n File \"./exc.py\", line 7, in b\n a()\n File \"./exc.py\", line 4, in a\n return UNBOUND\nNameError: global name 'UNBOUND' is not defined\n\nYou can modify some things about the e object, even if you just raise without that argument - for example:\ne.args = (\"hi!\",)\nraise \n\nwill actually change the exception message. You can probably change the other options too this way - without destroying the stack.\n"
] |
[
37
] |
[] |
[] |
[
"exception",
"python"
] |
stackoverflow_0001891572_exception_python.txt
|
Q:
Creating an Python/py2app application that simply opens a terminal on launch?
I've written a nice Python application that is basically an HTTP proxy for SMS modems, and I'd like to make it a double-clickable application on Macs. So far I've been including a .commmand file which is double-clickable, which basically consists of
cd `dirname $0`
(sleep 8;open http://127.0.0.1:8080/)&
mac/slingshotsms.app/Contents/MacOS/slingshotsms
How can I make the main .app executable call a different place / or what's the easiest way to make an application that is basically a wrapper for a terminal utility and only displays its output? Currently double-clicking on the application will use the open utility on Macs - I want to emulate the behavior of double-clicking on Contents/MacOS/slingshotsms when double-clicking on the application icon. any tips?
A:
If you're looking for 'easy', try just giving your python script a .command suffix, and make sure it's executable. For example:
#!/usr/bin/env python
# file: hello.command
print 'hello world'
If you're looking for 'polished', then you probably want to learn about Launch Services, PyObjC, Interface Builder, NIB files, app wrappers, and all sorts of Mac OS X-specific technology details. But, note that PyObjC is nearly impossible to use for anything non-trivial without already knowing, more or less, how to do the same task using the Objective-C Cocoa APIs. PyObjC is a fairly thin wrapper around those APIs, and you have to know the Cocoa idioms / design patterns to understand how the moving parts fit together.
A:
If you don't actually need a terminal, but instead just want an app wrapper around a script, have a look at Platypus
A:
Write an AppleScript application that launches Terminal and runs your Python script (which will be inside the application's bundle).
|
Creating an Python/py2app application that simply opens a terminal on launch?
|
I've written a nice Python application that is basically an HTTP proxy for SMS modems, and I'd like to make it a double-clickable application on Macs. So far I've been including a .commmand file which is double-clickable, which basically consists of
cd `dirname $0`
(sleep 8;open http://127.0.0.1:8080/)&
mac/slingshotsms.app/Contents/MacOS/slingshotsms
How can I make the main .app executable call a different place / or what's the easiest way to make an application that is basically a wrapper for a terminal utility and only displays its output? Currently double-clicking on the application will use the open utility on Macs - I want to emulate the behavior of double-clicking on Contents/MacOS/slingshotsms when double-clicking on the application icon. any tips?
|
[
"If you're looking for 'easy', try just giving your python script a .command suffix, and make sure it's executable. For example:\n#!/usr/bin/env python\n# file: hello.command\n\nprint 'hello world'\n\nIf you're looking for 'polished', then you probably want to learn about Launch Services, PyObjC, Interface Builder, NIB files, app wrappers, and all sorts of Mac OS X-specific technology details. But, note that PyObjC is nearly impossible to use for anything non-trivial without already knowing, more or less, how to do the same task using the Objective-C Cocoa APIs. PyObjC is a fairly thin wrapper around those APIs, and you have to know the Cocoa idioms / design patterns to understand how the moving parts fit together.\n",
"If you don't actually need a terminal, but instead just want an app wrapper around a script, have a look at Platypus\n",
"Write an AppleScript application that launches Terminal and runs your Python script (which will be inside the application's bundle).\n"
] |
[
2,
1,
0
] |
[] |
[] |
[
"macos",
"py2app",
"python"
] |
stackoverflow_0001882644_macos_py2app_python.txt
|
Q:
Big List Of Portability in Python
I thought it would be a good idea to compile a list of things to watch out for when making a Python app portable. There are a lot of subtle 'gotchas' in portability that are only discovered through experience and thorough testing; there needs to be some sort of list addressing the more common ones.
Please post one gotcha (with its fix) per comment.
A:
If you deal with binary file formats in Python, note that the struct and array modules uses machine dependent size and endianness. struct can be used portably by always using < or > in the format string. array can't. It will probably be portable for arrays of bytes, but the documentation makes no such guarantee.
A:
'Universal newline support' (as descrived in PEP278) can come in handy for portability reasons.
It makes sure python code only gets \n:
christophe@orion:~$ printf 'testing pep278\r\n' > test.txt
christophe@orion:~$ python
Python 2.6.2 (release26-maint, Apr 19 2009, 01:56:41)
[GCC 4.3.3] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> open('test.txt').read()
'testing pep278\r\n'
>>> open('test.txt','U').read()
'testing pep278\n'
A:
Getting away from the syntax side of things, I think the biggest thing to watch out for is that typically when people think of python, they might not think of all the libraries it is composed of.
Many python packages depend on C libraries which may or may not be cross platform compatible. In addition, Python runs under Java through Jython, and .Net through IronPython. Unless libraries are written in pure python, they will not, in many cases, work on anything other than the C based version of python.
A:
Some modules are not cross-platform. Two that come to mind are both curses (Linux) and msvcrt (Windows). The fix to this simple problem is simply not to use them but find an alternative instead.
A:
Unix vs. Windows: Using Popen in the subprocess module will exhibit different behavior when shell=True. I won't offer a fix because the discussion is covered so well here, but it's one of those areas that can unexpectedly bite you.
A:
I'll start off:
Windows uses backslashes for path separators --> '\'
Unix uses forward slashes for path separators --> '/'
The os module comes with os.sep, which contains the path separator for the current platform that the script is being run on. Use os.sep instead of forward or back slashes. os.path.join will join two or more path components this way.
A:
There are subtle differences in UCS2 and UCS4 (Windows and Linux, for example) builds of Python due to bugs, conflicting or deprecated standards, etc.
Example: Issue 3297
unicodetest.py:
#-*- coding: utf-8 -*-
print 'Result:', u'𐄣' == u'\U00010123'
print 'Len:', len(u'𐄣'), len(u'\U00010123')
print 'Repr:', repr(u'𐄣'), repr(u'\U00010123')
Output (Python 2.6, Linux):
Result: False
Len: 2 1
Repr: u'\ud800\udd23' u'\U00010123'
|
Big List Of Portability in Python
|
I thought it would be a good idea to compile a list of things to watch out for when making a Python app portable. There are a lot of subtle 'gotchas' in portability that are only discovered through experience and thorough testing; there needs to be some sort of list addressing the more common ones.
Please post one gotcha (with its fix) per comment.
|
[
"If you deal with binary file formats in Python, note that the struct and array modules uses machine dependent size and endianness. struct can be used portably by always using < or > in the format string. array can't. It will probably be portable for arrays of bytes, but the documentation makes no such guarantee.\n",
"'Universal newline support' (as descrived in PEP278) can come in handy for portability reasons.\nIt makes sure python code only gets \\n:\nchristophe@orion:~$ printf 'testing pep278\\r\\n' > test.txt\nchristophe@orion:~$ python\nPython 2.6.2 (release26-maint, Apr 19 2009, 01:56:41) \n[GCC 4.3.3] on linux2\nType \"help\", \"copyright\", \"credits\" or \"license\" for more information.\n>>> open('test.txt').read()\n'testing pep278\\r\\n'\n>>> open('test.txt','U').read()\n'testing pep278\\n'\n\n",
"Getting away from the syntax side of things, I think the biggest thing to watch out for is that typically when people think of python, they might not think of all the libraries it is composed of. \nMany python packages depend on C libraries which may or may not be cross platform compatible. In addition, Python runs under Java through Jython, and .Net through IronPython. Unless libraries are written in pure python, they will not, in many cases, work on anything other than the C based version of python.\n",
"Some modules are not cross-platform. Two that come to mind are both curses (Linux) and msvcrt (Windows). The fix to this simple problem is simply not to use them but find an alternative instead.\n",
"Unix vs. Windows: Using Popen in the subprocess module will exhibit different behavior when shell=True. I won't offer a fix because the discussion is covered so well here, but it's one of those areas that can unexpectedly bite you.\n",
"I'll start off:\nWindows uses backslashes for path separators --> '\\'\nUnix uses forward slashes for path separators --> '/'\nThe os module comes with os.sep, which contains the path separator for the current platform that the script is being run on. Use os.sep instead of forward or back slashes. os.path.join will join two or more path components this way.\n",
"There are subtle differences in UCS2 and UCS4 (Windows and Linux, for example) builds of Python due to bugs, conflicting or deprecated standards, etc.\nExample: Issue 3297\nunicodetest.py: \n#-*- coding: utf-8 -*-\nprint 'Result:', u'𐄣' == u'\\U00010123'\nprint 'Len:', len(u'𐄣'), len(u'\\U00010123')\nprint 'Repr:', repr(u'𐄣'), repr(u'\\U00010123')\nOutput (Python 2.6, Linux):\nResult: False\nLen: 2 1\nRepr: u'\\ud800\\udd23' u'\\U00010123'\n\n"
] |
[
4,
3,
2,
2,
2,
1,
1
] |
[] |
[] |
[
"portability",
"python"
] |
stackoverflow_0001883118_portability_python.txt
|
Q:
How do derived class constructors work in python?
I have the following base class:
class NeuralNetworkBase:
def __init__(self, numberOfInputs, numberOfHiddenNeurons, numberOfOutputs):
self.inputLayer = numpy.zeros(shape = (numberOfInputs))
self.hiddenLayer = numpy.zeros(shape = (numberOfHiddenNeurons))
self.outputLayer = numpy.zeros(shape = (numberOfOutputs))
self.hiddenLayerWeights = numpy.zeros(shape = (numberOfInputs, numberOfHiddenNeurons))
self.outputLayerWeights = numpy.zeros(shape = (numberOfHiddenNeurons, numberOfOutputs))
now, I have a derived class with the following code:
class NeuralNetworkBackPropagation(NeuralNetworkBase):
def __init__(self, numberOfInputs, numberOfHiddenNeurons, numberOfOutputs):
self.outputLayerDeltas = numpy.zeros(shape = (numberOfOutputs))
self.hiddenLayerDeltas = numpy.zeros(shape = (numberOfHiddenNeurons))
But when I instantiate NeuralNetworkBackPropagation I'd like that both constructors get called.This is, I don't want to override the base class' constructor. Does python call by default the base class constructor's when running the derived class' one? Do I have to implicitly do it inside the derived class constructor?
A:
Does python call by default the base
class constructor's when running the
derived class' one? Do I have to
implicitly do it inside the derived
class constructor?
No and yes.
This is consistent with the way Python handles other overridden methods - you have to explicitly call any method from the base class that's been overridden if you want that functionality to be used in the inherited class.
Your constructor should look something like this:
def __init__(self, numberOfInputs, numberOfHiddenNeurons, numberOfOutputs):
NeuralNetworkBase.__init__(self, numberOfInputers, numberOfHiddenNeurons, numberOfOutputs)
self.outputLayerDeltas = numpy.zeros(shape = (numberOfOutputs))
self.hiddenLayerDeltas = numpy.zeros(shape = (numberOfHiddenNeurons))
Alternatively, you could use Python's super function to achieve the same thing, but you need to be careful when using it.
A:
You will have to put this in the __init__() method of NeuralNetworkBackPropagation, that is to call the __init__() method of the parent class (NeuralNetworkBase):
NeuralNetworkBase.__init__(self, numberOfInputs, numberOfHiddenNeurons, numberOfOutputs)
The constructor of the parent class is always called automatically unless you overwrite it in the child class. If you overwrite it in the child class and want to call the parent's class constructor as well, then you'll have to do it as I showed above.
|
How do derived class constructors work in python?
|
I have the following base class:
class NeuralNetworkBase:
def __init__(self, numberOfInputs, numberOfHiddenNeurons, numberOfOutputs):
self.inputLayer = numpy.zeros(shape = (numberOfInputs))
self.hiddenLayer = numpy.zeros(shape = (numberOfHiddenNeurons))
self.outputLayer = numpy.zeros(shape = (numberOfOutputs))
self.hiddenLayerWeights = numpy.zeros(shape = (numberOfInputs, numberOfHiddenNeurons))
self.outputLayerWeights = numpy.zeros(shape = (numberOfHiddenNeurons, numberOfOutputs))
now, I have a derived class with the following code:
class NeuralNetworkBackPropagation(NeuralNetworkBase):
def __init__(self, numberOfInputs, numberOfHiddenNeurons, numberOfOutputs):
self.outputLayerDeltas = numpy.zeros(shape = (numberOfOutputs))
self.hiddenLayerDeltas = numpy.zeros(shape = (numberOfHiddenNeurons))
But when I instantiate NeuralNetworkBackPropagation I'd like that both constructors get called.This is, I don't want to override the base class' constructor. Does python call by default the base class constructor's when running the derived class' one? Do I have to implicitly do it inside the derived class constructor?
|
[
"\nDoes python call by default the base\n class constructor's when running the\n derived class' one? Do I have to\n implicitly do it inside the derived\n class constructor?\n\nNo and yes.\nThis is consistent with the way Python handles other overridden methods - you have to explicitly call any method from the base class that's been overridden if you want that functionality to be used in the inherited class.\nYour constructor should look something like this:\ndef __init__(self, numberOfInputs, numberOfHiddenNeurons, numberOfOutputs):\n NeuralNetworkBase.__init__(self, numberOfInputers, numberOfHiddenNeurons, numberOfOutputs)\n self.outputLayerDeltas = numpy.zeros(shape = (numberOfOutputs))\n self.hiddenLayerDeltas = numpy.zeros(shape = (numberOfHiddenNeurons))\n\nAlternatively, you could use Python's super function to achieve the same thing, but you need to be careful when using it.\n",
"You will have to put this in the __init__() method of NeuralNetworkBackPropagation, that is to call the __init__() method of the parent class (NeuralNetworkBase):\nNeuralNetworkBase.__init__(self, numberOfInputs, numberOfHiddenNeurons, numberOfOutputs)\n\nThe constructor of the parent class is always called automatically unless you overwrite it in the child class. If you overwrite it in the child class and want to call the parent's class constructor as well, then you'll have to do it as I showed above.\n"
] |
[
38,
7
] |
[] |
[] |
[
"base_class",
"constructor",
"derived_class",
"python"
] |
stackoverflow_0001892269_base_class_constructor_derived_class_python.txt
|
Q:
Where to put a Django template's dependent files?
My Django templates use a lot of related stuff: images, style sheets, etc.
Where should I put these file, or how should I refer to them in the template itself?
For now I'm using the development server.
I know it's a really common thing, but I can't really figure it out.
A:
I put them inside a folder named static, which is in the web project's top level folder.
Example:
/static/img/
/static/js/
/static/css/
/templates/
urls.py
settings.py
I then have the following rule in my urls.py file:
(r'^static/(?P<path>.*)$', 'django.views.static.serve', {'document_root': settings.MEDIA_ROOT}),
My settings.py contains:
MEDIA_ROOT = os.path.join(os.path.dirname(__file__), 'static').replace('\\', '/')
ADMIN_MEDIA_ROOT = os.path.join(os.path.dirname(__file__), 'static/admin').replace('\\', '/')
A:
Maybe you can read the doc http://docs.djangoproject.com/en/dev/howto/static-files/#howto-static-files
A:
We put ours under /media. Everything that is specifically tied to the layout of the sites is further separated. Of course none of this static content is served by Django on the production site. They often aren't even on the same physical server.
/media
/images - this is for content-specific images
/video - these next 2 are normally symlinks to a /big_content folder ...
/audio - so that they aren't included in our mercurial repository.
/layout - everything that is tied to the basic templates.
/css
/js
/images
|
Where to put a Django template's dependent files?
|
My Django templates use a lot of related stuff: images, style sheets, etc.
Where should I put these file, or how should I refer to them in the template itself?
For now I'm using the development server.
I know it's a really common thing, but I can't really figure it out.
|
[
"I put them inside a folder named static, which is in the web project's top level folder. \nExample: \n\n/static/img/\n /static/js/\n /static/css/\n /templates/\n urls.py\n settings.py \n\nI then have the following rule in my urls.py file:\n(r'^static/(?P<path>.*)$', 'django.views.static.serve', {'document_root': settings.MEDIA_ROOT}),\n\nMy settings.py contains:\nMEDIA_ROOT = os.path.join(os.path.dirname(__file__), 'static').replace('\\\\', '/')\nADMIN_MEDIA_ROOT = os.path.join(os.path.dirname(__file__), 'static/admin').replace('\\\\', '/')\n\n",
"Maybe you can read the doc http://docs.djangoproject.com/en/dev/howto/static-files/#howto-static-files\n",
"We put ours under /media. Everything that is specifically tied to the layout of the sites is further separated. Of course none of this static content is served by Django on the production site. They often aren't even on the same physical server.\n/media\n /images - this is for content-specific images\n /video - these next 2 are normally symlinks to a /big_content folder ...\n /audio - so that they aren't included in our mercurial repository.\n /layout - everything that is tied to the basic templates.\n /css\n /js\n /images\n\n"
] |
[
5,
2,
0
] |
[] |
[] |
[
"django",
"django_templates",
"python"
] |
stackoverflow_0001891884_django_django_templates_python.txt
|
Q:
What does "result.status_code == 200" in Python mean?
In this little piece of code, what is the fourth line all about?
from google.appengine.api import urlfetch
url = "http://www.google.com/"
result = urlfetch.fetch(url)
if result.status_code == 200:
doSomethingWithResult(result.content)
A:
It's a HTTP status code, it means "OK" (EG: The server successfully answered the http request).
See a list of them here on wikipedia
A:
Whoever wrote that should have used a constant instead of a magic number. The httplib module has all the http response codes.
E.g.:
>>> import httplib
>>> httplib.OK
200
>>> httplib.NOT_FOUND
404
A:
200 is the HTTP status code for "OK", a successful response. (Other codes you may be familiar with are 404 Not Found, 403 Forbidden, and 500 Internal Server Error.)
See RFC 2616 for more information.
|
What does "result.status_code == 200" in Python mean?
|
In this little piece of code, what is the fourth line all about?
from google.appengine.api import urlfetch
url = "http://www.google.com/"
result = urlfetch.fetch(url)
if result.status_code == 200:
doSomethingWithResult(result.content)
|
[
"It's a HTTP status code, it means \"OK\" (EG: The server successfully answered the http request).\nSee a list of them here on wikipedia\n",
"Whoever wrote that should have used a constant instead of a magic number. The httplib module has all the http response codes.\nE.g.:\n>>> import httplib\n>>> httplib.OK\n200\n>>> httplib.NOT_FOUND\n404\n\n",
"200 is the HTTP status code for \"OK\", a successful response. (Other codes you may be familiar with are 404 Not Found, 403 Forbidden, and 500 Internal Server Error.)\nSee RFC 2616 for more information.\n"
] |
[
16,
8,
6
] |
[] |
[] |
[
"http",
"python"
] |
stackoverflow_0001892161_http_python.txt
|
Q:
Web.py on shared hosting
I just built a small app with the very cool and minimalistic web.py.
I am using a cheap shared hosting package (at WebFaction) and have installed web.py via virtualenv. I cannot use the system python since I need additional packages which I'm not allowed to install into the system python.
So now I start my app with
/home/me/mypython/python myapp.py <myport>
It feels like a cumbersome solution, and I'm not sure how much traffic this setup can take. Any general hints?
Thanks in advance
A:
Is there a reason you're not using fastcgi? That's probably considerably better than trying to use some high-numbered port, particularly since your webhost may not be very happy about that at all. There are a few notes on doing that (on dreamhost, but it should be similar for you) in this post:
http://thefire.us/archives/261
|
Web.py on shared hosting
|
I just built a small app with the very cool and minimalistic web.py.
I am using a cheap shared hosting package (at WebFaction) and have installed web.py via virtualenv. I cannot use the system python since I need additional packages which I'm not allowed to install into the system python.
So now I start my app with
/home/me/mypython/python myapp.py <myport>
It feels like a cumbersome solution, and I'm not sure how much traffic this setup can take. Any general hints?
Thanks in advance
|
[
"Is there a reason you're not using fastcgi? That's probably considerably better than trying to use some high-numbered port, particularly since your webhost may not be very happy about that at all. There are a few notes on doing that (on dreamhost, but it should be similar for you) in this post:\nhttp://thefire.us/archives/261\n"
] |
[
2
] |
[] |
[] |
[
"performance",
"python",
"web.py"
] |
stackoverflow_0001892805_performance_python_web.py.txt
|
Q:
sending http request to apache through a python script
All,
How do we send a http request through a python script.which will login and in turn call another link?
Thanks.
A:
I find that Urllib2 suffices in most cases. It has great support for passwords, authentication and cookies. Cookielib might help too.
A:
Have you looked at httplib? urllib may also be worth looking at as it is a slightly higher level interface.
|
sending http request to apache through a python script
|
All,
How do we send a http request through a python script.which will login and in turn call another link?
Thanks.
|
[
"I find that Urllib2 suffices in most cases. It has great support for passwords, authentication and cookies. Cookielib might help too.\n",
"Have you looked at httplib? urllib may also be worth looking at as it is a slightly higher level interface.\n"
] |
[
1,
0
] |
[] |
[] |
[
"httprequest",
"python"
] |
stackoverflow_0001892958_httprequest_python.txt
|
Q:
Get window title with python?
I'm trying to write a python program that checks every X seconds if the 'window title' for 'last.fm' (http://www.last.fm/download) changed, if it did (or it's the first time I run the program) it should use use the string captured from the window title to search for the song's lyrics and display them to the user.
I'm currently using KDE4 as my desktop environment and I just need to be 'pointed in the right direction' on how I can capture the string that belongs to the window title for last.fm client.
Thanks!
A:
You can use the wmctrl utility through the subprocess module. You can type wmctrl -l into a terminal and see the output you can get from it.
A:
I think by using a automation framework you may be able to achieve this as a subset.
e.g. try dogtail(https://fedorahosted.org/dogtail/), it can focus on windows by name, click on buttons by name, so in the src code you may be able to see how to get title.
A:
Have a look at X11 utilities, specifically xlsclients and xprop.
As an example, this is the shell commands I used to get info about my firefox
window:
id_=$(xlsclients -al|grep "Command: firefox-bin" -A1 -B4|head -n1|cut -d ' ' -f 2|tr -d ':')
xprop -id "$_id"
Output:
SM_CLIENT_ID(STRING) = "1181f048b9000125508490000000037360008"
WM_CLASS(STRING) = "firefox-bin", "Firefox-bin"
WM_COMMAND(STRING) = { "firefox-bin" }
WM_CLIENT_LEADER(WINDOW): window id # 0x0
_NET_WM_PID(CARDINAL) = 4265
WM_LOCALE_NAME(STRING) = "no_NO"
WM_CLIENT_MACHINE(STRING) = "gnom.ifi.uio.no"
WM_NORMAL_HINTS(WM_SIZE_HINTS):
program specified size: 10 by 10
WM_PROTOCOLS(ATOM): protocols WM_DELETE_WINDOW, WM_TAKE_FOCUS, _NET_WM_PING
WM_ICON_NAME(STRING) = "firefox-bin"
_NET_WM_ICON_NAME(UTF8_STRING) = 0x66, 0x69, 0x72, 0x65, 0x66, 0x6f, 0x78, 0x2d, 0x62, 0x69, 0x6e
WM_NAME(STRING) = "Firefox"
_NET_WM_NAME(UTF8_STRING) = 0x46, 0x69, 0x72, 0x65, 0x66, 0x6f, 0x78
A:
Try using dcop and piloting kwin. You can probably list all the window titles.
See the following for an example on how to use dcop:
http://docs.kde.org/stable/en/kdegraphics/ksnapshot/dcop.html
A:
another answer maybe to check if the application publishes the song change to DBus. if it does then you can just listen for the event and act on that.
|
Get window title with python?
|
I'm trying to write a python program that checks every X seconds if the 'window title' for 'last.fm' (http://www.last.fm/download) changed, if it did (or it's the first time I run the program) it should use use the string captured from the window title to search for the song's lyrics and display them to the user.
I'm currently using KDE4 as my desktop environment and I just need to be 'pointed in the right direction' on how I can capture the string that belongs to the window title for last.fm client.
Thanks!
|
[
"You can use the wmctrl utility through the subprocess module. You can type wmctrl -l into a terminal and see the output you can get from it.\n",
"I think by using a automation framework you may be able to achieve this as a subset.\ne.g. try dogtail(https://fedorahosted.org/dogtail/), it can focus on windows by name, click on buttons by name, so in the src code you may be able to see how to get title.\n",
"Have a look at X11 utilities, specifically xlsclients and xprop.\nAs an example, this is the shell commands I used to get info about my firefox \nwindow:\nid_=$(xlsclients -al|grep \"Command: firefox-bin\" -A1 -B4|head -n1|cut -d ' ' -f 2|tr -d ':')\nxprop -id \"$_id\"\n\nOutput:\nSM_CLIENT_ID(STRING) = \"1181f048b9000125508490000000037360008\"\nWM_CLASS(STRING) = \"firefox-bin\", \"Firefox-bin\"\nWM_COMMAND(STRING) = { \"firefox-bin\" }\nWM_CLIENT_LEADER(WINDOW): window id # 0x0\n_NET_WM_PID(CARDINAL) = 4265\nWM_LOCALE_NAME(STRING) = \"no_NO\"\nWM_CLIENT_MACHINE(STRING) = \"gnom.ifi.uio.no\"\nWM_NORMAL_HINTS(WM_SIZE_HINTS):\n program specified size: 10 by 10\nWM_PROTOCOLS(ATOM): protocols WM_DELETE_WINDOW, WM_TAKE_FOCUS, _NET_WM_PING\nWM_ICON_NAME(STRING) = \"firefox-bin\"\n_NET_WM_ICON_NAME(UTF8_STRING) = 0x66, 0x69, 0x72, 0x65, 0x66, 0x6f, 0x78, 0x2d, 0x62, 0x69, 0x6e\nWM_NAME(STRING) = \"Firefox\"\n_NET_WM_NAME(UTF8_STRING) = 0x46, 0x69, 0x72, 0x65, 0x66, 0x6f, 0x78\n\n",
"Try using dcop and piloting kwin. You can probably list all the window titles.\nSee the following for an example on how to use dcop:\n http://docs.kde.org/stable/en/kdegraphics/ksnapshot/dcop.html\n",
"another answer maybe to check if the application publishes the song change to DBus. if it does then you can just listen for the event and act on that. \n"
] |
[
4,
2,
1,
0,
0
] |
[] |
[] |
[
"kde_plasma",
"python"
] |
stackoverflow_0001541784_kde_plasma_python.txt
|
Q:
Basic Python Numbers
Why does 0.1 + 0.1 + 0.1 - 0.3 evaluate to
5.5511151231257827e-17 in Python?
A:
Because that's how floating point numbers work. If you want precise numbers, use the decimal module. If you want to use floating point numbers, you have to remember to round them to a specific precision when you are displaying them.
>>> print '%.2f' % (0.1+0.1+0.1-0.3,)
0.00
A:
This is a problem with floating point numbers in general. See this section on Wikipedia for a description. Roughly speaking - there are rounding errors. Notice that the number you gave us was very small - about 0.00000000000000005551115123 . Here is a more technical paper about the subject.
A:
The answer is here: What Every Computer Scientist Should Know About Floating-Point Arithmetic
A:
You might be interested in knowing that Python 3 has improved the situation by changing how repr works. It will now give you the shortest string representation that will be converted back to the original float:
Python 3.1.1+ (r311:74480, Oct 11 2009, 20:19:13)
[GCC 4.3.4] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> 0.1
'0.1'
Older versions behave like this:
Python 2.6.4 (r264:75706, Oct 28 2009, 22:19:17)
[GCC 4.3.4] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> 0.1
'0.10000000000000001'
It is only the output of repr (called implicitly when you enter a value in the interactive interpreter) that has changed. The underlying values are still IEEE-754 floating-point numbers, and they still have the usual limitations:
Python 3.1.1+ (r311:74480, Oct 11 2009, 20:19:13)
[GCC 4.3.4] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> 0.1
0.1
>>> 0.2
0.2
>>> 0.3
0.3
>>> 0.1 + 0.2
0.30000000000000004
>>> 0.1 + 0.2 - 0.3
5.551115123125783e-17
A:
Because of the way floating points numbers are represented in a computer. It's not just a Python thing.
A:
As an example, consider representing 1/3 as a scientific number in base 10. With only a finite number of digits (say, 10), you'll wind up with a rounding error. Say 1/3 ≈ 0.3333333333e0. Then 1/3+1/3+1/3 (after first converting to decimal expansions) is represented as 0.9999999999e0, but 1 is 1.0e0. Similarly, 1/7 ≈ 0.1428571429e0, and 1/7+1/7 would be 0.2857142858e0, but the representation for 2/7 would be 0.2857142857e0. In both cases, the sum is off by 1e-10.
|
Basic Python Numbers
|
Why does 0.1 + 0.1 + 0.1 - 0.3 evaluate to
5.5511151231257827e-17 in Python?
|
[
"Because that's how floating point numbers work. If you want precise numbers, use the decimal module. If you want to use floating point numbers, you have to remember to round them to a specific precision when you are displaying them.\n>>> print '%.2f' % (0.1+0.1+0.1-0.3,)\n0.00\n\n",
"This is a problem with floating point numbers in general. See this section on Wikipedia for a description. Roughly speaking - there are rounding errors. Notice that the number you gave us was very small - about 0.00000000000000005551115123 . Here is a more technical paper about the subject.\n",
"The answer is here: What Every Computer Scientist Should Know About Floating-Point Arithmetic\n",
"You might be interested in knowing that Python 3 has improved the situation by changing how repr works. It will now give you the shortest string representation that will be converted back to the original float:\n\nPython 3.1.1+ (r311:74480, Oct 11 2009, 20:19:13) \n[GCC 4.3.4] on linux2\nType \"help\", \"copyright\", \"credits\" or \"license\" for more information.\n>>> 0.1\n'0.1'\n\nOlder versions behave like this:\n\nPython 2.6.4 (r264:75706, Oct 28 2009, 22:19:17) \n[GCC 4.3.4] on linux2\nType \"help\", \"copyright\", \"credits\" or \"license\" for more information.\n>>> 0.1\n'0.10000000000000001'\n\nIt is only the output of repr (called implicitly when you enter a value in the interactive interpreter) that has changed. The underlying values are still IEEE-754 floating-point numbers, and they still have the usual limitations:\n\nPython 3.1.1+ (r311:74480, Oct 11 2009, 20:19:13) \n[GCC 4.3.4] on linux2\nType \"help\", \"copyright\", \"credits\" or \"license\" for more information.\n>>> 0.1\n0.1\n>>> 0.2\n0.2\n>>> 0.3\n0.3\n>>> 0.1 + 0.2\n0.30000000000000004\n>>> 0.1 + 0.2 - 0.3\n5.551115123125783e-17\n\n",
"Because of the way floating points numbers are represented in a computer. It's not just a Python thing.\n",
"As an example, consider representing 1/3 as a scientific number in base 10. With only a finite number of digits (say, 10), you'll wind up with a rounding error. Say 1/3 ≈ 0.3333333333e0. Then 1/3+1/3+1/3 (after first converting to decimal expansions) is represented as 0.9999999999e0, but 1 is 1.0e0. Similarly, 1/7 ≈ 0.1428571429e0, and 1/7+1/7 would be 0.2857142858e0, but the representation for 2/7 would be 0.2857142857e0. In both cases, the sum is off by 1e-10. \n"
] |
[
15,
7,
4,
3,
2,
0
] |
[] |
[] |
[
"floating_point",
"python"
] |
stackoverflow_0001893094_floating_point_python.txt
|
Q:
How to implement a stdin, stdout wrapper?
I have an interactive program that runs stdin and stdout.
I need to create wrapper that will send X to it's stdin, check that it prints Y and then
redirects wrapper's stdin and stdout to program's stdin and stdout just like program would be executed directly.
How to implement this ? X and Y can be hardcoded. Bash? Python?
Edit: I can't run the program twice. It has to be one instance.
Here is the pseudocode:
def wrap(cmd, in, expected_out):
p = exec(cmd)
p.writeToStdin(in)
out = p.readBytes (expected_out.size())
if (out != expected_out) return fail;
# if the above 4 lines would be absent or (in == "" and out == "")
# then this wrapper would be exactly like direct execution of cmd
connectpipe (p.stdout, stdout)
connectpipe (stdin, p.stdin)
p.continueExecution()
A:
Expect is made for automating the running of other programs - essentially you write something like, in plain text,
Start this program. When it prints out the word "username", send it my username. When it sends "password", send it my password.
It's really great for driving other programs.
A:
Assuming X and Y are files, and that you can invoke the program more than once:
#!/bin/bash
test "`program <X`" = "`cat Y`" && program
Or, to fail more verbosely:
#!/bin/bash
if [[ `program <X` != `cat Y` ]]; then
echo -e "Assertion that input X produces Y failed, exiting."
exit 1
fi
program
If you only invoke the program once, Expect is a much simpler alternative than reassigning standard file I/O on the fly.
A:
You can overwrite the sys module's stdin and stdout
import sys
sys.stdin, sys.stdout = wrapper.stdin, wrapper.stdout
These need to be file objects opened for reading and writing respectively.
The original stdin and stdout are found at
sys.stdin, sys.stdout = sys.__stdin__, sys.__stdout__
A:
I'm a little confused as to what exactly you're trying to achieve; as I understand you wish to:
Start the wrapper program specifying the input X, and expected output Y.
Have the wrapper initiate the target program attaching input X to it's stdin, and verifying that it's output matches Y.
Have the target program return, and after output is verified, rerun it from the same instance of the wrapper program, this time using the wrapper programs stdin and stdout.
If this is the case you want to do this:
Have the wrapper program open pipes for the stdin and stdout of the target program.
Fork, and close the appropriate ends of said pipes.
Have the parent process and verify the output, while the child exec()s and executes thh target program.
Wait for the child process to terminate when it's stdout closes.
Have the wrapper program exec() into the target program.
Now the target program will be executing as normal.
If this is correct, I can provide a ~30 line C program, or ~10 line Python program that achives this.
|
How to implement a stdin, stdout wrapper?
|
I have an interactive program that runs stdin and stdout.
I need to create wrapper that will send X to it's stdin, check that it prints Y and then
redirects wrapper's stdin and stdout to program's stdin and stdout just like program would be executed directly.
How to implement this ? X and Y can be hardcoded. Bash? Python?
Edit: I can't run the program twice. It has to be one instance.
Here is the pseudocode:
def wrap(cmd, in, expected_out):
p = exec(cmd)
p.writeToStdin(in)
out = p.readBytes (expected_out.size())
if (out != expected_out) return fail;
# if the above 4 lines would be absent or (in == "" and out == "")
# then this wrapper would be exactly like direct execution of cmd
connectpipe (p.stdout, stdout)
connectpipe (stdin, p.stdin)
p.continueExecution()
|
[
"Expect is made for automating the running of other programs - essentially you write something like, in plain text,\nStart this program. When it prints out the word \"username\", send it my username. When it sends \"password\", send it my password.\nIt's really great for driving other programs.\n",
"Assuming X and Y are files, and that you can invoke the program more than once:\n#!/bin/bash\n\ntest \"`program <X`\" = \"`cat Y`\" && program\n\nOr, to fail more verbosely:\n#!/bin/bash\n\nif [[ `program <X` != `cat Y` ]]; then\n echo -e \"Assertion that input X produces Y failed, exiting.\"\n exit 1\nfi\n\nprogram\n\nIf you only invoke the program once, Expect is a much simpler alternative than reassigning standard file I/O on the fly.\n",
"You can overwrite the sys module's stdin and stdout\nimport sys\nsys.stdin, sys.stdout = wrapper.stdin, wrapper.stdout\n\nThese need to be file objects opened for reading and writing respectively.\nThe original stdin and stdout are found at\nsys.stdin, sys.stdout = sys.__stdin__, sys.__stdout__\n\n",
"I'm a little confused as to what exactly you're trying to achieve; as I understand you wish to:\n\nStart the wrapper program specifying the input X, and expected output Y.\nHave the wrapper initiate the target program attaching input X to it's stdin, and verifying that it's output matches Y.\nHave the target program return, and after output is verified, rerun it from the same instance of the wrapper program, this time using the wrapper programs stdin and stdout.\n\nIf this is the case you want to do this:\n\nHave the wrapper program open pipes for the stdin and stdout of the target program.\nFork, and close the appropriate ends of said pipes.\nHave the parent process and verify the output, while the child exec()s and executes thh target program.\nWait for the child process to terminate when it's stdout closes.\nHave the wrapper program exec() into the target program.\nNow the target program will be executing as normal.\n\nIf this is correct, I can provide a ~30 line C program, or ~10 line Python program that achives this.\n"
] |
[
3,
1,
0,
0
] |
[] |
[] |
[
"bash",
"python",
"stdin",
"stdout",
"wrapper"
] |
stackoverflow_0001890803_bash_python_stdin_stdout_wrapper.txt
|
Q:
Why import urlfetch from Google App Engines?
Here in Google App Engines I got this code that would help fetch an HTML code of any web page by its URL:
from google.appengine.api import urlfetch
url = "http://www.google.com/"
result = urlfetch.fetch(url)
if result.status_code == 200:
doSomethingWithResult(result.content)
I don't understand one thing here (among many other things, in fact) why it is suggested in this code to import urlfecth from google.appengine.api ? Does Python not have this command onits own?
A:
Python has libraries such as urllib and httplib for fetching URLs, but on App Engine, all requests must go through the custom urlfetch library. App Engine includes stubs for urllib and httplib that cause them to use urlfetch internally, but if you have a choice, using urlfetch directly is more efficient and flexible.
A:
google.appengine.api is a library that contains Google's version of urlfetch class. Quoting from the manual:
The URL Fetch service uses Google's
network infrastructure for efficiency
and scaling purposes.
Python has url retrieval classes in its standard library too, but those whould not be able to use the infrastructure that is available inside App Engine.
In short google.appengine.api urlfetch is more powerful, but there is nothing blocking from you from using Pythons own urllib either, that too is described in the manual page I linked above.
|
Why import urlfetch from Google App Engines?
|
Here in Google App Engines I got this code that would help fetch an HTML code of any web page by its URL:
from google.appengine.api import urlfetch
url = "http://www.google.com/"
result = urlfetch.fetch(url)
if result.status_code == 200:
doSomethingWithResult(result.content)
I don't understand one thing here (among many other things, in fact) why it is suggested in this code to import urlfecth from google.appengine.api ? Does Python not have this command onits own?
|
[
"Python has libraries such as urllib and httplib for fetching URLs, but on App Engine, all requests must go through the custom urlfetch library. App Engine includes stubs for urllib and httplib that cause them to use urlfetch internally, but if you have a choice, using urlfetch directly is more efficient and flexible.\n",
"google.appengine.api is a library that contains Google's version of urlfetch class. Quoting from the manual: \n\nThe URL Fetch service uses Google's\n network infrastructure for efficiency\n and scaling purposes.\n\nPython has url retrieval classes in its standard library too, but those whould not be able to use the infrastructure that is available inside App Engine.\nIn short google.appengine.api urlfetch is more powerful, but there is nothing blocking from you from using Pythons own urllib either, that too is described in the manual page I linked above.\n"
] |
[
17,
6
] |
[] |
[] |
[
"google_app_engine",
"import",
"python",
"urlfetch"
] |
stackoverflow_0001893012_google_app_engine_import_python_urlfetch.txt
|
Q:
Use Python to extract ListView items from another application
I have an application with a ListView ('SysListView32') control, from which I would like to extract data. The control has 4 columns, only textual data.
I have been playing around the following lines (found online somewhere):
VALUE_LENGTH = 256
bufferlength_int=struct.pack('i', VALUE_LENGTH)
count = win32gui.SendMessage(TargetHwnd, commctrl.LVM_GETITEMCOUNT, 0, 0)
for ItemIndex in range(count):
valuebuffer = array.array('c',bufferlength_int + " " * (VALUE_LENGTH - len(bufferlength_int)))
ListItems = win32gui.SendMessage(TargetHwnd, commctrl.LVM_GETITEMTEXT, ItemIndex, valuebuffer)
[The above code may not be entirely executable, as I stripped it from irrelevant stuff. but the gist is certainly here.]
This seems to run ok but I must be doing something wrong - I get all sorts of mostly-zeroed data buffers in return, and none of the actual text contents I was looking for.
Any suggestions?
Thanks,
Yonatan
A:
Well, it turns out I was wrong on several points there. However it is possible to do by allocating memory inside the target process, constructing the required struct (LVITEM) there, sending the message and reading back the result from the buffer allocated in said process.
For the sake of completeness, I attach a code example for reading SysListView32 items from a foreign process, given a window handle of the control.
from win32con import PAGE_READWRITE, MEM_COMMIT, MEM_RESERVE, MEM_RELEASE,\
PROCESS_ALL_ACCESS
from commctrl import LVM_GETITEMTEXT, LVM_GETITEMCOUNT
import struct
import ctypes
import win32api
import win32gui
GetWindowThreadProcessId = ctypes.windll.user32.GetWindowThreadProcessId
VirtualAllocEx = ctypes.windll.kernel32.VirtualAllocEx
VirtualFreeEx = ctypes.windll.kernel32.VirtualFreeEx
OpenProcess = ctypes.windll.kernel32.OpenProcess
WriteProcessMemory = ctypes.windll.kernel32.WriteProcessMemory
ReadProcessMemory = ctypes.windll.kernel32.ReadProcessMemory
memcpy = ctypes.cdll.msvcrt.memcpy
def readListViewItems(hwnd, column_index=0):
# Allocate virtual memory inside target process
pid = ctypes.create_string_buffer(4)
p_pid = ctypes.addressof(pid)
GetWindowThreadProcessId(hwnd, p_pid) # process owning the given hwnd
hProcHnd = OpenProcess(PROCESS_ALL_ACCESS, False, struct.unpack("i",pid)[0])
pLVI = VirtualAllocEx(hProcHnd, 0, 4096, MEM_RESERVE|MEM_COMMIT, PAGE_READWRITE)
pBuffer = VirtualAllocEx(hProcHnd, 0, 4096, MEM_RESERVE|MEM_COMMIT, PAGE_READWRITE)
# Prepare an LVITEM record and write it to target process memory
lvitem_str = struct.pack('iiiiiiiii', *[0,0,column_index,0,0,pBuffer,4096,0,0])
lvitem_buffer = ctypes.create_string_buffer(lvitem_str)
copied = ctypes.create_string_buffer(4)
p_copied = ctypes.addressof(copied)
WriteProcessMemory(hProcHnd, pLVI, ctypes.addressof(lvitem_buffer), ctypes.sizeof(lvitem_buffer), p_copied)
# iterate items in the SysListView32 control
num_items = win32gui.SendMessage(hwnd, LVM_GETITEMCOUNT)
item_texts = []
for item_index in range(num_items):
win32gui.SendMessage(hwnd, LVM_GETITEMTEXT, item_index, pLVI)
target_buff = ctypes.create_string_buffer(4096)
ReadProcessMemory(hProcHnd, pBuffer, ctypes.addressof(target_buff), 4096, p_copied)
item_texts.append(target_buff.value)
VirtualFreeEx(hProcHnd, pBuffer, 0, MEM_RELEASE)
VirtualFreeEx(hProcHnd, pLVI, 0, MEM_RELEASE)
win32api.CloseHandle(hProcHnd)
return item_texts
A:
If the control is in the same process as your code, it should work. If it's in a different process (as "another application" suggests), then this doesn't work (or at least it shouldn't). Check the error codes, you should get something along the lines of "permission denied": Applications can't see into each others memory.
|
Use Python to extract ListView items from another application
|
I have an application with a ListView ('SysListView32') control, from which I would like to extract data. The control has 4 columns, only textual data.
I have been playing around the following lines (found online somewhere):
VALUE_LENGTH = 256
bufferlength_int=struct.pack('i', VALUE_LENGTH)
count = win32gui.SendMessage(TargetHwnd, commctrl.LVM_GETITEMCOUNT, 0, 0)
for ItemIndex in range(count):
valuebuffer = array.array('c',bufferlength_int + " " * (VALUE_LENGTH - len(bufferlength_int)))
ListItems = win32gui.SendMessage(TargetHwnd, commctrl.LVM_GETITEMTEXT, ItemIndex, valuebuffer)
[The above code may not be entirely executable, as I stripped it from irrelevant stuff. but the gist is certainly here.]
This seems to run ok but I must be doing something wrong - I get all sorts of mostly-zeroed data buffers in return, and none of the actual text contents I was looking for.
Any suggestions?
Thanks,
Yonatan
|
[
"Well, it turns out I was wrong on several points there. However it is possible to do by allocating memory inside the target process, constructing the required struct (LVITEM) there, sending the message and reading back the result from the buffer allocated in said process.\nFor the sake of completeness, I attach a code example for reading SysListView32 items from a foreign process, given a window handle of the control.\nfrom win32con import PAGE_READWRITE, MEM_COMMIT, MEM_RESERVE, MEM_RELEASE,\\\n PROCESS_ALL_ACCESS\nfrom commctrl import LVM_GETITEMTEXT, LVM_GETITEMCOUNT\n\nimport struct\nimport ctypes\nimport win32api\nimport win32gui\n\nGetWindowThreadProcessId = ctypes.windll.user32.GetWindowThreadProcessId\nVirtualAllocEx = ctypes.windll.kernel32.VirtualAllocEx\nVirtualFreeEx = ctypes.windll.kernel32.VirtualFreeEx\nOpenProcess = ctypes.windll.kernel32.OpenProcess\nWriteProcessMemory = ctypes.windll.kernel32.WriteProcessMemory\nReadProcessMemory = ctypes.windll.kernel32.ReadProcessMemory\nmemcpy = ctypes.cdll.msvcrt.memcpy\n\n\ndef readListViewItems(hwnd, column_index=0):\n\n # Allocate virtual memory inside target process\n pid = ctypes.create_string_buffer(4)\n p_pid = ctypes.addressof(pid)\n GetWindowThreadProcessId(hwnd, p_pid) # process owning the given hwnd\n hProcHnd = OpenProcess(PROCESS_ALL_ACCESS, False, struct.unpack(\"i\",pid)[0])\n pLVI = VirtualAllocEx(hProcHnd, 0, 4096, MEM_RESERVE|MEM_COMMIT, PAGE_READWRITE)\n pBuffer = VirtualAllocEx(hProcHnd, 0, 4096, MEM_RESERVE|MEM_COMMIT, PAGE_READWRITE)\n\n # Prepare an LVITEM record and write it to target process memory\n lvitem_str = struct.pack('iiiiiiiii', *[0,0,column_index,0,0,pBuffer,4096,0,0])\n lvitem_buffer = ctypes.create_string_buffer(lvitem_str)\n copied = ctypes.create_string_buffer(4)\n p_copied = ctypes.addressof(copied)\n WriteProcessMemory(hProcHnd, pLVI, ctypes.addressof(lvitem_buffer), ctypes.sizeof(lvitem_buffer), p_copied)\n\n # iterate items in the SysListView32 control\n num_items = win32gui.SendMessage(hwnd, LVM_GETITEMCOUNT)\n item_texts = []\n for item_index in range(num_items):\n win32gui.SendMessage(hwnd, LVM_GETITEMTEXT, item_index, pLVI)\n target_buff = ctypes.create_string_buffer(4096)\n ReadProcessMemory(hProcHnd, pBuffer, ctypes.addressof(target_buff), 4096, p_copied)\n item_texts.append(target_buff.value)\n\n VirtualFreeEx(hProcHnd, pBuffer, 0, MEM_RELEASE)\n VirtualFreeEx(hProcHnd, pLVI, 0, MEM_RELEASE)\n win32api.CloseHandle(hProcHnd)\n return item_texts\n\n",
"If the control is in the same process as your code, it should work. If it's in a different process (as \"another application\" suggests), then this doesn't work (or at least it shouldn't). Check the error codes, you should get something along the lines of \"permission denied\": Applications can't see into each others memory.\n"
] |
[
7,
1
] |
[] |
[] |
[
"listview",
"python",
"pywin32",
"syslistview32"
] |
stackoverflow_0001872480_listview_python_pywin32_syslistview32.txt
|
Q:
How to override ord behaivour in Python for str childs?
I have this class:
class STR(str):
def __int__(self):
return 42
If i use it in the promt like this:
>>> a=STR('8')
>>> ord(a)
56
>>> int(a)
42
>>> chr(a)
'*'
that's the behaivour. I'd like to ord(a) be 42. How can I do it? Which method should I override in the str class? Is all this documented anywhere?
Thanks!
A:
Here's the C source for Python's builtin ord from the current SVN revision of bltinmodule.c:
static PyObject *
builtin_ord(PyObject *self, PyObject* obj)
{
long ord;
Py_ssize_t size;
if (PyString_Check(obj)) {
size = PyString_GET_SIZE(obj);
if (size == 1) {
ord = (long)((unsigned char)*PyString_AS_STRING(obj));
return PyInt_FromLong(ord);
}
} else if (PyByteArray_Check(obj)) {
size = PyByteArray_GET_SIZE(obj);
if (size == 1) {
ord = (long)((unsigned char)*PyByteArray_AS_STRING(obj));
return PyInt_FromLong(ord);
}
#ifdef Py_USING_UNICODE
} else if (PyUnicode_Check(obj)) {
size = PyUnicode_GET_SIZE(obj);
if (size == 1) {
ord = (long)*PyUnicode_AS_UNICODE(obj);
return PyInt_FromLong(ord);
}
#endif
} else {
PyErr_Format(PyExc_TypeError,
"ord() expected string of length 1, but " \
"%.200s found", obj->ob_type->tp_name);
return NULL;
}
PyErr_Format(PyExc_TypeError,
"ord() expected a character, "
"but string of length %zd found",
size);
return NULL;
}
As you can see, it doesn't make any method calls on the instance you pass in. As far as I can tell, if you don't pass it an explicit string, there's no way to override the functionality of ord.
In fact, it's essentially verifying that the PyObject is either a string, byte array, or Unicode -- that's what the PyString_Check, etc. functions do. If it's none of those, you get the TypeError exception.
One workaround that doesn't scale very well would be to write your own ord in the global namespace:
>>> class STR(str):
... def __int__(self):
... return 42
...
>>>
>>> def ord(s):
... if isinstance(s, STR):
... return int(s)
... else:
... return __builtins__.ord(s)
...
>>>
>>> ord(STR('fdsafds'))
42
>>> ord("!")
33
Of course, this scales horribly because another module using your class may be directly calling __builtins__.ord, or they might even be overwriting ord themselves! But, if you only need this to work on a single, standalone module, this is one way to go about it.
A:
Somebody already posted the builtin ord code, and there is no method call you may intercept.
One solution could be override the ord function, for example:
backup_ord = ord
def ord(obj):
if hasattr(obj, '__ord__'):
return obj.__ord__()
else:
return backup_ord(obj)
Then you define your class with the __ord__ method and do something like:
class MyStr(str):
def __ord__(self):
return 'LOL'
For tests:
normal_five = '5'
strange_five = MyStr('5')
print ord(normal_five)
print ord(strange_five)
Outputs:
53
LOL
A:
ord is not overloadable, it doesn't call any method on string objects (at least in CPython - Python/bltinmodule.c, builtin_ord function).
The best way is probably to create STR.ord method and call that instead of the built-in.
A:
You can't override ord but you can overwrite as variable for example
backup original ord
origord= ord
def ord(x):
return 42
ord(a)
42
origord(a)
56
But I think its not good a idea to overwrite it.
|
How to override ord behaivour in Python for str childs?
|
I have this class:
class STR(str):
def __int__(self):
return 42
If i use it in the promt like this:
>>> a=STR('8')
>>> ord(a)
56
>>> int(a)
42
>>> chr(a)
'*'
that's the behaivour. I'd like to ord(a) be 42. How can I do it? Which method should I override in the str class? Is all this documented anywhere?
Thanks!
|
[
"Here's the C source for Python's builtin ord from the current SVN revision of bltinmodule.c:\nstatic PyObject *\nbuiltin_ord(PyObject *self, PyObject* obj)\n{\n long ord;\n Py_ssize_t size;\n\n if (PyString_Check(obj)) {\n size = PyString_GET_SIZE(obj);\n if (size == 1) {\n ord = (long)((unsigned char)*PyString_AS_STRING(obj));\n return PyInt_FromLong(ord);\n }\n } else if (PyByteArray_Check(obj)) {\n size = PyByteArray_GET_SIZE(obj);\n if (size == 1) {\n ord = (long)((unsigned char)*PyByteArray_AS_STRING(obj));\n return PyInt_FromLong(ord);\n }\n\n#ifdef Py_USING_UNICODE\n } else if (PyUnicode_Check(obj)) {\n size = PyUnicode_GET_SIZE(obj);\n if (size == 1) {\n ord = (long)*PyUnicode_AS_UNICODE(obj);\n return PyInt_FromLong(ord);\n }\n#endif\n } else {\n PyErr_Format(PyExc_TypeError,\n \"ord() expected string of length 1, but \" \\\n \"%.200s found\", obj->ob_type->tp_name);\n return NULL;\n }\n\n PyErr_Format(PyExc_TypeError,\n \"ord() expected a character, \"\n \"but string of length %zd found\",\n size);\n return NULL;\n}\n\nAs you can see, it doesn't make any method calls on the instance you pass in. As far as I can tell, if you don't pass it an explicit string, there's no way to override the functionality of ord.\nIn fact, it's essentially verifying that the PyObject is either a string, byte array, or Unicode -- that's what the PyString_Check, etc. functions do. If it's none of those, you get the TypeError exception.\nOne workaround that doesn't scale very well would be to write your own ord in the global namespace:\n>>> class STR(str):\n... def __int__(self):\n... return 42\n... \n>>> \n>>> def ord(s):\n... if isinstance(s, STR):\n... return int(s)\n... else:\n... return __builtins__.ord(s)\n... \n>>> \n>>> ord(STR('fdsafds'))\n42\n>>> ord(\"!\")\n33\n\nOf course, this scales horribly because another module using your class may be directly calling __builtins__.ord, or they might even be overwriting ord themselves! But, if you only need this to work on a single, standalone module, this is one way to go about it.\n",
"Somebody already posted the builtin ord code, and there is no method call you may intercept.\nOne solution could be override the ord function, for example:\nbackup_ord = ord\ndef ord(obj):\n if hasattr(obj, '__ord__'):\n return obj.__ord__()\n else:\n return backup_ord(obj)\n\nThen you define your class with the __ord__ method and do something like:\nclass MyStr(str):\n def __ord__(self):\n return 'LOL'\n\nFor tests:\nnormal_five = '5'\nstrange_five = MyStr('5')\nprint ord(normal_five)\nprint ord(strange_five)\n\nOutputs:\n53\nLOL\n\n",
"ord is not overloadable, it doesn't call any method on string objects (at least in CPython - Python/bltinmodule.c, builtin_ord function).\nThe best way is probably to create STR.ord method and call that instead of the built-in.\n",
"You can't override ord but you can overwrite as variable for example\nbackup original ord\norigord= ord\n\ndef ord(x):\n return 42\n\n\nord(a)\n42\n\norigord(a)\n56\n\nBut I think its not good a idea to overwrite it.\n"
] |
[
3,
2,
0,
0
] |
[] |
[] |
[
"overriding",
"python",
"string"
] |
stackoverflow_0001893816_overriding_python_string.txt
|
Q:
Why am I getting a file permission error with Python
I am working with a shared hosting environment which as well as other things supports Python. I have followed the examples and deployed my cgi file and then through chmod, gave it Read and Execute Permissions to the world and then Read, Write and Execute to the owner.
The code is simply this:
#!/usr/bin/python
# Required header that tells the browser how to render the text.
print "Content-Type: text/plain\n\n"
# Print a simple message to the display window.
print "Hello, World!\n"
When I then run this I get the following error:
A file permissions error has occurred.
Please check the permissions on the
script and the directory it is in and
try again.
Any help is appreciated!
Andrew
A:
the account the webserver is running as doesn't have privileges to execute the script, or a directory in the path leading to it.
A:
Make sure the python location is really /usr/bin/python
Give read & execute permissions to all, and write permission to owner: chmod 755 file.py
EDIT: are you getting the error from the command line or in your web browser? The directory could be configured in the web server not to run CGI scripts.
A:
Another thing to check: Does the directory you have the script in have ExecCGI permissions (assuming you are running Apache)?
A:
OK, I listened to the tech support, and it would appear that was the biggest problem, lol :-) I was toldnot to put my cgi file in the cgi-bin, and during testing their servers were crashing quite a lot. So after everything has calmed down with the server and it started working again, I placed the file inside the cgi-bin and added the permissions and hey presto it worked.
The new folder/file structure is as follows:
cgi-bin
- test.cgi
mevadata
public_html
- index.html
Now it works. I have had very little experience on a linux box, so thank you all for your time and input.
Cheers again,
Andrew
|
Why am I getting a file permission error with Python
|
I am working with a shared hosting environment which as well as other things supports Python. I have followed the examples and deployed my cgi file and then through chmod, gave it Read and Execute Permissions to the world and then Read, Write and Execute to the owner.
The code is simply this:
#!/usr/bin/python
# Required header that tells the browser how to render the text.
print "Content-Type: text/plain\n\n"
# Print a simple message to the display window.
print "Hello, World!\n"
When I then run this I get the following error:
A file permissions error has occurred.
Please check the permissions on the
script and the directory it is in and
try again.
Any help is appreciated!
Andrew
|
[
"the account the webserver is running as doesn't have privileges to execute the script, or a directory in the path leading to it.\n",
"\nMake sure the python location is really /usr/bin/python\nGive read & execute permissions to all, and write permission to owner: chmod 755 file.py\n\nEDIT: are you getting the error from the command line or in your web browser? The directory could be configured in the web server not to run CGI scripts.\n",
"Another thing to check: Does the directory you have the script in have ExecCGI permissions (assuming you are running Apache)?\n",
"OK, I listened to the tech support, and it would appear that was the biggest problem, lol :-) I was toldnot to put my cgi file in the cgi-bin, and during testing their servers were crashing quite a lot. So after everything has calmed down with the server and it started working again, I placed the file inside the cgi-bin and added the permissions and hey presto it worked.\nThe new folder/file structure is as follows:\ncgi-bin\n - test.cgi\nmevadata\npublic_html\n - index.html\n\nNow it works. I have had very little experience on a linux box, so thank you all for your time and input. \nCheers again,\nAndrew\n"
] |
[
8,
3,
1,
0
] |
[] |
[] |
[
"linux",
"python"
] |
stackoverflow_0001893959_linux_python.txt
|
Q:
Python random and int to string question
I am using this line of code to generate a random list of integers:
random.sample(range(2000), 100)
With this code i know i wont have double value's with my result. Is their maybe a faster way to achieve the same results?
Now i actually have to convert these int to string. Whats the fastest way to do this?
Thanks
A:
Use xrange instead of range:
lst = random.sample(xrange(10**9), 100)
To convert to a list of strings:
strings = map(str, lst)
As one string:
s = ''.join(strings)
A:
random.sample chooses integers from the list without replacement. If you are trying to avoid duplicates then what you are doing is the right method. Could your numbers get much larger? You need to use Python 3, or xrange in Python 2 to avoid generating the entire list of integers in the range.
(Thanks to J.F. Sebastian for pointing out that random.sample does NOT have to generate all integers if you use xrange.)
If you want to allow duplicates you can use randrange instead:
randomInts = [random.randrange(2000) for _ in range(100)]
To convert to strings:
randomStrings = [str(x) for x in randomInts]
A:
import random
r = random.sample(range(2000), 100)
# One way to convert them to strings:
s = [str(x) for x in r]
A:
If you'll be generating lots and lots of lists of random numbers, you can pre-generate the strings to accelerate the lookup, something like this.
stringcache = dict((val, str(val)) for val in range(2000))
while some_condition:
r_strings = map(stringcache.get, random.sample(range(2000), 100))
|
Python random and int to string question
|
I am using this line of code to generate a random list of integers:
random.sample(range(2000), 100)
With this code i know i wont have double value's with my result. Is their maybe a faster way to achieve the same results?
Now i actually have to convert these int to string. Whats the fastest way to do this?
Thanks
|
[
"Use xrange instead of range:\nlst = random.sample(xrange(10**9), 100)\n\nTo convert to a list of strings:\nstrings = map(str, lst)\n\nAs one string:\ns = ''.join(strings)\n\n",
"random.sample chooses integers from the list without replacement. If you are trying to avoid duplicates then what you are doing is the right method. Could your numbers get much larger? You need to use Python 3, or xrange in Python 2 to avoid generating the entire list of integers in the range.\n(Thanks to J.F. Sebastian for pointing out that random.sample does NOT have to generate all integers if you use xrange.)\nIf you want to allow duplicates you can use randrange instead:\nrandomInts = [random.randrange(2000) for _ in range(100)]\n\nTo convert to strings:\nrandomStrings = [str(x) for x in randomInts]\n\n",
"import random\nr = random.sample(range(2000), 100)\n# One way to convert them to strings:\ns = [str(x) for x in r]\n\n",
"If you'll be generating lots and lots of lists of random numbers, you can pre-generate the strings to accelerate the lookup, something like this. \nstringcache = dict((val, str(val)) for val in range(2000))\n\nwhile some_condition: \n r_strings = map(stringcache.get, random.sample(range(2000), 100))\n\n"
] |
[
2,
1,
0,
0
] |
[] |
[] |
[
"python",
"random"
] |
stackoverflow_0001893867_python_random.txt
|
Q:
Color a Button after subprocess has finished
I have a Tk python program that creates a list of python files in the current directory and generates a button for each of them. When you click a button the corresponding python program is launched via subprocess in a new gnome-terminal. I'd like to switch the button's color to red after the subprocess has finished executing on the new terminal. Unfortunately, the button is changing color almost immediately.
from Tkinter import *
import os, subprocess
root = Tk()
buttonsD = {}
def launch(ourfile):
p=subprocess.Popen(["gnome-terminal","-e","python " + ourfile], shell=False)
buttonsD[ourfile].configure(bg='red')
dirlist=os.listdir(os.getcwd())
for fname in dirlist:
if fname.endswith('py') and fname != 'gui2.py':
buttonsD[fname] = Button(root,text=fname,command=lambda i=fname: launch(i))
buttonsD[fname].pack(side=TOP,expand=YES,fill=BOTH)
root.mainloop()
Almost immediately means that I can wait while p.poll == None, and see that it takes a moment for gnome-terminal to be created. But as soon as the terminal is created the button goes red, even though a process is still running in the new terminal. I can't create a new gnome-terminal and then communicate the process I'd like to run either. It seems gnome-terminal just creates a new instance of bash and then returns done, so there's a pipe error if I try to communicate to its stdin.
A:
There are two questions here: what command line to use to launch a Python program in gnome-terminal, and how to use subprocess in a Tkinter app. I only know about the latter.
subprocess.Popen returns immediately, which is why the button is turning red immediately. I think you probably need to make a list of which programs are running. Then write a function poll_processes which calls poll() on each running process, and when the result is not None, removes it from the list and turns the button red.
Then all you have to do is arrange for Tkinter to periodically call that function, which you can do by calling frame.after(msec, poll_processes) to schedule the first call to poll_processes and then having poll_processes do the same thing to schedule the next call.
A:
I believe gnome terminal is doing a double fork, in order to detach itself from the process group of its parent -- so what's actually your subprocess terminates almost immediately, as you observe, and everything is happening in a further descendant that you have no direct access to.
Unfortunately I don't believe gnome terminal offers any way to disable this double fork behavior; so, to find out when the "further descendant" is finished, you'll have to identify that process and monitor it periodically. Interacting directly with it is also a pretty tall order -- no easier than interacting with any "random" process you're not related to:-(.
|
Color a Button after subprocess has finished
|
I have a Tk python program that creates a list of python files in the current directory and generates a button for each of them. When you click a button the corresponding python program is launched via subprocess in a new gnome-terminal. I'd like to switch the button's color to red after the subprocess has finished executing on the new terminal. Unfortunately, the button is changing color almost immediately.
from Tkinter import *
import os, subprocess
root = Tk()
buttonsD = {}
def launch(ourfile):
p=subprocess.Popen(["gnome-terminal","-e","python " + ourfile], shell=False)
buttonsD[ourfile].configure(bg='red')
dirlist=os.listdir(os.getcwd())
for fname in dirlist:
if fname.endswith('py') and fname != 'gui2.py':
buttonsD[fname] = Button(root,text=fname,command=lambda i=fname: launch(i))
buttonsD[fname].pack(side=TOP,expand=YES,fill=BOTH)
root.mainloop()
Almost immediately means that I can wait while p.poll == None, and see that it takes a moment for gnome-terminal to be created. But as soon as the terminal is created the button goes red, even though a process is still running in the new terminal. I can't create a new gnome-terminal and then communicate the process I'd like to run either. It seems gnome-terminal just creates a new instance of bash and then returns done, so there's a pipe error if I try to communicate to its stdin.
|
[
"There are two questions here: what command line to use to launch a Python program in gnome-terminal, and how to use subprocess in a Tkinter app. I only know about the latter.\nsubprocess.Popen returns immediately, which is why the button is turning red immediately. I think you probably need to make a list of which programs are running. Then write a function poll_processes which calls poll() on each running process, and when the result is not None, removes it from the list and turns the button red.\nThen all you have to do is arrange for Tkinter to periodically call that function, which you can do by calling frame.after(msec, poll_processes) to schedule the first call to poll_processes and then having poll_processes do the same thing to schedule the next call.\n",
"I believe gnome terminal is doing a double fork, in order to detach itself from the process group of its parent -- so what's actually your subprocess terminates almost immediately, as you observe, and everything is happening in a further descendant that you have no direct access to.\nUnfortunately I don't believe gnome terminal offers any way to disable this double fork behavior; so, to find out when the \"further descendant\" is finished, you'll have to identify that process and monitor it periodically. Interacting directly with it is also a pretty tall order -- no easier than interacting with any \"random\" process you're not related to:-(.\n"
] |
[
1,
1
] |
[] |
[] |
[
"gnome",
"python",
"subprocess",
"tk_toolkit"
] |
stackoverflow_0001893629_gnome_python_subprocess_tk_toolkit.txt
|
Q:
csv2json.py error
I am trying to run the script csv2json.py in the Command Prompt, but I get this error:
C:\Users\A\Documents\PROJECTS\Django\sw2>csv2json.py csvtest1.csv wkw1.Lawyer
Converting C:\Users\A\Documents\PROJECTS\Django\sw2csvtest1.csv from CSV to JSON as C:\Users\A\Documents\PROJECTS\Django\sw2csvtest1.csv.json
Traceback (most recent call last):
File "C:\Users\A\Documents\PROJECTS\Django\sw2\csv2json.py", line 37, in <module>
f = open(in_file, 'r' )
IOError: [Errno 2] No such file or directory: 'C:\\Users\\A\\Documents\\PROJECTS\\Django\\sw2csvtest1.csv'
Here are the relevant lines from the snippet:
31 in_file = dirname(__file__) + input_file_name
32 out_file = dirname(__file__) + input_file_name + ".json"
34 print "Converting %s from CSV to JSON as %s" % (in_file, out_file)
36 f = open(in_file, 'r' )
37 fo = open(out_file, 'w')
It seems that the directory name and file name are combined. How can I make this script run?
Thanks.
Edit:
Altering lines 31 and 32 as answered by Denis Otkidach worked fine. But I realized that the first column name needs to be pk and each row needs to start with an integer:
for row in reader:
if not header_row:
header_row = row
continue
pk = row[0]
model = model_name
fields = {}
for i in range(len(row)-1):
active_field = row[i+1]
So my csv row now looks like this (including the header row):
pk, firm_url, firm_name, first, last, school, year_graduated
1, http://www.graychase.com/aabbas, Gray & Chase, Amr A, Babas, The George Washington University Law School, 2005
Is this a requirement of the django fixture or json format? If so, I need to find a way to add the pk numbers to each row. Can I delete this pk column? Any suggestions?
Edit 2
I keep getting this ValidationError: "This value must be an integer". There is only one integer field and that's the pk. Is there a way to find out from the traceback what the line numbers refer to?
Problem installing fixture 'C:\Users\A\Documents\Projects\Django\sw2\wkw2\fixtures\csvtest1.csv.json': Traceback (most recent call last):
File "C:\Python26\Lib\site-packages\django\core\management\commands\loaddata.py", line 150, in handle
for obj in objects:
File "C:\Python26\lib\site-packages\django\core\serializers\json.py", line 41, in Deserializer
for obj in PythonDeserializer(simplejson.load(stream)):
File "C:\Python26\lib\site-packages\django\core\serializers\python.py", line 95, in Deserializer
data[field.attname] = field.rel.to._meta.get_field(field.rel.field_name).to_python(field_value)
File "C:\Python26\lib\site-packages\django\db\models\fields\__init__.py", line 356, in to_python
_("This value must be an integer."))
ValidationError: This value must be an integer.
A:
from os import path
in_file = path.join(dirname(__file__), input_file_name )
out_file = path.join(dirname(__file__), input_file_name + ".json" )
[...]
A:
+ is used incorrectly here, the proper way to combine directory name and file name is using os.path.join(). But there is no need to combine directory where script is located with file name, since it's common to pass relative path to current working directory. So, change lines 31-32 to the following:
in_file = input_file_name
out_file = in_file + '.json'
A:
You should be using os.path.join rather than just concatenating dirname() and filenames.
import os.path
in_file = os.path.join(dirname(__file__), input_file_name)
out_file = os.path.join(dirname(__file__), input_file_name + ".json")
will fix your problem, though depending on what exactly you're doing, there's probably a more elegant way to do it.
|
csv2json.py error
|
I am trying to run the script csv2json.py in the Command Prompt, but I get this error:
C:\Users\A\Documents\PROJECTS\Django\sw2>csv2json.py csvtest1.csv wkw1.Lawyer
Converting C:\Users\A\Documents\PROJECTS\Django\sw2csvtest1.csv from CSV to JSON as C:\Users\A\Documents\PROJECTS\Django\sw2csvtest1.csv.json
Traceback (most recent call last):
File "C:\Users\A\Documents\PROJECTS\Django\sw2\csv2json.py", line 37, in <module>
f = open(in_file, 'r' )
IOError: [Errno 2] No such file or directory: 'C:\\Users\\A\\Documents\\PROJECTS\\Django\\sw2csvtest1.csv'
Here are the relevant lines from the snippet:
31 in_file = dirname(__file__) + input_file_name
32 out_file = dirname(__file__) + input_file_name + ".json"
34 print "Converting %s from CSV to JSON as %s" % (in_file, out_file)
36 f = open(in_file, 'r' )
37 fo = open(out_file, 'w')
It seems that the directory name and file name are combined. How can I make this script run?
Thanks.
Edit:
Altering lines 31 and 32 as answered by Denis Otkidach worked fine. But I realized that the first column name needs to be pk and each row needs to start with an integer:
for row in reader:
if not header_row:
header_row = row
continue
pk = row[0]
model = model_name
fields = {}
for i in range(len(row)-1):
active_field = row[i+1]
So my csv row now looks like this (including the header row):
pk, firm_url, firm_name, first, last, school, year_graduated
1, http://www.graychase.com/aabbas, Gray & Chase, Amr A, Babas, The George Washington University Law School, 2005
Is this a requirement of the django fixture or json format? If so, I need to find a way to add the pk numbers to each row. Can I delete this pk column? Any suggestions?
Edit 2
I keep getting this ValidationError: "This value must be an integer". There is only one integer field and that's the pk. Is there a way to find out from the traceback what the line numbers refer to?
Problem installing fixture 'C:\Users\A\Documents\Projects\Django\sw2\wkw2\fixtures\csvtest1.csv.json': Traceback (most recent call last):
File "C:\Python26\Lib\site-packages\django\core\management\commands\loaddata.py", line 150, in handle
for obj in objects:
File "C:\Python26\lib\site-packages\django\core\serializers\json.py", line 41, in Deserializer
for obj in PythonDeserializer(simplejson.load(stream)):
File "C:\Python26\lib\site-packages\django\core\serializers\python.py", line 95, in Deserializer
data[field.attname] = field.rel.to._meta.get_field(field.rel.field_name).to_python(field_value)
File "C:\Python26\lib\site-packages\django\db\models\fields\__init__.py", line 356, in to_python
_("This value must be an integer."))
ValidationError: This value must be an integer.
|
[
"from os import path\nin_file = path.join(dirname(__file__), input_file_name )\nout_file = path.join(dirname(__file__), input_file_name + \".json\" )\n[...]\n\n",
"+ is used incorrectly here, the proper way to combine directory name and file name is using os.path.join(). But there is no need to combine directory where script is located with file name, since it's common to pass relative path to current working directory. So, change lines 31-32 to the following:\nin_file = input_file_name\nout_file = in_file + '.json'\n\n",
"You should be using os.path.join rather than just concatenating dirname() and filenames.\nimport os.path\nin_file = os.path.join(dirname(__file__), input_file_name)\nout_file = os.path.join(dirname(__file__), input_file_name + \".json\")\n\nwill fix your problem, though depending on what exactly you're doing, there's probably a more elegant way to do it.\n"
] |
[
1,
1,
0
] |
[] |
[] |
[
"csv",
"django",
"json",
"python"
] |
stackoverflow_0001894099_csv_django_json_python.txt
|
Q:
setting XML value using xmlrpc & python
I need to set the value of a field in an XML file which exists on a remote Linux box. How do I find out which port I should connect to ?
But even a proper ping is not happening:
import xmlrpclib
server = xmlrpclib.ServerProxy('http://10.77.21.240:9000')
print server.ping()
print "I'm in hurray"
bUT instead I got:
Traceback (most recent call last):
File "ping.py", line 3, in <module>
print server.ping()
File "C:\Python26\lib\xmlrpclib.py", line 1199, in __call__
return self.__send(self.__name, args)
File "C:\Python26\lib\xmlrpclib.py", line 1489, in __request
verbose=self.__verbose
File "C:\Python26\lib\xmlrpclib.py", line 1235, in request
self.send_content(h, request_body)
File "C:\Python26\lib\xmlrpclib.py", line 1349, in send_content
connection.endheaders()
File "C:\Python26\lib\httplib.py", line 892, in endheaders
self._send_output()
File "C:\Python26\lib\httplib.py", line 764, in _send_output
self.send(msg)
File "C:\Python26\lib\httplib.py", line 723, in send
self.connect()
File "C:\Python26\lib\httplib.py", line 704, in connect
self.timeout)
File "C:\Python26\lib\socket.py", line 514, in create_connection
raise error, msg
socket.error: [Errno 10061] No connection could be made because the target machine actively refused it.
What did I do wrong?
A:
A couple of things to try / think about:
Go to a command prompt on the remote host and type "netstat -nap | grep 9000". If you don't get back something interesting it means that nothing is running at port 9000.
You show the remote host at 10.77.21.240. This is an unroutable address on the net (AKA Private Network), so is the server itself (not just your app) pingable? If you are on windows, goto Start -> Run and type "cmd". At the prompt type, "ping 10.77.21.240" and see what you get.
One more thought: the process may be up and running at 9000 on a reachable host, but it may have opened the port as 127.0.0.1:9000 instead of 0.0.0.0:9000. The first address will only be reachable by processes on the same machine, the second one will open the port on all available IP addresses the machine has.
Update in response to comment: The fact that it shouldn't be a problem doesn't eliminate the possibility it is. When you are debugging something that should be working, but isn't, you need to get fairly pedantic about checking each step, allowing yourself no room for 'Oh, I know that couldn't be the problem.' -- this is a verbal 'handwave' (often accompanied by a real handwave). You'd be surprised how often the problem exists in exactly the area you are handwaving! It takes 3 seconds to do the ping test. If it works, you move on, if it doesn't work ...
The first three steps in dealing with any system problem are:
Is it plugged in?
Is it turned on?
Is it configured properly?
And you have to do this for each and every piece of hardware/software in the food chain from your keyboard to the app. I'd guess 80% of 'sudden' failures are items 1 or 2 -- yes, really. Cables are a huge pain in the ass.
When on the phone with novices I normally start by going for the long pass -- if they can get news.google.com in a browser and then click on a random story, then I know that in general the network is OK. Why the news and why a random story? To sidestep browser cache issues. I've lost count of the number of times my older sister has called me up and announced "The Internet is broken!" The first thing we do is the google news test. 99% of the time it works, so I have her fire up reverse-WinVNC (UltraVNC's SingleClick is a God-send), I get on her machine, and then we see what the real problem is.
If the long pass doesn't work, then I see if they can get to their router. Etc. etc.
|
setting XML value using xmlrpc & python
|
I need to set the value of a field in an XML file which exists on a remote Linux box. How do I find out which port I should connect to ?
But even a proper ping is not happening:
import xmlrpclib
server = xmlrpclib.ServerProxy('http://10.77.21.240:9000')
print server.ping()
print "I'm in hurray"
bUT instead I got:
Traceback (most recent call last):
File "ping.py", line 3, in <module>
print server.ping()
File "C:\Python26\lib\xmlrpclib.py", line 1199, in __call__
return self.__send(self.__name, args)
File "C:\Python26\lib\xmlrpclib.py", line 1489, in __request
verbose=self.__verbose
File "C:\Python26\lib\xmlrpclib.py", line 1235, in request
self.send_content(h, request_body)
File "C:\Python26\lib\xmlrpclib.py", line 1349, in send_content
connection.endheaders()
File "C:\Python26\lib\httplib.py", line 892, in endheaders
self._send_output()
File "C:\Python26\lib\httplib.py", line 764, in _send_output
self.send(msg)
File "C:\Python26\lib\httplib.py", line 723, in send
self.connect()
File "C:\Python26\lib\httplib.py", line 704, in connect
self.timeout)
File "C:\Python26\lib\socket.py", line 514, in create_connection
raise error, msg
socket.error: [Errno 10061] No connection could be made because the target machine actively refused it.
What did I do wrong?
|
[
"A couple of things to try / think about:\n\nGo to a command prompt on the remote host and type \"netstat -nap | grep 9000\". If you don't get back something interesting it means that nothing is running at port 9000.\n\nYou show the remote host at 10.77.21.240. This is an unroutable address on the net (AKA Private Network), so is the server itself (not just your app) pingable? If you are on windows, goto Start -> Run and type \"cmd\". At the prompt type, \"ping 10.77.21.240\" and see what you get.\n\nOne more thought: the process may be up and running at 9000 on a reachable host, but it may have opened the port as 127.0.0.1:9000 instead of 0.0.0.0:9000. The first address will only be reachable by processes on the same machine, the second one will open the port on all available IP addresses the machine has.\n\n\nUpdate in response to comment: The fact that it shouldn't be a problem doesn't eliminate the possibility it is. When you are debugging something that should be working, but isn't, you need to get fairly pedantic about checking each step, allowing yourself no room for 'Oh, I know that couldn't be the problem.' -- this is a verbal 'handwave' (often accompanied by a real handwave). You'd be surprised how often the problem exists in exactly the area you are handwaving! It takes 3 seconds to do the ping test. If it works, you move on, if it doesn't work ...\nThe first three steps in dealing with any system problem are:\n\nIs it plugged in?\nIs it turned on?\nIs it configured properly?\n\nAnd you have to do this for each and every piece of hardware/software in the food chain from your keyboard to the app. I'd guess 80% of 'sudden' failures are items 1 or 2 -- yes, really. Cables are a huge pain in the ass.\nWhen on the phone with novices I normally start by going for the long pass -- if they can get news.google.com in a browser and then click on a random story, then I know that in general the network is OK. Why the news and why a random story? To sidestep browser cache issues. I've lost count of the number of times my older sister has called me up and announced \"The Internet is broken!\" The first thing we do is the google news test. 99% of the time it works, so I have her fire up reverse-WinVNC (UltraVNC's SingleClick is a God-send), I get on her machine, and then we see what the real problem is.\nIf the long pass doesn't work, then I see if they can get to their router. Etc. etc.\n"
] |
[
2
] |
[] |
[] |
[
"python",
"xml",
"xml_rpc"
] |
stackoverflow_0001889313_python_xml_xml_rpc.txt
|
Q:
Write a data string to a NumPy character array?
I want to write a data string to a NumPy array. Pseudocode:
d = numpy.zeros(10, dtype = numpy.character)
d[1:6] = 'hello'
Example result:
d=
array(['', 'h', 'e', 'l', 'l', 'o', '', '', '', ''],
dtype='|S1')
How can this be done most naturally and efficiently with NumPy?
I don't want for loops, generators, or anything iterative. Can it be done with one command as with the pseudocode?
A:
Just explicitly make your text a list (rather than that it is iterable from Python) and NumPy will understand it automatically:
>>> text = 'hello'
>>> offset = 1
>>> d[offset:offset+len(text)] = list(text)
>>> d
array(['', 'h', 'e', 'l', 'l', 'o', '', '', '', ''],
dtype='|S1')
A:
There's little need to build a list when you have numpy.fromstring and numpy.fromiter.
A:
You might try Python's array type. It will not have as high an overhead as a list.
from array import array as pyarray
d[1:6] = pyarray('c', 'hello')
|
Write a data string to a NumPy character array?
|
I want to write a data string to a NumPy array. Pseudocode:
d = numpy.zeros(10, dtype = numpy.character)
d[1:6] = 'hello'
Example result:
d=
array(['', 'h', 'e', 'l', 'l', 'o', '', '', '', ''],
dtype='|S1')
How can this be done most naturally and efficiently with NumPy?
I don't want for loops, generators, or anything iterative. Can it be done with one command as with the pseudocode?
|
[
"Just explicitly make your text a list (rather than that it is iterable from Python) and NumPy will understand it automatically:\n>>> text = 'hello'\n>>> offset = 1\n>>> d[offset:offset+len(text)] = list(text)\n>>> d\n\narray(['', 'h', 'e', 'l', 'l', 'o', '', '', '', ''],\n dtype='|S1')\n\n",
"There's little need to build a list when you have numpy.fromstring and numpy.fromiter.\n",
"You might try Python's array type. It will not have as high an overhead as a list.\nfrom array import array as pyarray\nd[1:6] = pyarray('c', 'hello')\n\n"
] |
[
3,
2,
1
] |
[] |
[] |
[
"numpy",
"python"
] |
stackoverflow_0001759208_numpy_python.txt
|
Q:
How does incr work with expiry times?
In memcached (appengine api implementation), how does expiration interact with incr()? There isn't a time argument for incr(), but what happens if I add the key with another call
rather than using the initial_value param, like so:
memcache.add('testcounter', 0, time=60*90)
newcnt = memcache.incr('testcounter')
will testcounter still expire in 90 minutes? Whether or not I call this again in that time?
A:
In the memcache overview of GAE they say:
"The app can provide an expiration time when a value is stored, as either a number of seconds relative to when the value is added, or as an absolute Unix epoch time in the future (a number of seconds from midnight January 1, 1970). The value will be evicted no later than this time, though it may be evicted for other reasons."
it doesn't mention modifications.
If you look at the code of memcache in google.appengine.api.memcache.init.py you'll see that neither in incr or in _incrdecr there is a call to the set_expiration_time function
A:
The expiration time is not affected by incr.
That object will expire from the cache no later than 90 seconds after you add it regardless of the number of times you incr it.
(and, of course, it may expire sooner)
|
How does incr work with expiry times?
|
In memcached (appengine api implementation), how does expiration interact with incr()? There isn't a time argument for incr(), but what happens if I add the key with another call
rather than using the initial_value param, like so:
memcache.add('testcounter', 0, time=60*90)
newcnt = memcache.incr('testcounter')
will testcounter still expire in 90 minutes? Whether or not I call this again in that time?
|
[
"In the memcache overview of GAE they say:\n\"The app can provide an expiration time when a value is stored, as either a number of seconds relative to when the value is added, or as an absolute Unix epoch time in the future (a number of seconds from midnight January 1, 1970). The value will be evicted no later than this time, though it may be evicted for other reasons.\" \nit doesn't mention modifications.\nIf you look at the code of memcache in google.appengine.api.memcache.init.py you'll see that neither in incr or in _incrdecr there is a call to the set_expiration_time function\n",
"The expiration time is not affected by incr.\nThat object will expire from the cache no later than 90 seconds after you add it regardless of the number of times you incr it.\n(and, of course, it may expire sooner)\n"
] |
[
4,
1
] |
[] |
[] |
[
"google_app_engine",
"memcached",
"python"
] |
stackoverflow_0001890682_google_app_engine_memcached_python.txt
|
Q:
Processing output from cmdline via a Python script
I'm trying to use the subprocess module with Python 2.6 in order to run a command and get its output. The command is typically ran like this:
/usr/local/sbin/kamctl fifo profile_get_size myprofile | awk -F ':: ' '{print $2}'
What's the best way to use the subprocess module in my script to execute that command with those arguments and get the return value from the command? I'm using Python 2.6.
A:
Do you want the output, the return value (AKA status code), or both?
If the amount of data emitted by the pipeline on stdout and/or stderr is not too large, it's pretty simple to get "all of the above":
import subprocess
s = """/usr/local/sbin/kamctl fifo profile_get_size myprofile | awk -F ':: ' '{print $2}'"""
p = subprocess.Popen(s, shell=True, stdout=subprocess.PIPE)
out, err = p.communicate()
print 'out: %r' % out
print 'err: %r' % err
print 'status: %r' % p.returncode
If you have to deal with potentially huge amounts of output, it takes a bit more code -- doesn't look like you should have that problem, judging from the pipeline in question.
A:
f.e. stdout you can get like this:
>>> import subprocess
>>> process = subprocess.Popen("echo 'test'", shell=True, stdout=subprocess.PIPE)
>>> process.wait()
0
>>> process.stdout.read()
'test\n'
|
Processing output from cmdline via a Python script
|
I'm trying to use the subprocess module with Python 2.6 in order to run a command and get its output. The command is typically ran like this:
/usr/local/sbin/kamctl fifo profile_get_size myprofile | awk -F ':: ' '{print $2}'
What's the best way to use the subprocess module in my script to execute that command with those arguments and get the return value from the command? I'm using Python 2.6.
|
[
"Do you want the output, the return value (AKA status code), or both?\nIf the amount of data emitted by the pipeline on stdout and/or stderr is not too large, it's pretty simple to get \"all of the above\":\nimport subprocess\n\ns = \"\"\"/usr/local/sbin/kamctl fifo profile_get_size myprofile | awk -F ':: ' '{print $2}'\"\"\"\n\np = subprocess.Popen(s, shell=True, stdout=subprocess.PIPE)\n\nout, err = p.communicate()\n\nprint 'out: %r' % out\nprint 'err: %r' % err\nprint 'status: %r' % p.returncode\n\nIf you have to deal with potentially huge amounts of output, it takes a bit more code -- doesn't look like you should have that problem, judging from the pipeline in question.\n",
"f.e. stdout you can get like this:\n>>> import subprocess\n>>> process = subprocess.Popen(\"echo 'test'\", shell=True, stdout=subprocess.PIPE)\n>>> process.wait()\n0\n>>> process.stdout.read()\n'test\\n'\n\n"
] |
[
4,
2
] |
[] |
[] |
[
"process",
"python",
"scripting"
] |
stackoverflow_0001894325_process_python_scripting.txt
|
Q:
Should Pylons' development.ini be checked in?
I'm learning about Pylons and I've read a few tutorials, but none of them have addressed collaboration practices. Starting on a practice project. I'd like to keep my code in a revision-control system (Git, specifically) as if it were an open-source project with multiple developers, in order to practice that aspect of Pylons development as well.
I'm wondering what I should do with the development.ini file that was generated by Paster as part of my new application. On one hand, it contains lots of settings that other develpers wouldn't want to have to recreate by hand, so it seems like it ought to be stored in my Git repository so that other developers can access it. On the other hand, some of the settings, such as the database connection URL, are specific to one person's development environment and wouldn't make sense to share with others.
What do real-world Pylons applications do with this file?
A:
You could check it in as sample.ini for example so that everyone can copy to their own development.ini and modify as needed
A:
On a team development, we make an effort to ensure everyone has a common development environment, or we make adjustments to things (like database URLs) to allow people on different environments (we do Mac, Windows, and Linux) to share all files.
And our Pylons development.ini files are committed to subversion, just like everything else.
A:
The most important aspect of collaboration is communicating with your teammates. See if you can come to a quick consensus on how to handle the situation.
My suggestion though, would be to pass around your completed ini file for the other devs to modify for their own purposes. If there are a lot of hand tuned settings that they won't want (or need) to change, then they shouldn't have to do the work. At the end of the day though, they'll need to write the settings somehow.
A:
You should check in development.ini. Most developers are smart enough to realize that if they want to run your application they need to make some tweaks. The development.ini will serve as a template. A file that has the database configured incorrectly is still useful since I can see that the system is trying to connect to the database and failing.
Later on you will be making files such as development.ini, staging.ini, and production.ini. This will help when you move environments.
|
Should Pylons' development.ini be checked in?
|
I'm learning about Pylons and I've read a few tutorials, but none of them have addressed collaboration practices. Starting on a practice project. I'd like to keep my code in a revision-control system (Git, specifically) as if it were an open-source project with multiple developers, in order to practice that aspect of Pylons development as well.
I'm wondering what I should do with the development.ini file that was generated by Paster as part of my new application. On one hand, it contains lots of settings that other develpers wouldn't want to have to recreate by hand, so it seems like it ought to be stored in my Git repository so that other developers can access it. On the other hand, some of the settings, such as the database connection URL, are specific to one person's development environment and wouldn't make sense to share with others.
What do real-world Pylons applications do with this file?
|
[
"You could check it in as sample.ini for example so that everyone can copy to their own development.ini and modify as needed\n",
"On a team development, we make an effort to ensure everyone has a common development environment, or we make adjustments to things (like database URLs) to allow people on different environments (we do Mac, Windows, and Linux) to share all files.\nAnd our Pylons development.ini files are committed to subversion, just like everything else.\n",
"The most important aspect of collaboration is communicating with your teammates. See if you can come to a quick consensus on how to handle the situation.\nMy suggestion though, would be to pass around your completed ini file for the other devs to modify for their own purposes. If there are a lot of hand tuned settings that they won't want (or need) to change, then they shouldn't have to do the work. At the end of the day though, they'll need to write the settings somehow.\n",
"You should check in development.ini. Most developers are smart enough to realize that if they want to run your application they need to make some tweaks. The development.ini will serve as a template. A file that has the database configured incorrectly is still useful since I can see that the system is trying to connect to the database and failing.\nLater on you will be making files such as development.ini, staging.ini, and production.ini. This will help when you move environments.\n"
] |
[
2,
2,
0,
0
] |
[] |
[] |
[
"pylons",
"python"
] |
stackoverflow_0001886192_pylons_python.txt
|
Q:
Is Pylons enterprise-ready?
I am a developer who is looking for an Enterprise-ready web application framework for Python. My main concern is long-term support, extensive feature set and reliability.
I have been experimenting with Pylons and after my horrendous experience with Ruby on Rails on Windows where I even had to compile my own Postgres driver, Pylons and Python have been a godsend.
I believe Python, due to a very strong community and commercial interest, is definitely 'enterprise-ready' due to the number of available libraries and their efforts to maintain some semblance of backward compatibility for Python 3.0. My worry is:
Can we all say the same for Pylons 0.97?
On a side note, I have been figuring out how to get SQLAlchemy working with DB2 on Pylons so that I can automate basic CRUD operations. The current DB2 driver on http://code.google.com is quite useless only supporting SQLAlchemy 0.4. Do you think IBM is committed with making DB2 work with SQLAlchemy for the long term? Or you guys feel it's better to make SQLAlchemy interface with the ODBC driver supplied with DB2. Any disadvantages compared to using IBM's SQLAlchemy driver?
A:
When it comes to enterprise ready, I'm not sure how much more ready a stack using Pylons with SQLAlchemy can be in the Python world. You're ready for massive legacy databases with crazy schemas (totally common in large corporate worlds), something where Django just falls apart at the seams. Sure, in Django, you could still use SQLAlchemy, but then all the Django contrib tools fall apart since they all rely on the assumption that you'd doing things the "Django" way.
Pylons has been around since mid-2005, and it isn't going anywhere. It's actually quite mature, and has a fairly slow and solid release schedule of 6-10 months between releases, with quite a bit of testing. One of the core Pylons developers is also a developer on Jython ensuring that Pylons can run on the JVM (which helps get Pylons based apps into enterprise environments that are hostile to things that can't be packaged up into a WAR file for deployment).
Regarding some of the other 'answers' here, the question is about whether Pylons is enterprise-ready, I have no idea why others were unable to read the question and instead chose to start preaching their own favorite framework. It's quite silly to say that you should use Django/Zope/Grok because it has "bigger uptake" or a "larger community", if that's the criteria the choice should be PHP, which makes the Django and Zope communities look itty bitty in comparison. Pylons definitely has a large enough community to sustain itself, especially as its rather lean and compact code-base don't pick up nearly as many bugs as the "kitchen sink" frameworks of Zope/Django.
A:
I would say that if you're worried about 'enterprise-level' support, you should be looking more at Django. Although you can debate the relative technical merits of the two frameworks, there's no doubt that Django has the bigger uptake, and there are quite a few large companies using it.
One additional reason is that IBM have (just in the last couple of days) released a Django driver for DB2, so you should have no problem using your existing database with the Django ORM.
A:
define enterprise ready.
Also, if we're talking scalability, I would say you have a better shot with sqlalchemy since you can drop down to raw sql when necessary. Whereas the active Record pattern seems to be the cause of a lot of the value of high level frameworks, that can lead to scalability issues if you are throwing stuff together.
Of course "enterprise ready" to some people means complicated and expensive, is this is your definition, than I would say that no python web framework is going to meet your needs.
A:
I consider a piece of software enterprise ready when it has stability and support.
I believe that Pylons/Python is stable. There are a load of sites using Pylons (including one of the highest traffic'ed sites, reddit.com).
Support wise I'd consider aspects like how easy it is to hire people who know Pylons or to purchase support contracts. This is a bit harder. If you plan to support in house Pylons is more than ready to go. If you are looking for support so that you have someone to take liability when the software breaks you might want to look elsewhere.
A:
I'd second the call to use Django. I actually prefer Pylons, because it is much leaner than Django, but considering you specify "enterprise ready" I think you might want to hedge toward the larger framework and carry the kitchen sink around with you.
A:
+1 for Django
Pylons is a good framework, but you will have to match all the components to create your own architecture, so I think it's more appropriate for leaner projects. For something bigger, I suggest Django, that's know to be on production on some large scale sites.
IBM recently released a DB2 back-end for Django, so might fit you well.
A:
If you want frameworks that aren't likely to go away anytime soon look at Django and one of the frameworks in the Zope community (Grok, BFG, Zope3). Zope has a big community and have been around for more than ten years and isn't going away any time soon, and is a breeding ground for many of the new cool Python web technologies. Django is newer and did only recently come in version 1.0, but it has a very large community and is also going to stay around more or less forever.
|
Is Pylons enterprise-ready?
|
I am a developer who is looking for an Enterprise-ready web application framework for Python. My main concern is long-term support, extensive feature set and reliability.
I have been experimenting with Pylons and after my horrendous experience with Ruby on Rails on Windows where I even had to compile my own Postgres driver, Pylons and Python have been a godsend.
I believe Python, due to a very strong community and commercial interest, is definitely 'enterprise-ready' due to the number of available libraries and their efforts to maintain some semblance of backward compatibility for Python 3.0. My worry is:
Can we all say the same for Pylons 0.97?
On a side note, I have been figuring out how to get SQLAlchemy working with DB2 on Pylons so that I can automate basic CRUD operations. The current DB2 driver on http://code.google.com is quite useless only supporting SQLAlchemy 0.4. Do you think IBM is committed with making DB2 work with SQLAlchemy for the long term? Or you guys feel it's better to make SQLAlchemy interface with the ODBC driver supplied with DB2. Any disadvantages compared to using IBM's SQLAlchemy driver?
|
[
"When it comes to enterprise ready, I'm not sure how much more ready a stack using Pylons with SQLAlchemy can be in the Python world. You're ready for massive legacy databases with crazy schemas (totally common in large corporate worlds), something where Django just falls apart at the seams. Sure, in Django, you could still use SQLAlchemy, but then all the Django contrib tools fall apart since they all rely on the assumption that you'd doing things the \"Django\" way.\nPylons has been around since mid-2005, and it isn't going anywhere. It's actually quite mature, and has a fairly slow and solid release schedule of 6-10 months between releases, with quite a bit of testing. One of the core Pylons developers is also a developer on Jython ensuring that Pylons can run on the JVM (which helps get Pylons based apps into enterprise environments that are hostile to things that can't be packaged up into a WAR file for deployment).\nRegarding some of the other 'answers' here, the question is about whether Pylons is enterprise-ready, I have no idea why others were unable to read the question and instead chose to start preaching their own favorite framework. It's quite silly to say that you should use Django/Zope/Grok because it has \"bigger uptake\" or a \"larger community\", if that's the criteria the choice should be PHP, which makes the Django and Zope communities look itty bitty in comparison. Pylons definitely has a large enough community to sustain itself, especially as its rather lean and compact code-base don't pick up nearly as many bugs as the \"kitchen sink\" frameworks of Zope/Django.\n",
"I would say that if you're worried about 'enterprise-level' support, you should be looking more at Django. Although you can debate the relative technical merits of the two frameworks, there's no doubt that Django has the bigger uptake, and there are quite a few large companies using it.\nOne additional reason is that IBM have (just in the last couple of days) released a Django driver for DB2, so you should have no problem using your existing database with the Django ORM.\n",
"define enterprise ready.\nAlso, if we're talking scalability, I would say you have a better shot with sqlalchemy since you can drop down to raw sql when necessary. Whereas the active Record pattern seems to be the cause of a lot of the value of high level frameworks, that can lead to scalability issues if you are throwing stuff together.\nOf course \"enterprise ready\" to some people means complicated and expensive, is this is your definition, than I would say that no python web framework is going to meet your needs.\n",
"I consider a piece of software enterprise ready when it has stability and support.\nI believe that Pylons/Python is stable. There are a load of sites using Pylons (including one of the highest traffic'ed sites, reddit.com).\nSupport wise I'd consider aspects like how easy it is to hire people who know Pylons or to purchase support contracts. This is a bit harder. If you plan to support in house Pylons is more than ready to go. If you are looking for support so that you have someone to take liability when the software breaks you might want to look elsewhere.\n",
"I'd second the call to use Django. I actually prefer Pylons, because it is much leaner than Django, but considering you specify \"enterprise ready\" I think you might want to hedge toward the larger framework and carry the kitchen sink around with you.\n",
"+1 for Django\nPylons is a good framework, but you will have to match all the components to create your own architecture, so I think it's more appropriate for leaner projects. For something bigger, I suggest Django, that's know to be on production on some large scale sites.\nIBM recently released a DB2 back-end for Django, so might fit you well.\n",
"If you want frameworks that aren't likely to go away anytime soon look at Django and one of the frameworks in the Zope community (Grok, BFG, Zope3). Zope has a big community and have been around for more than ten years and isn't going away any time soon, and is a breeding ground for many of the new cool Python web technologies. Django is newer and did only recently come in version 1.0, but it has a very large community and is also going to stay around more or less forever.\n"
] |
[
39,
2,
1,
1,
0,
0,
0
] |
[] |
[] |
[
"pylons",
"python",
"sqlalchemy",
"web_applications"
] |
stackoverflow_0001044667_pylons_python_sqlalchemy_web_applications.txt
|
Q:
variable name introspection in Python
Is it possible to dynamically determine the name of a variable in Python?
For example, I sometimes have the following situation:
name = foo if bar else baz
type = alpha or bravo
D = {
"name": name,
"type": type
}
It would be nice if duplication there could be reduced with something like D = makedict(name, type).
Somewhat relatedly, it would sometimes be helpful for a function to know its own name:
class Item(object):
def item_create(self, item):
dispatch("create", item)
def item_delete(self, item):
dispatch("delete", item)
Here duplication might be reduced by passing something like __methodname__ instead of explicitly repeating "create" and "delete", respectively.
(I assume a decorator could be used for this, but that seems like overkill.)
A:
In the general case, you cannot deduce the name from a value (there might be no name, there might be multiple ones, etc); when you call your hypothetical makedict(name), the value of name is what makedict receives, so (again, in the general case) it cannot discern what name (if any) the value came from. You could introspect your caller's namespaces to see if you're lucky enough to hit a special case where the value does let you infer the name (e.g., you receive 23, and there's only one name throughout the namespaces of interest which happens to have a value of 23!), but that's clearly a fragile and iffy architecture. Plus, in your first example case, it's absolutely guaranteed that the special case will not occur -- the value in name is exactly the same as in either foo or baz, so it's 100% certain that the name for that value will be hopelessly ambiguous.
You could take a completely different tack, such as calling makedict('name type', locals()) (passing locals() explicitly might be obviated with dark and deep introspection magic, but that's not the most solid choice in general) -- pass in the names (and namespaces, I suggest!) and have makedict deduce the values, which is obviously a much more solid proposition (since each name has exactly one value, but not viceversa). I.e.:
def makedict(names, *namespaces):
d = {}
for n in names.split():
for ns in namespaces:
if n in ns:
d[n] = ns[n]
break
else:
d[n] = None # or, raise an exception
If you're keen on digging out the namespaces by introspection, rather than have them cleanly specified by the caller, look at inspect.getouterframes -- but I suggest you reconsider.
The second issue you raise is quite different (though you could use inspect functions again to introspect the caller's name, or a function's own name -- what a peculiar idea!). What's in common in the two cases is that you're using extremely powerful and dangerous machinery to do a job that could be done much more simply (easier to ensure correctness, easier to debug any problems, easier to test, etc, etc) -- far from having decorators be "overkill", they're far simpler and more explicit than the introspection you propose. If you have a zillion methods all of the form:
def item_blah(self, item):
dispatch("blah", item)
the simplest way to create them might be:
class Item(object): pass
def _makedispcall(n):
def item_whatever(self, item):
dispatch(n, item)
item_whatever.__name__ = 'item_' + n
return item_whatever
for n in 'create delete blah but wait theres more'.split():
setattr(Item, 'item_' + n, _makedispcall(n))
Avoiding repetition is an excellent idea, but runtime introspection is not generally the best way to implement that idea, and Python offers many alternative ways to such implementation.
A:
In general, you can't do this in Python, because Python has objects, not variables.
If I have
L1 = [1,2]
L2 = L1
Then, L1 and L2 both refer to the same object. It has no single name.
Similarly:
def f1(): pass
f2 = f1
Now the function has no single name, and as such, you can't find out "the" name of the function.
An object in Python can be referenced by many names - when the reference count of an object goes to zero, Python frees the memory for it.
A:
You can do what you want for functions:
>>> def blagnorf():
pass
>>> print blagnorf.__name__
blagnorf
But not for variables, unfortunately. You could probably write a preprocessor for your python code to do it for you, though...
Note that you can do this in Scheme/Lisp with the macro system they have there.
A:
Whenever you get a hankering to make a gazillion simple methods whose internals only differ according to the method's name, you probably should reconsider your interface. Instead, you could do this:
class Item(object):
def item_action(self, action, item):
dispatch(action, item)
where action could be "create", "delete", etc.
|
variable name introspection in Python
|
Is it possible to dynamically determine the name of a variable in Python?
For example, I sometimes have the following situation:
name = foo if bar else baz
type = alpha or bravo
D = {
"name": name,
"type": type
}
It would be nice if duplication there could be reduced with something like D = makedict(name, type).
Somewhat relatedly, it would sometimes be helpful for a function to know its own name:
class Item(object):
def item_create(self, item):
dispatch("create", item)
def item_delete(self, item):
dispatch("delete", item)
Here duplication might be reduced by passing something like __methodname__ instead of explicitly repeating "create" and "delete", respectively.
(I assume a decorator could be used for this, but that seems like overkill.)
|
[
"In the general case, you cannot deduce the name from a value (there might be no name, there might be multiple ones, etc); when you call your hypothetical makedict(name), the value of name is what makedict receives, so (again, in the general case) it cannot discern what name (if any) the value came from. You could introspect your caller's namespaces to see if you're lucky enough to hit a special case where the value does let you infer the name (e.g., you receive 23, and there's only one name throughout the namespaces of interest which happens to have a value of 23!), but that's clearly a fragile and iffy architecture. Plus, in your first example case, it's absolutely guaranteed that the special case will not occur -- the value in name is exactly the same as in either foo or baz, so it's 100% certain that the name for that value will be hopelessly ambiguous.\nYou could take a completely different tack, such as calling makedict('name type', locals()) (passing locals() explicitly might be obviated with dark and deep introspection magic, but that's not the most solid choice in general) -- pass in the names (and namespaces, I suggest!) and have makedict deduce the values, which is obviously a much more solid proposition (since each name has exactly one value, but not viceversa). I.e.:\ndef makedict(names, *namespaces):\n d = {}\n for n in names.split():\n for ns in namespaces:\n if n in ns:\n d[n] = ns[n]\n break\n else:\n d[n] = None # or, raise an exception\n\nIf you're keen on digging out the namespaces by introspection, rather than have them cleanly specified by the caller, look at inspect.getouterframes -- but I suggest you reconsider.\nThe second issue you raise is quite different (though you could use inspect functions again to introspect the caller's name, or a function's own name -- what a peculiar idea!). What's in common in the two cases is that you're using extremely powerful and dangerous machinery to do a job that could be done much more simply (easier to ensure correctness, easier to debug any problems, easier to test, etc, etc) -- far from having decorators be \"overkill\", they're far simpler and more explicit than the introspection you propose. If you have a zillion methods all of the form:\ndef item_blah(self, item):\n dispatch(\"blah\", item)\n\nthe simplest way to create them might be:\nclass Item(object): pass\n\ndef _makedispcall(n):\n def item_whatever(self, item):\n dispatch(n, item)\n item_whatever.__name__ = 'item_' + n\n return item_whatever\n\nfor n in 'create delete blah but wait theres more'.split():\n setattr(Item, 'item_' + n, _makedispcall(n))\n\nAvoiding repetition is an excellent idea, but runtime introspection is not generally the best way to implement that idea, and Python offers many alternative ways to such implementation.\n",
"In general, you can't do this in Python, because Python has objects, not variables.\nIf I have\nL1 = [1,2]\nL2 = L1\n\nThen, L1 and L2 both refer to the same object. It has no single name.\nSimilarly:\ndef f1(): pass\nf2 = f1\n\nNow the function has no single name, and as such, you can't find out \"the\" name of the function.\nAn object in Python can be referenced by many names - when the reference count of an object goes to zero, Python frees the memory for it.\n",
"You can do what you want for functions:\n>>> def blagnorf():\n pass\n\n>>> print blagnorf.__name__\nblagnorf\n\nBut not for variables, unfortunately. You could probably write a preprocessor for your python code to do it for you, though...\nNote that you can do this in Scheme/Lisp with the macro system they have there. \n",
"Whenever you get a hankering to make a gazillion simple methods whose internals only differ according to the method's name, you probably should reconsider your interface. Instead, you could do this:\nclass Item(object):\n def item_action(self, action, item):\n dispatch(action, item)\n\nwhere action could be \"create\", \"delete\", etc.\n"
] |
[
11,
4,
2,
2
] |
[] |
[] |
[
"metaprogramming",
"python"
] |
stackoverflow_0001894591_metaprogramming_python.txt
|
Q:
Scaling an image to its parent button size in GTK?
I have a GTK layout with a widget on the left of an HBox deciding the maximum height I want, and a VBox on the right containing three buttons, each containing only an image and no text. The images are a GTK stock icon, and so have the stock storage type.
Using expand=True, fill=True packing the buttons without images are exactly the height I want - some arbitrary small width, and 1/3 each the height of the left half of the HBox. However with an image, they are either too tall - 3 * ICON_SIZE_MENU is too tall in many themes - or if I force the button's height request, they get clipped. I would rather scale them to the size of the parent button.
Do I have to make my own pixbufs for each of the stock icons I'm using (and regenerate them if the size changes)? Or can GTK automatically size the image to fit the button, rather than the other way around? Since the images are only a few pixels off from fitting in every theme I've tried, is there a way to just disable the button's clipping?
This application is written in Python using PyGTK, but solutions in any language are appreciated.
(I tried just making it an icon name storage type, but one of the icons is REVERT_TO_SAVED, which turned into the broken stock image when I tried to force it to a particular pixel height. Plus, I'd rather not force it to any fixed pixel height.)
A:
There's no way to automatically do you want you want. You might want to subclass gtk.Image and in your subclass, scale a pixbuf to your widget's allocation size. The advantage of this is that you'll have a reusable widget and you'll be able to have it resize your image on the fly.
The downside is that you'll have an ugly, scaled up pixmap. You may want to look into scalable vector graphics.
A:
I've been having luck using SVG files and scaling them since it's easy to incorporate SVG in pyGtk programs.
img = gtk.gdk.pixbuf_new_from_file(fname)
What I do is copy the svg to a temporary file and modify the first '
Then I read i that modified svg and it'll load as a pixbuf scaled and with all the alpha channel goodness.
see http://code.google.com/p/key-mon/source/browse/src/keymon/lazy_pixbuf_creator.py
|
Scaling an image to its parent button size in GTK?
|
I have a GTK layout with a widget on the left of an HBox deciding the maximum height I want, and a VBox on the right containing three buttons, each containing only an image and no text. The images are a GTK stock icon, and so have the stock storage type.
Using expand=True, fill=True packing the buttons without images are exactly the height I want - some arbitrary small width, and 1/3 each the height of the left half of the HBox. However with an image, they are either too tall - 3 * ICON_SIZE_MENU is too tall in many themes - or if I force the button's height request, they get clipped. I would rather scale them to the size of the parent button.
Do I have to make my own pixbufs for each of the stock icons I'm using (and regenerate them if the size changes)? Or can GTK automatically size the image to fit the button, rather than the other way around? Since the images are only a few pixels off from fitting in every theme I've tried, is there a way to just disable the button's clipping?
This application is written in Python using PyGTK, but solutions in any language are appreciated.
(I tried just making it an icon name storage type, but one of the icons is REVERT_TO_SAVED, which turned into the broken stock image when I tried to force it to a particular pixel height. Plus, I'd rather not force it to any fixed pixel height.)
|
[
"There's no way to automatically do you want you want. You might want to subclass gtk.Image and in your subclass, scale a pixbuf to your widget's allocation size. The advantage of this is that you'll have a reusable widget and you'll be able to have it resize your image on the fly.\nThe downside is that you'll have an ugly, scaled up pixmap. You may want to look into scalable vector graphics.\n",
"I've been having luck using SVG files and scaling them since it's easy to incorporate SVG in pyGtk programs. \nimg = gtk.gdk.pixbuf_new_from_file(fname)\n\nWhat I do is copy the svg to a temporary file and modify the first '\n\nThen I read i that modified svg and it'll load as a pixbuf scaled and with all the alpha channel goodness.\nsee http://code.google.com/p/key-mon/source/browse/src/keymon/lazy_pixbuf_creator.py\n"
] |
[
2,
1
] |
[] |
[] |
[
"gtk",
"pygtk",
"python",
"user_interface"
] |
stackoverflow_0001851862_gtk_pygtk_python_user_interface.txt
|
Q:
How best to hold 1000 different data series using TimeSeries module in Python?
I want to create a massive TimeSeries object which will hold 1000 different financial markets data series, each storing 1500 daily-data points. I'm quite new to the TimeSeries module and am a little confused as to how I would best go about it. So a few basic questions:
1) Should I use a huge numpy array of 1000x1500 and simply feed that to the time series constructor function time_series()?
2) If I do this how will I index each series by name (eg "S&P500" or "GOLD" for example)? I know I will be able to access the array by date, but will I have to have a separate data structure to link series names with their column numbers in the large array?
3) Or should I use a structured data type as per the example given in the docs(http://pytseries.sourceforge.net/core.timeseries.html)? If so, how do I append series one by one to the timeseries, since I don't want to create a massive non-numpy structure to feed to the time_series() constructor in one shot?
Advice on where I can get some good examples for financial markets and timeseries module in general would also be appreciated.
Thanks.
A:
1) i once implemented a pagerank algorithm for a small set (~10K) of linked documents, therefore in during the calculation a 10Kx10K matrix had to be handled, for which the numpy array implementation was - as i recall - blazingly fast.
2) imho storing metadata like series name externally does not hurt that much ..
3) i haven't worked with scikits.timeseries, but would definitely look into it; as far as i can see, the project lives around the same scipy orbit as numpy ..
A:
For help on this, have a look at Quantlib which is a useful library for financial work, and which has an active users mailing list.
In addition, read this book review for a book entitled Financial Modeling in Python.
|
How best to hold 1000 different data series using TimeSeries module in Python?
|
I want to create a massive TimeSeries object which will hold 1000 different financial markets data series, each storing 1500 daily-data points. I'm quite new to the TimeSeries module and am a little confused as to how I would best go about it. So a few basic questions:
1) Should I use a huge numpy array of 1000x1500 and simply feed that to the time series constructor function time_series()?
2) If I do this how will I index each series by name (eg "S&P500" or "GOLD" for example)? I know I will be able to access the array by date, but will I have to have a separate data structure to link series names with their column numbers in the large array?
3) Or should I use a structured data type as per the example given in the docs(http://pytseries.sourceforge.net/core.timeseries.html)? If so, how do I append series one by one to the timeseries, since I don't want to create a massive non-numpy structure to feed to the time_series() constructor in one shot?
Advice on where I can get some good examples for financial markets and timeseries module in general would also be appreciated.
Thanks.
|
[
"1) i once implemented a pagerank algorithm for a small set (~10K) of linked documents, therefore in during the calculation a 10Kx10K matrix had to be handled, for which the numpy array implementation was - as i recall - blazingly fast.\n2) imho storing metadata like series name externally does not hurt that much ..\n3) i haven't worked with scikits.timeseries, but would definitely look into it; as far as i can see, the project lives around the same scipy orbit as numpy ..\n",
"For help on this, have a look at Quantlib which is a useful library for financial work, and which has an active users mailing list.\nIn addition, read this book review for a book entitled Financial Modeling in Python.\n"
] |
[
1,
0
] |
[] |
[] |
[
"finance",
"numpy",
"python"
] |
stackoverflow_0001894981_finance_numpy_python.txt
|
Q:
What are the various popularity metrics and sites for programming languages such as Ruby, Python, Java, etc?
What are the various sites that offer metrics that compare Ruby, Python, Perl, Smalltalk etc. What are their respective metrics?
Do any of them control or account for the time that Rails was introduced, and/or the adoption rates for various languages?
Will someone please help me close this question? Clearly it was not a successful venture :-)
A:
I don't mean to be nasty but what you are saying sounds like this to me: "I enjoy programming in Ruby and really don't want to learn another technology. Is there a site that can tell me that Ruby is not going away anytime soon to put my mind at ease?".
There is nothing wrong with that attitude but you have to be prepared to adapt to the changing environment and learn new technologies, techniques, do a little self-improvement if you want to remain competitive. Plenty of people are comfortable using five different programming languages. Boxing yourself into a narrow field will eventually disadvantage you.
You will also find that learning a second language is a lot easier than the first one. At the end of the day good programmers transcend the language barriers. This is what you should be doing instead of reading metrics that tell you that your language of choice is still popular.
A:
TIOBE attempts to rate the popularity of programming languages. Ruby is in the top 10 just below Perl. Therefore I would say that your investment is protected. As or what the index actually measures they can explain it better than I can.
A:
Better than Google trends is Google insight. It allows you to limit queries to a given subject, like eg programming. And since all of smalltalk, ruby, python, and perl are also used in other context, I limited the search to programming.
http://www.google.com/insights/search/#cat=31&q=smalltalk%2Cruby%2Cpython%2Cperl
If you choose "growth relative to category" the boost of Ruby search queries in 2005 is striking.
A:
Also, see Google trends comparing number of searches for ruby, python, php and perl over time.
A:
One of the more interesting metrics is the State of the Computer Book Market posts that Mike Hendrickson posts on his O'Reilly Radar blog. I tend to favor metrics that are tied to the exchange of value rather than spotty things like the number of search engine queries. His latest post doesn't drill down into topic areas, but sometimes they do (using nice TreeMaps even).
A:
Don't Worry
I also like Ruby1, and I worried about exactly the same thing.
But a closer look at the same data allayed my fears.
Ruby's Tiobe Index score has been fairly stable, after a big jump in popularity when Rails exploded onto the scene.
Ruby is in the top ten, albeit in the 10-slot. That's really quite good. It will pass Perl any day now and be #9, and may someday pass VB and, who knows, perhaps even C++.
Perhaps an initial decline was expected. Not long ago, hardly anyone knew Ruby, but lots of us knew the other languages. So perhaps a temporary flurry of Ruby activity was expected as people got up to speed.
Ruby is a great language. C and Java rule the world because both languages really do solve certain problems effectively. Ruby does too and it has the attention of the technology trend-setters. How much better could it really get?
You can learn another language easily. There is a worry, just not the one you identified. The problem is you won't want to work in lesser languages after learning Ruby and RoR.
1. The original version of the question revealed a concern about the future of Ruby.
A:
I usually use Google Trends for this:
http://www.google.com/trends
The more popular an item is (in this case a language) the more that people are searching for it.
If you look at this chart on Google Trends:
http://www.google.com/trends?q=+Ruby,+Python,+Perl,+Smalltalk
you'll see that they've all stayed pretty much flat except for Perl that's been steadily declining.
|
What are the various popularity metrics and sites for programming languages such as Ruby, Python, Java, etc?
|
What are the various sites that offer metrics that compare Ruby, Python, Perl, Smalltalk etc. What are their respective metrics?
Do any of them control or account for the time that Rails was introduced, and/or the adoption rates for various languages?
Will someone please help me close this question? Clearly it was not a successful venture :-)
|
[
"I don't mean to be nasty but what you are saying sounds like this to me: \"I enjoy programming in Ruby and really don't want to learn another technology. Is there a site that can tell me that Ruby is not going away anytime soon to put my mind at ease?\".\nThere is nothing wrong with that attitude but you have to be prepared to adapt to the changing environment and learn new technologies, techniques, do a little self-improvement if you want to remain competitive. Plenty of people are comfortable using five different programming languages. Boxing yourself into a narrow field will eventually disadvantage you.\nYou will also find that learning a second language is a lot easier than the first one. At the end of the day good programmers transcend the language barriers. This is what you should be doing instead of reading metrics that tell you that your language of choice is still popular.\n",
"TIOBE attempts to rate the popularity of programming languages. Ruby is in the top 10 just below Perl. Therefore I would say that your investment is protected. As or what the index actually measures they can explain it better than I can.\n",
"Better than Google trends is Google insight. It allows you to limit queries to a given subject, like eg programming. And since all of smalltalk, ruby, python, and perl are also used in other context, I limited the search to programming.\nhttp://www.google.com/insights/search/#cat=31&q=smalltalk%2Cruby%2Cpython%2Cperl\nIf you choose \"growth relative to category\" the boost of Ruby search queries in 2005 is striking.\n",
"Also, see Google trends comparing number of searches for ruby, python, php and perl over time.\n",
"One of the more interesting metrics is the State of the Computer Book Market posts that Mike Hendrickson posts on his O'Reilly Radar blog. I tend to favor metrics that are tied to the exchange of value rather than spotty things like the number of search engine queries. His latest post doesn't drill down into topic areas, but sometimes they do (using nice TreeMaps even).\n",
"Don't Worry\nI also like Ruby1, and I worried about exactly the same thing.\nBut a closer look at the same data allayed my fears.\n\nRuby's Tiobe Index score has been fairly stable, after a big jump in popularity when Rails exploded onto the scene.\nRuby is in the top ten, albeit in the 10-slot. That's really quite good. It will pass Perl any day now and be #9, and may someday pass VB and, who knows, perhaps even C++.\nPerhaps an initial decline was expected. Not long ago, hardly anyone knew Ruby, but lots of us knew the other languages. So perhaps a temporary flurry of Ruby activity was expected as people got up to speed.\nRuby is a great language. C and Java rule the world because both languages really do solve certain problems effectively. Ruby does too and it has the attention of the technology trend-setters. How much better could it really get?\nYou can learn another language easily. There is a worry, just not the one you identified. The problem is you won't want to work in lesser languages after learning Ruby and RoR.\n\n\n\n1. The original version of the question revealed a concern about the future of Ruby.\n",
"I usually use Google Trends for this:\nhttp://www.google.com/trends\nThe more popular an item is (in this case a language) the more that people are searching for it.\nIf you look at this chart on Google Trends:\nhttp://www.google.com/trends?q=+Ruby,+Python,+Perl,+Smalltalk\nyou'll see that they've all stayed pretty much flat except for Perl that's been steadily declining.\n"
] |
[
6,
4,
2,
1,
1,
1,
0
] |
[] |
[] |
[
"asp.net",
"c#",
"python",
"ruby",
"smalltalk"
] |
stackoverflow_0001892254_asp.net_c#_python_ruby_smalltalk.txt
|
Q:
Django loaddata ValidationError
This thread got too confusing (for me) so I am asking the question again. I could not make the csv2json.py script mentioned in the original question work. I am just trying to find a way to import data to sqlite3 database.
Here's the model I am working with:
from django.db import models
class School(models.Model):
school = models.CharField(max_length=300)
def __unicode__(self):
return self.school
class Lawyer(models.Model):
firm_url = models.URLField('Bio', max_length=200)
firm_name = models.CharField('Firm', max_length=100)
first = models.CharField('First Name', max_length=50)
last = models.CharField('Last Name', max_length=50)
year_graduated = models.IntegerField('Year graduated')
school = models.CharField(max_length=300)
school = models.ForeignKey(School)
class Meta:
ordering = ('?',)
def __unicode__(self):
return self.first
(I'll fix the duplicate "school" later.)
I have this data1.csv file:
pk,firm_url,firm_name,first,last,school,year_graduated
1,http://www.graychase.com/babbas, Gray & Chase, Amr A, Babbas, The George Washington University Law School, 2005
I have to put in "pk" and 1 manually as required by the script.
Then, I run the script and I get the data1.csv.json file:
[
{
"pk": 1,
"model": "wkw2.Lawyer",
"fields": {
"school": "The George Washington University Law School",
"last": "Babbas",
"firm_url": "http://www.graychase.com/babbas",
"year_graduated": "2005",
"firm_name": "Gray & Chase",
"first": "Amr A"
}
}
]
I put this file in the fixtures folder in the app directory and run manage.py loaddata data1.csv.json
and I get the error
Installing json fixture 'data1.csv' from 'C:\~\Django\sw2\wkw2\fixtures'.
Problem installing fixture 'C:\~\Django\sw2\wkw2\fixtures\data1.csv.json': Traceback (most recent call last):
File "C:\Python26\Lib\site-packages\django\core\management\commands\loaddata.py", line 150, in handle for obj in objects:
File "C:\Python26\lib\site-packages\django\core\serializers\json.py", line 41, in Deserializer for obj in PythonDeserializer(simplejson.load(stream)):
File "C:\Python26\lib\site-packages\django\core\serializers\python.py", line 95, in Deserializer data[field.attname] = field.rel.to._meta.get_fie(field.rel.field_name).to_python(field_value)
File "C:\Python26\lib\site-packages\django\db\models\fields\__init__.py", line 356, in to_python_("This value must be an integer."))
ValidationError: This value must be an integer.
When I comment out the two lines in the script with pk in them I get this error message:
Installing json fixture 'data1.csv' from 'C:\~\Django\sw2\wkw2\fixtures'.
Problem installing fixture 'C:\Users\A\Documents\Projects\Django\sw2\wkw2\fixtures\data1.csv.json': Traceback (most recent call last):
File "C:\Python26\Lib\site-packages\django\core\management\commands\loaddata.py", line 150, in handle for obj in objects:
File "C:\Python26\lib\site-packages\django\core\serializers\json.py", line 41, in Deserializer for obj in PythonDeserializer(simplejson.load(stream)):
File "C:\Python26\lib\site-packages\django\core\serializers\python.py", line 77, in Deserializer data = {Model._meta.pk.attname : Model._meta.pk.to_pytho(["pk"])}
KeyError: 'pk'
What am I doing wrong?
Edit:
I took out the quotes around the year to make it an integer but I still got the same ValidationError:
...
"year_graduated": 2005,
...
A:
(I'll fix the duplicate "school" later.)
Actually, that is your problem. The second definition of school as a foreign key will require it to be an integer, thus the error.
You can confirm this by dumping the schema of your table with
sqlite3 <database-file> '.schema wkw2_Lawyer'
|
Django loaddata ValidationError
|
This thread got too confusing (for me) so I am asking the question again. I could not make the csv2json.py script mentioned in the original question work. I am just trying to find a way to import data to sqlite3 database.
Here's the model I am working with:
from django.db import models
class School(models.Model):
school = models.CharField(max_length=300)
def __unicode__(self):
return self.school
class Lawyer(models.Model):
firm_url = models.URLField('Bio', max_length=200)
firm_name = models.CharField('Firm', max_length=100)
first = models.CharField('First Name', max_length=50)
last = models.CharField('Last Name', max_length=50)
year_graduated = models.IntegerField('Year graduated')
school = models.CharField(max_length=300)
school = models.ForeignKey(School)
class Meta:
ordering = ('?',)
def __unicode__(self):
return self.first
(I'll fix the duplicate "school" later.)
I have this data1.csv file:
pk,firm_url,firm_name,first,last,school,year_graduated
1,http://www.graychase.com/babbas, Gray & Chase, Amr A, Babbas, The George Washington University Law School, 2005
I have to put in "pk" and 1 manually as required by the script.
Then, I run the script and I get the data1.csv.json file:
[
{
"pk": 1,
"model": "wkw2.Lawyer",
"fields": {
"school": "The George Washington University Law School",
"last": "Babbas",
"firm_url": "http://www.graychase.com/babbas",
"year_graduated": "2005",
"firm_name": "Gray & Chase",
"first": "Amr A"
}
}
]
I put this file in the fixtures folder in the app directory and run manage.py loaddata data1.csv.json
and I get the error
Installing json fixture 'data1.csv' from 'C:\~\Django\sw2\wkw2\fixtures'.
Problem installing fixture 'C:\~\Django\sw2\wkw2\fixtures\data1.csv.json': Traceback (most recent call last):
File "C:\Python26\Lib\site-packages\django\core\management\commands\loaddata.py", line 150, in handle for obj in objects:
File "C:\Python26\lib\site-packages\django\core\serializers\json.py", line 41, in Deserializer for obj in PythonDeserializer(simplejson.load(stream)):
File "C:\Python26\lib\site-packages\django\core\serializers\python.py", line 95, in Deserializer data[field.attname] = field.rel.to._meta.get_fie(field.rel.field_name).to_python(field_value)
File "C:\Python26\lib\site-packages\django\db\models\fields\__init__.py", line 356, in to_python_("This value must be an integer."))
ValidationError: This value must be an integer.
When I comment out the two lines in the script with pk in them I get this error message:
Installing json fixture 'data1.csv' from 'C:\~\Django\sw2\wkw2\fixtures'.
Problem installing fixture 'C:\Users\A\Documents\Projects\Django\sw2\wkw2\fixtures\data1.csv.json': Traceback (most recent call last):
File "C:\Python26\Lib\site-packages\django\core\management\commands\loaddata.py", line 150, in handle for obj in objects:
File "C:\Python26\lib\site-packages\django\core\serializers\json.py", line 41, in Deserializer for obj in PythonDeserializer(simplejson.load(stream)):
File "C:\Python26\lib\site-packages\django\core\serializers\python.py", line 77, in Deserializer data = {Model._meta.pk.attname : Model._meta.pk.to_pytho(["pk"])}
KeyError: 'pk'
What am I doing wrong?
Edit:
I took out the quotes around the year to make it an integer but I still got the same ValidationError:
...
"year_graduated": 2005,
...
|
[
"\n(I'll fix the duplicate \"school\" later.)\n\nActually, that is your problem. The second definition of school as a foreign key will require it to be an integer, thus the error.\nYou can confirm this by dumping the schema of your table with \n\nsqlite3 <database-file> '.schema wkw2_Lawyer'\n\n"
] |
[
2
] |
[] |
[] |
[
"csv",
"django",
"json",
"python"
] |
stackoverflow_0001894628_csv_django_json_python.txt
|
Q:
How to pass an instance's reference in a method?
I have the following Bird definition:
class Bird:
def __init__(self, swarm, position = None):
if (swarm == None):
raise ValueError("swarm variable should not be None!")
if (not(type(swarm)).__name__ == 'ParticleSwarmOptimization'):
raise TypeError("swarm variable must be of type ParticleSwarmOptimization!")
It is raising error in the last line. In the interpreter it prints:
(type(swarm)).__name__
'instance'
I'd expect it to print "ParticleSwarmOptimization".
I'm calling Bird's constructor the following way:
def AddBird(self, position = None):
self.birds += Bird(self, position)
With this I want that every bird has a reference to the main ParticleSwarmOptimization class, and I want to ensure that every time a Bird is created I have in fact a ParticleSwarmOptimization instance reference and not anything else.
Thanks!
A:
use:
assert isinstance(swarm, ParticleSwarmOptimization)
The culture of Python is to not do these sorts of defensive checks, instead to simply use the variable. If it is of the wrong type, an exception will eventually be raised.
A:
Other people have mentioned the correct way to do this, however the reason you get that error is because you are using an old style class. To get a new-style class make your classes subclass object.
A:
try using
isinstance
instead.
|
How to pass an instance's reference in a method?
|
I have the following Bird definition:
class Bird:
def __init__(self, swarm, position = None):
if (swarm == None):
raise ValueError("swarm variable should not be None!")
if (not(type(swarm)).__name__ == 'ParticleSwarmOptimization'):
raise TypeError("swarm variable must be of type ParticleSwarmOptimization!")
It is raising error in the last line. In the interpreter it prints:
(type(swarm)).__name__
'instance'
I'd expect it to print "ParticleSwarmOptimization".
I'm calling Bird's constructor the following way:
def AddBird(self, position = None):
self.birds += Bird(self, position)
With this I want that every bird has a reference to the main ParticleSwarmOptimization class, and I want to ensure that every time a Bird is created I have in fact a ParticleSwarmOptimization instance reference and not anything else.
Thanks!
|
[
"use:\nassert isinstance(swarm, ParticleSwarmOptimization)\n\nThe culture of Python is to not do these sorts of defensive checks, instead to simply use the variable. If it is of the wrong type, an exception will eventually be raised.\n",
"Other people have mentioned the correct way to do this, however the reason you get that error is because you are using an old style class. To get a new-style class make your classes subclass object.\n",
"try using \nisinstance\n\ninstead.\n"
] |
[
4,
4,
0
] |
[] |
[] |
[
"python"
] |
stackoverflow_0001895501_python.txt
|
Q:
Emacs: Pymacs not loading ropemacs with Carbon Emacs
I'm attempting to use Pymacs with rope/ropemacs for flymake syntax checking as described here:
http://www.enigmacurry.com/2009/01/21/autocompleteel-python-code-completion-in-emacs/
When I start Carbon Emacs "normally" it throws the error:
error: Pymacs loading ropemacs...failed
I had this working on OSX 10.5 with Carbon Emacs but it fails in 10.6. However, it works when loading "terminal" emacs, Aquamacs, or if I open Carbon Emacs from the command line using "/Applications/Emacs.app/Contents/MacOS/Emacs". I'm assuming this is some kind of path error, but I can't figure it out for the life of me.
My setup is OSX 10.6.2 and I'm using macports python 2.6.4.
Thanks!
A:
Chances are it is a path problem. When you start an emacs from the terminal, your PATH environment variable presumably includes the MacPorts bin directory /opt/local/bin because presumably you modified one of your shell profiles, probably .bash_profile, to include that directory on PATH.
But when you launch an application directly (by double-clicking it) the shell is not involved so, by default, /opt/local/bin doesn't get included in the process's PATH variable. Depending on how Pymacs, et al, invoke python, it most likely ends up with the Apple-supplied python2.6 (python or /usr/bin/env python). If you can figure out where it's calling python, you could change that to an absolute path, like /opt/local/bin/python2.6.
If you can't figure out how to do that, you may be able to work around the problem by either modifying the plist file inside of the Carbon Emacs.app bundle to include a LSEnvironment key with the proper value for PATH. Or you can create a user-wide environment definition for PATH in ~/.MacOSX/environment.plist. Both options are described here.
Otherwise you could try installing Pymacs with the Apple-supplied Python 2.6.1.
By the way, the installation instructions in the link you cite use easy_install. If you need to install packages into the MacPorts python, make sure you install and use an easy_install instance for it and not use the Apple-supplied one in /usr/bin:
$ sudo port install py26-setuptools
$ /opt/local/bin/easy_install-2.6 <package>
|
Emacs: Pymacs not loading ropemacs with Carbon Emacs
|
I'm attempting to use Pymacs with rope/ropemacs for flymake syntax checking as described here:
http://www.enigmacurry.com/2009/01/21/autocompleteel-python-code-completion-in-emacs/
When I start Carbon Emacs "normally" it throws the error:
error: Pymacs loading ropemacs...failed
I had this working on OSX 10.5 with Carbon Emacs but it fails in 10.6. However, it works when loading "terminal" emacs, Aquamacs, or if I open Carbon Emacs from the command line using "/Applications/Emacs.app/Contents/MacOS/Emacs". I'm assuming this is some kind of path error, but I can't figure it out for the life of me.
My setup is OSX 10.6.2 and I'm using macports python 2.6.4.
Thanks!
|
[
"Chances are it is a path problem. When you start an emacs from the terminal, your PATH environment variable presumably includes the MacPorts bin directory /opt/local/bin because presumably you modified one of your shell profiles, probably .bash_profile, to include that directory on PATH.\nBut when you launch an application directly (by double-clicking it) the shell is not involved so, by default, /opt/local/bin doesn't get included in the process's PATH variable. Depending on how Pymacs, et al, invoke python, it most likely ends up with the Apple-supplied python2.6 (python or /usr/bin/env python). If you can figure out where it's calling python, you could change that to an absolute path, like /opt/local/bin/python2.6.\nIf you can't figure out how to do that, you may be able to work around the problem by either modifying the plist file inside of the Carbon Emacs.app bundle to include a LSEnvironment key with the proper value for PATH. Or you can create a user-wide environment definition for PATH in ~/.MacOSX/environment.plist. Both options are described here.\nOtherwise you could try installing Pymacs with the Apple-supplied Python 2.6.1.\nBy the way, the installation instructions in the link you cite use easy_install. If you need to install packages into the MacPorts python, make sure you install and use an easy_install instance for it and not use the Apple-supplied one in /usr/bin:\n$ sudo port install py26-setuptools\n$ /opt/local/bin/easy_install-2.6 <package>\n\n"
] |
[
1
] |
[] |
[] |
[
"emacs",
"flymake",
"pymacs",
"python",
"ropemacs"
] |
stackoverflow_0001895459_emacs_flymake_pymacs_python_ropemacs.txt
|
Q:
String representation of arrays in python
Is there anything that performs the following, in python? Or will I have to implement it myself?
array = [0, 1, 2]
myString = SOME_FUNCTION_THAT_TAKES_AN_ARRAY_AS_INPUT(array)
print myString
which prints
(0, 1, 2)
Thanks
A:
You're in luck, Python has a function for this purpose exactly. It's called join.
print "(" + ", ".join(array) + ")"
If you're familiar with PHP, join is similar to implode. The ", " above is the element separator, and can be replaced with any string. For example,
print "123".join(['a','b','c'])
will print
a123b123c
A:
def SOME_FUNCTION_THAT_TAKES_AN_ARRAY_AS_INPUT (arr):
return str(tuple(arr))
Replace str with unicode if you need to.
A:
SOME_FUNCTION_THAT_TAKES_AN_ARRAY_AS_INPUT = tuple
A:
If your array's items are specifically integers, str(tuple(array)) as suggested in @jboxer's answer will work. For most other types of items, it may be more of a problem, since str(tuple(...)) uses repr, not str -- that's really needed as a default behavior (otherwise printing a tuple with an item such as the string '1, 2' would be extremely confusing, looking just like a string with the two int items 1 and 2!-), but it may or may not be what you want. For example:
>>> array = [0.1, 0.2]
>>> print str(tuple(array))
(0.10000000000000001, 0.20000000000000001)
With floating point numbers, repr emits many more digits than make sense in most cases (while str, if called directly on the numbers, behaves a bit better). So if your items are liable to be floats (as well as ints, which would need no precaution but won't be hurt by this one;-), you might better off with:
>>> print '(%s)' % (', '.join(str(x) for x in array))
(0.1, 0.2)
However, this might produce ambiguous output if some of the items are strings, as I mentioned earlier!
If you know what types of data you're liable to have in the list which you call "array", it would give a better basis on which to recommend a solution.
|
String representation of arrays in python
|
Is there anything that performs the following, in python? Or will I have to implement it myself?
array = [0, 1, 2]
myString = SOME_FUNCTION_THAT_TAKES_AN_ARRAY_AS_INPUT(array)
print myString
which prints
(0, 1, 2)
Thanks
|
[
"You're in luck, Python has a function for this purpose exactly. It's called join.\nprint \"(\" + \", \".join(array) + \")\"\n\nIf you're familiar with PHP, join is similar to implode. The \", \" above is the element separator, and can be replaced with any string. For example,\nprint \"123\".join(['a','b','c'])\n\nwill print\na123b123c\n\n",
"def SOME_FUNCTION_THAT_TAKES_AN_ARRAY_AS_INPUT (arr):\n return str(tuple(arr))\n\nReplace str with unicode if you need to.\n",
"SOME_FUNCTION_THAT_TAKES_AN_ARRAY_AS_INPUT = tuple \n\n",
"If your array's items are specifically integers, str(tuple(array)) as suggested in @jboxer's answer will work. For most other types of items, it may be more of a problem, since str(tuple(...)) uses repr, not str -- that's really needed as a default behavior (otherwise printing a tuple with an item such as the string '1, 2' would be extremely confusing, looking just like a string with the two int items 1 and 2!-), but it may or may not be what you want. For example:\n>>> array = [0.1, 0.2]\n>>> print str(tuple(array))\n(0.10000000000000001, 0.20000000000000001)\n\nWith floating point numbers, repr emits many more digits than make sense in most cases (while str, if called directly on the numbers, behaves a bit better). So if your items are liable to be floats (as well as ints, which would need no precaution but won't be hurt by this one;-), you might better off with:\n>>> print '(%s)' % (', '.join(str(x) for x in array))\n(0.1, 0.2)\n\nHowever, this might produce ambiguous output if some of the items are strings, as I mentioned earlier!\nIf you know what types of data you're liable to have in the list which you call \"array\", it would give a better basis on which to recommend a solution.\n"
] |
[
5,
5,
4,
2
] |
[] |
[] |
[
"python"
] |
stackoverflow_0001895539_python.txt
|
Q:
How to filter data from a file using Python?
I'm trying to filter certain data from an HTML file. For example, the HTML file is as follows:
<tr><td valign="top"><img src="/icons/unknown.gif" alt="[ ]">software_0.1-0.log</td><td align="right">17-Nov-2009 13:46 </td><td align="right">186K</td></tr>
I need to extract the software_0.1-0 part as well as the 17-Nov-2009 part. How can I do this?
Thanks a lot.
A:
It's quite easy with BeautifulSoup:
html = '''<tr><td valign="top"><img src="/icons/unknown.gif" alt="[ ]">software_0.1-0.log</td><td align="right">17-Nov-2009 13:46 </td><td align="right">186K</td></tr>'''
import BeautifulSoup
soup = BeautifulSoup.BeautifulSoup(html)
print soup.td.next.next
print soup.td.nextSibling.next
Output:
software_0.1-0.log
17-Nov-2009 13:46
A:
You can extract the strings of interest (and some more text) using for example the popular beautifulsoup package. Then, you'll need some string manipulation (or maybe regular expressions) to separate the exact part of interest, but that depends on exactly what are the rules you want to apply -- i.e., is it always the .log suffix you want to drop from the filename, is it always a space that separates the date from the time, and so forth. If you specify the rules precisely it will not be hard to implement them (without a precise specification, however, it would all be a big mess of guesses;-).
A:
Try Beautifull Soup, a parser for HTML. You'll get a structured document out of there and could select the first and second td contents.
It may be overkill in this instance, but especially if your HTML is from the outside and can change the maintenance guy will thank you for choosing a readable solution.
A:
you requirement seems simple, so here's the non BeautifulSoup way, just pure string manipulation
s="""<tr><td valign="top"><img src="/icons/unknown.gif" alt="[ ]">software_0.1-0.log</td><td align="right">17-Nov-2009 13:46 </td><td align="right">186K</td></tr>"""
string=s.split(">")
for i in string:
try:
e=i.index("<")
except: pass
else:
print i[:e]
Now you can use i[:e] to find "software" and the date part
|
How to filter data from a file using Python?
|
I'm trying to filter certain data from an HTML file. For example, the HTML file is as follows:
<tr><td valign="top"><img src="/icons/unknown.gif" alt="[ ]">software_0.1-0.log</td><td align="right">17-Nov-2009 13:46 </td><td align="right">186K</td></tr>
I need to extract the software_0.1-0 part as well as the 17-Nov-2009 part. How can I do this?
Thanks a lot.
|
[
"It's quite easy with BeautifulSoup:\nhtml = '''<tr><td valign=\"top\"><img src=\"/icons/unknown.gif\" alt=\"[ ]\">software_0.1-0.log</td><td align=\"right\">17-Nov-2009 13:46 </td><td align=\"right\">186K</td></tr>'''\n\nimport BeautifulSoup\nsoup = BeautifulSoup.BeautifulSoup(html)\nprint soup.td.next.next\nprint soup.td.nextSibling.next\n\nOutput:\nsoftware_0.1-0.log\n17-Nov-2009 13:46\n\n",
"You can extract the strings of interest (and some more text) using for example the popular beautifulsoup package. Then, you'll need some string manipulation (or maybe regular expressions) to separate the exact part of interest, but that depends on exactly what are the rules you want to apply -- i.e., is it always the .log suffix you want to drop from the filename, is it always a space that separates the date from the time, and so forth. If you specify the rules precisely it will not be hard to implement them (without a precise specification, however, it would all be a big mess of guesses;-).\n",
"Try Beautifull Soup, a parser for HTML. You'll get a structured document out of there and could select the first and second td contents.\nIt may be overkill in this instance, but especially if your HTML is from the outside and can change the maintenance guy will thank you for choosing a readable solution.\n",
"you requirement seems simple, so here's the non BeautifulSoup way, just pure string manipulation\ns=\"\"\"<tr><td valign=\"top\"><img src=\"/icons/unknown.gif\" alt=\"[ ]\">software_0.1-0.log</td><td align=\"right\">17-Nov-2009 13:46 </td><td align=\"right\">186K</td></tr>\"\"\"\n\nstring=s.split(\">\")\nfor i in string:\n try:\n e=i.index(\"<\")\n except: pass\n else:\n print i[:e]\n\nNow you can use i[:e] to find \"software\" and the date part\n"
] |
[
6,
2,
0,
0
] |
[] |
[] |
[
"filter",
"parsing",
"python"
] |
stackoverflow_0001894711_filter_parsing_python.txt
|
Q:
How can I create a regular expression in Python?
I'm trying to create regular expressions to filter certain text from a text file. What I want to filter has this format:
word_*_word.word
So for example, I would like the python code every match. Sample results would be:
program1_0.0-1_log.build
program2_0.1-3_log.build
How can I do this?
Thanks a lot for your help
A:
Try something like this:
r'[a-zA-Z0-9]+_[^_]+_[a-zA-Z0-9]+\.[a-zA-Z0-9]+'
A:
Looks like you want to use a pattern such as r'\w+_.*_\w+\.\w+' -- assuming that * you have does stand for "zero or more totally arbitrary characters" (if not, then the .* part in the middle needs to be changed accordingly). Once you have the right pattern (depending exactly on what you mean by that *;-), you can re.compile it to get a regular expression object, and use the .findall method of the RE object, with your overall string as an argument, to get a list of all non-overlapping substrings matching this pattern (there are also alternatives such as e.g. .finditer if you want to get one such substring at a time, looping over them).
A:
Python's regular expression module is called re. You need to import it and use the provided functions:
import re
if re.match(r'\w+_.*_\w+.\w+', "some_text_abc.x"):
print "yeah."
It is useful to prefix the regular expression string with r, so that it will be interpreted literally, without special handling for escape characters. Otherwise backslashes will be treated specially by the python interpreter and backslashes that are part of the regular expression need to be escaped.
A:
try with ^\w+_.*_\w+\.\w+$
A:
i don't understand why you would need a regex here.
If the strings you want ends with ".build", you can do this for example
s="blah blah program1_0.0-1_log.build blah blah"
for item in s.split():
if item.endswith(".build"):
print item
and that's it. If you want to do further checking, then
for item in s.split():
if item.endswith(".build"):
s = item.split("_")
if len(s) != 3:
print "not enough _"
|
How can I create a regular expression in Python?
|
I'm trying to create regular expressions to filter certain text from a text file. What I want to filter has this format:
word_*_word.word
So for example, I would like the python code every match. Sample results would be:
program1_0.0-1_log.build
program2_0.1-3_log.build
How can I do this?
Thanks a lot for your help
|
[
"Try something like this:\nr'[a-zA-Z0-9]+_[^_]+_[a-zA-Z0-9]+\\.[a-zA-Z0-9]+'\n\n",
"Looks like you want to use a pattern such as r'\\w+_.*_\\w+\\.\\w+' -- assuming that * you have does stand for \"zero or more totally arbitrary characters\" (if not, then the .* part in the middle needs to be changed accordingly). Once you have the right pattern (depending exactly on what you mean by that *;-), you can re.compile it to get a regular expression object, and use the .findall method of the RE object, with your overall string as an argument, to get a list of all non-overlapping substrings matching this pattern (there are also alternatives such as e.g. .finditer if you want to get one such substring at a time, looping over them).\n",
"Python's regular expression module is called re. You need to import it and use the provided functions:\nimport re\nif re.match(r'\\w+_.*_\\w+.\\w+', \"some_text_abc.x\"):\n print \"yeah.\"\n\nIt is useful to prefix the regular expression string with r, so that it will be interpreted literally, without special handling for escape characters. Otherwise backslashes will be treated specially by the python interpreter and backslashes that are part of the regular expression need to be escaped.\n",
"try with ^\\w+_.*_\\w+\\.\\w+$\n",
"i don't understand why you would need a regex here. \nIf the strings you want ends with \".build\", you can do this for example\ns=\"blah blah program1_0.0-1_log.build blah blah\" \nfor item in s.split():\n if item.endswith(\".build\"):\n print item\n\nand that's it. If you want to do further checking, then\nfor item in s.split():\n if item.endswith(\".build\"):\n s = item.split(\"_\")\n if len(s) != 3:\n print \"not enough _\"\n\n"
] |
[
3,
3,
1,
0,
0
] |
[] |
[] |
[
"python",
"regex"
] |
stackoverflow_0001895026_python_regex.txt
|
Q:
Persistent MySQL connections in Python
PHP provides mysql_connect() and mysql_pconnect() which allow creating both temporary and persistent database connections.
Is there a similar functionality in Python? The environment on which this will be used is lighttpd server with FastCGI.
Thank you!
A:
If you're using FastCGI, there's no need for "persistent connections", because if you create a connection it is by default persistent, since FastCGI python isn't request based, but constantly running.
This is how FastCGI works in python, to put it short:
1. Run startup code
2. Run request function
3. Wait for new request, then goto step 2.
In PHP/FastCGI this is different, because only the PHP engine is loaded all the time, while the PHP script itself is executed for each request.
1. Start PHP Engine
2. Run script
3. Wait for new request, then goto step 2.
So the difference is that in Python you can define your own initialization. And that's where you put your MySQL connection. :)
A:
Note: Persistent connections can have a very negative effect on your system performance. If you have a large number of web server processes all holding persistent connections to your DB server you may exhaust the DB server's limit on connections. This is one of those areas where you need to test it under heavy simulated loads to make sure you won't hit the wall at 100MPH.
|
Persistent MySQL connections in Python
|
PHP provides mysql_connect() and mysql_pconnect() which allow creating both temporary and persistent database connections.
Is there a similar functionality in Python? The environment on which this will be used is lighttpd server with FastCGI.
Thank you!
|
[
"If you're using FastCGI, there's no need for \"persistent connections\", because if you create a connection it is by default persistent, since FastCGI python isn't request based, but constantly running.\nThis is how FastCGI works in python, to put it short:\n1. Run startup code\n2. Run request function\n3. Wait for new request, then goto step 2. \n\nIn PHP/FastCGI this is different, because only the PHP engine is loaded all the time, while the PHP script itself is executed for each request.\n1. Start PHP Engine\n2. Run script\n3. Wait for new request, then goto step 2.\n\nSo the difference is that in Python you can define your own initialization. And that's where you put your MySQL connection. :)\n",
"Note: Persistent connections can have a very negative effect on your system performance. If you have a large number of web server processes all holding persistent connections to your DB server you may exhaust the DB server's limit on connections. This is one of those areas where you need to test it under heavy simulated loads to make sure you won't hit the wall at 100MPH.\n"
] |
[
5,
0
] |
[] |
[] |
[
"mysql",
"python",
"web_services"
] |
stackoverflow_0001895089_mysql_python_web_services.txt
|
Q:
Imports with Pydev/Eclipse
I'm working with the interactive console in eclipse, and reload does not show updated functions in my code. My code was :
def func1():
return 1
def func2():
return 2
but when I changed it to
def afunc1():
return 1
def func2():
return 2
def func1():
return 3
and ran imp.reload(TestMod), I got a 'module' object has no attribute 'afunc1()'.
Also, sometimes the functions are loaded and sometimes they are not.
A:
Turns out, eclipse was not saving the file (or not saving it to the correct location) when I hit ctl-s. To get it to work, I had to right click the file name in the Package Explorer and select open with PyDev and save it under that
|
Imports with Pydev/Eclipse
|
I'm working with the interactive console in eclipse, and reload does not show updated functions in my code. My code was :
def func1():
return 1
def func2():
return 2
but when I changed it to
def afunc1():
return 1
def func2():
return 2
def func1():
return 3
and ran imp.reload(TestMod), I got a 'module' object has no attribute 'afunc1()'.
Also, sometimes the functions are loaded and sometimes they are not.
|
[
"Turns out, eclipse was not saving the file (or not saving it to the correct location) when I hit ctl-s. To get it to work, I had to right click the file name in the Package Explorer and select open with PyDev and save it under that\n"
] |
[
0
] |
[] |
[] |
[
"eclipse",
"import",
"pydev",
"python",
"reload"
] |
stackoverflow_0001895745_eclipse_import_pydev_python_reload.txt
|
Q:
Inheritance and factory functions in Python and Django
I'm creating a Django app that uses some inheritance in it's model, mainly because I need to assign everything a UUID and a reference so I know what class it was. Here's a simplified version of the base class:
class BaseElement(models.Model):
uuid = models.CharField(max_length=64, editable=False, blank=True, default=lambda:unicode(uuid4()))
objmodule = models.CharField(max_length=255, editable=False, blank=False)
objclass = models.CharField(max_length=255, editable=False, blank=False)
class ChildElement(BaseElement):
somefield = models.CharField(max_length=255)
I'd like to make sure that objmodule, objclass, and uuid are set automatically. I've learned from this post that it's a bad idea to do that by writing my own constructor, and that I'm better off writing a factory function. So now my BaseElement and ChildElement looks like this:
class BaseElement(models.Model):
uuid = models.CharField(max_length=64, editable=False, blank=True, default=lambda:unicode(uuid4()))
objmodule = models.CharField(max_length=255, editable=False, blank=False)
objclass = models.CharField(max_length=255, editable=False, blank=False)
def set_defaults(self):
self.objmodule = unicode(self.__class__.__module__)
self.objclass = unicode(self.__class__.__name__)
self.uuid = unicode(uuid4())
class ChildElement(BaseElement):
somefield = models.CharField(max_length=255)
@staticmethod
def create(*args, **kwargs):
ce = ChildElement(*args, **kwargs)
ce.set_defaults()
return ce
This works. I can call ChildElement.create(somefield="foo") and I will get an appropriate object with uuid, objmodule, and objclass fields set correct. However, as I go through and create more classes like ChildElement2 and ChildElement3, I'm finding that I'm inserting the exact same static factory function. This grates on me because code duplication is bad.
With normal methods I'd just insert the create factory function in BaseElement, however, I can't do that here because I don't have a handle to self (because it hasn't been created yet) to get information about the class of the object that invoked the method.
Is there a way that I can migrate this factory into the BaseElement class so I don't have to duplicate this code everywhere and still have it so it automatically sets the values of uuid, objmodule, and objclass?
A:
If you make create() a @classmethod instead of @staticmethod, you'll have access to the class object, which you can use instead of referring to it by name:
@classmethod
def create(cls, *args, **kwargs):
obj = cls(*args, **kwargs)
obj.set_defaults()
return obj
This is now generic and can go on the base class instead of each child class.
A:
I think you might have been better off overriding save in your BaseElement instead. Then on save you could set those fields. It'd be something like:
class MyBase(models.Model):
uuid = models.CharField(max_length=64, editable=False, blank=True,
default=lambda:unicode(uuid4()))
objmodule = models.CharField(max_length=255, editable=False, blank=False)
objclass = models.CharField(max_length=255, editable=False, blank=False)
def save(self):
if not self.id:
self.objmodule = unicode(self.__class__.__module__)
self.objclass = unicode(self.__class__.__name__)
self.uuid = unicode(uuid4())
super(self.__class__.__base__, self).save()
class InheritedFromBase(MyBase):
new_field = models.CharField(max_length=100)
I tested with that and it seemed to do what you're looking for. I was able to create an "InheritedFromBase" object that had the fields you needed, without a lot of code duplication.
|
Inheritance and factory functions in Python and Django
|
I'm creating a Django app that uses some inheritance in it's model, mainly because I need to assign everything a UUID and a reference so I know what class it was. Here's a simplified version of the base class:
class BaseElement(models.Model):
uuid = models.CharField(max_length=64, editable=False, blank=True, default=lambda:unicode(uuid4()))
objmodule = models.CharField(max_length=255, editable=False, blank=False)
objclass = models.CharField(max_length=255, editable=False, blank=False)
class ChildElement(BaseElement):
somefield = models.CharField(max_length=255)
I'd like to make sure that objmodule, objclass, and uuid are set automatically. I've learned from this post that it's a bad idea to do that by writing my own constructor, and that I'm better off writing a factory function. So now my BaseElement and ChildElement looks like this:
class BaseElement(models.Model):
uuid = models.CharField(max_length=64, editable=False, blank=True, default=lambda:unicode(uuid4()))
objmodule = models.CharField(max_length=255, editable=False, blank=False)
objclass = models.CharField(max_length=255, editable=False, blank=False)
def set_defaults(self):
self.objmodule = unicode(self.__class__.__module__)
self.objclass = unicode(self.__class__.__name__)
self.uuid = unicode(uuid4())
class ChildElement(BaseElement):
somefield = models.CharField(max_length=255)
@staticmethod
def create(*args, **kwargs):
ce = ChildElement(*args, **kwargs)
ce.set_defaults()
return ce
This works. I can call ChildElement.create(somefield="foo") and I will get an appropriate object with uuid, objmodule, and objclass fields set correct. However, as I go through and create more classes like ChildElement2 and ChildElement3, I'm finding that I'm inserting the exact same static factory function. This grates on me because code duplication is bad.
With normal methods I'd just insert the create factory function in BaseElement, however, I can't do that here because I don't have a handle to self (because it hasn't been created yet) to get information about the class of the object that invoked the method.
Is there a way that I can migrate this factory into the BaseElement class so I don't have to duplicate this code everywhere and still have it so it automatically sets the values of uuid, objmodule, and objclass?
|
[
"If you make create() a @classmethod instead of @staticmethod, you'll have access to the class object, which you can use instead of referring to it by name:\n@classmethod\ndef create(cls, *args, **kwargs):\n obj = cls(*args, **kwargs)\n obj.set_defaults()\n return obj\n\nThis is now generic and can go on the base class instead of each child class.\n",
"I think you might have been better off overriding save in your BaseElement instead. Then on save you could set those fields. It'd be something like:\nclass MyBase(models.Model):\n uuid = models.CharField(max_length=64, editable=False, blank=True,\n default=lambda:unicode(uuid4()))\n objmodule = models.CharField(max_length=255, editable=False, blank=False)\n objclass = models.CharField(max_length=255, editable=False, blank=False)\n\n def save(self):\n if not self.id:\n self.objmodule = unicode(self.__class__.__module__)\n self.objclass = unicode(self.__class__.__name__)\n self.uuid = unicode(uuid4())\n super(self.__class__.__base__, self).save()\n\nclass InheritedFromBase(MyBase):\n new_field = models.CharField(max_length=100)\n\nI tested with that and it seemed to do what you're looking for. I was able to create an \"InheritedFromBase\" object that had the fields you needed, without a lot of code duplication.\n"
] |
[
7,
2
] |
[] |
[] |
[
"django",
"inheritance",
"python"
] |
stackoverflow_0001891004_django_inheritance_python.txt
|
Q:
How to determine the datatype in Python?
astring
('a','tuple')
How do I determine if "x" is a tuple or string?
A:
if isinstance(x, basestring):
# a string
else:
try: it = iter(x)
except TypeError:
# not an iterable
else:
# iterable (tuple, list, etc)
@Alex Martelli's answer describes in detail why you should prefer the above style when you're working with types in Python (thanks to @Mike Hordecki for the link).
A:
isinstance(x, str)
isinstance(x, tuple)
In general:
isinstance(variable, type)
Checks whether variable is an instance of type (or its subtype) (docs).
PS. Don't forget that strings can also be in unicode (isinstance(x, unicode) in this case) (or isinstance(x, basestring) (thanks, J.F. Sebastian!) which checks for both str and unicode).
A:
use isinstance(), general syntax is:
if isinstance(var, type):
# do something
|
How to determine the datatype in Python?
|
astring
('a','tuple')
How do I determine if "x" is a tuple or string?
|
[
"if isinstance(x, basestring):\n # a string\nelse:\n try: it = iter(x)\n except TypeError:\n # not an iterable\n else:\n # iterable (tuple, list, etc)\n\n@Alex Martelli's answer describes in detail why you should prefer the above style when you're working with types in Python (thanks to @Mike Hordecki for the link).\n",
"isinstance(x, str)\nisinstance(x, tuple)\n\nIn general:\nisinstance(variable, type)\n\nChecks whether variable is an instance of type (or its subtype) (docs).\nPS. Don't forget that strings can also be in unicode (isinstance(x, unicode) in this case) (or isinstance(x, basestring) (thanks, J.F. Sebastian!) which checks for both str and unicode).\n",
"use isinstance(), general syntax is:\nif isinstance(var, type):\n # do something\n\n"
] |
[
8,
5,
0
] |
[] |
[] |
[
"python"
] |
stackoverflow_0001896261_python.txt
|
Q:
Will this urllib2 python code download the page of the file?
urllib2.urlopen(theurl).read() ...this downloads the file.
urllib2.urlopen(theurl).geturl()...does this download the file? (how long does it take)
A:
From the documentation:
The geturl() method returns the real
URL of the page. In some cases, the
HTTP server redirects a client to
another URL. The urlopen() function
handles this transparently, but in
some cases the caller needs to know
which URL the client was redirected
to. The geturl() method can be used to
get at this redirected URL.
A:
Tested with Wireshark and Python 2.5: urllib2.urlopen(theurl).geturl() downloads some of the body. It issues a GET, reads the header and a couple of K of the body, and then stops.
A:
It does not.
For me, a test on google.com:
x= time.time(); urllib2.urlopen("http://www.google.com").read(); print time.time()-x
0.166881084442
x= time.time(); urllib2.urlopen("http://www.google.com").geturl(); print time.time()-x
0.0772399902344
A:
urllib2.urlopen() returns a file like object, so that when using urlopen() you are actually download the document, and it's loaded into your machine's memory, you can use file functions to read write your file, like so...
#to store python.org into your local file d:\python.org.html
from urllib2 import urlopen
doc = urlopen("http://www.python.org")
html=doc.read( )
f=open("d:/python.org.html","w+")
f.write(html)
f.close()
or simply using urllib
import urllib
urllib.urlretrieve("http://www.python.org","d:/python.org.html")
hope that helps ;)
A:
No. geturl() returns the url.
For example; urllib2.urlopen("http://www.python.org").geturl() returns the string 'http://www.python.org'.
You can find this sort of stuff really easily in the python interactive shell e.g;
$ python
Python 2.4.3 (#1, Jul 27 2009, 17:57:39)
[GCC 4.1.2 20080704 (Red Hat 4.1.2-44)] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> import urllib2
>>> u = urllib2.urlopen("http://www.python.org")
>>> u.geturl()
'http://www.python.org'
>>>
|
Will this urllib2 python code download the page of the file?
|
urllib2.urlopen(theurl).read() ...this downloads the file.
urllib2.urlopen(theurl).geturl()...does this download the file? (how long does it take)
|
[
"From the documentation:\n\nThe geturl() method returns the real\n URL of the page. In some cases, the\n HTTP server redirects a client to\n another URL. The urlopen() function\n handles this transparently, but in\n some cases the caller needs to know\n which URL the client was redirected\n to. The geturl() method can be used to\n get at this redirected URL.\n\n",
"Tested with Wireshark and Python 2.5: urllib2.urlopen(theurl).geturl() downloads some of the body. It issues a GET, reads the header and a couple of K of the body, and then stops.\n",
"It does not.\nFor me, a test on google.com:\nx= time.time(); urllib2.urlopen(\"http://www.google.com\").read(); print time.time()-x\n0.166881084442\n\nx= time.time(); urllib2.urlopen(\"http://www.google.com\").geturl(); print time.time()-x\n0.0772399902344\n\n",
"urllib2.urlopen() returns a file like object, so that when using urlopen() you are actually download the document, and it's loaded into your machine's memory, you can use file functions to read write your file, like so...\n#to store python.org into your local file d:\\python.org.html\nfrom urllib2 import urlopen\ndoc = urlopen(\"http://www.python.org\")\nhtml=doc.read( )\nf=open(\"d:/python.org.html\",\"w+\")\nf.write(html)\nf.close()\n\nor simply using urllib\nimport urllib\nurllib.urlretrieve(\"http://www.python.org\",\"d:/python.org.html\")\n\nhope that helps ;)\n",
"No. geturl() returns the url.\nFor example; urllib2.urlopen(\"http://www.python.org\").geturl() returns the string 'http://www.python.org'.\nYou can find this sort of stuff really easily in the python interactive shell e.g;\n$ python\nPython 2.4.3 (#1, Jul 27 2009, 17:57:39)\n[GCC 4.1.2 20080704 (Red Hat 4.1.2-44)] on linux2\nType \"help\", \"copyright\", \"credits\" or \"license\" for more information.\n>>> import urllib2\n>>> u = urllib2.urlopen(\"http://www.python.org\")\n>>> u.geturl()\n'http://www.python.org'\n>>>\n\n"
] |
[
5,
4,
3,
2,
1
] |
[] |
[] |
[
"http",
"python",
"urllib2"
] |
stackoverflow_0001895949_http_python_urllib2.txt
|
Q:
Pythonic way to write a for loop that doesn't use the loop index
This is to do with the following code, which uses a for loop to generate a series of random offsets for use elsewhere in the program.
The index of this for loop is unused, and this is resulting in the 'offending' code being highlighted as a warning by Eclipse / PyDev
def RandomSample(count):
pattern = []
for i in range(count):
pattern.append( (random() - 0.5, random() - 0.5) )
return pattern
So I either need a better way to write this loop that doesn't need a loop index, or a way to tell PyDev to ignore this particular instance of an unused variable.
Does anyone have any suggestions?
A:
Just for reference for ignoring variables in PyDev
By default pydev will ignore following variables
['_', 'empty', 'unused', 'dummy']
You can add more by passing supression parameters
-E, --unusednames ignore unused locals/arguments if name is one of these values
Ref:
http://eclipse-pydev.sourcearchive.com/documentation/1.0.3/PyCheckerLauncher_8java-source.html
A:
How about itertools.repeat:
import itertools
count = 5
def make_pat():
return (random() - 0.5, random() - 0.5)
list(x() for x in itertools.repeat(make_pat, count))
Sample output:
[(-0.056940506273799985, 0.27886450895662607),
(-0.48772848046066863, 0.24359038079935535),
(0.1523758626306998, 0.34423337290256517),
(-0.018504578280469697, 0.33002406492294756),
(0.052096928160727196, -0.49089780124549254)]
A:
randomSample = [(random() - 0.5, random() - 0.5) for _ in range(count)]
Sample output, for count=10 and assuming that you mean the Standard Library random() function:
[(-0.07, -0.40), (0.39, 0.18), (0.13, 0.29), (-0.11, -0.15),\
(-0.49, 0.42), (-0.20, 0.21), (-0.44, 0.36), (0.22, -0.08),\
(0.21, 0.31), (0.33, 0.02)]
If you really need to make it a function, then you can abbreviate by using a lambda:
f = lambda count: [(random() - 0.5, random() - 0.5) for _ in range(count)]
This way you can call it like:
>>> f(1)
f(1)
[(0.03, -0.09)]
>>> f(2)
f(2)
[(-0.13, 0.38), (0.10, -0.04)]
>>> f(5)
f(5)
[(-0.38, -0.14), (0.31, -0.16), (-0.34, -0.46), (-0.45, 0.28), (-0.01, -0.18)]
>>> f(10)
f(10)
[(0.01, -0.24), (0.39, -0.11), (-0.06, 0.09), (0.42, -0.26), (0.24, -0.44) , (-0.29, -0.30), (-0.27, 0.45), (0.10, -0.41), (0.36, -0.07), (0.00, -0.42)]
>>>
you get the idea...
A:
Late to the party, but here's a potential idea:
def RandomSample(count):
f = lambda: random() - 0.5
r = range if count < 100 else xrange # or some other number
return [(f(), f()) for _ in r(count)]
Strictly speaking, this is more or less the same as the other answers, but it does two things that look kind of nice to me.
First, it removes that duplicate code you have from writing random() - 0.5 twice by putting that into a lambda.
Second, for a certain size range, it chooses to use xrange() instead of range() so as not to unnecessarily generate a giant list of numbers you're going to throw away. You may want to adjust the exact number, because I haven't played with it at all, I just thought it might be a potential efficiency concern.
A:
There should be a way to suppress code analysis errors in PyDev, like this:
http://pydev.org/manual_adv_assistants.html
Also, PyDev will ignore unused variables that begin with an underscore, as shown here:
http://pydev.org/manual_adv_code_analysis.html
A:
Try this:
while count > 0:
pattern.append((random() - 0.5, random() - 0.5))
count -= 1
A:
import itertools, random
def RandomSample2D(npoints, get_random=lambda: random.uniform(-.5, .5)):
return ((r(), r()) for r in itertools.repeat(get_random, npoints))
uses random.uniform() explicitly
returns an iterator instead of list
|
Pythonic way to write a for loop that doesn't use the loop index
|
This is to do with the following code, which uses a for loop to generate a series of random offsets for use elsewhere in the program.
The index of this for loop is unused, and this is resulting in the 'offending' code being highlighted as a warning by Eclipse / PyDev
def RandomSample(count):
pattern = []
for i in range(count):
pattern.append( (random() - 0.5, random() - 0.5) )
return pattern
So I either need a better way to write this loop that doesn't need a loop index, or a way to tell PyDev to ignore this particular instance of an unused variable.
Does anyone have any suggestions?
|
[
"Just for reference for ignoring variables in PyDev\nBy default pydev will ignore following variables \n['_', 'empty', 'unused', 'dummy']\n\nYou can add more by passing supression parameters\n-E, --unusednames ignore unused locals/arguments if name is one of these values\n\nRef:\nhttp://eclipse-pydev.sourcearchive.com/documentation/1.0.3/PyCheckerLauncher_8java-source.html\n",
"How about itertools.repeat:\nimport itertools\ncount = 5\ndef make_pat():\n return (random() - 0.5, random() - 0.5)\nlist(x() for x in itertools.repeat(make_pat, count))\n\nSample output:\n[(-0.056940506273799985, 0.27886450895662607), \n(-0.48772848046066863, 0.24359038079935535), \n(0.1523758626306998, 0.34423337290256517), \n(-0.018504578280469697, 0.33002406492294756), \n(0.052096928160727196, -0.49089780124549254)]\n\n",
"randomSample = [(random() - 0.5, random() - 0.5) for _ in range(count)]\n\nSample output, for count=10 and assuming that you mean the Standard Library random() function:\n[(-0.07, -0.40), (0.39, 0.18), (0.13, 0.29), (-0.11, -0.15),\\\n(-0.49, 0.42), (-0.20, 0.21), (-0.44, 0.36), (0.22, -0.08),\\\n(0.21, 0.31), (0.33, 0.02)]\n\nIf you really need to make it a function, then you can abbreviate by using a lambda:\nf = lambda count: [(random() - 0.5, random() - 0.5) for _ in range(count)]\n\nThis way you can call it like:\n>>> f(1)\nf(1)\n[(0.03, -0.09)]\n>>> f(2)\nf(2)\n[(-0.13, 0.38), (0.10, -0.04)]\n>>> f(5)\nf(5)\n[(-0.38, -0.14), (0.31, -0.16), (-0.34, -0.46), (-0.45, 0.28), (-0.01, -0.18)]\n>>> f(10)\nf(10)\n[(0.01, -0.24), (0.39, -0.11), (-0.06, 0.09), (0.42, -0.26), (0.24, -0.44) , (-0.29, -0.30), (-0.27, 0.45), (0.10, -0.41), (0.36, -0.07), (0.00, -0.42)]\n>>> \n\nyou get the idea...\n",
"Late to the party, but here's a potential idea:\ndef RandomSample(count):\n f = lambda: random() - 0.5\n r = range if count < 100 else xrange # or some other number\n return [(f(), f()) for _ in r(count)]\n\nStrictly speaking, this is more or less the same as the other answers, but it does two things that look kind of nice to me.\nFirst, it removes that duplicate code you have from writing random() - 0.5 twice by putting that into a lambda.\nSecond, for a certain size range, it chooses to use xrange() instead of range() so as not to unnecessarily generate a giant list of numbers you're going to throw away. You may want to adjust the exact number, because I haven't played with it at all, I just thought it might be a potential efficiency concern.\n",
"There should be a way to suppress code analysis errors in PyDev, like this:\nhttp://pydev.org/manual_adv_assistants.html\nAlso, PyDev will ignore unused variables that begin with an underscore, as shown here:\nhttp://pydev.org/manual_adv_code_analysis.html\n",
"Try this:\nwhile count > 0:\n pattern.append((random() - 0.5, random() - 0.5))\n count -= 1\n\n",
"import itertools, random \n\ndef RandomSample2D(npoints, get_random=lambda: random.uniform(-.5, .5)):\n return ((r(), r()) for r in itertools.repeat(get_random, npoints))\n\n\nuses random.uniform() explicitly\nreturns an iterator instead of list\n\n"
] |
[
18,
5,
4,
2,
1,
0,
0
] |
[] |
[] |
[
"eclipse",
"for_loop",
"python"
] |
stackoverflow_0001895615_eclipse_for_loop_python.txt
|
Q:
Special characters in OSX filename ? (Python os.rename)
I am trying to rename some files automatically on OSX with a python script. But I fail to work with special characters like forward slash etc.:
oldname = "/test"
newname = "/test(1\/10)"
os.rename(oldname, newname)
I think I do have an encoding problem. But different tries with re.escape or using UTF-8 unicode encodings havent been successful for me. Would you have a hint?
Thanks!
Marco
A:
What most of the file systems have in common is that they do not allow directory separators (slashes) in filenames.
That said, in Mac OS X you can have file names appear with slashes in finder, you can try replacing slashes with :.
A:
If you're trying to rename the folder '/test' you'll need to run python as root, otherwise you won't have privileges to change stuff in the root. Furthermore the slash in your new name won't work as python will try find a directory "/test(1", so you'll have to let the directory separator go. Also this from the python documentation might be helpful.
Rename the file or directory src to dst. If dst is a directory, OSError will be raised. On Unix, if dst exists and is a file, it will be replaced silently if the user has permission. The operation may fail on some Unix flavors if src and dst are on different filesystems. If successful, the renaming will be an atomic operation (this is a POSIX requirement). On Windows, if dst already exists, OSError will be raised even if it is a file; there may be no way to implement an atomic rename when dst names an existing file. Availability: Unix, Windows.
|
Special characters in OSX filename ? (Python os.rename)
|
I am trying to rename some files automatically on OSX with a python script. But I fail to work with special characters like forward slash etc.:
oldname = "/test"
newname = "/test(1\/10)"
os.rename(oldname, newname)
I think I do have an encoding problem. But different tries with re.escape or using UTF-8 unicode encodings havent been successful for me. Would you have a hint?
Thanks!
Marco
|
[
"What most of the file systems have in common is that they do not allow directory separators (slashes) in filenames.\nThat said, in Mac OS X you can have file names appear with slashes in finder, you can try replacing slashes with :.\n",
"If you're trying to rename the folder '/test' you'll need to run python as root, otherwise you won't have privileges to change stuff in the root. Furthermore the slash in your new name won't work as python will try find a directory \"/test(1\", so you'll have to let the directory separator go. Also this from the python documentation might be helpful.\n\nRename the file or directory src to dst. If dst is a directory, OSError will be raised. On Unix, if dst exists and is a file, it will be replaced silently if the user has permission. The operation may fail on some Unix flavors if src and dst are on different filesystems. If successful, the renaming will be an atomic operation (this is a POSIX requirement). On Windows, if dst already exists, OSError will be raised even if it is a file; there may be no way to implement an atomic rename when dst names an existing file. Availability: Unix, Windows.\n\n"
] |
[
2,
0
] |
[] |
[] |
[
"character_encoding",
"filesystems",
"macos",
"path",
"python"
] |
stackoverflow_0001896442_character_encoding_filesystems_macos_path_python.txt
|
Q:
Django form in Google App Engine unable to find module PIL
There are actually a couple of questions here. For what I'm doing, I'm doing a basic image upload with Django 1.1 and Google App Engine. Here is my form class:
class UploadPictureForm(forms.Form):
picture = forms.ImageField()
And then on submit, I have the following code:
def handle_picture(request):
form = UploadPictureForm(request.POST, request.FILES)
if form.is_valid():
save_picture(request.FILES['picture']
I get the following error:
Exception Type: ImportError
Exception Value: No module named PIL
Exception Location: /Library/Python/2.6/site-packages/django/forms/fields.py in clean, line 495
Python Executable: /usr/bin/python2.6
Python Version: 2.6.1
Python Path: [..., '/Library/Python/2.6/site-packages', '/Library/Python/2.6/site-packages/PIL']
and I've installed PIL in the site-packages directory and if I run python from the command line, I can import PIL with import PIL
SO question #1 is why doesn't this work? Is GAE doing something that's keeping this from working? The second thing is that I notice GAE has some Image APIs. Should I be using those instead? All of this is somewhat new for me.
A:
For starters, you shouldn't use GAE with Python 2.6. Google App Engine is created with 2.5 in mind and it usually breaks in multiple ways on 2.6.
More, I'm not quite sure you can use PIL at all with GAE. It's a C-based library and therefore it's a no-no for GAE (which requires custom packages to be pure-Python only) (there's even a ticket for this issue).
That's what images API was created for. It still uses PIL as a backend (at least on the user side), but offers a 'safe' subset of it.
A:
Can you show us the full stacktrace? Based on what you provided, there's several options:
Django is trying to use PIL directly for some reason. This won't work on App Engine, as PIL isn't available there, and you can't upload it because it's C code.
Your own code is trying to use PIL directly. You need to use the Images API instead.
The App Engine framework is trying to use PIL, but can't locate it. The local stub for the Images API relies on PIL, so if your code is trying to use that, App Engine needs to import PIL.
A:
More, I'm not quite sure you can use PIL at all with GAE. It's a C-based library and therefore it's a no-no for GAE (which requires custom packages to be pure-Python only) (there's even a ticket for this issue).
PIL is used by the development server locally to simulate all image api calls. You can found the installation instructions here
|
Django form in Google App Engine unable to find module PIL
|
There are actually a couple of questions here. For what I'm doing, I'm doing a basic image upload with Django 1.1 and Google App Engine. Here is my form class:
class UploadPictureForm(forms.Form):
picture = forms.ImageField()
And then on submit, I have the following code:
def handle_picture(request):
form = UploadPictureForm(request.POST, request.FILES)
if form.is_valid():
save_picture(request.FILES['picture']
I get the following error:
Exception Type: ImportError
Exception Value: No module named PIL
Exception Location: /Library/Python/2.6/site-packages/django/forms/fields.py in clean, line 495
Python Executable: /usr/bin/python2.6
Python Version: 2.6.1
Python Path: [..., '/Library/Python/2.6/site-packages', '/Library/Python/2.6/site-packages/PIL']
and I've installed PIL in the site-packages directory and if I run python from the command line, I can import PIL with import PIL
SO question #1 is why doesn't this work? Is GAE doing something that's keeping this from working? The second thing is that I notice GAE has some Image APIs. Should I be using those instead? All of this is somewhat new for me.
|
[
"For starters, you shouldn't use GAE with Python 2.6. Google App Engine is created with 2.5 in mind and it usually breaks in multiple ways on 2.6.\nMore, I'm not quite sure you can use PIL at all with GAE. It's a C-based library and therefore it's a no-no for GAE (which requires custom packages to be pure-Python only) (there's even a ticket for this issue).\nThat's what images API was created for. It still uses PIL as a backend (at least on the user side), but offers a 'safe' subset of it.\n",
"Can you show us the full stacktrace? Based on what you provided, there's several options:\n\nDjango is trying to use PIL directly for some reason. This won't work on App Engine, as PIL isn't available there, and you can't upload it because it's C code.\nYour own code is trying to use PIL directly. You need to use the Images API instead.\nThe App Engine framework is trying to use PIL, but can't locate it. The local stub for the Images API relies on PIL, so if your code is trying to use that, App Engine needs to import PIL.\n\n",
"\nMore, I'm not quite sure you can use PIL at all with GAE. It's a C-based library and therefore it's a no-no for GAE (which requires custom packages to be pure-Python only) (there's even a ticket for this issue).\n\nPIL is used by the development server locally to simulate all image api calls. You can found the installation instructions here\n"
] |
[
3,
0,
0
] |
[] |
[] |
[
"google_app_engine",
"python",
"python_imaging_library"
] |
stackoverflow_0001894875_google_app_engine_python_python_imaging_library.txt
|
Q:
How to return a float point number with a defined number of decimal places?
So I know how to print a floating point number with a certain decimal places.
My question is how to return it with a specified number of decimal places?
Thanks.
A:
You could use the round() function
The docs about it:
round(x[, n])
x rounded to n digits, rounding half to even. If n is omitted, it defaults to 0.
A:
In order to get two decimal places, multiply the number by 100, floor it, then divide by 100.
And note that the number you will return will not really have only two decimal places because division by 100 cannot be represented exactly in IEEE-754 floating-point arithmetic most of the time. It will only be the closest representable approximation to a number with only two decimal places.
A:
If you really want floating point numbers with a fixed precision you could use the decimal module. Those numbers have a user alterable precision and you could just do your calculation on two-digit decimals.
A:
Floating point numbers have infinite number of decimal places. The physical representation on the computer is dependent on the representation of float, or double, or whatever and is dependent on a) language b) construct, e.g. float, double, etc. c) compiler implementation d) hardware.
Now, given that you have a representation of a floating point number (i.e. a real) within a particular language, is your question how to round it off or truncate it to a specific number of digits?
There is no need to do this within the return call, since you can always truncate/round afterwards. In fact, you would usually not want to truncate until actually printing, to preserve more precision. An exception might be if you wanted to ensure that results were consistent across different algorithms/hardware, ie. say you had some financial trading software that needed to pass unit tests across different languages/platforms etc.
|
How to return a float point number with a defined number of decimal places?
|
So I know how to print a floating point number with a certain decimal places.
My question is how to return it with a specified number of decimal places?
Thanks.
|
[
"You could use the round() function\nThe docs about it:\nround(x[, n])\n\nx rounded to n digits, rounding half to even. If n is omitted, it defaults to 0.\n",
"In order to get two decimal places, multiply the number by 100, floor it, then divide by 100.\nAnd note that the number you will return will not really have only two decimal places because division by 100 cannot be represented exactly in IEEE-754 floating-point arithmetic most of the time. It will only be the closest representable approximation to a number with only two decimal places.\n",
"If you really want floating point numbers with a fixed precision you could use the decimal module. Those numbers have a user alterable precision and you could just do your calculation on two-digit decimals.\n",
"Floating point numbers have infinite number of decimal places. The physical representation on the computer is dependent on the representation of float, or double, or whatever and is dependent on a) language b) construct, e.g. float, double, etc. c) compiler implementation d) hardware.\nNow, given that you have a representation of a floating point number (i.e. a real) within a particular language, is your question how to round it off or truncate it to a specific number of digits? \nThere is no need to do this within the return call, since you can always truncate/round afterwards. In fact, you would usually not want to truncate until actually printing, to preserve more precision. An exception might be if you wanted to ensure that results were consistent across different algorithms/hardware, ie. say you had some financial trading software that needed to pass unit tests across different languages/platforms etc.\n"
] |
[
6,
4,
4,
2
] |
[] |
[] |
[
"floating_point",
"python"
] |
stackoverflow_0001896722_floating_point_python.txt
|
Q:
Writing to stdout from within a Microsoft VBA macro
I'm using Python (and the Win32 extensions) to execute macros in an Excel spreadsheet via the COM interface, as shown below:
import win32com.client
o = win32com.client.Dispatch("Excel.Application")
o.Visible = 1
o.Workbooks.Open (r"C:\test.xls")
o.Application.Run("macro1")
What I'd like to do is have the Excel macro output text warning messages, which the Python code can catch via COM or stdout (or some other mechanism). Is it possible to write to stdout from within a Microsoft VBA app? Is there another way to do this that I don't know about?
A:
You can write to and read stdout with VB6 with a bit of drama.. but creating a console app with Excel and VBA? I'm not sure that is possible.
I've found a simple Python COM example which you may have already investigated. Could you make your macro just create a sheet a write to a cell and have Python poll that cell?
Also you could raise custom errors via Err.Raise() ... or worse case use an environment variable.. these would be better than firing up a console.
Since i'm guesing you want asynchronous communication another possibility is DDE or Dynamic Data Exchange. In the mid 90's we used to have an in-house scripting language (the DDE client) talk to a running Excel session (the DDE server) and request it to input data, run macros, return cell values etc. It wasn't nice but it worked.
There's a Python DDE library as well as several examples. One warning; I remember any DDE coding being a massive pain and relied a lot on a tool called DDESpy. I'm surprised you can't do what you need via COM, so i'd investigate a little more before turning to DDE.
A:
One solution is to write a COM server in Python. The VBA macro could instantiate the COM server, and then send it messages.
Once you've sent the data from VBA to your Python COM server, writing to stdout via a console application would be tricky, but you could write to a file, a web browser (via COM automation), a web server (e.g. via HTTP), a GUI edit window (e.g. via sockets), and so on.
Here's a free chapter to Python Programming on Win32. Check out the section titled "Implementing a COM Server". The whole book is well worth reading if you're interested in Windows programming using Python, although it's now showing its age.
A:
You almost certainly have to use Win32 API to get anywhere here. The question Redirect stdout to an edit control (Win32) refers to using stdin/stdout in a GUI application. Unfortunately the questioner has not solved their problem yet.
I'm interested in what mechanism in Windows supports stdin / stdout. It seems very much a second class citizen compared to its role in Unix.
|
Writing to stdout from within a Microsoft VBA macro
|
I'm using Python (and the Win32 extensions) to execute macros in an Excel spreadsheet via the COM interface, as shown below:
import win32com.client
o = win32com.client.Dispatch("Excel.Application")
o.Visible = 1
o.Workbooks.Open (r"C:\test.xls")
o.Application.Run("macro1")
What I'd like to do is have the Excel macro output text warning messages, which the Python code can catch via COM or stdout (or some other mechanism). Is it possible to write to stdout from within a Microsoft VBA app? Is there another way to do this that I don't know about?
|
[
"You can write to and read stdout with VB6 with a bit of drama.. but creating a console app with Excel and VBA? I'm not sure that is possible.\nI've found a simple Python COM example which you may have already investigated. Could you make your macro just create a sheet a write to a cell and have Python poll that cell?\nAlso you could raise custom errors via Err.Raise() ... or worse case use an environment variable.. these would be better than firing up a console.\nSince i'm guesing you want asynchronous communication another possibility is DDE or Dynamic Data Exchange. In the mid 90's we used to have an in-house scripting language (the DDE client) talk to a running Excel session (the DDE server) and request it to input data, run macros, return cell values etc. It wasn't nice but it worked.\nThere's a Python DDE library as well as several examples. One warning; I remember any DDE coding being a massive pain and relied a lot on a tool called DDESpy. I'm surprised you can't do what you need via COM, so i'd investigate a little more before turning to DDE.\n",
"One solution is to write a COM server in Python. The VBA macro could instantiate the COM server, and then send it messages.\nOnce you've sent the data from VBA to your Python COM server, writing to stdout via a console application would be tricky, but you could write to a file, a web browser (via COM automation), a web server (e.g. via HTTP), a GUI edit window (e.g. via sockets), and so on.\nHere's a free chapter to Python Programming on Win32. Check out the section titled \"Implementing a COM Server\". The whole book is well worth reading if you're interested in Windows programming using Python, although it's now showing its age.\n",
"You almost certainly have to use Win32 API to get anywhere here. The question Redirect stdout to an edit control (Win32) refers to using stdin/stdout in a GUI application. Unfortunately the questioner has not solved their problem yet.\nI'm interested in what mechanism in Windows supports stdin / stdout. It seems very much a second class citizen compared to its role in Unix.\n"
] |
[
1,
1,
0
] |
[
"What happens if you write to stdout? Either:\nprint \"Hello, world!\"\n\nor:\nimport sys\nsys.stdout.write(\"Hello, world!\\n\")\n\nor even:\nimport sys\nsys.__stdout__.write(\"Hello, world!\\n\")\n\nsys.stdout is the current stdout file, __stdout__ is the original stdout when the Python interpreter started.\n"
] |
[
-1
] |
[
"com",
"excel",
"python",
"stdout",
"vba"
] |
stackoverflow_0001889175_com_excel_python_stdout_vba.txt
|
Q:
Enable pylint in Netbeans
How can I integrate pylint with netbeans?
A:
I haven't tried this myself, but this website:
http://jpydbg.sourceforge.net/
seems to document a method to get it working.
A:
There's a PyLint plugin for Eric. It's a nice little open source IDE for aimed particularly for Python and Ruby. Perhaps you will find it useful.
A:
On the netbeans-python (nbpython) dev list there seems to be a whole thread about this:
http://markmail.org/message/rrjcooygoleufje6
So, seemingly, it's not ready yet.
In light of that, you might want to check out the alternatives: http://meandubuntu.wordpress.com/2008/11/14/in-search-of-a-python-ide/
|
Enable pylint in Netbeans
|
How can I integrate pylint with netbeans?
|
[
"I haven't tried this myself, but this website:\nhttp://jpydbg.sourceforge.net/\nseems to document a method to get it working.\n",
"There's a PyLint plugin for Eric. It's a nice little open source IDE for aimed particularly for Python and Ruby. Perhaps you will find it useful. \n",
"On the netbeans-python (nbpython) dev list there seems to be a whole thread about this:\nhttp://markmail.org/message/rrjcooygoleufje6\nSo, seemingly, it's not ready yet.\nIn light of that, you might want to check out the alternatives: http://meandubuntu.wordpress.com/2008/11/14/in-search-of-a-python-ide/\n"
] |
[
1,
0,
0
] |
[] |
[] |
[
"netbeans",
"pylint",
"python"
] |
stackoverflow_0001817047_netbeans_pylint_python.txt
|
Q:
Creating Regular Expressions in Python
I'm trying to create regular expression that filters from the following partial text:
amd64 build of software 1:0.98.10-0.2svn20090909 in archive
what I want to extract is:
software 1:0.98.10-0.2svn20090909
How can I do this?? I've been trying and this is what I have so far:
p = re.compile('([a-zA-Z0-9\-\+\.]+)\ ([0-9\:\.\-]+)')
iterator = p.finditer("amd64 build of software 1:0.98.10-0.2svn20090909 in archive")
for match in iterator:
print match.group()
with result:
software 1:0.98.10-0.2
(svn20090909 is missing)
Thanks a lot.
A:
This will work:
p = re.compile(r'([a-zA-Z0-9\-\+\.]+)\ ([0-9][0-9a-zA-Z\:\.\-]+)')
iterator = p.finditer("amd64 build of dvdrip software 1:0.98.10-0.2svn20090909 in archive")
for match in iterator:
print match.group()
# Prints: software 1:0.98.10-0.2svn20090909
That works by allowing the captured section to contain letters while still insisting that it starts with a number.
Without seeing all the other strings it needs to match, I can't be sure whether that's good enough.
A:
If you have consistent lines, this is, if each entry is on one line and the first word you want is always before the numbers part (the 1:0.98 ... part) you don't need a regexp. Try this:
>>> s = 'amd64 build of software 1:0.98.10-0.2svn20090909 in archive'
>>> match = [s.split()[3], s.split()[4]]
>>> print match
['software', '1:0.98.10-0.2svn20090909']
>>> # alternatively
>>> match = s.split()[3:5] # for same result
what this is doing is the following: it first splits the line s at the spaces (using the string method split()) and selects the fourth and fifth elements of the resulting list; both are stored in the variable match.
Again , this only works if you have one entry per line and if the 'software' part always comes before the 1:0.98.10-0.2svn20090909 part.
I often avoid regexps when I can do with split lists. If the parsing becomes a nightmare, I use pyparsing.
A:
Don't use a capturing group if you want everything in one piece.
|
Creating Regular Expressions in Python
|
I'm trying to create regular expression that filters from the following partial text:
amd64 build of software 1:0.98.10-0.2svn20090909 in archive
what I want to extract is:
software 1:0.98.10-0.2svn20090909
How can I do this?? I've been trying and this is what I have so far:
p = re.compile('([a-zA-Z0-9\-\+\.]+)\ ([0-9\:\.\-]+)')
iterator = p.finditer("amd64 build of software 1:0.98.10-0.2svn20090909 in archive")
for match in iterator:
print match.group()
with result:
software 1:0.98.10-0.2
(svn20090909 is missing)
Thanks a lot.
|
[
"This will work:\np = re.compile(r'([a-zA-Z0-9\\-\\+\\.]+)\\ ([0-9][0-9a-zA-Z\\:\\.\\-]+)')\niterator = p.finditer(\"amd64 build of dvdrip software 1:0.98.10-0.2svn20090909 in archive\")\nfor match in iterator:\n print match.group()\n# Prints: software 1:0.98.10-0.2svn20090909\n\nThat works by allowing the captured section to contain letters while still insisting that it starts with a number.\nWithout seeing all the other strings it needs to match, I can't be sure whether that's good enough.\n",
"If you have consistent lines, this is, if each entry is on one line and the first word you want is always before the numbers part (the 1:0.98 ... part) you don't need a regexp. Try this:\n>>> s = 'amd64 build of software 1:0.98.10-0.2svn20090909 in archive'\n>>> match = [s.split()[3], s.split()[4]]\n>>> print match\n['software', '1:0.98.10-0.2svn20090909']\n>>> # alternatively\n>>> match = s.split()[3:5] # for same result\n\nwhat this is doing is the following: it first splits the line s at the spaces (using the string method split()) and selects the fourth and fifth elements of the resulting list; both are stored in the variable match.\nAgain , this only works if you have one entry per line and if the 'software' part always comes before the 1:0.98.10-0.2svn20090909 part.\nI often avoid regexps when I can do with split lists. If the parsing becomes a nightmare, I use pyparsing.\n",
"Don't use a capturing group if you want everything in one piece.\n"
] |
[
3,
3,
0
] |
[] |
[] |
[
"expression",
"python",
"regex"
] |
stackoverflow_0001897254_expression_python_regex.txt
|
Q:
validating correct answer with loops in python
Sorry for the non descriptive question I had no idea how to word it.
I'm trying to write a program (GUI) where I ask the users questions and then in return they answer and see if they are correct however when I enter the correct answer it's still showing as being incorrect.
My code looks something like this.
prompt for question 1
txtQuestion = Text(Point(5,8), "Question 1")
txtQuestion.setTextColor("red")
txtQuestion.setSize(16)
txtQuestion.setStyle("bold")
txtQuestion.draw(win)
txtAnswer = Text(Point(1.5,4), "Answer 1: ")
txtAnswer.setTextColor(color_rgb(255,127,80))
txtAnswer.setSize(14)
txtAnswer.setStyle("bold")
txtAnswer.draw(win)
txtAnswer2 = Text(Point(1.5,3), "Answer 2: ")
txtAnswer2.setTextColor(color_rgb(255,127,80))
txtAnswer2.setSize(14)
txtAnswer2.setStyle("bold")
txtAnswer2.draw(win)
txtAnswer3 = Text(Point(1.5,2), "Answer 3: ")
txtAnswer3.setTextColor(color_rgb(255,127,80))
txtAnswer3.setSize(14)
txtAnswer3.setStyle("bold")
txtAnswer3.draw(win)
txtAnswer4 = Text(Point(1.5,1), "Answer 4: ")
txtAnswer4.setTextColor(color_rgb(255,127,80))
txtAnswer4.setSize(14)
txtAnswer4.setStyle("bold")
txtAnswer4.draw(win)
txtEnterAn = Text(Point(8,3), "Enter your answer below: ")
txtEnterAn.setTextColor("black")
txtEnterAn.draw(win)
entAnswer = Entry(Point(8,2), 3)
entAnswer.draw(win)
Answer1 = entAnswer.getText()
win.getMouse()
#loop for answer
if Answer1 == "A":
txtCorrect = Text(Point(5,9), "Correct!")
txtCorrect.setTextColor("black")
txtCorrect.draw(win)
else:
txtCorrect = Text(Point(5,9), "Inorrect!")
txtCorrect.setTextColor("black")
txtCorrect.draw(win)
Now I'm not sure why every time I enter "A" it still shows as incorrect I know in another program I had to float the entAnswer variable but I figured this time I wouldn't have to since it's a string.
I must be overlooking the situation but I can't lay my finger down on it, any help would be appreciated, thanks!
p.s. I didn't put it in with the code but I do have the variables up top initialized such as Answer1 = " " and so forth
A:
The problem here seems to be that you're misunderstanding how GUIs work. It's not like the sequential print/read code that most programming instruction starts with. The GUI widgets only create themselves, draw to the screen and wait for events.
This line:
Answer1 = entAnswer.getText()
will end up setting Answer1 to an empty string, because at that point, the user hasn't entered anything in the text box. Instead, you have to create a callback function that will be called by the GUI when the user hits a button to score the answer. Then in that function you will be able to read the user's answer and mark it correct or incorrect.
I recommend going through your GUI library's tutorial again to get a feel for the event-driven style of GUI programming.
A:
I'd recommend that you abstract that user interface detail away from the problem of showing questions, obtaining answers, and determining correctness. You can sort all of that out with nothing more than a command line, text based user interface. Once you have that, then you can proceed with the user interface design with confidence, knowing that the logic behind the questionnaire is sound.
This idea goes by several names: layering, MVC, etc. I'd recommend it for this problem, because it'll help you learn the idea for those more difficult problems to come where it'll be indispensable.
A:
i don't see a reason the logic would fail, but are you sure you are pressing "A" and not "a" .
A:
I can't say anything about this particular problem, but I would do a
print "'" + answer + "'"
print answer.__class__
I have encountered wrapper classes (in OTHER situations) which behave like strings
but are not actually strings. Furthermore spaces and newlines can be added everywhere :)
|
validating correct answer with loops in python
|
Sorry for the non descriptive question I had no idea how to word it.
I'm trying to write a program (GUI) where I ask the users questions and then in return they answer and see if they are correct however when I enter the correct answer it's still showing as being incorrect.
My code looks something like this.
prompt for question 1
txtQuestion = Text(Point(5,8), "Question 1")
txtQuestion.setTextColor("red")
txtQuestion.setSize(16)
txtQuestion.setStyle("bold")
txtQuestion.draw(win)
txtAnswer = Text(Point(1.5,4), "Answer 1: ")
txtAnswer.setTextColor(color_rgb(255,127,80))
txtAnswer.setSize(14)
txtAnswer.setStyle("bold")
txtAnswer.draw(win)
txtAnswer2 = Text(Point(1.5,3), "Answer 2: ")
txtAnswer2.setTextColor(color_rgb(255,127,80))
txtAnswer2.setSize(14)
txtAnswer2.setStyle("bold")
txtAnswer2.draw(win)
txtAnswer3 = Text(Point(1.5,2), "Answer 3: ")
txtAnswer3.setTextColor(color_rgb(255,127,80))
txtAnswer3.setSize(14)
txtAnswer3.setStyle("bold")
txtAnswer3.draw(win)
txtAnswer4 = Text(Point(1.5,1), "Answer 4: ")
txtAnswer4.setTextColor(color_rgb(255,127,80))
txtAnswer4.setSize(14)
txtAnswer4.setStyle("bold")
txtAnswer4.draw(win)
txtEnterAn = Text(Point(8,3), "Enter your answer below: ")
txtEnterAn.setTextColor("black")
txtEnterAn.draw(win)
entAnswer = Entry(Point(8,2), 3)
entAnswer.draw(win)
Answer1 = entAnswer.getText()
win.getMouse()
#loop for answer
if Answer1 == "A":
txtCorrect = Text(Point(5,9), "Correct!")
txtCorrect.setTextColor("black")
txtCorrect.draw(win)
else:
txtCorrect = Text(Point(5,9), "Inorrect!")
txtCorrect.setTextColor("black")
txtCorrect.draw(win)
Now I'm not sure why every time I enter "A" it still shows as incorrect I know in another program I had to float the entAnswer variable but I figured this time I wouldn't have to since it's a string.
I must be overlooking the situation but I can't lay my finger down on it, any help would be appreciated, thanks!
p.s. I didn't put it in with the code but I do have the variables up top initialized such as Answer1 = " " and so forth
|
[
"The problem here seems to be that you're misunderstanding how GUIs work. It's not like the sequential print/read code that most programming instruction starts with. The GUI widgets only create themselves, draw to the screen and wait for events. \nThis line:\nAnswer1 = entAnswer.getText()\n\nwill end up setting Answer1 to an empty string, because at that point, the user hasn't entered anything in the text box. Instead, you have to create a callback function that will be called by the GUI when the user hits a button to score the answer. Then in that function you will be able to read the user's answer and mark it correct or incorrect. \nI recommend going through your GUI library's tutorial again to get a feel for the event-driven style of GUI programming.\n",
"I'd recommend that you abstract that user interface detail away from the problem of showing questions, obtaining answers, and determining correctness. You can sort all of that out with nothing more than a command line, text based user interface. Once you have that, then you can proceed with the user interface design with confidence, knowing that the logic behind the questionnaire is sound. \nThis idea goes by several names: layering, MVC, etc. I'd recommend it for this problem, because it'll help you learn the idea for those more difficult problems to come where it'll be indispensable.\n",
"i don't see a reason the logic would fail, but are you sure you are pressing \"A\" and not \"a\" .\n",
"I can't say anything about this particular problem, but I would do a\nprint \"'\" + answer + \"'\"\nprint answer.__class__\n\nI have encountered wrapper classes (in OTHER situations) which behave like strings\nbut are not actually strings. Furthermore spaces and newlines can be added everywhere :)\n"
] |
[
4,
0,
0,
0
] |
[] |
[] |
[
"python",
"user_interface"
] |
stackoverflow_0001897531_python_user_interface.txt
|
Q:
Test if point is in some rectangle
I have a large collection of rectangles, all of the same size. I am generating random points that should not fall in these rectangles, so what I wish to do is test if the generated point lies in one of the rectangles, and if it does, generate a new point.
Using R-trees seem to work, but they are really meant for rectangles and not points. I could use a modified version of a R-tree algorithm which works with points too, but I'd rather not reinvent the wheel, if there is already some better solution. I'm not very familiar with data-structures, so maybe there already exists some structure that works for my problem?
In summary, basically what I'm asking is if anyone knows of a good algorithm, that works in Python, that can be used to check if a point lies in any rectangle in a given set of rectangles.
edit: This is in 2D and the rectangles are not rotated.
A:
This Reddit thread addresses your problem:
I have a set of rectangles, and need to determine whether a point is contained within any of them. What are some good data structures to do this, with fast lookup being important?
If your universe is integer, or if the level of precision is well known and is not too high, you can use abelsson's suggestion from the thread, using O(1) lookup using coloring:
As usual you can trade space for
time.. here is a O(1) lookup with very
low constant. init: Create a bitmap
large enough to envelop all rectangles
with sufficient precision, initialize
it to black. Color all pixels
containing any rectangle white. O(1)
lookup: is the point (x,y) white? If
so, a rectangle was hit.
I recommend you go to that post and fully read ModernRonin's answer which is the most accepted one. I pasted it here:
First, the micro problem. You have an
arbitrarily rotated rectangle, and a
point. Is the point inside the
rectangle?
There are many ways to do this. But
the best, I think, is using the 2d
vector cross product. First, make sure
the points of the rectangle are stored
in clockwise order. Then do the vector
cross product with 1) the vector
formed by the two points of the side
and 2) a vector from the first point
of the side to the test point. Check
the sign of the result - positive is
inside (to the right of) the side,
negative is outside. If it's inside
all four sides, it's inside the
rectangle. Or equivalently, if it's
outside any of the sides, it's outside
the rectangle. More explanation here.
This method will take 3 subtracts per
vector * times 2 vectors per side,
plus one cross product per side which
is three multiplies and two adds. 11
flops per side, 44 flops per
rectangle.
If you don't like the cross product,
then you could do something like:
figure out the inscribed and
circumscribed circles for each
rectangle, check if the point inside
the inscribed one. If so, it's in the
rectangle as well. If not, check if
it's outside the circumscribed
rectangle. If so, it's outside the
rectangle as well. If it falls between
the two circles, you're f****d and you
have to check it the hard way.
Finding if a point is inside a circle
in 2d takes two subtractions and two
squarings (= multiplies), and then you
compare distance squared to avoid
having to do a square root. That's 4
flops, times two circles is 8 flops -
but sometimes you still won't know.
Also this assumes that you don't pay
any CPU time to compute the
circumscribed or inscribed circles,
which may or may not be true depending
on how much pre-computation you're
willing to do on your rectangle set.
In any event, it's probably not a
great idea to test the point against
every rectangle, especially if you
have a hundred million of them.
Which brings us to the macro problem.
How to avoid testing the point against
every single rectangle in the set? In
2D, this is probably a quad-tree
problem. In 3d, what generic_handle
said - an octree. Off the top of my
head, I would probably implement it as
a B+ tree. It's tempting to use d = 5,
so that each node can have up to 4
children, since that maps so nicely
onto the quad-tree abstraction. But if
the set of rectangles is too big to
fit into main memory (not very likely
these days), then having nodes the
same size as disk blocks is probably
the way to go.
Watch out for annoying degenerate
cases, like some data set that has ten
thousand nearly identical rectangles
with centers at the same exact point.
:P
Why is this problem important? It's
useful in computer graphics, to check
if a ray intersects a polygon. I.e.,
did that sniper rifle shot you just
made hit the person you were shooting
at? It's also used in real-time map
software, like say GPS units. GPS
tells you the coordinates you're at,
but the map software has to find where
that point is in a huge amount of map
data, and do it several times per
second.
Again, credit to ModernRonin...
A:
For rectangles that are aligned with the axes, you only need two points (four numbers) to identify the rectangle - conventionally, bottom-left and top-right corners. To establish whether a given point (Xtest, Ytest) overlaps with a rectangle (XBL, YBL, XTR, YTR) by testing both:
Xtest >= XBL && Xtest <= XTR
Ytest >= YBL && Ytest <= YTR
Clearly, for a large enough set of points to test, this could be fairly time consuming. The question, then, is how to optimize the testing.
Clearly, one optimization is to establish the minimum and maximum X and Y values for the box surrounding all the rectangles (the bounding box): a swift test on this shows whether there is any need to look further.
Xtest >= Xmin && Xtest <= Xmax
Ytest >= Ymin && Ytest <= Ymax
Depending on how much of the total surface area is covered with rectangles, you might be able to find non-overlapping sub-areas that contain rectangles, and you could then avoid searching those sub-areas that cannot contain a rectangle overlapping the point, again saving comparisons during the search at the cost of pre-computation of suitable data structures. If the set of rectangles is sparse enough, there may be no overlapping, in which case this degenerates into the brute-force search. Equally, if the set of rectangles is so dense that there are no sub-ranges in the bounding box that can be split up without breaking rectangles.
However, you could also arbitrarily break up the bounding area into, say, quarters (half in each direction). You would then use a list of boxes which would include more boxes than in the original set (two or four boxes for each box that overlapped one of the arbitrary boundaries). The advantage of this is that you could then eliminate three of the four quarters from the search, reducing the amount of searching to be done in total - at the expense of auxilliary storage.
So, there are space-time trade-offs, as ever. And pre-computation versus search trade-offs. If you are unlucky, the pre-computation achieves nothing (for example, there are two boxes only, and they don't overlap on either axis). On the other hand, it could achieve considerable search-time benefit.
A:
I suggest you take a look at BSP trees (and possible quadtrees or octrees, links available on that page as well). They are used to partition the whole space recursively and allow you to quickly check for a point which rectangles you need to check at all.
At minimum you just have one huge partition and need to check all rectangles, at maximum your partitions get so small, that they get down to the size of single rectangles. Of course the more fine-grained the partition, the longer you need to walk down the tree in order to find the rectangles you want to check.
However, you can freely decide how many rectangles are suitable to be checked for a point and then create the corresponding structure.
Pay attention to overlapping rectangles though. As the BSP tree needs to be precomputed anyways, you may as well remove overlaps during that time, so you can get clear partitions.
A:
Your R-tree approach is the best approach I know of (that's the approach I would choose over quadtrees, B+ trees, or BSP trees, as R-trees seem convenient to build in your case). Caveat: I'm no expert, even though I remember a few things from my senior year university class of algorithmic!
A:
Why not try this. It seems rather light on both computation and memory.
Consider the projections of all the rectangles onto the base line of your space. Denote that set of line intervals as
{[Rl1, Rr1], [Rl2, Rr2],..., [Rln, Rrn]}, ordered by increasing left coordinates.
Now suppose your point is (x, y), start a search at the left of this set until you reach a line interval that contains the point x.
If none does, your point (x,y) is outside all rectangles.
If some do, say [Rlk, Rrk], ..., [Rlh, Rrh], (k <= h) then just check whether y is within the vertical extent of any of these rectangles.
Done.
Good luck.
John Doner
|
Test if point is in some rectangle
|
I have a large collection of rectangles, all of the same size. I am generating random points that should not fall in these rectangles, so what I wish to do is test if the generated point lies in one of the rectangles, and if it does, generate a new point.
Using R-trees seem to work, but they are really meant for rectangles and not points. I could use a modified version of a R-tree algorithm which works with points too, but I'd rather not reinvent the wheel, if there is already some better solution. I'm not very familiar with data-structures, so maybe there already exists some structure that works for my problem?
In summary, basically what I'm asking is if anyone knows of a good algorithm, that works in Python, that can be used to check if a point lies in any rectangle in a given set of rectangles.
edit: This is in 2D and the rectangles are not rotated.
|
[
"This Reddit thread addresses your problem: \nI have a set of rectangles, and need to determine whether a point is contained within any of them. What are some good data structures to do this, with fast lookup being important?\nIf your universe is integer, or if the level of precision is well known and is not too high, you can use abelsson's suggestion from the thread, using O(1) lookup using coloring:\n\nAs usual you can trade space for\n time.. here is a O(1) lookup with very\n low constant. init: Create a bitmap\n large enough to envelop all rectangles\n with sufficient precision, initialize\n it to black. Color all pixels\n containing any rectangle white. O(1)\n lookup: is the point (x,y) white? If\n so, a rectangle was hit.\n\nI recommend you go to that post and fully read ModernRonin's answer which is the most accepted one. I pasted it here:\n\nFirst, the micro problem. You have an\n arbitrarily rotated rectangle, and a\n point. Is the point inside the\n rectangle?\nThere are many ways to do this. But\n the best, I think, is using the 2d\n vector cross product. First, make sure\n the points of the rectangle are stored\n in clockwise order. Then do the vector\n cross product with 1) the vector\n formed by the two points of the side\n and 2) a vector from the first point\n of the side to the test point. Check\n the sign of the result - positive is\n inside (to the right of) the side,\n negative is outside. If it's inside\n all four sides, it's inside the\n rectangle. Or equivalently, if it's\n outside any of the sides, it's outside\n the rectangle. More explanation here.\nThis method will take 3 subtracts per\n vector * times 2 vectors per side,\n plus one cross product per side which\n is three multiplies and two adds. 11\n flops per side, 44 flops per\n rectangle.\nIf you don't like the cross product,\n then you could do something like:\n figure out the inscribed and\n circumscribed circles for each\n rectangle, check if the point inside\n the inscribed one. If so, it's in the\n rectangle as well. If not, check if\n it's outside the circumscribed\n rectangle. If so, it's outside the\n rectangle as well. If it falls between\n the two circles, you're f****d and you\n have to check it the hard way.\nFinding if a point is inside a circle\n in 2d takes two subtractions and two\n squarings (= multiplies), and then you\n compare distance squared to avoid\n having to do a square root. That's 4\n flops, times two circles is 8 flops -\n but sometimes you still won't know.\n Also this assumes that you don't pay\n any CPU time to compute the\n circumscribed or inscribed circles,\n which may or may not be true depending\n on how much pre-computation you're\n willing to do on your rectangle set.\nIn any event, it's probably not a\n great idea to test the point against\n every rectangle, especially if you\n have a hundred million of them.\nWhich brings us to the macro problem.\n How to avoid testing the point against\n every single rectangle in the set? In\n 2D, this is probably a quad-tree\n problem. In 3d, what generic_handle\n said - an octree. Off the top of my\n head, I would probably implement it as\n a B+ tree. It's tempting to use d = 5,\n so that each node can have up to 4\n children, since that maps so nicely\n onto the quad-tree abstraction. But if\n the set of rectangles is too big to\n fit into main memory (not very likely\n these days), then having nodes the\n same size as disk blocks is probably\n the way to go.\nWatch out for annoying degenerate\n cases, like some data set that has ten\n thousand nearly identical rectangles\n with centers at the same exact point.\n :P\nWhy is this problem important? It's\n useful in computer graphics, to check\n if a ray intersects a polygon. I.e.,\n did that sniper rifle shot you just\n made hit the person you were shooting\n at? It's also used in real-time map\n software, like say GPS units. GPS\n tells you the coordinates you're at,\n but the map software has to find where\n that point is in a huge amount of map\n data, and do it several times per\n second.\n\nAgain, credit to ModernRonin...\n",
"For rectangles that are aligned with the axes, you only need two points (four numbers) to identify the rectangle - conventionally, bottom-left and top-right corners. To establish whether a given point (Xtest, Ytest) overlaps with a rectangle (XBL, YBL, XTR, YTR) by testing both:\n\nXtest >= XBL && Xtest <= XTR\nYtest >= YBL && Ytest <= YTR\n\nClearly, for a large enough set of points to test, this could be fairly time consuming. The question, then, is how to optimize the testing.\nClearly, one optimization is to establish the minimum and maximum X and Y values for the box surrounding all the rectangles (the bounding box): a swift test on this shows whether there is any need to look further.\n\nXtest >= Xmin && Xtest <= Xmax\nYtest >= Ymin && Ytest <= Ymax\n\nDepending on how much of the total surface area is covered with rectangles, you might be able to find non-overlapping sub-areas that contain rectangles, and you could then avoid searching those sub-areas that cannot contain a rectangle overlapping the point, again saving comparisons during the search at the cost of pre-computation of suitable data structures. If the set of rectangles is sparse enough, there may be no overlapping, in which case this degenerates into the brute-force search. Equally, if the set of rectangles is so dense that there are no sub-ranges in the bounding box that can be split up without breaking rectangles.\nHowever, you could also arbitrarily break up the bounding area into, say, quarters (half in each direction). You would then use a list of boxes which would include more boxes than in the original set (two or four boxes for each box that overlapped one of the arbitrary boundaries). The advantage of this is that you could then eliminate three of the four quarters from the search, reducing the amount of searching to be done in total - at the expense of auxilliary storage.\nSo, there are space-time trade-offs, as ever. And pre-computation versus search trade-offs. If you are unlucky, the pre-computation achieves nothing (for example, there are two boxes only, and they don't overlap on either axis). On the other hand, it could achieve considerable search-time benefit.\n",
"I suggest you take a look at BSP trees (and possible quadtrees or octrees, links available on that page as well). They are used to partition the whole space recursively and allow you to quickly check for a point which rectangles you need to check at all.\nAt minimum you just have one huge partition and need to check all rectangles, at maximum your partitions get so small, that they get down to the size of single rectangles. Of course the more fine-grained the partition, the longer you need to walk down the tree in order to find the rectangles you want to check.\nHowever, you can freely decide how many rectangles are suitable to be checked for a point and then create the corresponding structure.\nPay attention to overlapping rectangles though. As the BSP tree needs to be precomputed anyways, you may as well remove overlaps during that time, so you can get clear partitions.\n",
"Your R-tree approach is the best approach I know of (that's the approach I would choose over quadtrees, B+ trees, or BSP trees, as R-trees seem convenient to build in your case). Caveat: I'm no expert, even though I remember a few things from my senior year university class of algorithmic!\n",
"Why not try this. It seems rather light on both computation and memory.\nConsider the projections of all the rectangles onto the base line of your space. Denote that set of line intervals as\n {[Rl1, Rr1], [Rl2, Rr2],..., [Rln, Rrn]}, ordered by increasing left coordinates. \n\nNow suppose your point is (x, y), start a search at the left of this set until you reach a line interval that contains the point x. \nIf none does, your point (x,y) is outside all rectangles.\nIf some do, say [Rlk, Rrk], ..., [Rlh, Rrh], (k <= h) then just check whether y is within the vertical extent of any of these rectangles. \nDone.\nGood luck.\nJohn Doner\n"
] |
[
8,
4,
0,
0,
0
] |
[] |
[] |
[
"algorithm",
"point",
"python"
] |
stackoverflow_0001897779_algorithm_point_python.txt
|
Q:
How can you migrate Django models similar to Ruby on Rails migrations?
Django has a number of open source projects that tackle one of the framework's more notable missing features: model "evolution". Ruby on Rails has native support for migrations, but I'm curious if anyone can recommend one of the following Django "evolution" projects:
South
django-evolution
dmigrations
A:
South has the most steam behind it. dmigrations is too basic IMO. django-evolution screams if you ever touch the db outside of it.
South is the strongest contender by far. With the model freezing and auto-migrations it's come a long way.
A:
South and django-evolution are certainly the best options. South's model-freezing and auto-hinting are still quite fragile in my experience (django-evolution's hinting is much more robust in edge cases), but django-evolution's development seems to have mostly stalled since last summer. If I were starting now I'd probably pick South, mostly for that reason.
A:
After reading this, I went from 'knowing nothing about data model evolution' to 'using south to manage model migration' in less than 1 hour. South's documentation is outstanding and got me up to speed in record time. Not having looked at the other tools mentioned, I fully recommend it.
Update: Since posting this answer about a month ago, I went through several data model reviews, ranging from simple field renaming to completely replacing some tables by new ones. South can not do everything in a fully automated manner (e.g. a rename looks like delete & add), but the documentation guides you smoothly through the manual steps.
I will bring south into any future project. Fantastic tool!
A:
I'm a member of the team that developed dmigrations - but I would wholeheartedly recommend South. It's much more mature, is under active development, and has some killer features like ORM freezing (if you try to use ORM code in dmigrations, then change your models, you're in for a world of pain).
|
How can you migrate Django models similar to Ruby on Rails migrations?
|
Django has a number of open source projects that tackle one of the framework's more notable missing features: model "evolution". Ruby on Rails has native support for migrations, but I'm curious if anyone can recommend one of the following Django "evolution" projects:
South
django-evolution
dmigrations
|
[
"South has the most steam behind it. dmigrations is too basic IMO. django-evolution screams if you ever touch the db outside of it.\nSouth is the strongest contender by far. With the model freezing and auto-migrations it's come a long way.\n",
"South and django-evolution are certainly the best options. South's model-freezing and auto-hinting are still quite fragile in my experience (django-evolution's hinting is much more robust in edge cases), but django-evolution's development seems to have mostly stalled since last summer. If I were starting now I'd probably pick South, mostly for that reason.\n",
"After reading this, I went from 'knowing nothing about data model evolution' to 'using south to manage model migration' in less than 1 hour. South's documentation is outstanding and got me up to speed in record time. Not having looked at the other tools mentioned, I fully recommend it.\nUpdate: Since posting this answer about a month ago, I went through several data model reviews, ranging from simple field renaming to completely replacing some tables by new ones. South can not do everything in a fully automated manner (e.g. a rename looks like delete & add), but the documentation guides you smoothly through the manual steps.\nI will bring south into any future project. Fantastic tool!\n",
"I'm a member of the team that developed dmigrations - but I would wholeheartedly recommend South. It's much more mature, is under active development, and has some killer features like ORM freezing (if you try to use ORM code in dmigrations, then change your models, you're in for a world of pain).\n"
] |
[
10,
5,
2,
1
] |
[] |
[] |
[
"django",
"migration",
"python"
] |
stackoverflow_0000853248_django_migration_python.txt
|
Q:
lxml[.objectify] documentElement tagName
I'm receiving data packets in XML format, each with a specific documentRoot tag, and I'd like to delegate specialized methods to take care of those packets, based on the root tag name. This worked with xml.dom.minidom, something like this:
dom = minidom.parseString(the_data)
root = dom.documentElement
deleg = getattr(self,'elem_' + str(root.tagName))
deleg(dom)
However, I want to simplify the things (in other parts of the code, not here) by using the more pythonic lxml.objectify.
The problem is I don't know how to get "root.tagName" with lxml, preferably strictly lxml.objectify. Any ideas?
A:
With the help of the lxml docs and the dir() built_in, I managed to produce this:
>>> from lxml import objectify
>>> import StringIO
>>> tree = objectify.parse(StringIO.StringIO('<parent><child>Billy</child><child>Bob</child></parent>'))
>>> root = tree.getroot()
>>> root.tag
'parent'
>>> [(foo.tag, foo.text) for foo in root.getchildren()]
[('child', 'Billy'), ('child', 'Bob')]
>>>
Looks like you need something like
deleg = getattr(self,'elem_' + str(root.tag))
deleg(tree)
A:
FWIW in Amara Bindery you can do something like:
from amara import bindery
doc = bindery.parse(the_data)
top_elem = doc.xml_elements.next()
deleg = getattr(self, 'elem_' + str(top_elem.xml_qname))
deleg(doc)
And you get a Pythonic API as well, e.g.: doc.html.head.title = u"Change HTML document title"
|
lxml[.objectify] documentElement tagName
|
I'm receiving data packets in XML format, each with a specific documentRoot tag, and I'd like to delegate specialized methods to take care of those packets, based on the root tag name. This worked with xml.dom.minidom, something like this:
dom = minidom.parseString(the_data)
root = dom.documentElement
deleg = getattr(self,'elem_' + str(root.tagName))
deleg(dom)
However, I want to simplify the things (in other parts of the code, not here) by using the more pythonic lxml.objectify.
The problem is I don't know how to get "root.tagName" with lxml, preferably strictly lxml.objectify. Any ideas?
|
[
"With the help of the lxml docs and the dir() built_in, I managed to produce this:\n>>> from lxml import objectify\n>>> import StringIO\n>>> tree = objectify.parse(StringIO.StringIO('<parent><child>Billy</child><child>Bob</child></parent>'))\n>>> root = tree.getroot()\n>>> root.tag\n'parent'\n>>> [(foo.tag, foo.text) for foo in root.getchildren()]\n[('child', 'Billy'), ('child', 'Bob')]\n>>>\n\nLooks like you need something like\ndeleg = getattr(self,'elem_' + str(root.tag))\ndeleg(tree)\n\n",
"FWIW in Amara Bindery you can do something like:\nfrom amara import bindery\ndoc = bindery.parse(the_data)\ntop_elem = doc.xml_elements.next()\ndeleg = getattr(self, 'elem_' + str(top_elem.xml_qname))\ndeleg(doc)\n\nAnd you get a Pythonic API as well, e.g.: doc.html.head.title = u\"Change HTML document title\"\n"
] |
[
3,
0
] |
[] |
[] |
[
"lxml",
"python",
"xml"
] |
stackoverflow_0001896628_lxml_python_xml.txt
|
Q:
What is the difference between the __int__ and __index__ methods in Python 3?
The Data Model section of the Python 3.2 documentation provides the following descriptions for the __int__ and __index__ methods:
object.__int__(self)
Called to implement the built-in [function int()]. Should return [an integer].
object.__index__(self)
Called to implement operator.index(). Also called whenever Python needs an integer object (such as in slicing, or in the built-in bin(), hex() and oct() functions). Must return an integer.
I understand that they're used for different purposes, but I've been unable to figure out why two different methods are necessary. What is the difference between these methods? Is it safe to just alias __index__ = __int__ in my classes?
A:
See PEP 357: Allowing Any Object to be Used for Slicing.
The nb_int method is used for coercion and so means something
fundamentally different than what is requested here. This PEP
proposes a method for something that can already be thought of as
an integer communicate that information to Python when it needs an
integer. The biggest example of why using nb_int would be a bad
thing is that float objects already define the nb_int method, but
float objects should not be used as indexes in a sequence.
Edit: It seems that it was implemented in Python 2.5.
A:
I believe you'll find the answer in PEP 357, which has this abstract:
This PEP proposes adding an nb_index
slot in PyNumberMethods and an
__index__ special method so that arbitrary objects can be used
whenever integers are explicitly needed in Python, such as in slice
syntax (from which the slot gets its name).
|
What is the difference between the __int__ and __index__ methods in Python 3?
|
The Data Model section of the Python 3.2 documentation provides the following descriptions for the __int__ and __index__ methods:
object.__int__(self)
Called to implement the built-in [function int()]. Should return [an integer].
object.__index__(self)
Called to implement operator.index(). Also called whenever Python needs an integer object (such as in slicing, or in the built-in bin(), hex() and oct() functions). Must return an integer.
I understand that they're used for different purposes, but I've been unable to figure out why two different methods are necessary. What is the difference between these methods? Is it safe to just alias __index__ = __int__ in my classes?
|
[
"See PEP 357: Allowing Any Object to be Used for Slicing.\n\nThe nb_int method is used for coercion and so means something\n fundamentally different than what is requested here. This PEP\n proposes a method for something that can already be thought of as\n an integer communicate that information to Python when it needs an\n integer. The biggest example of why using nb_int would be a bad\n thing is that float objects already define the nb_int method, but\n float objects should not be used as indexes in a sequence.\n\nEdit: It seems that it was implemented in Python 2.5.\n",
"I believe you'll find the answer in PEP 357, which has this abstract:\n\nThis PEP proposes adding an nb_index\n slot in PyNumberMethods and an\n __index__ special method so that arbitrary objects can be used\n whenever integers are explicitly needed in Python, such as in slice\n syntax (from which the slot gets its name).\n\n"
] |
[
20,
1
] |
[] |
[] |
[
"casting",
"python"
] |
stackoverflow_0001898310_casting_python.txt
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.