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:
Handling spreadsheet data through the clipboard in GTK
I'm using a GtkSheet widget in PyGTK to power my application's spreadsheet, and it gives me an API to pull and push data out of cells. (I looked at using GtkTreeView, but it seemed to be too much work)
What I don't understand is how to intercept paste requests (via ie. CTRL+V) so that I can process them rather than passing it through to the widget. Currently, when pasting from a spreadsheet the data shows up as follows:
becomes
Is there a signal I should intercept?
I'm on Ubuntu 9.10, Python 2.6.
A:
To catch the paste event, you need to first create a custom entry class (PastableEntry in this example) that inherits from gtksheet.ItemEntry. During its initialisation, we connect to the paste-clipboard signal to trap paste events:
class PastableEntry(gtksheet.ItemEntry):
def __init__(self):
gtksheet.ItemEntry.__init__(self)
self.connect('paste-clipboard', self.__on_paste)
The hard work is in the event handler. First we need to get the clipboard contents. In Unix, clipboard sources can advertise multiple data formats. Based on your screenshot, I assume you're trying to copy data from Gnumeric. Gnumeric supports application/x-gnumeric, text/html, UTF8_STRING, COMPOUND_TEXT, and STRING. For this example we'll use the UTF8_STRING format, which looks like this:
1,1 <tab> 1,2 <tab> 1,3 <newline>
2,1 <tab> 2,2 <tab> 2,3 <newline>
3,1 <tab> 3,2 <tab> 3,3
Obviously this fails horribly if any of the cells contain a tab or newline character, but we'll use this for simplicity. In a real world application you may want to parse the application/x-gnumeric or text/html formatted data.
Back to our PastableEntry class, now we define the paste event handler:
def __on_paste(self, entry):
clip = gtk.Clipboard()
data = clip.wait_for_contents('UTF8_STRING')
text = data.get_text()
sheet = self.parent
o_row, o_col = sheet.get_active_cell()
for i_row, row in enumerate(text.split('\n')):
for i_col, cell in enumerate(row.split('\t')):
sheet.set_cell_text(o_row + i_row, o_col + i_col, cell)
self.stop_emission('paste-clipboard')
It should be quite self-explanatory. We split the clipboard data into rows (by newline characters) and then into cells (by tab characters), and set the Sheet cell values accordingly.
The stop_emission is there to stop GTK+ from running the default handler for paste operations. Without that line, the selected cell will be overwritten with the raw data.
We then register the class with GObject:
gobject.type_register(PastableEntry)
Finally, to actually use our custom entry class, pass it to the constructor of gtksheet.Sheet:
s = gtksheet.Sheet(20, 20, "Sheet 1", entry_type=PastableEntry)
| Handling spreadsheet data through the clipboard in GTK | I'm using a GtkSheet widget in PyGTK to power my application's spreadsheet, and it gives me an API to pull and push data out of cells. (I looked at using GtkTreeView, but it seemed to be too much work)
What I don't understand is how to intercept paste requests (via ie. CTRL+V) so that I can process them rather than passing it through to the widget. Currently, when pasting from a spreadsheet the data shows up as follows:
becomes
Is there a signal I should intercept?
I'm on Ubuntu 9.10, Python 2.6.
| [
"To catch the paste event, you need to first create a custom entry class (PastableEntry in this example) that inherits from gtksheet.ItemEntry. During its initialisation, we connect to the paste-clipboard signal to trap paste events:\nclass PastableEntry(gtksheet.ItemEntry):\n def __init__(self):\n gtksheet.ItemEntry.__init__(self)\n self.connect('paste-clipboard', self.__on_paste)\n\nThe hard work is in the event handler. First we need to get the clipboard contents. In Unix, clipboard sources can advertise multiple data formats. Based on your screenshot, I assume you're trying to copy data from Gnumeric. Gnumeric supports application/x-gnumeric, text/html, UTF8_STRING, COMPOUND_TEXT, and STRING. For this example we'll use the UTF8_STRING format, which looks like this:\n1,1 <tab> 1,2 <tab> 1,3 <newline>\n2,1 <tab> 2,2 <tab> 2,3 <newline>\n3,1 <tab> 3,2 <tab> 3,3\n\nObviously this fails horribly if any of the cells contain a tab or newline character, but we'll use this for simplicity. In a real world application you may want to parse the application/x-gnumeric or text/html formatted data.\nBack to our PastableEntry class, now we define the paste event handler:\n def __on_paste(self, entry):\n clip = gtk.Clipboard()\n data = clip.wait_for_contents('UTF8_STRING')\n text = data.get_text()\n sheet = self.parent\n o_row, o_col = sheet.get_active_cell()\n for i_row, row in enumerate(text.split('\\n')):\n for i_col, cell in enumerate(row.split('\\t')):\n sheet.set_cell_text(o_row + i_row, o_col + i_col, cell)\n self.stop_emission('paste-clipboard')\n\nIt should be quite self-explanatory. We split the clipboard data into rows (by newline characters) and then into cells (by tab characters), and set the Sheet cell values accordingly.\nThe stop_emission is there to stop GTK+ from running the default handler for paste operations. Without that line, the selected cell will be overwritten with the raw data.\nWe then register the class with GObject:\ngobject.type_register(PastableEntry)\n\nFinally, to actually use our custom entry class, pass it to the constructor of gtksheet.Sheet:\ns = gtksheet.Sheet(20, 20, \"Sheet 1\", entry_type=PastableEntry)\n\n"
] | [
7
] | [] | [] | [
"clipboard",
"gtk",
"linux",
"pygtk",
"python"
] | stackoverflow_0002022594_clipboard_gtk_linux_pygtk_python.txt |
Q:
In what version of Python was set initialisation syntax added
I only just noticed this feature today!
s={1,2,3} #Set initialisation
t={x for x in s if x!=3} #Set comprehension
t=={1,2}
What version is it in? I also noticed that it has set comprehension. Was this added in the same version?
Resources
Sets in Python 2.4 Docs
What's new in Python 3.0
A:
The sets module was added in Python 2.3, but the built-in set type was added to the language in 2.4, with essentially the same interface. (As of 2.6, the sets module has been deprecated.)
So you can use sets as far back as 2.3, as long as you
import sets
But you will get a DeprecationWarning if you try that import in 2.6
Set comprehensions, and the set literal syntax -- that is, being able to say
a = { 1, 2, 3 }
are new in Python 3.0. To be very specific, both set literals and set comprehensions were present in Python 3.0a1, the first public release of Python 3.0, from 2007. Python 3 release notes
The comprehensions and literals were later implemented in 2.7. 3.x Python features incorporated into 2.7
A:
Well, testing it:
>>> s = {1, 2, 3}
File "<stdin>", line 1
s = {1, 2, 3}
^
SyntaxError: invalid syntax
I'm running 2.5, so I would assume that this syntax was added sometime in 2.6 (Update: actually added in 3.0, but Ian beat me). I should probably be upgrading sometime soon. I'm glad they added a syntax for it - I'm rather tired of set([1, 2, 3]).
Set comprehensions have probably been around since sets were first created. The Python documentation site isn't very clear, but I wouldn't imagine sets would be too useful without iterators.
A:
The set literal and set and dict comprehension syntaxes were backported to 2.x trunk, about 2-3 days ago. So I guess this feature should be available from python 2.7.
| In what version of Python was set initialisation syntax added | I only just noticed this feature today!
s={1,2,3} #Set initialisation
t={x for x in s if x!=3} #Set comprehension
t=={1,2}
What version is it in? I also noticed that it has set comprehension. Was this added in the same version?
Resources
Sets in Python 2.4 Docs
What's new in Python 3.0
| [
"The sets module was added in Python 2.3, but the built-in set type was added to the language in 2.4, with essentially the same interface. (As of 2.6, the sets module has been deprecated.)\nSo you can use sets as far back as 2.3, as long as you\nimport sets\n\nBut you will get a DeprecationWarning if you try that import in 2.6\nSet comprehensions, and the set literal syntax -- that is, being able to say\na = { 1, 2, 3 }\n\nare new in Python 3.0. To be very specific, both set literals and set comprehensions were present in Python 3.0a1, the first public release of Python 3.0, from 2007. Python 3 release notes\nThe comprehensions and literals were later implemented in 2.7. 3.x Python features incorporated into 2.7\n",
"Well, testing it:\n>>> s = {1, 2, 3}\n File \"<stdin>\", line 1\n s = {1, 2, 3}\n ^\nSyntaxError: invalid syntax\n\nI'm running 2.5, so I would assume that this syntax was added sometime in 2.6 (Update: actually added in 3.0, but Ian beat me). I should probably be upgrading sometime soon. I'm glad they added a syntax for it - I'm rather tired of set([1, 2, 3]).\nSet comprehensions have probably been around since sets were first created. The Python documentation site isn't very clear, but I wouldn't imagine sets would be too useful without iterators.\n",
"The set literal and set and dict comprehension syntaxes were backported to 2.x trunk, about 2-3 days ago. So I guess this feature should be available from python 2.7.\n"
] | [
11,
0,
0
] | [] | [] | [
"python"
] | stackoverflow_0001611625_python.txt |
Q:
All members package/module defines?
How can I know which members module/package defines? By defining I mean:
somemodule.py
import os # <-- Not defined in this module
from os.path import sep # <-- Not defined in this module
I_AM_ATTRIBUTE = None # <-- Is defined in this module
class SomeClass(object): # <-- Is defined also...
pass
So I need a some sort of function that when called would yield only I_AM_ATTRIBUTE and SomeClass.
Now I have been trying to do using dir(somemodule), but how can I know which ones are defined in somemodule? Checking against __module__ does not work, since that is not defined in modules and attributes (such as os package, or sep attribute).
Apparently wild import (from somemodule import *) also fails to filter those, so is it even possible?
Best I can get is:
import somemodule
for name in dir(somemodule):
try:
value = getattr(somemodule, name)
except:
pass
else:
if hasattr(value, "__module__"):
if value.__module__ != somemodule.__name__:
continue
if hasattr(value, "__name__"):
if not value.__name__.startswith(__name__):
continue
print "somemodule defines:", name
Takes os out, but leaves sep.
A:
There is no way to do this. This is because simple attributes (like I_AM_ATTRIBUTE in your example) are simply values stored in the module's dictionary. When they are copied to another module, they are placed in that module's dictionary as well, and there is no way to tell which was the original location. You can only tell with objects that provide a __module__ attribute such as classes and functions.
Regarding wild import, running from somemodule import * on your example will import all attributes, including os and sep. If a package provides an __all__ variable, wild import will import the names contained there. Otherwise, it will import all names not beginning with an underscore, regardless of which module they are originally from.
A:
What does "define" mean? For me, defined means that some symbol is part of the module's public interface. This matches up with how it seems you're trying to use the term, including in your example, but if you have some purpose which doesn't align with this definition, you'll have to clarify the question on what you're really trying to do. This makes it a documentation issue.
So you can't know what a module defines, and some things which are imported might still be "defined in that module" or "defined to be part of that module's public interface". This happens often when importing from a private module, including C extension modules.
For your own modules, use __all__ (can do that easily) or the informal underscore prefix for non-public (e.g. _private_var = 42). Both conventions are recognized by help() and should be used by other documentation generators.
| All members package/module defines? | How can I know which members module/package defines? By defining I mean:
somemodule.py
import os # <-- Not defined in this module
from os.path import sep # <-- Not defined in this module
I_AM_ATTRIBUTE = None # <-- Is defined in this module
class SomeClass(object): # <-- Is defined also...
pass
So I need a some sort of function that when called would yield only I_AM_ATTRIBUTE and SomeClass.
Now I have been trying to do using dir(somemodule), but how can I know which ones are defined in somemodule? Checking against __module__ does not work, since that is not defined in modules and attributes (such as os package, or sep attribute).
Apparently wild import (from somemodule import *) also fails to filter those, so is it even possible?
Best I can get is:
import somemodule
for name in dir(somemodule):
try:
value = getattr(somemodule, name)
except:
pass
else:
if hasattr(value, "__module__"):
if value.__module__ != somemodule.__name__:
continue
if hasattr(value, "__name__"):
if not value.__name__.startswith(__name__):
continue
print "somemodule defines:", name
Takes os out, but leaves sep.
| [
"There is no way to do this. This is because simple attributes (like I_AM_ATTRIBUTE in your example) are simply values stored in the module's dictionary. When they are copied to another module, they are placed in that module's dictionary as well, and there is no way to tell which was the original location. You can only tell with objects that provide a __module__ attribute such as classes and functions.\nRegarding wild import, running from somemodule import * on your example will import all attributes, including os and sep. If a package provides an __all__ variable, wild import will import the names contained there. Otherwise, it will import all names not beginning with an underscore, regardless of which module they are originally from.\n",
"What does \"define\" mean? For me, defined means that some symbol is part of the module's public interface. This matches up with how it seems you're trying to use the term, including in your example, but if you have some purpose which doesn't align with this definition, you'll have to clarify the question on what you're really trying to do. This makes it a documentation issue.\nSo you can't know what a module defines, and some things which are imported might still be \"defined in that module\" or \"defined to be part of that module's public interface\". This happens often when importing from a private module, including C extension modules.\nFor your own modules, use __all__ (can do that easily) or the informal underscore prefix for non-public (e.g. _private_var = 42). Both conventions are recognized by help() and should be used by other documentation generators.\n"
] | [
1,
1
] | [] | [] | [
"python"
] | stackoverflow_0002055961_python.txt |
Q:
how to perform ssh and scp equivalent function in python code
I want to login in different machine in the network and copy a file from that machine to my machine.I want to do this using python.Any idea how can i do this .I have python 2.5 a nd ubuntu 8.10
A:
Use subprocess and call scp directly. This has the advantage of using your ssh settings, private keys and agent.
Look into Fabric if you need a more structured framework for doing local and remote operations.
A:
get paramiko or similar libraries.
| how to perform ssh and scp equivalent function in python code | I want to login in different machine in the network and copy a file from that machine to my machine.I want to do this using python.Any idea how can i do this .I have python 2.5 a nd ubuntu 8.10
| [
"Use subprocess and call scp directly. This has the advantage of using your ssh settings, private keys and agent.\nLook into Fabric if you need a more structured framework for doing local and remote operations.\n",
"get paramiko or similar libraries.\n"
] | [
5,
0
] | [] | [] | [
"automation",
"python",
"scp",
"ssh"
] | stackoverflow_0002056282_automation_python_scp_ssh.txt |
Q:
Help with Python strings
I have a program which reads commands from a text file
for example, the command syntax will be as follows and is a string
'index command param1 param2 param3'
The number of parameters is variable from 0 up to 3
index is an integer
command is a string
all the params are integers
I would like to split them so that I have a list as follows
[index,'command',params[]]
What is the best way to do this?
Thanks
A:
Not sure if it's the best way, but here's one way:
lines = open('file.txt')
for line in lines:
as_list = line.split()
result = [as_list[0], as_list[1], as_list[2:]]
print result
Result will contain
['index', 'command', ['param1', 'param2', 'param3']]
A:
def add_command(index, command, *params):
index = int(index)
#do what you need to with index, command and params here
with open('commands.txt') as f:
for line in f:
add_command(*line.split())
A:
i typically write:
lines = open('a.txt').readlines()
for line in lines:
para = lines.split()
index = int(para[0])
command = para[1]
para1 = float(para[2])
...
A:
Open the file
Read each line and parse the line via line.split( )
A:
>>> for line in open("file"):
... line=line.rstrip().split(" ",2)
... line[0]=int(line[0])
... line[2]=line[2].split()
... print line
...
[1, 'command', ['param1', 'param2', 'param3']]
A:
If you use Python 3+, then following should be enough as indicated in PEP 3132: Extended Iterable Unpacking:
(index,command,*parameters) = line.split()
Otherwise, I like solution from James best:
def add_command(index, command, *params):
...
A:
The Answer provided by cb160 is correct and smart way, But, I did it in this way.
In cb160's code, Only thing is index should be in Integer format, as you have mentioned.
In my below code, I added exceptions for empty lines in input file if there are any.
#Example Input File: (file content)
"""
1 command1 parm1a parm1b parm1c
2 command2 parm2a parm2b parm2c
3 command3 parm3a parm3b parm3c
"""
li = []
for line in open('list_of_commands.txt'):
try:
lis = line.split()
li.append([int(lis[0]),lis[1], lis[2:]])
except IndexError:
pass # do nothing if empty lines are found
print li
Output
[1, 'command1', ['parm1a', 'parm1b', 'parm1c']]
[2, 'command2', ['parm2a', 'parm2b', 'parm2c']]
[3, 'command3', ['parm3a', 'parm3b', 'parm3c']]
let me know if I missed anything.
Thanks
| Help with Python strings | I have a program which reads commands from a text file
for example, the command syntax will be as follows and is a string
'index command param1 param2 param3'
The number of parameters is variable from 0 up to 3
index is an integer
command is a string
all the params are integers
I would like to split them so that I have a list as follows
[index,'command',params[]]
What is the best way to do this?
Thanks
| [
"Not sure if it's the best way, but here's one way:\nlines = open('file.txt')\nfor line in lines:\n as_list = line.split()\n result = [as_list[0], as_list[1], as_list[2:]]\n print result\n\nResult will contain\n['index', 'command', ['param1', 'param2', 'param3']]\n\n",
"def add_command(index, command, *params):\n index = int(index)\n #do what you need to with index, command and params here\n\nwith open('commands.txt') as f:\n for line in f:\n add_command(*line.split())\n\n",
"i typically write: \nlines = open('a.txt').readlines()\nfor line in lines:\n para = lines.split()\n index = int(para[0])\n command = para[1]\n para1 = float(para[2])\n ...\n\n",
"\nOpen the file\nRead each line and parse the line via line.split( )\n\n",
">>> for line in open(\"file\"):\n... line=line.rstrip().split(\" \",2)\n... line[0]=int(line[0])\n... line[2]=line[2].split()\n... print line\n...\n[1, 'command', ['param1', 'param2', 'param3']]\n\n",
"If you use Python 3+, then following should be enough as indicated in PEP 3132: Extended Iterable Unpacking:\n(index,command,*parameters) = line.split()\n\n\nOtherwise, I like solution from James best:\ndef add_command(index, command, *params):\n ...\n\n",
"The Answer provided by cb160 is correct and smart way, But, I did it in this way.\nIn cb160's code, Only thing is index should be in Integer format, as you have mentioned.\nIn my below code, I added exceptions for empty lines in input file if there are any.\n#Example Input File: (file content)\n\"\"\"\n1 command1 parm1a parm1b parm1c\n2 command2 parm2a parm2b parm2c\n\n3 command3 parm3a parm3b parm3c\n\n\"\"\"\n\nli = []\n\nfor line in open('list_of_commands.txt'):\n try:\n lis = line.split()\n li.append([int(lis[0]),lis[1], lis[2:]])\n except IndexError:\n pass # do nothing if empty lines are found\n\nprint li\n\nOutput\n[1, 'command1', ['parm1a', 'parm1b', 'parm1c']]\n[2, 'command2', ['parm2a', 'parm2b', 'parm2c']]\n[3, 'command3', ['parm3a', 'parm3b', 'parm3c']]\n\nlet me know if I missed anything.\nThanks\n"
] | [
8,
5,
2,
1,
1,
1,
0
] | [] | [] | [
"python",
"string"
] | stackoverflow_0002055738_python_string.txt |
Q:
How to protect Python source code?
Is it possible to distribute only the bytecode version (.pyc file) of a Python script instead of the original .py file? My app embeds the Python interpreter and calls PyImport_Import to load a script. How can I tell it to look for a .pyc file and import that?
A:
Use the freeze tool, which is included in the Python source tree as Tools/freeze. It converts Python byte code to C arrays; with a C compiler you can embed all your modules into a new program, which is then linked with the standard Python modules.
Note that freeze requires a C compiler.
Other utilities:
1- PyInstaller
2- Py2Exe
3- Squeeze
4- cx_freeze
more info on effbot.org
A:
I did it by creating .py library and simple .py program that uses that library. Then I compiled library to .pyc and distributed: program as .py source and library as compiled .pyc.
A:
Since you are writing your main program in C++, you can do whatever you want to protect your Python files. You could encrypt them for distribution, then decrypt them just in time to import them into the Python interpreter, for example.
Since you are using PyImport_Import, you can write your own __import__ hook to import the modules not from a file but from a memory buffer, so your transformation to .pyc file can happen all in memory, with no understandable Python code on disk at all.
A:
This should not be a problem, if you create a stand alone program using py2exe you only get the .pyc files.
Normally you don't need to tell python to look for .pyc files, it does so anyway. Only if there is a newer .py source file this is used.
However, the level of protection of you source code may not be very high.
A:
In the interactive interpreter, that's automatic - if there is no .py, the .pyc will still be used:
$ echo 'print "hello"' > test.py
$ python -m compileall .
$ rm test.py
$ python -m test
hello
$
Could you just try if that works the same way with the API?
Edited to add:
I agree with Ber in that your code protection will be rather weak. -O will remove docstrings, if that doesn't change the behaviour of your programme, that may make reconstructing behaviour harder, but what you'd really need some sort of bytecode obfuscation.
I don't know if a ready-made obfuscation tool exists for python, but this sounds viable, if you want to / can invest the time (and don't feel all too silly doing it, and can ship your own interpreter).
| How to protect Python source code? | Is it possible to distribute only the bytecode version (.pyc file) of a Python script instead of the original .py file? My app embeds the Python interpreter and calls PyImport_Import to load a script. How can I tell it to look for a .pyc file and import that?
| [
"Use the freeze tool, which is included in the Python source tree as Tools/freeze. It converts Python byte code to C arrays; with a C compiler you can embed all your modules into a new program, which is then linked with the standard Python modules. \nNote that freeze requires a C compiler.\nOther utilities:\n1- PyInstaller\n2- Py2Exe\n3- Squeeze\n4- cx_freeze\nmore info on effbot.org\n",
"I did it by creating .py library and simple .py program that uses that library. Then I compiled library to .pyc and distributed: program as .py source and library as compiled .pyc.\n",
"Since you are writing your main program in C++, you can do whatever you want to protect your Python files. You could encrypt them for distribution, then decrypt them just in time to import them into the Python interpreter, for example.\nSince you are using PyImport_Import, you can write your own __import__ hook to import the modules not from a file but from a memory buffer, so your transformation to .pyc file can happen all in memory, with no understandable Python code on disk at all.\n",
"This should not be a problem, if you create a stand alone program using py2exe you only get the .pyc files. \nNormally you don't need to tell python to look for .pyc files, it does so anyway. Only if there is a newer .py source file this is used.\nHowever, the level of protection of you source code may not be very high.\n",
"In the interactive interpreter, that's automatic - if there is no .py, the .pyc will still be used:\n$ echo 'print \"hello\"' > test.py\n$ python -m compileall .\n$ rm test.py\n$ python -m test\nhello\n$\n\nCould you just try if that works the same way with the API?\nEdited to add:\nI agree with Ber in that your code protection will be rather weak. -O will remove docstrings, if that doesn't change the behaviour of your programme, that may make reconstructing behaviour harder, but what you'd really need some sort of bytecode obfuscation.\nI don't know if a ready-made obfuscation tool exists for python, but this sounds viable, if you want to / can invest the time (and don't feel all too silly doing it, and can ship your own interpreter).\n"
] | [
12,
5,
5,
2,
2
] | [] | [] | [
"bytecode",
"c",
"compilation",
"python"
] | stackoverflow_0002055355_bytecode_c_compilation_python.txt |
Q:
Recover process with subprocess.Popen?
I have a python program that uses subprocess.Popen to launch another process (python process or whatever), and after launching it I save the child's PID to a file. Let's suppose that suddenly the parent process dies (because of an exception or whatever). Is there any way to access again to the object returned by Popen?
I mean, the basic idea is to read the file at first, and if it exists and it has a PID written on it, then access to that process someway, in order to know the return code or whatever. If there isn't a PID, then launch the process with Popen.
Thanks a lot!!
A:
The Popen object is effectively just a wrapper for the child processes PID, stdin, stdout, and stderr, plus some convenience functions for using those.
So the question is why do you need access to the Popen object? Do you want to communicate with the child, terminate it, or check whether it's still running?
In any case there is no way reacquire a Popen object for an already running process.
The proper way to approach this is to launch the child as a daemon, like Tobu suggested. Part of the procedure for daemonising a process is to close stdin and stdout, so you cannot use those to talk to the child process. Instead most daemons use either pipes or sockets to allow clients to connect to them and to send them messages.
The easiest way to talk to the child is to open a named pipe from the child process at e.g. /etc/my_pipe, open that named pipe from the parent / controlling process, and write / read to / from it.
After a quick look at python-daemon it seems to me that python-daemon will help you daemonise your child process, which is tricky to get right, but it doesn't help you with the messaging side of things.
But like I said, I think you need to tell us why you need a Popen object for the child process before we can help you any further.
A:
If a process dies, all its open file handles are closed. This includes any unnamed pipes created by popen(). So, no, there's no way to recover a Popen object from just a PID. The OS won't even consider your new process the parent, so you won't even get SIGCHLD signals (though waitpid() might still work).
I'm not sure if the child is guaranteed to survive, either, since a write to a pipe with no reader (namely, the redirected stdout of the child) should kill the child with a SIGPIPE.
If you want your parent process to pick up where the child left off, you need to spawn the child to write to a file, usually in /tmp or /var/log, and have it record its PID like you are now (the usual location is /var/run). (Having it write to a named pipe risks getting it killed with SIGPIPE as above.) If you suffix your filename with the PID, then it becomes easy for the manager process to figure out which file belongs to which daemon.
A:
Looks like you're trying to write a daemon, and it needs pidfile support. You can't go wrong with python-daemon.
For example:
import daemon
import lockfile
import os
with daemon.DaemonContext(pidfile=lockfile.FileLock('/var/run/spam.pid')):
os.execl('/path/to/prog', args…)
| Recover process with subprocess.Popen? | I have a python program that uses subprocess.Popen to launch another process (python process or whatever), and after launching it I save the child's PID to a file. Let's suppose that suddenly the parent process dies (because of an exception or whatever). Is there any way to access again to the object returned by Popen?
I mean, the basic idea is to read the file at first, and if it exists and it has a PID written on it, then access to that process someway, in order to know the return code or whatever. If there isn't a PID, then launch the process with Popen.
Thanks a lot!!
| [
"The Popen object is effectively just a wrapper for the child processes PID, stdin, stdout, and stderr, plus some convenience functions for using those.\nSo the question is why do you need access to the Popen object? Do you want to communicate with the child, terminate it, or check whether it's still running?\nIn any case there is no way reacquire a Popen object for an already running process.\nThe proper way to approach this is to launch the child as a daemon, like Tobu suggested. Part of the procedure for daemonising a process is to close stdin and stdout, so you cannot use those to talk to the child process. Instead most daemons use either pipes or sockets to allow clients to connect to them and to send them messages.\nThe easiest way to talk to the child is to open a named pipe from the child process at e.g. /etc/my_pipe, open that named pipe from the parent / controlling process, and write / read to / from it.\nAfter a quick look at python-daemon it seems to me that python-daemon will help you daemonise your child process, which is tricky to get right, but it doesn't help you with the messaging side of things.\nBut like I said, I think you need to tell us why you need a Popen object for the child process before we can help you any further.\n",
"If a process dies, all its open file handles are closed. This includes any unnamed pipes created by popen(). So, no, there's no way to recover a Popen object from just a PID. The OS won't even consider your new process the parent, so you won't even get SIGCHLD signals (though waitpid() might still work).\nI'm not sure if the child is guaranteed to survive, either, since a write to a pipe with no reader (namely, the redirected stdout of the child) should kill the child with a SIGPIPE.\nIf you want your parent process to pick up where the child left off, you need to spawn the child to write to a file, usually in /tmp or /var/log, and have it record its PID like you are now (the usual location is /var/run). (Having it write to a named pipe risks getting it killed with SIGPIPE as above.) If you suffix your filename with the PID, then it becomes easy for the manager process to figure out which file belongs to which daemon.\n",
"Looks like you're trying to write a daemon, and it needs pidfile support. You can't go wrong with python-daemon.\nFor example:\nimport daemon\nimport lockfile\nimport os\n\nwith daemon.DaemonContext(pidfile=lockfile.FileLock('/var/run/spam.pid')):\n os.execl('/path/to/prog', args…)\n\n"
] | [
3,
1,
0
] | [] | [] | [
"popen",
"python"
] | stackoverflow_0002056594_popen_python.txt |
Q:
How to revert to content of a Dijit text box when browser back-button is clicked?
I am using a Dojo Textarea Dijit to input and submit text (to be processed).
I found that after submiting, if a browser back-button is pressed (IE8, Firefox) unlike regular HTML Textarea, I return to the input screen, but the Textarea is EMPTY.
What I would like to happen is that after back-button is pressed, I would return to the previous page WITH the previously written text already in the Textarea - so that I can edit it, instead of writing it all again.
Can anyone explain how I do that (and some specific code example would be appreciated).
Thanks,
Barry.
A:
You may consider using dojo.back module: http://dojocampus.org/content/2009/05/17/using-dojo-back-button-and-bookmarks to store the page's state and handle back / forward events. However not sure if it's worth powder and shot in your case. :)
| How to revert to content of a Dijit text box when browser back-button is clicked? | I am using a Dojo Textarea Dijit to input and submit text (to be processed).
I found that after submiting, if a browser back-button is pressed (IE8, Firefox) unlike regular HTML Textarea, I return to the input screen, but the Textarea is EMPTY.
What I would like to happen is that after back-button is pressed, I would return to the previous page WITH the previously written text already in the Textarea - so that I can edit it, instead of writing it all again.
Can anyone explain how I do that (and some specific code example would be appreciated).
Thanks,
Barry.
| [
"You may consider using dojo.back module: http://dojocampus.org/content/2009/05/17/using-dojo-back-button-and-bookmarks to store the page's state and handle back / forward events. However not sure if it's worth powder and shot in your case. :)\n"
] | [
2
] | [] | [] | [
"back_button",
"dojo",
"python",
"textarea"
] | stackoverflow_0001994581_back_button_dojo_python_textarea.txt |
Q:
os.makedirs doesn't understand "~" in my path
I have a little problem with ~ in my paths.
This code example creates some directories called ~/some_dir and do not understand that I wanted to create some_dir in my home directory.
my_dir = "~/some_dir"
if not os.path.exists(my_dir):
os.makedirs(my_dir)
Note this is on a Linux-based system.
A:
You need to expand the tilde manually:
my_dir = os.path.expanduser('~/some_dir')
A:
The conversion of ~/some_dir to $HOME/some_dir is called tilde expansion and is a common user interface feature. The file system does not know anything about it.
In Python, this feature is implemented by os.path.expanduser:
my_dir = os.path.expanduser("~/some_dir")
A:
That's probably because Python is not Bash and doesn't follow same conventions. You may use this:
homedir = os.path.expanduser('~')
| os.makedirs doesn't understand "~" in my path | I have a little problem with ~ in my paths.
This code example creates some directories called ~/some_dir and do not understand that I wanted to create some_dir in my home directory.
my_dir = "~/some_dir"
if not os.path.exists(my_dir):
os.makedirs(my_dir)
Note this is on a Linux-based system.
| [
"You need to expand the tilde manually:\nmy_dir = os.path.expanduser('~/some_dir')\n\n",
"The conversion of ~/some_dir to $HOME/some_dir is called tilde expansion and is a common user interface feature. The file system does not know anything about it.\nIn Python, this feature is implemented by os.path.expanduser:\nmy_dir = os.path.expanduser(\"~/some_dir\")\n\n",
"That's probably because Python is not Bash and doesn't follow same conventions. You may use this:\nhomedir = os.path.expanduser('~')\n\n"
] | [
348,
84,
15
] | [] | [] | [
"path",
"python"
] | stackoverflow_0002057045_path_python.txt |
Q:
What is the Java Equivalent of Python's property()?
I'm new to Java, and I'd like to create some class variables that are dynamically calculated when accessed, as you can do in Python by using the property() method. However, I'm not really sure how to describe this, so Googling shows me lots about the Java "Property" class, but this doesn't appear to be the same thing. What is the Java equivalent of Python's property()?
A:
There's no such facility built into Java language. You have to write all the getters and setters explicitly by yourself. IDEs like Eclipse can generate this boilerplate code for you though.
For example :
class Point{
private int x, y;
public Point(int x, int y){
this.x = x;
this.y = y;
}
public void setX(int x){
this.x = x;
}
public int getX(){
return x;
}
public void setY(int y){
this.y = y;
}
public int getY(){
return y;
}
}
You might want to have a look at Project Lombok which provides the annotations @Getter and @Setter that are somewhat similar to Python's property.
With Lombok, the above example reduces to :
class Point{
@Getter @Setter private int x, y;
public Point(int x, int y){
this.x = x;
this.y = y;
}
}
A:
the built-in property() function does exactly the opposite of what's described here in the answers. it's not about generating getters and setters for member variables. it just allows you to call a method by accessing a property (so, although you just access a variable in te Python class, a function will be called). (this post ecplains how and why to use it.)
this said, Java doesn't offer anything like this. even more, property access is discouraged in Java. i guess you could do it in Groovy script language and the meta magic though. but i don't know out of my head how to do this.
A:
They don't really exist. In Java it's common practice to declare members as private or protected and only allow access to them via methods. Often this leads to lots of small getFoo() and setFoo(newFoo) methods. Python doesn't really have private and protected and it's more common to allow direct access to members.
A:
As others have noted, java has getters and setters, but there is no strict analogon. There is a third party library called Project Lombok tha uses annotation to generate the getters and setters in the .class files at comile time. This could be used to make things a little less verbose.
A:
Do you want to create new fields/getters/setters in the class? If you want to do this in runtime, you have to create completely new class with your fields and methods, and load it into the JVM. To create new class you can use library like ASM or CGLib, but if you're new to Java, this isn't something you want to start with.
| What is the Java Equivalent of Python's property()? | I'm new to Java, and I'd like to create some class variables that are dynamically calculated when accessed, as you can do in Python by using the property() method. However, I'm not really sure how to describe this, so Googling shows me lots about the Java "Property" class, but this doesn't appear to be the same thing. What is the Java equivalent of Python's property()?
| [
"There's no such facility built into Java language. You have to write all the getters and setters explicitly by yourself. IDEs like Eclipse can generate this boilerplate code for you though.\nFor example :\nclass Point{\n private int x, y;\n\n public Point(int x, int y){\n this.x = x;\n this.y = y;\n }\n\n public void setX(int x){\n this.x = x;\n }\n\n public int getX(){\n return x;\n }\n\n public void setY(int y){\n this.y = y;\n }\n\n public int getY(){\n return y;\n }\n}\n\n\nYou might want to have a look at Project Lombok which provides the annotations @Getter and @Setter that are somewhat similar to Python's property.\nWith Lombok, the above example reduces to :\nclass Point{\n @Getter @Setter private int x, y;\n\n public Point(int x, int y){\n this.x = x;\n this.y = y;\n }\n}\n\n",
"the built-in property() function does exactly the opposite of what's described here in the answers. it's not about generating getters and setters for member variables. it just allows you to call a method by accessing a property (so, although you just access a variable in te Python class, a function will be called). (this post ecplains how and why to use it.)\n\nthis said, Java doesn't offer anything like this. even more, property access is discouraged in Java. i guess you could do it in Groovy script language and the meta magic though. but i don't know out of my head how to do this.\n",
"They don't really exist. In Java it's common practice to declare members as private or protected and only allow access to them via methods. Often this leads to lots of small getFoo() and setFoo(newFoo) methods. Python doesn't really have private and protected and it's more common to allow direct access to members. \n",
"As others have noted, java has getters and setters, but there is no strict analogon. There is a third party library called Project Lombok tha uses annotation to generate the getters and setters in the .class files at comile time. This could be used to make things a little less verbose.\n",
"Do you want to create new fields/getters/setters in the class? If you want to do this in runtime, you have to create completely new class with your fields and methods, and load it into the JVM. To create new class you can use library like ASM or CGLib, but if you're new to Java, this isn't something you want to start with.\n"
] | [
9,
4,
2,
1,
0
] | [
"Actually you may simulate this behavior in Java.\nWARNING: ugly solution below\nYou can write a method in an utility class like the code below:\npublic Object getProperty(String property, Object obj) {\n if (obj != null && property != null) {\n Field field = obj.getClass().getDeclaredField(property);\n field.setAccessible(true);\n try {\n return field.get(obj);\n } catch (Exception ex) {\n return null;\n }\n }\n return null;\n}\n\nYou may actually declare it as a static method and then just import this method into your classes which will need this behavior.\nBy the way, Groovy support this feature.\n"
] | [
-1
] | [
"java",
"properties",
"python"
] | stackoverflow_0002056752_java_properties_python.txt |
Q:
How to delete an inner element from a nested list in Python?
I have created a list
a = [[3, 4], [5], [6, 7, 8]]
I want to delete 3 from this list. What is the command for this?
A:
lots of possible ways
>>> mylist = [[3,4],[5],[6,7,8]]
>>> mylist[0] = [4]
>>> mylist
[[4], [5], [6, 7, 8]]
>>> mylist = [[3,4],[5],[6,7,8]]
>>> del mylist[0][0]
>>> mylist
[[4], [5], [6, 7, 8]]
>>> mylist = [[3,4],[5],[6,7,8]]
>>> mylist[0].remove(3)
>>> mylist
[[4], [5], [6, 7, 8]]
Take your pick :)
A:
Easy, you can try this
del a[0][0]
A:
a[0].remove(3)
(had to add more text so it was long enough)
A:
Using this:
del a[0][0]
For a better understanding of lists, dictionaries, etc., I suggest you should read Dive Into Python
You'll find Chapter 3 very useful.
A:
Assuming, you want to delete all 3s from a list of lists:
>>> lst = [[3,4],[5],[6,7,8]]
>>> [[i for i in el if i != 3] for el in lst]
[[4], [5], [6, 7, 8]]
A:
if you don't know where "3" is,
>>> for n,i in enumerate(list):
... if 3 in i: list[n].remove(3)
...
>>> list
[[4], [5], [6, 7, 8]]
>>>
A:
If I understand your question you have list in a list and you want to delete first element from first list. So use:
del a[0][0]
A:
First of all, be careful because you are shadowing the built in name "list".
This
a_list = [[3,4],[5],[6,7,3, 3, 8]]
def clear_list_from_item(a_list, item):
try:
while True: a_list.remove(item)
except ValueError:
return a_list
a_list = [clear_list_from_item(x, 3) for x in a_list]
This will modify your original list in place.
A:
two easy ways to remove from a list, if you know the element of concern is at position 0:
a[0].pop (0)
del a[0][0]
| How to delete an inner element from a nested list in Python? | I have created a list
a = [[3, 4], [5], [6, 7, 8]]
I want to delete 3 from this list. What is the command for this?
| [
"lots of possible ways\n>>> mylist = [[3,4],[5],[6,7,8]]\n>>> mylist[0] = [4]\n>>> mylist\n[[4], [5], [6, 7, 8]]\n>>> mylist = [[3,4],[5],[6,7,8]]\n>>> del mylist[0][0]\n>>> mylist\n[[4], [5], [6, 7, 8]]\n>>> mylist = [[3,4],[5],[6,7,8]]\n>>> mylist[0].remove(3)\n>>> mylist\n[[4], [5], [6, 7, 8]]\n\nTake your pick :)\n",
"Easy, you can try this\ndel a[0][0]\n\n",
"a[0].remove(3)\n\n(had to add more text so it was long enough)\n",
"Using this:\ndel a[0][0]\n\nFor a better understanding of lists, dictionaries, etc., I suggest you should read Dive Into Python\nYou'll find Chapter 3 very useful.\n",
"Assuming, you want to delete all 3s from a list of lists:\n>>> lst = [[3,4],[5],[6,7,8]]\n>>> [[i for i in el if i != 3] for el in lst]\n[[4], [5], [6, 7, 8]]\n\n",
"if you don't know where \"3\" is, \n>>> for n,i in enumerate(list):\n... if 3 in i: list[n].remove(3)\n...\n>>> list\n[[4], [5], [6, 7, 8]]\n>>>\n\n",
"If I understand your question you have list in a list and you want to delete first element from first list. So use:\ndel a[0][0]\n\n",
"First of all, be careful because you are shadowing the built in name \"list\".\nThis \na_list = [[3,4],[5],[6,7,3, 3, 8]]\n\ndef clear_list_from_item(a_list, item):\n try:\n while True: a_list.remove(item)\n except ValueError:\n return a_list\n\na_list = [clear_list_from_item(x, 3) for x in a_list]\n\nThis will modify your original list in place.\n",
"two easy ways to remove from a list, if you know the element of concern is at position 0: \na[0].pop (0)\ndel a[0][0]\n\n"
] | [
11,
5,
2,
2,
2,
1,
0,
0,
0
] | [] | [] | [
"python"
] | stackoverflow_0002056341_python.txt |
Q:
Build, syntax-check, parse and evaluate a query
I am building a query in a textarea with different conditions selected from the html controls. Also users are open to do modification to it.
Client side:
For the below list of condition:
a(1, 3) > 20
b(4, 5) < 90
c(3, 0) = 80
I form a query:
a(1, 3) > 20 and b(4, 5) < 90 or c(3, 0) = 80
On the server side this has to be parsed, lookup and call each function with arguments. (a, b and c are the functions)
I want to check for the query syntax (not sure at the client side or the server side) before processing it.
For example if the user enters incorrect function / arguments or they use incorrect operators.
Appreciate your suggestions and feedback.
PS: Using python
A:
PLY has a simple expression example that will get you most of the way there.
| Build, syntax-check, parse and evaluate a query | I am building a query in a textarea with different conditions selected from the html controls. Also users are open to do modification to it.
Client side:
For the below list of condition:
a(1, 3) > 20
b(4, 5) < 90
c(3, 0) = 80
I form a query:
a(1, 3) > 20 and b(4, 5) < 90 or c(3, 0) = 80
On the server side this has to be parsed, lookup and call each function with arguments. (a, b and c are the functions)
I want to check for the query syntax (not sure at the client side or the server side) before processing it.
For example if the user enters incorrect function / arguments or they use incorrect operators.
Appreciate your suggestions and feedback.
PS: Using python
| [
"PLY has a simple expression example that will get you most of the way there.\n"
] | [
4
] | [] | [] | [
"html",
"javascript",
"jquery",
"python"
] | stackoverflow_0002057820_html_javascript_jquery_python.txt |
Q:
Merging two event loops (Cherrypy and Wxpython)
Okay, I have an application written with cherrypy, and I want to build a wxpython gui for it. The problem is that both modules use a close loop for event handling, which (I assume) means while one is running the other will be locked.
I asked for some advice and it was suggested that I merge the two event loops rather than using the stock entrypoints (quickloop() for cherrypy and MainLoop() for wx)
The problem is I have no idea how to do this. Any advice would be greatly appreciated.
A:
You already asked the same question here: cherrypy and wxpython, and I gave you the best response you're going to find anywhere there, which was voted up and you approved, apparently. Why are you asking again?
A:
In the case of cherrypy, you have the source. Look in the code what quickloop() does and then try to merge this code with the MainLoop() of WX.
Both loops will probably look like this:
while (true) {
if (pendingEvents()) processEvents ();
else waitForEvents ();
}
You must find a way to merge the two waiting calls into one (so the code continues if either event source had pending events). For WX, look at Dispatch(), Pending() and ProcessIdle().
Or you can look at wxIdleEvent (see the docs) and process all cherrypy events in there.
Another solution might be to run the two loops in different threads. In this case, you can't call WX methods from cherrypy code and vice versa. To solve this, you must find a way to send messages to the other thread with all the information which method to call. This makes sure that WX methods get executed in the WX thread and cherrypy methods get executed in the cherrypy thread.
| Merging two event loops (Cherrypy and Wxpython) | Okay, I have an application written with cherrypy, and I want to build a wxpython gui for it. The problem is that both modules use a close loop for event handling, which (I assume) means while one is running the other will be locked.
I asked for some advice and it was suggested that I merge the two event loops rather than using the stock entrypoints (quickloop() for cherrypy and MainLoop() for wx)
The problem is I have no idea how to do this. Any advice would be greatly appreciated.
| [
"You already asked the same question here: cherrypy and wxpython, and I gave you the best response you're going to find anywhere there, which was voted up and you approved, apparently. Why are you asking again?\n",
"In the case of cherrypy, you have the source. Look in the code what quickloop() does and then try to merge this code with the MainLoop() of WX.\nBoth loops will probably look like this:\nwhile (true) {\n if (pendingEvents()) processEvents ();\n else waitForEvents ();\n}\n\nYou must find a way to merge the two waiting calls into one (so the code continues if either event source had pending events). For WX, look at Dispatch(), Pending() and ProcessIdle().\nOr you can look at wxIdleEvent (see the docs) and process all cherrypy events in there.\nAnother solution might be to run the two loops in different threads. In this case, you can't call WX methods from cherrypy code and vice versa. To solve this, you must find a way to send messages to the other thread with all the information which method to call. This makes sure that WX methods get executed in the WX thread and cherrypy methods get executed in the cherrypy thread.\n"
] | [
6,
0
] | [] | [] | [
"cherrypy",
"python",
"wxpython"
] | stackoverflow_0002055193_cherrypy_python_wxpython.txt |
Q:
What are the major differences in object models of dynamic languages like Smalltalk, Ruby and Python
I dived into understanding the Ruby object model in the last weeks, and although so far was only a user of the fruits of ruby's and python's object in the past, I became curious how these things might differ in other languages.
Years ago I touched smalltalk's squeak. Smalltalk is often figuring as a referential object oriented language, that's why I am interested in it. The ruby object model does not make distinction between objects and classes, the existence singleton object makes every object a prototype extendible when necessary. As I know all these things where defined as the meta-object protocol. These things make life easier than what other less-or-non-dynamic languages like C++ or Java enable.
Please could you give me an idea, how dynamic languages, particularly smalltalk, python and ruby differ in the realisation of the meta-object protocol?
A:
The main difference between Python and Smalltalk that I remember is the way attribute privacy is handled. In Smalltalk I defined attributes and had to generate all the accessors instantly (fortunately Dolphin Smalltalk did this) and the use them. On the other hand in Python everything can be accessed, even attributes considered private (those with __ at the beginning, which are mangled to form ___). Some might say, that this is potentially dangerous - say, at some point in the future you need to perform some operations, when you change certain attribute. But Python solves it gracefully, with properties.
I like the notion, that I can access anything I want. If only I know, what I am doing, I can do it :-)
A:
In Python, each object has one namespace -- the object's "attributes", accessible in that namespace, can be methods, simple references to other objects (callable or not), or be synthesized on the fly by descriptors (plain attributes may live in the instance or in the class, but descriptors -- including functions as descriptors that synthesize methods -- are only used if they live in the class, not the instance; so in particular "special methods" are only special if defined in the class, not the instance). Attribute-handling builtins and special methods (getattr, setattr, __getattr__, __setattr__, ...) work just the same way across the single namespace of the object, whether referring to "plain attributes" or not.
The key point is that for any object a, in Python, a.b may be a method (or other callable) or not: the Python compiler doesn't know (nor care), you can take the reference a.b and (e.g.) pass it as an argument, return it as a result, append it to a list, and so forth, none of these operations implies calling a.b. If and when you want to (try and) call a.b, you do it explicitly by postfixing parentheses: a.b() if you want to call it without arguments.
In Ruby, methods and attributes of an object live in separate namespaces (so you can have an object with a method and an attribute with the same name, which in Python you can't) and "just mentioning" an argument-less method implicitly calls it (so c=a.b might be just taking an attribute reference, or it might be calling a.b(); if b names both a method and an attribute in a, I don't recall what heuristic rule is used to disambiguate the use). So if you want to just take method references (e.g to stash in some container or use as arguments or return values), and later perform the call, you use different syntax.
Smalltalk also has separate namespaces, like Ruby, but then you can't refer to a given object's "non-method" attributes (each object only "sees" its own attributes), so this ambiguity does not arise (but you still do have to use specific messages to extract, and later call, a "method reference").
| What are the major differences in object models of dynamic languages like Smalltalk, Ruby and Python | I dived into understanding the Ruby object model in the last weeks, and although so far was only a user of the fruits of ruby's and python's object in the past, I became curious how these things might differ in other languages.
Years ago I touched smalltalk's squeak. Smalltalk is often figuring as a referential object oriented language, that's why I am interested in it. The ruby object model does not make distinction between objects and classes, the existence singleton object makes every object a prototype extendible when necessary. As I know all these things where defined as the meta-object protocol. These things make life easier than what other less-or-non-dynamic languages like C++ or Java enable.
Please could you give me an idea, how dynamic languages, particularly smalltalk, python and ruby differ in the realisation of the meta-object protocol?
| [
"The main difference between Python and Smalltalk that I remember is the way attribute privacy is handled. In Smalltalk I defined attributes and had to generate all the accessors instantly (fortunately Dolphin Smalltalk did this) and the use them. On the other hand in Python everything can be accessed, even attributes considered private (those with __ at the beginning, which are mangled to form ___). Some might say, that this is potentially dangerous - say, at some point in the future you need to perform some operations, when you change certain attribute. But Python solves it gracefully, with properties. \nI like the notion, that I can access anything I want. If only I know, what I am doing, I can do it :-)\n",
"In Python, each object has one namespace -- the object's \"attributes\", accessible in that namespace, can be methods, simple references to other objects (callable or not), or be synthesized on the fly by descriptors (plain attributes may live in the instance or in the class, but descriptors -- including functions as descriptors that synthesize methods -- are only used if they live in the class, not the instance; so in particular \"special methods\" are only special if defined in the class, not the instance). Attribute-handling builtins and special methods (getattr, setattr, __getattr__, __setattr__, ...) work just the same way across the single namespace of the object, whether referring to \"plain attributes\" or not.\nThe key point is that for any object a, in Python, a.b may be a method (or other callable) or not: the Python compiler doesn't know (nor care), you can take the reference a.b and (e.g.) pass it as an argument, return it as a result, append it to a list, and so forth, none of these operations implies calling a.b. If and when you want to (try and) call a.b, you do it explicitly by postfixing parentheses: a.b() if you want to call it without arguments.\nIn Ruby, methods and attributes of an object live in separate namespaces (so you can have an object with a method and an attribute with the same name, which in Python you can't) and \"just mentioning\" an argument-less method implicitly calls it (so c=a.b might be just taking an attribute reference, or it might be calling a.b(); if b names both a method and an attribute in a, I don't recall what heuristic rule is used to disambiguate the use). So if you want to just take method references (e.g to stash in some container or use as arguments or return values), and later perform the call, you use different syntax.\nSmalltalk also has separate namespaces, like Ruby, but then you can't refer to a given object's \"non-method\" attributes (each object only \"sees\" its own attributes), so this ambiguity does not arise (but you still do have to use specific messages to extract, and later call, a \"method reference\").\n"
] | [
2,
2
] | [] | [] | [
"comparison",
"oop",
"python",
"ruby",
"smalltalk"
] | stackoverflow_0002055966_comparison_oop_python_ruby_smalltalk.txt |
Q:
Some tables mixed together
I have 2 different tables in my database. They have some variables common and some different. For example:
Table1:
ID
Date
Name
Address
Fax
Table2:
ID
Date
Name
e-mail
Telephone number
I want to display data together sorted by date & ID but from both tables. For example, first displayed will be the newest record from first table, but the second one will be the record from another table posted right after first one.
Hope everybody understand, sorry for my English.
Cheers.
A:
Select entries from both models, than put them into a single list and sort them. Like that:
result = (list(first_query) + list(second_query))
result.sort(cmp=foo)
return result
where foo is a function, which is used to compare two elements:
def foo(a, b):
if a.date > b.date:
return 1
if a.date < b.date:
return -1
if a.date == b.date:
if a.id > b.id:
return 1
if a.id < b.id:
return -1
return 0
And the to display:
<table>
{% for object in result %}
{{ object.render_table }}
{% endfor %}
</table>
and in models (just one table):
class Table1(models.Model):
..
def render_table(self):
return '<tr><td>table1</td></tr>'
| Some tables mixed together | I have 2 different tables in my database. They have some variables common and some different. For example:
Table1:
ID
Date
Name
Address
Fax
Table2:
ID
Date
Name
e-mail
Telephone number
I want to display data together sorted by date & ID but from both tables. For example, first displayed will be the newest record from first table, but the second one will be the record from another table posted right after first one.
Hope everybody understand, sorry for my English.
Cheers.
| [
"Select entries from both models, than put them into a single list and sort them. Like that:\nresult = (list(first_query) + list(second_query))\nresult.sort(cmp=foo)\nreturn result\n\nwhere foo is a function, which is used to compare two elements:\ndef foo(a, b):\n if a.date > b.date:\n return 1\n if a.date < b.date:\n return -1\n if a.date == b.date:\n if a.id > b.id:\n return 1\n if a.id < b.id:\n return -1\n return 0\n\nAnd the to display:\n<table>\n{% for object in result %}\n {{ object.render_table }}\n{% endfor %}\n</table>\n\nand in models (just one table):\nclass Table1(models.Model):\n\n ..\n\n def render_table(self):\n return '<tr><td>table1</td></tr>'\n\n"
] | [
0
] | [] | [] | [
"django",
"python"
] | stackoverflow_0002058197_django_python.txt |
Q:
Django custom auth backend not recognized on Apache
I'm trying to deploy my Django application to an Apache2 based server with mod_python. I've set the handlers right and made the configuration to make mod_python work with my project. My project implements a custom auth backend to connect my users to twitter, and my backend implementation is on:
myproject
|- backends/
directory.Everything seems to be working fine, my pages load and I can make read/write operations properly. But whenever I try to login with my Twitter account, application fires an exception telling me:
Error importing authentication backend backends.twitteroauth: "No module named backends.twitteroauth"
In my settings.py, I'm registering my backend as
AUTHENTICATION_BACKENDS = (
'django.contrib.auth.backends.ModelBackend',
'myproject.backends.twitteroauth.TwitterBackend',
)
What is the problem?
A:
The problem is that python cannot find the module twitteroauth. What is the name of the file TwitterBackend is in? Also make sure that there is a __init__.py file in backends to mark it as a package.
edit:
What happens if you run the shell
python manage.py shell
and try to import it there?
from myproject.backends.twitteroauth import TwitterBackend
As anything else works fine, I guess myproject is in your python path.
A:
Removing database solved my problem. As far as I can guess, if a user is logged, his corresponding login backend is kept as a session variable on the database. My settings.py file was
AUTHENTICATION_BACKENDS = (
'django.contrib.auth.backends.ModelBackend',
'backends.twitteroauth.TwitterBackend',
)
before I made the correction. Changing settings.py and restarting the application was simply not enough. You have to remove session related records from db too.
A:
Make sure that backends is on the python path and has a init.py file in the folder.
| Django custom auth backend not recognized on Apache | I'm trying to deploy my Django application to an Apache2 based server with mod_python. I've set the handlers right and made the configuration to make mod_python work with my project. My project implements a custom auth backend to connect my users to twitter, and my backend implementation is on:
myproject
|- backends/
directory.Everything seems to be working fine, my pages load and I can make read/write operations properly. But whenever I try to login with my Twitter account, application fires an exception telling me:
Error importing authentication backend backends.twitteroauth: "No module named backends.twitteroauth"
In my settings.py, I'm registering my backend as
AUTHENTICATION_BACKENDS = (
'django.contrib.auth.backends.ModelBackend',
'myproject.backends.twitteroauth.TwitterBackend',
)
What is the problem?
| [
"The problem is that python cannot find the module twitteroauth. What is the name of the file TwitterBackend is in? Also make sure that there is a __init__.py file in backends to mark it as a package.\nedit:\nWhat happens if you run the shell\npython manage.py shell\n\nand try to import it there?\nfrom myproject.backends.twitteroauth import TwitterBackend\n\nAs anything else works fine, I guess myproject is in your python path.\n",
"Removing database solved my problem. As far as I can guess, if a user is logged, his corresponding login backend is kept as a session variable on the database. My settings.py file was\nAUTHENTICATION_BACKENDS = (\n 'django.contrib.auth.backends.ModelBackend',\n 'backends.twitteroauth.TwitterBackend',\n)\n\nbefore I made the correction. Changing settings.py and restarting the application was simply not enough. You have to remove session related records from db too.\n",
"Make sure that backends is on the python path and has a init.py file in the folder.\n"
] | [
2,
2,
1
] | [] | [] | [
"django",
"mod_python",
"python"
] | stackoverflow_0002056384_django_mod_python_python.txt |
Q:
Dynamic direct_to_template
In my webapp, there are a lot of errors or other messages that just show a template that is very close to the URL. At the moment, I have half a dozen static mappers like this:
(r'^/message/foo/$', 'direct_to_template', {'template': 'message/foo.html'}),
(r'^/message/bar/$', 'direct_to_template', {'template': 'message/bar.html'}),
Is there some built-in way I can hook up /message/*/ to show the template message/*.html?
A:
This is pretty easy. Do it like this:
(r'^/message/(?<name>\d+)/$', 'your_app.views.direct_to_template')
and:
def direct_to_template(name):
return render_to_response('message/%s.html' % name)
| Dynamic direct_to_template | In my webapp, there are a lot of errors or other messages that just show a template that is very close to the URL. At the moment, I have half a dozen static mappers like this:
(r'^/message/foo/$', 'direct_to_template', {'template': 'message/foo.html'}),
(r'^/message/bar/$', 'direct_to_template', {'template': 'message/bar.html'}),
Is there some built-in way I can hook up /message/*/ to show the template message/*.html?
| [
"This is pretty easy. Do it like this:\n(r'^/message/(?<name>\\d+)/$', 'your_app.views.direct_to_template')\n\nand:\ndef direct_to_template(name):\n return render_to_response('message/%s.html' % name)\n\n"
] | [
4
] | [] | [] | [
"django",
"django_templates",
"django_urls",
"python",
"regex"
] | stackoverflow_0002058261_django_django_templates_django_urls_python_regex.txt |
Q:
Awk, bash or python for converting a regular file?
I have a text file with lots of lines and with this structure:
[('name_1a',
'name_1b',
value_1),
('name_2a',
'name_2b',
value_2),
.....
.....
('name_XXXa',
'name_XXXb',
value_XXX)]
I would like to convert it to:
name_1a, name_1b, value_1
name_2a, name_2b, value_2
......
name_XXXa, name_XXXb, value_XXX
I wonder what would be the best way, whether awk, python or bash.
Thanks
Jose
A:
Tried evaluating it python? Looks like a list of tuples to me.
eval(your_string)
Note, it's massively unsafe! If there's code in there to delete your hard disk, evaluating it will run that code!
A:
I would like to use Python:
lines = open('filename.txt','r').readlines()
n = len(lines) # n % 3 == 0
for i in range(0,n,3):
name1 = lines[i].strip("',[]\n\r")
name2 = lines[i+1].strip("',[]\n\r")
value = lines[i+2].strip("',[]\n\r")
print name1,name2,value
A:
It looks like legal Python. You might be able to just import it as a module and then write it back out after formatting it.
A:
Oh boy, here is a job for ast.literal_eval:
(literal_eval is safer than eval, since it restricts the input string to literals such as strings, numbers, tuples, lists, dicts, booleans and None:
import ast
filename='in'
with open(filename,'r') as f:
contents=f.read()
data=ast.literal_eval(contents)
for elt in data:
print(', '.join(map(str,elt)))
A:
here's one way to do it with (g)awk
$ awk -vRS=")," ' { gsub(/\n|[\047\]\[)(]/,"") } 1' file
name_1a,name_1b,value_1
name_2a,name_2b,value_2
name_XXXa,name_XXXb,value_XXX
A:
Awk is typically line oriented, and bash is a shell, with limited numbrer of string manipulation functions. It really depends on where your strength as a programmer lies, but all other things being equal, I would choose python.
Did you ever consider that by redirecting the time it took to post this on SO, you could have had it done?
"AWK is a language for processing
files of text. A file is treated as a
sequence of records, and by default
each line is a record. Each line is
broken up into a sequence of fields,
so we can think of the first word in a
line as the first field, the second
word as the second field, and so on.
An AWK program is of a sequence of
pattern-action statements. AWK reads
the input a line at a time. A line is
scanned for each pattern in the
program, and for each pattern that
matches, the associated action is
executed." - Alfred V. Aho[2]
A:
Asking what's the best language for doing a given task is a very different question to say, asking: 'what's the best way of doing a given task in a particular language'. The first, what you're asking, is in most cases entirely subjective.
Since this is a fairly simple task, I would suggest going with what you know (unless you're doing this for learning purposes, which I doubt).
If you know any of the languages you suggested, go ahead and solve this in a matter of minutes. If you know none of them, now enters the subjective part, I would suggest learning Python, since it's so much more fun than the other 2 ;)
A:
If the values are legal python values, you can take advantage of eval() since your data is a legal python data sucture. The following would work if values are integers, otherwise you might have to massage the print call a bit:
input = """[('name_1a',
'name_1b',
1),
('name_2a',
'name_2b',
2),
('name_XXXa',
'name_XXXb',
3)]"""
for e in eval(input):
print '%s,%s,%d' % e
P.S. using eval() is quite controversial since it will execute any valid python code that you pass into it, so take care.
| Awk, bash or python for converting a regular file? | I have a text file with lots of lines and with this structure:
[('name_1a',
'name_1b',
value_1),
('name_2a',
'name_2b',
value_2),
.....
.....
('name_XXXa',
'name_XXXb',
value_XXX)]
I would like to convert it to:
name_1a, name_1b, value_1
name_2a, name_2b, value_2
......
name_XXXa, name_XXXb, value_XXX
I wonder what would be the best way, whether awk, python or bash.
Thanks
Jose
| [
"Tried evaluating it python? Looks like a list of tuples to me.\neval(your_string)\n\nNote, it's massively unsafe! If there's code in there to delete your hard disk, evaluating it will run that code!\n",
"I would like to use Python:\nlines = open('filename.txt','r').readlines()\nn = len(lines) # n % 3 == 0\nfor i in range(0,n,3):\n name1 = lines[i].strip(\"',[]\\n\\r\")\n name2 = lines[i+1].strip(\"',[]\\n\\r\")\n value = lines[i+2].strip(\"',[]\\n\\r\")\n print name1,name2,value\n\n",
"It looks like legal Python. You might be able to just import it as a module and then write it back out after formatting it. \n",
"Oh boy, here is a job for ast.literal_eval:\n(literal_eval is safer than eval, since it restricts the input string to literals such as strings, numbers, tuples, lists, dicts, booleans and None:\nimport ast\nfilename='in'\nwith open(filename,'r') as f:\n contents=f.read()\n data=ast.literal_eval(contents)\n\nfor elt in data:\n print(', '.join(map(str,elt)))\n\n",
"here's one way to do it with (g)awk\n$ awk -vRS=\"),\" ' { gsub(/\\n|[\\047\\]\\[)(]/,\"\") } 1' file\nname_1a,name_1b,value_1\nname_2a,name_2b,value_2\nname_XXXa,name_XXXb,value_XXX\n\n",
"Awk is typically line oriented, and bash is a shell, with limited numbrer of string manipulation functions. It really depends on where your strength as a programmer lies, but all other things being equal, I would choose python.\nDid you ever consider that by redirecting the time it took to post this on SO, you could have had it done?\n\n\"AWK is a language for processing\n files of text. A file is treated as a\n sequence of records, and by default\n each line is a record. Each line is\n broken up into a sequence of fields,\n so we can think of the first word in a\n line as the first field, the second\n word as the second field, and so on.\n An AWK program is of a sequence of\n pattern-action statements. AWK reads\n the input a line at a time. A line is\n scanned for each pattern in the\n program, and for each pattern that\n matches, the associated action is\n executed.\" - Alfred V. Aho[2]\n\n",
"Asking what's the best language for doing a given task is a very different question to say, asking: 'what's the best way of doing a given task in a particular language'. The first, what you're asking, is in most cases entirely subjective.\nSince this is a fairly simple task, I would suggest going with what you know (unless you're doing this for learning purposes, which I doubt).\n If you know any of the languages you suggested, go ahead and solve this in a matter of minutes. If you know none of them, now enters the subjective part, I would suggest learning Python, since it's so much more fun than the other 2 ;)\n",
"If the values are legal python values, you can take advantage of eval() since your data is a legal python data sucture. The following would work if values are integers, otherwise you might have to massage the print call a bit:\ninput = \"\"\"[('name_1a',\n 'name_1b',\n 1),\n ('name_2a',\n 'name_2b',\n 2),\n ('name_XXXa',\n 'name_XXXb',\n 3)]\"\"\"\n\nfor e in eval(input):\n print '%s,%s,%d' % e\n\nP.S. using eval() is quite controversial since it will execute any valid python code that you pass into it, so take care.\n"
] | [
2,
2,
1,
1,
1,
0,
0,
0
] | [] | [] | [
"awk",
"bash",
"python"
] | stackoverflow_0002058339_awk_bash_python.txt |
Q:
Python’s ftplib STOR reliable?
I'm using this code to upload myfile.txt from my windows machine to a ftp server. after the upoad the script deletes the file on my local machine (I'm not deleting it on the ftp).
try:
ftp = FTP(ftp.host.com)
ftp.login(your_username, your_password)
file = open(myfile.txt, "rb")
ftp.storbinary('STOR myfile.txt', file)
print 'STORing File now...'
ftp.quit()
file.close()
subprocess.Popen('del myfile.txt', shell=True)
print 'File deleted'
except all_errors:
print 'An error occured'
This code runs, however it's not reliable! At every ~10th upload my script hangs while STORing the file.
print 'STORing File now...' # So I just get 'STORING File now...'
The file is not big and should be uploaded within a few seconds, but I often have to wait an hour or two and only then the exception is thrown:
print 'An error occured'
If the exception were thrown 'earlier' it would be nice so I could just restart the upload (e.g. in a while loop). Because I need this file to be uploaded as soon as possible I need to make the file upload faster (I don't want to wait so long for the exception being thrown)
Second issue: Sometimes this happens: After the file has been successfully uploaded, the script fails to delete the file on my local machine because 'some other process is accessing it already' <- I think ftplib did not 'released' the file. What can I do to prevent this?
I'm searching for a better/reliable simple fileupload solution. Anyone have an idea?
Thanks!
A:
Don't use subprocess to shell out to delete a file - the os.unlink call will allow you to do this portably (the shutil library fills in the gaps when os fails)
Right now, you are gobbling the error with your silly print statement - get a traceback from the exception which would give you a large number of clues. However, your problem is likely related to socket timeout issues - either you are not running passive FTP, or the server is misconfigured and given you an invalid passive connect port number (something its firewall blocks).
A:
how about this
def upload(ftp, filename):
ftp.storbinary("STOR " + filename, open(filename, "rb"), 1024)
try:
ftp = FTP("ftp.host.com")
ftp.login(your_username, your_password)
except Exception,e:
print e
else:
file = open("myfile.txt", "rb")
print 'STORing File now...'
try:
upload(ftp,file)
except Exception,e:
print e
else:
ftp.quit()
file.close()
try:
os.remove("myfile.txt")
except Exception,e:
print e
else:
print 'File deleted'
remember, Python has its own file removing module. don't call system del unnecessarily
A:
To get the exception earlier, use socket.setdefaulttimeout: e.g.,
import socket
socket.setdefaulttimeout(20.0)
will give you an exception if a socket it blocked for 20 seconds.
To remove a file from your Pyton script, use os.unlink -- much better than shelling out to a separate process for a del.
| Python’s ftplib STOR reliable? | I'm using this code to upload myfile.txt from my windows machine to a ftp server. after the upoad the script deletes the file on my local machine (I'm not deleting it on the ftp).
try:
ftp = FTP(ftp.host.com)
ftp.login(your_username, your_password)
file = open(myfile.txt, "rb")
ftp.storbinary('STOR myfile.txt', file)
print 'STORing File now...'
ftp.quit()
file.close()
subprocess.Popen('del myfile.txt', shell=True)
print 'File deleted'
except all_errors:
print 'An error occured'
This code runs, however it's not reliable! At every ~10th upload my script hangs while STORing the file.
print 'STORing File now...' # So I just get 'STORING File now...'
The file is not big and should be uploaded within a few seconds, but I often have to wait an hour or two and only then the exception is thrown:
print 'An error occured'
If the exception were thrown 'earlier' it would be nice so I could just restart the upload (e.g. in a while loop). Because I need this file to be uploaded as soon as possible I need to make the file upload faster (I don't want to wait so long for the exception being thrown)
Second issue: Sometimes this happens: After the file has been successfully uploaded, the script fails to delete the file on my local machine because 'some other process is accessing it already' <- I think ftplib did not 'released' the file. What can I do to prevent this?
I'm searching for a better/reliable simple fileupload solution. Anyone have an idea?
Thanks!
| [
"Don't use subprocess to shell out to delete a file - the os.unlink call will allow you to do this portably (the shutil library fills in the gaps when os fails)\nRight now, you are gobbling the error with your silly print statement - get a traceback from the exception which would give you a large number of clues. However, your problem is likely related to socket timeout issues - either you are not running passive FTP, or the server is misconfigured and given you an invalid passive connect port number (something its firewall blocks). \n",
"how about this\ndef upload(ftp, filename):\n ftp.storbinary(\"STOR \" + filename, open(filename, \"rb\"), 1024)\ntry:\n ftp = FTP(\"ftp.host.com\")\n ftp.login(your_username, your_password)\nexcept Exception,e:\n print e\nelse:\n file = open(\"myfile.txt\", \"rb\")\n print 'STORing File now...'\n try:\n upload(ftp,file)\n except Exception,e:\n print e\n else:\n ftp.quit()\n file.close()\n try:\n os.remove(\"myfile.txt\")\n except Exception,e:\n print e\n else:\n print 'File deleted'\n\nremember, Python has its own file removing module. don't call system del unnecessarily\n",
"To get the exception earlier, use socket.setdefaulttimeout: e.g.,\nimport socket\nsocket.setdefaulttimeout(20.0)\n\nwill give you an exception if a socket it blocked for 20 seconds.\nTo remove a file from your Pyton script, use os.unlink -- much better than shelling out to a separate process for a del.\n"
] | [
2,
2,
1
] | [] | [] | [
"exception",
"file_upload",
"ftp",
"ftplib",
"python"
] | stackoverflow_0002058584_exception_file_upload_ftp_ftplib_python.txt |
Q:
Utilizing objects in another class in Python
In code(pseudo) like this
def path():
dirList = ['c:\\', 'y:\\', 'z:\\']
home_folder = 'peter.txt'
complete = [s + home_folder for s in dirList]
print complete
def fileWrite():
filename = 'c:\peter.txt'
text = 'Hello World'
file = open(filename, 'w')
file.write(text)
file.close()
I can make both work. I want all the items from the first to be iterated and run in the second. I am not entirely sure how to do that. Any help, much appreciated.
A:
If I understand question correclty - you can add additional parameter to fileWrite like fileWrite(filename) and simply iterate over 'complete' sequence.
A:
import os
def paths(filename):
dirList = ['c:\\', 'y:\\', 'z:\\']
complete = [os.path.join(s, filename) for s in dirList]
return complete
def fileWrite():
for each_file in paths('c:\\peter.txt'):
text = 'Hello World'
file = open(each_file, 'w')
file.write(text)
file.close()
Or, as Ipthnc points out below, the paths function can be shortened to:
def paths(filename):
return [os.path.join(s, filename) for s in ('c:\\', 'y:\\', 'z:\\')]
| Utilizing objects in another class in Python | In code(pseudo) like this
def path():
dirList = ['c:\\', 'y:\\', 'z:\\']
home_folder = 'peter.txt'
complete = [s + home_folder for s in dirList]
print complete
def fileWrite():
filename = 'c:\peter.txt'
text = 'Hello World'
file = open(filename, 'w')
file.write(text)
file.close()
I can make both work. I want all the items from the first to be iterated and run in the second. I am not entirely sure how to do that. Any help, much appreciated.
| [
"If I understand question correclty - you can add additional parameter to fileWrite like fileWrite(filename) and simply iterate over 'complete' sequence.\n",
"import os\n\ndef paths(filename):\n dirList = ['c:\\\\', 'y:\\\\', 'z:\\\\']\n complete = [os.path.join(s, filename) for s in dirList]\n return complete\n\ndef fileWrite():\n for each_file in paths('c:\\\\peter.txt'):\n text = 'Hello World'\n file = open(each_file, 'w')\n file.write(text)\n file.close()\n\nOr, as Ipthnc points out below, the paths function can be shortened to:\ndef paths(filename):\n return [os.path.join(s, filename) for s in ('c:\\\\', 'y:\\\\', 'z:\\\\')]\n\n"
] | [
1,
1
] | [] | [] | [
"class",
"iteration",
"python"
] | stackoverflow_0002059013_class_iteration_python.txt |
Q:
Contents of PyString in Qt Creator debugger?
I've got a PyString* object that I would like to see the contents of. Is there any way to see the text of the PyString using Qt Creator's debugger?
PyObject *import_str = PyString_InternFromString("__import__");
If it makes a difference, Qt Creator is a front end to GDB.
A:
I doubt that Qt Creator can display the contents of the string like it does with QString, etc. This is because PyObject is a custom class that Qt Creator/gdbv does not know how to handle.
For instance: QString is a custom class as well, but Qt Creator loads some special commands/modules/whatever which allows for direct display of string values in the debugger.
I never did that myself, but I guess that there are ways to make gdb pass the correct information to Qt Creator.
A:
You can write debugging info to be displayed in QtCreator for any class using Python with the latest QtCreator. It's actually quite simple. This is thanks to gdb 7 that added support for Python in addition to C++.
You can see the ones that ship with QtCreator in /usr/share/qtcreator/gdbmacros.
For more info you can check QtCreator documentation and this blog post from Qt Labs.
| Contents of PyString in Qt Creator debugger? | I've got a PyString* object that I would like to see the contents of. Is there any way to see the text of the PyString using Qt Creator's debugger?
PyObject *import_str = PyString_InternFromString("__import__");
If it makes a difference, Qt Creator is a front end to GDB.
| [
"I doubt that Qt Creator can display the contents of the string like it does with QString, etc. This is because PyObject is a custom class that Qt Creator/gdbv does not know how to handle.\nFor instance: QString is a custom class as well, but Qt Creator loads some special commands/modules/whatever which allows for direct display of string values in the debugger.\nI never did that myself, but I guess that there are ways to make gdb pass the correct information to Qt Creator.\n",
"You can write debugging info to be displayed in QtCreator for any class using Python with the latest QtCreator. It's actually quite simple. This is thanks to gdb 7 that added support for Python in addition to C++.\nYou can see the ones that ship with QtCreator in /usr/share/qtcreator/gdbmacros.\nFor more info you can check QtCreator documentation and this blog post from Qt Labs.\n"
] | [
0,
0
] | [] | [] | [
"cpython",
"debugging",
"python",
"qt",
"qt_creator"
] | stackoverflow_0001883316_cpython_debugging_python_qt_qt_creator.txt |
Q:
Grabbing the output of MAPLE via Python
How would I use the subprocess module in Python to start a command line instance of MAPLE to feed and return output to the main code? For example I'd like:
X = '1+1;'
print MAPLE(X)
To return the value of "2".
The best I've seen is a SAGE wrapper around the MAPLE commands, but I'd like to not install and use the overhead of SAGE for my purposes.
A:
Trying to drive a subprocess "interactively" more often than not runs into issues with the subprocess doing some buffering, which blocks things.
That's why for such purposes I suggest instead using pexpect (everywhere but Windows: wexpect on Windows), which is designed exactly for this purpose -- letting your program simulate (from the subprocess's viewpoint) a human user typing input/commands and looking at results at a terminal/console.
A:
Using the tip from Alex Martelli (thank you!), I've came up with an explicit answer to my question. Posting here in hopes that others may find useful:
import pexpect
MW = "/usr/local/maple12/bin/maple -tu"
X = '1+1;'
child = pexpect.spawn(MW)
child.expect('#--')
child.sendline(X)
child.expect('#--')
out = child.before
out = out[out.find(';')+1:].strip()
out = ''.join(out.split('\r\n'))
print out
The parsing of the output is needed as MAPLE deems it necessary to break up long outputs onto many lines. This approach has the advantage of keeping a connection open to MAPLE for future computation.
A:
Here's an example of how to do interactive IO with a command line program. I used something similar to build a spell checker based on the ispell command line utility:
f = popen2.Popen3("ispell -a")
f.fromchild.readline() #skip the credit line
for word in words:
f.tochild.write(word+'\n') #send a word to ispell
f.tochild.flush()
line = f.fromchild.readline() #get the result line
f.fromchild.readline() #skip the empty line after the result
#do something useful with the output:
status = parse_status(line)
suggestions = parse_suggestions(line)
#etc..
The only problem with this is that it's very brittle and a trial-and-error process to make sure you're not sending any bad input and handling all the different output the program could produce.
| Grabbing the output of MAPLE via Python | How would I use the subprocess module in Python to start a command line instance of MAPLE to feed and return output to the main code? For example I'd like:
X = '1+1;'
print MAPLE(X)
To return the value of "2".
The best I've seen is a SAGE wrapper around the MAPLE commands, but I'd like to not install and use the overhead of SAGE for my purposes.
| [
"Trying to drive a subprocess \"interactively\" more often than not runs into issues with the subprocess doing some buffering, which blocks things.\nThat's why for such purposes I suggest instead using pexpect (everywhere but Windows: wexpect on Windows), which is designed exactly for this purpose -- letting your program simulate (from the subprocess's viewpoint) a human user typing input/commands and looking at results at a terminal/console.\n",
"Using the tip from Alex Martelli (thank you!), I've came up with an explicit answer to my question. Posting here in hopes that others may find useful:\nimport pexpect\nMW = \"/usr/local/maple12/bin/maple -tu\"\nX = '1+1;'\nchild = pexpect.spawn(MW)\nchild.expect('#--')\nchild.sendline(X)\nchild.expect('#--')\nout = child.before\nout = out[out.find(';')+1:].strip()\nout = ''.join(out.split('\\r\\n'))\nprint out\n\nThe parsing of the output is needed as MAPLE deems it necessary to break up long outputs onto many lines. This approach has the advantage of keeping a connection open to MAPLE for future computation.\n",
"Here's an example of how to do interactive IO with a command line program. I used something similar to build a spell checker based on the ispell command line utility:\nf = popen2.Popen3(\"ispell -a\")\nf.fromchild.readline() #skip the credit line\n\nfor word in words:\n f.tochild.write(word+'\\n') #send a word to ispell\n f.tochild.flush()\n\n line = f.fromchild.readline() #get the result line\n f.fromchild.readline() #skip the empty line after the result\n\n #do something useful with the output:\n status = parse_status(line)\n suggestions = parse_suggestions(line)\n #etc..\n\nThe only problem with this is that it's very brittle and a trial-and-error process to make sure you're not sending any bad input and handling all the different output the program could produce.\n"
] | [
3,
3,
0
] | [] | [] | [
"maple",
"pexpect",
"python",
"subprocess"
] | stackoverflow_0002053231_maple_pexpect_python_subprocess.txt |
Q:
Python identity: Multiple personality disorder, need code shrink
Possible Duplicate:
Python “is” operator behaves unexpectedly with integers
I stumbled upon the following Python weirdity:
>>> two = 2
>>> ii = 2
>>> id(two) == id(ii)
True
>>> [id(i) for i in [42,42,42,42]]
[10084276, 10084276, 10084276, 10084276]
>>> help(id)
Help on built-in function id in module __builtin__:
id(...)
id(object) -> integer
Return the identity of an object. This is guaranteed to be unique among
simultaneously existing objects. (Hint: it's the object's memory address.)
Is every number a unique object?
Are different variables holding the same elemental values (for example, two,ii) the same object?
How is the id of a number generated by Python?
In the above example, are two and ii pointers to a memory cell holding the value 2? That would be extremely weird.
Help me untangle this identity crisis.
Some more weirdities:
>>> a,b=id(0),id(1)
>>> for i in range(2,1000):
a,b=b,id(i)
if abs(a-b) != 12:
print('%i:%i -> %i' % (i,a,b))
The above code examines if ids of consecutive integers are also consecutive, and prints out
anomalies:
77:10083868 -> 10085840
159:10084868 -> 10086840
241:10085868 -> 10087840
257:10087660 -> 11689620
258:11689620 -> 11689512
259:11689512 -> 11689692
260:11689692 -> 11689548
261:11689548 -> 11689644
262:11689644 -> 11689572
263:11689572 -> 11689536
264:11689536 -> 11689560
265:11689560 -> 11689596
266:11689596 -> 11689656
267:11689656 -> 11689608
268:11689608 -> 11689500
331:11688756 -> 13807288
413:13806316 -> 13814224
495:13813252 -> 13815224
577:13814252 -> 13816224
659:13815252 -> 13817224
741:13816252 -> 13818224
823:13817252 -> 13819224
905:13818252 -> 13820224
987:13819252 -> 13821224
Note that a pattern emerges from 413 onwards. Maybe it's due to some voodoo accounting at the beginning of each new memory page.
A:
Integers between -1 and 255(?), as well as string literals, are interned. Each instance in the source actually represents the same object.
In CPython, the result of id() is the address in the process space of the PyObject.
A:
Every implementation of Python is fully allowed to optimize to any extent (including.... none at all;-) the identity and allocation of immutable objects (such as numbers, tuples and strings) [[no such latitude exists for mutable objects, such as lists, dicts and sets]].
Between two immutable object references a and b, all the implementation must guarantee is:
id(a) == id(b), AKA a is b, must always imply a == b
and therefore a != b must always imply id(a) != id(b) AKA a is not b
Note in particular there is no constraint, even for immutable types, that a == b must imply a is b (i.e. that id(a) == id(b)). Only None makes that guarantee (so you can always test if x is None: rather than if x == None:).
Current CPython implementations take advantage of these degrees of freedom by "merging" (having a single allocation, thus a single id, for) small integers in a certain range, and built-in immutable-type objects whose literals appear more than once within a given function (so for example if your function f has four occurrences of literal 'foobar' they will all refer to a single instance of string 'foobar' within the function's constants, saving a little space compared to the permissible implementation that would store four identical but separate copies of that constant).
All of these implementation considerations are of pretty minor interest to Python coders (unless you're working on a Python implementation, or at least something that's tightly bound to a specific implementation, such as a debugging system).
A:
Your fourth question, "in the above example, are two and ii pointers to a memory cell holding the value 2? that would be extremely weird", is really the key to understanding the whole thing.
If you're familiar with languages like C, Python "variables" don't really work the same way. A C variable declaration like:
int j=1;
int k=2;
k += j;
says, "compiler, reserve for me two areas of memory, on the stack, each with enough space to hold an integer, and remember one as 'j' and the other as 'k'. Then fill j with the value '1' and k with the value '2'." At runtime, the code says "take the integer contents of k, add the integer contents of j, and store the result back to k."
The seemingly equivalent code in Python:
j = 1
k = 2
k += j
says something different: "Python, look up the object known as '1', and create a label called 'j' that points to it. Look up the object known as '2', and create a label called 'k' that points to it. Now look up the object 'k' points to ('2'), look up the object 'j' points to ('1'), and point 'k' to the object resulting from performing the 'add' operation on the two."
Disassembling this code (with the dis module) shows this nicely:
2 0 LOAD_CONST 1 (1)
3 STORE_FAST 0 (j)
3 6 LOAD_CONST 1 (2)
9 STORE_FAST 1 (k)
4 12 LOAD_FAST 1 (k)
15 LOAD_FAST 0 (j)
18 INPLACE_ADD
19 STORE_FAST 1 (k)
So yes, Python "variables" are labels that point to objects, rather than containers that can be filled with data.
The other three questions are all variations on "when does Python create a new object from a piece of code, and when does it reuse one it already has?". The latter is called "interning"; it happens to smaller integers and strings that look (to Python) like they might be symbol names.
A:
You should be very careful with these sorts of investigations. You are looking into the internals of the implementation of the language, and those are not guaranteed. The help on id is spot-on: the number will be different for two different objects, and the same for the same object. As an implementation detail, in CPython it is the memory address of the object. CPython might decide to change this detail at any time.
The detail of small integers being interned to same allocation time is also a detail that could change at any time.
Also, if you switch from CPython to Jython, or PyPy, or IronPython, all bets are off, other than the documentation on id().
A:
Not every number is a unique object, and the fact that some are is an optimization detail of the CPython interpreter. Do not rely on this behavior. For that matter, never use is to test for equality. Only use is if you are absolutely sure you need the exact same object.
| Python identity: Multiple personality disorder, need code shrink |
Possible Duplicate:
Python “is” operator behaves unexpectedly with integers
I stumbled upon the following Python weirdity:
>>> two = 2
>>> ii = 2
>>> id(two) == id(ii)
True
>>> [id(i) for i in [42,42,42,42]]
[10084276, 10084276, 10084276, 10084276]
>>> help(id)
Help on built-in function id in module __builtin__:
id(...)
id(object) -> integer
Return the identity of an object. This is guaranteed to be unique among
simultaneously existing objects. (Hint: it's the object's memory address.)
Is every number a unique object?
Are different variables holding the same elemental values (for example, two,ii) the same object?
How is the id of a number generated by Python?
In the above example, are two and ii pointers to a memory cell holding the value 2? That would be extremely weird.
Help me untangle this identity crisis.
Some more weirdities:
>>> a,b=id(0),id(1)
>>> for i in range(2,1000):
a,b=b,id(i)
if abs(a-b) != 12:
print('%i:%i -> %i' % (i,a,b))
The above code examines if ids of consecutive integers are also consecutive, and prints out
anomalies:
77:10083868 -> 10085840
159:10084868 -> 10086840
241:10085868 -> 10087840
257:10087660 -> 11689620
258:11689620 -> 11689512
259:11689512 -> 11689692
260:11689692 -> 11689548
261:11689548 -> 11689644
262:11689644 -> 11689572
263:11689572 -> 11689536
264:11689536 -> 11689560
265:11689560 -> 11689596
266:11689596 -> 11689656
267:11689656 -> 11689608
268:11689608 -> 11689500
331:11688756 -> 13807288
413:13806316 -> 13814224
495:13813252 -> 13815224
577:13814252 -> 13816224
659:13815252 -> 13817224
741:13816252 -> 13818224
823:13817252 -> 13819224
905:13818252 -> 13820224
987:13819252 -> 13821224
Note that a pattern emerges from 413 onwards. Maybe it's due to some voodoo accounting at the beginning of each new memory page.
| [
"Integers between -1 and 255(?), as well as string literals, are interned. Each instance in the source actually represents the same object.\nIn CPython, the result of id() is the address in the process space of the PyObject.\n",
"Every implementation of Python is fully allowed to optimize to any extent (including.... none at all;-) the identity and allocation of immutable objects (such as numbers, tuples and strings) [[no such latitude exists for mutable objects, such as lists, dicts and sets]].\nBetween two immutable object references a and b, all the implementation must guarantee is:\n\nid(a) == id(b), AKA a is b, must always imply a == b\nand therefore a != b must always imply id(a) != id(b) AKA a is not b\n\nNote in particular there is no constraint, even for immutable types, that a == b must imply a is b (i.e. that id(a) == id(b)). Only None makes that guarantee (so you can always test if x is None: rather than if x == None:).\nCurrent CPython implementations take advantage of these degrees of freedom by \"merging\" (having a single allocation, thus a single id, for) small integers in a certain range, and built-in immutable-type objects whose literals appear more than once within a given function (so for example if your function f has four occurrences of literal 'foobar' they will all refer to a single instance of string 'foobar' within the function's constants, saving a little space compared to the permissible implementation that would store four identical but separate copies of that constant).\nAll of these implementation considerations are of pretty minor interest to Python coders (unless you're working on a Python implementation, or at least something that's tightly bound to a specific implementation, such as a debugging system).\n",
"Your fourth question, \"in the above example, are two and ii pointers to a memory cell holding the value 2? that would be extremely weird\", is really the key to understanding the whole thing.\nIf you're familiar with languages like C, Python \"variables\" don't really work the same way. A C variable declaration like:\nint j=1;\nint k=2;\nk += j;\n\nsays, \"compiler, reserve for me two areas of memory, on the stack, each with enough space to hold an integer, and remember one as 'j' and the other as 'k'. Then fill j with the value '1' and k with the value '2'.\" At runtime, the code says \"take the integer contents of k, add the integer contents of j, and store the result back to k.\"\nThe seemingly equivalent code in Python:\nj = 1\nk = 2\nk += j\n\nsays something different: \"Python, look up the object known as '1', and create a label called 'j' that points to it. Look up the object known as '2', and create a label called 'k' that points to it. Now look up the object 'k' points to ('2'), look up the object 'j' points to ('1'), and point 'k' to the object resulting from performing the 'add' operation on the two.\"\nDisassembling this code (with the dis module) shows this nicely:\n 2 0 LOAD_CONST 1 (1)\n 3 STORE_FAST 0 (j)\n\n 3 6 LOAD_CONST 1 (2)\n 9 STORE_FAST 1 (k)\n\n 4 12 LOAD_FAST 1 (k)\n 15 LOAD_FAST 0 (j)\n 18 INPLACE_ADD\n 19 STORE_FAST 1 (k)\n\nSo yes, Python \"variables\" are labels that point to objects, rather than containers that can be filled with data. \nThe other three questions are all variations on \"when does Python create a new object from a piece of code, and when does it reuse one it already has?\". The latter is called \"interning\"; it happens to smaller integers and strings that look (to Python) like they might be symbol names.\n",
"You should be very careful with these sorts of investigations. You are looking into the internals of the implementation of the language, and those are not guaranteed. The help on id is spot-on: the number will be different for two different objects, and the same for the same object. As an implementation detail, in CPython it is the memory address of the object. CPython might decide to change this detail at any time.\nThe detail of small integers being interned to same allocation time is also a detail that could change at any time.\nAlso, if you switch from CPython to Jython, or PyPy, or IronPython, all bets are off, other than the documentation on id().\n",
"Not every number is a unique object, and the fact that some are is an optimization detail of the CPython interpreter. Do not rely on this behavior. For that matter, never use is to test for equality. Only use is if you are absolutely sure you need the exact same object.\n"
] | [
9,
8,
4,
2,
1
] | [] | [] | [
"identity",
"memory",
"memory_management",
"python",
"uniqueidentifier"
] | stackoverflow_0002058948_identity_memory_memory_management_python_uniqueidentifier.txt |
Q:
Lazy SAX XML parser with stop/resume
I am pretty sure the answer is no but of course there are cleverer guys than me!
Is there a way to construct a lazy SAX based XML parser that can be stopped (e.g. raising an exception is a possible way of doing this) but also resumable ?
I am looking for a possible solution for Python >= 2.6 with standard XML libraries. The "lazy" part is also trivial: I am really after the "resumable" property here.
A:
Expat can be stopped and is resumable. AFAIK Python SAX parser uses Expat. Does the API really not expose the stopping stuff to the Python side??
EDIT: nope, looks like the parser stopping isn't available from Python...
| Lazy SAX XML parser with stop/resume | I am pretty sure the answer is no but of course there are cleverer guys than me!
Is there a way to construct a lazy SAX based XML parser that can be stopped (e.g. raising an exception is a possible way of doing this) but also resumable ?
I am looking for a possible solution for Python >= 2.6 with standard XML libraries. The "lazy" part is also trivial: I am really after the "resumable" property here.
| [
"Expat can be stopped and is resumable. AFAIK Python SAX parser uses Expat. Does the API really not expose the stopping stuff to the Python side?? \nEDIT: nope, looks like the parser stopping isn't available from Python...\n"
] | [
0
] | [] | [] | [
"python",
"sax",
"xml"
] | stackoverflow_0002059455_python_sax_xml.txt |
Q:
Return Django form contents on error
All,
I have a template page say x.html
i have 3 text fields name(varchar2) ,age(int),school(varchar2) in it.
If the users enters values in the form in x.html(say values name="a" ,age="2" ,school="a") and submit it.I need to return the same values back to x.html indicating an error.
My question is how to return the same values to x.html.
Thanks.....
A:
from docs:
The standard pattern for processing a form in a view looks like this:
def contact(request):
if request.method == 'POST': # If the form has been submitted...
form = ContactForm(request.POST) # A form bound to the POST data
if form.is_valid(): # All validation rules pass
# Process the data in form.cleaned_data
# ...
return HttpResponseRedirect('/thanks/') # Redirect after POST
else:
form = ContactForm() # An unbound form
return render_to_response('contact.html', {
'form': form,
})
A:
Django will write the submitted values back as long as you provide the form object to the rendered template. For example, in your view, something like:
# handle POST
form = MyForm(request.POST)
if form.is_valid():
# do something and redirect
else:
# render the template with the invalid form
return render_to_response('mytemplate.html', {'form': form})
and in your template, something like:
{{ form.myfield.label_tag }}
{% if form.myfield.errors %} indicate error message/icon here {% endif %}
{{ form.myfield }}
Note that {{ form.myfield }} will show an HTML widget for myfield with the previous submitted values based on the view code above. And it will be blank when you render it with a blank form in response to a GET (e.g. form = MyForm()).
A:
If you are using django forms, it would do validation itself and then return the values you need. Here you can read about using forms and how they validate values. Basically, when you pass some values into the form and it's not valid, you just render the site again, but django will automagically fill fields. Don't bother writing your own forms, unless you really, really need them. And in your example you really don't ;-)
A:
I'm not sure how you are processing your form information. However if you use the Form API built into Django, it takes care of much of this for you. For details take a look at the Django Docs for Forms http://docs.djangoproject.com/en/dev/topics/forms/#topics-forms-index
If you use the Form API and the submission is not valid, Django provides the template with a bound copy of the form with the user supplied data already in it. Again you will have to read the details of the API for how to implement it in your situation.
| Return Django form contents on error | All,
I have a template page say x.html
i have 3 text fields name(varchar2) ,age(int),school(varchar2) in it.
If the users enters values in the form in x.html(say values name="a" ,age="2" ,school="a") and submit it.I need to return the same values back to x.html indicating an error.
My question is how to return the same values to x.html.
Thanks.....
| [
"from docs:\n\nThe standard pattern for processing a form in a view looks like this:\n\ndef contact(request):\n if request.method == 'POST': # If the form has been submitted...\n form = ContactForm(request.POST) # A form bound to the POST data\n if form.is_valid(): # All validation rules pass\n # Process the data in form.cleaned_data\n # ...\n return HttpResponseRedirect('/thanks/') # Redirect after POST\n else:\n form = ContactForm() # An unbound form\n\n return render_to_response('contact.html', {\n 'form': form,\n })\n\n",
"Django will write the submitted values back as long as you provide the form object to the rendered template. For example, in your view, something like:\n# handle POST\nform = MyForm(request.POST)\nif form.is_valid():\n # do something and redirect\nelse:\n # render the template with the invalid form\n return render_to_response('mytemplate.html', {'form': form})\n\nand in your template, something like:\n{{ form.myfield.label_tag }}\n{% if form.myfield.errors %} indicate error message/icon here {% endif %}\n{{ form.myfield }}\n\nNote that {{ form.myfield }} will show an HTML widget for myfield with the previous submitted values based on the view code above. And it will be blank when you render it with a blank form in response to a GET (e.g. form = MyForm()).\n",
"If you are using django forms, it would do validation itself and then return the values you need. Here you can read about using forms and how they validate values. Basically, when you pass some values into the form and it's not valid, you just render the site again, but django will automagically fill fields. Don't bother writing your own forms, unless you really, really need them. And in your example you really don't ;-)\n",
"I'm not sure how you are processing your form information. However if you use the Form API built into Django, it takes care of much of this for you. For details take a look at the Django Docs for Forms http://docs.djangoproject.com/en/dev/topics/forms/#topics-forms-index\nIf you use the Form API and the submission is not valid, Django provides the template with a bound copy of the form with the user supplied data already in it. Again you will have to read the details of the API for how to implement it in your situation.\n"
] | [
2,
2,
0,
0
] | [] | [] | [
"django",
"python"
] | stackoverflow_0002059374_django_python.txt |
Q:
Catching warnings pre-python 2.6
In Python 2.6 it is possible to suppress warnings from the warnings module by using
with warnings.catch_warnings():
warnings.simplefilter("ignore")
fxn()
Versions of Python before 2.6 don't support with however, so I'm wondering if there alternatives to the above that would work with pre-2.6 versions?
A:
This is similar:
# Save the existing list of warning filters before we modify it using simplefilter().
# Note: the '[:]' causes a copy of the list to be created. Without it, original_filter
# would alias the one and only 'real' list and then we'd have nothing to restore.
original_filters = warnings.filters[:]
# Ignore warnings.
warnings.simplefilter("ignore")
try:
# Execute the code that presumably causes the warnings.
fxn()
finally:
# Restore the list of warning filters.
warnings.filters = original_filters
Edit: Without the try/finally, the original warning filters would not be restored if fxn() threw an exception. See PEP 343 for more discussion on how the with statement serves to replace try/finally when used like this.
| Catching warnings pre-python 2.6 | In Python 2.6 it is possible to suppress warnings from the warnings module by using
with warnings.catch_warnings():
warnings.simplefilter("ignore")
fxn()
Versions of Python before 2.6 don't support with however, so I'm wondering if there alternatives to the above that would work with pre-2.6 versions?
| [
"This is similar:\n# Save the existing list of warning filters before we modify it using simplefilter().\n# Note: the '[:]' causes a copy of the list to be created. Without it, original_filter\n# would alias the one and only 'real' list and then we'd have nothing to restore.\noriginal_filters = warnings.filters[:]\n\n# Ignore warnings.\nwarnings.simplefilter(\"ignore\")\n\ntry:\n # Execute the code that presumably causes the warnings.\n fxn()\n\nfinally:\n # Restore the list of warning filters.\n warnings.filters = original_filters\n\nEdit: Without the try/finally, the original warning filters would not be restored if fxn() threw an exception. See PEP 343 for more discussion on how the with statement serves to replace try/finally when used like this.\n"
] | [
3
] | [
"Depending on what the minimum version you need to support using Python 2.5's \nfrom __future__ import with_statement\n\nmight be an option, else you'll probably need to fallback to what Jon suggested.\n"
] | [
-1
] | [
"python",
"suppress_warnings",
"warnings"
] | stackoverflow_0002059675_python_suppress_warnings_warnings.txt |
Q:
Python C API and data persistent in memory?
I'm considering integrating some C code into a Python system (Django), and I was considering using the Python / C API. The alternative is two separate processes with IPC, but I'm looking into direct interaction first. I'm new to Python so I'm trying to get a feel for the right direction to take.
Is it possible for a call to a C initialiser function to malloc a block of memory (and put something in it) and return a handle to it back to the Python script (pointer to the start of the memory block). The allocated memory should remain on the heap after the init function returns. The Python script can then call subsequent C functions (passing as an argument the pointer to the start of memory) and the function can do some thinking and return a value to the Python script. Finally, there's another C function to deallocate the memory.
Assume that the application is single-threaded and that after the init function, the memory is only read from so concurrency isn't an issue. The amount of memory will be a few hundred megabytes.
Is this even possible? Will Python let me malloc from the heap and allow it to stay there? Will it come from the Python process's memory? Will Python try and clear it up (i.e. does it do its own memory allocation and not expect any other processes to interfere with its address space)?
Could I just return the byte array as a Python managed string (or similar datatype) and pass the reference back as an argument to the C call? Would Python be OK with such a large string?
Would I be better off doing this with a separate process and IPC?
A:
Cython
A:
You can certainly use the C API to do what you want. You'll create a class in C, which can hold onto any memory it wants. That memory doesn't have to be exposed to Python at all if you don't want.
If you are comfortable building C DLLs, and don't need to perform Python operations in C, then ctypes might be your best bet.
| Python C API and data persistent in memory? | I'm considering integrating some C code into a Python system (Django), and I was considering using the Python / C API. The alternative is two separate processes with IPC, but I'm looking into direct interaction first. I'm new to Python so I'm trying to get a feel for the right direction to take.
Is it possible for a call to a C initialiser function to malloc a block of memory (and put something in it) and return a handle to it back to the Python script (pointer to the start of the memory block). The allocated memory should remain on the heap after the init function returns. The Python script can then call subsequent C functions (passing as an argument the pointer to the start of memory) and the function can do some thinking and return a value to the Python script. Finally, there's another C function to deallocate the memory.
Assume that the application is single-threaded and that after the init function, the memory is only read from so concurrency isn't an issue. The amount of memory will be a few hundred megabytes.
Is this even possible? Will Python let me malloc from the heap and allow it to stay there? Will it come from the Python process's memory? Will Python try and clear it up (i.e. does it do its own memory allocation and not expect any other processes to interfere with its address space)?
Could I just return the byte array as a Python managed string (or similar datatype) and pass the reference back as an argument to the C call? Would Python be OK with such a large string?
Would I be better off doing this with a separate process and IPC?
| [
"Cython\n",
"You can certainly use the C API to do what you want. You'll create a class in C, which can hold onto any memory it wants. That memory doesn't have to be exposed to Python at all if you don't want.\nIf you are comfortable building C DLLs, and don't need to perform Python operations in C, then ctypes might be your best bet.\n"
] | [
2,
1
] | [] | [] | [
"c",
"ipc",
"python"
] | stackoverflow_0002059685_c_ipc_python.txt |
Q:
How to refine an initial query in Django?
Following the reply to this question (Thanks again Ellie P!) I created a search page and a results page.
For instance if you search for the lawyer "delelle" the result page shows her firm, school and year graduated. But instead of displaying her info, I want to display other lawyers who graduated from the same school the same year.
This is the view:
def search(request):
if 'q' in request.GET and request.GET['q']:
q = request.GET['q']
lawyers = Lawyer.objects.filter(last__icontains=q)
return render_to_response('search_results.html', {'lawyers': lawyers, 'query': q})
else:
return HttpResponse('Please submit a search term.')
Can anyone help me understand how I can save the school and year_graduated from the initial query and do a school and year_graduated search and display that result?
Thank you!
Edit
Model is here
Edit2
I tried a few things from the QuerySet API
Given the search query is "akira":
>>> akira_year = Lawyer.objects.filter(first__icontains="Akira").values_list('year_graduated').order_by('year_graduated')
>>> print akira_year
[(u'2000',)]
But
>>> Lawyer.objects.filter(year_graduated__icontains=akira_year[0])
[]
doesn't work.
Can anyone help with the correct syntax to use in this case?
Thanks
A:
This view function answers the question:
def search(request):
if 'q' in request.GET and request.GET['q']:
q = request.GET['q']
q_school = Lawyer.objects.filter(last__icontains=q).values_list('school', flat=True)
q_year = Lawyer.objects.filter(last__icontains=q).values_list('year_graduated', flat=True)
lawyers = Lawyer.objects.filter(school__icontains=q_school[0]).filter(year_graduated__icontains=q_year[0])
return render_to_response('search_results.html', {'lawyers': lawyers, 'query': q})
else:
return HttpResponse('Please submit a search term.')
| How to refine an initial query in Django? | Following the reply to this question (Thanks again Ellie P!) I created a search page and a results page.
For instance if you search for the lawyer "delelle" the result page shows her firm, school and year graduated. But instead of displaying her info, I want to display other lawyers who graduated from the same school the same year.
This is the view:
def search(request):
if 'q' in request.GET and request.GET['q']:
q = request.GET['q']
lawyers = Lawyer.objects.filter(last__icontains=q)
return render_to_response('search_results.html', {'lawyers': lawyers, 'query': q})
else:
return HttpResponse('Please submit a search term.')
Can anyone help me understand how I can save the school and year_graduated from the initial query and do a school and year_graduated search and display that result?
Thank you!
Edit
Model is here
Edit2
I tried a few things from the QuerySet API
Given the search query is "akira":
>>> akira_year = Lawyer.objects.filter(first__icontains="Akira").values_list('year_graduated').order_by('year_graduated')
>>> print akira_year
[(u'2000',)]
But
>>> Lawyer.objects.filter(year_graduated__icontains=akira_year[0])
[]
doesn't work.
Can anyone help with the correct syntax to use in this case?
Thanks
| [
"This view function answers the question:\ndef search(request):\n if 'q' in request.GET and request.GET['q']:\n q = request.GET['q']\n q_school = Lawyer.objects.filter(last__icontains=q).values_list('school', flat=True)\n q_year = Lawyer.objects.filter(last__icontains=q).values_list('year_graduated', flat=True)\n lawyers = Lawyer.objects.filter(school__icontains=q_school[0]).filter(year_graduated__icontains=q_year[0]) \n return render_to_response('search_results.html', {'lawyers': lawyers, 'query': q})\n else:\n return HttpResponse('Please submit a search term.')\n\n"
] | [
0
] | [] | [] | [
"django",
"python"
] | stackoverflow_0002058573_django_python.txt |
Q:
drop table in python with sqlite3
I have question about python and sqlite3. I want to drop a table from within Python. The command
cur.execute('drop table if exists tab1')
Does not work.
cur.executescript('drop table if exists tab1;')
does the job.
The execute method allows the creation of tables. However, it won't drop them? Is there a reason for this?
A:
The cur.executescript command issues a COMMIT before running the provided script. Additionally a CREATE executes a COMMIT intrinsically. Perhaps you have an open transaction that needs committed before your changes take place.
| drop table in python with sqlite3 | I have question about python and sqlite3. I want to drop a table from within Python. The command
cur.execute('drop table if exists tab1')
Does not work.
cur.executescript('drop table if exists tab1;')
does the job.
The execute method allows the creation of tables. However, it won't drop them? Is there a reason for this?
| [
"The cur.executescript command issues a COMMIT before running the provided script. Additionally a CREATE executes a COMMIT intrinsically. Perhaps you have an open transaction that needs committed before your changes take place.\n"
] | [
14
] | [] | [] | [
"python",
"sqlite"
] | stackoverflow_0002060032_python_sqlite.txt |
Q:
Python: sort the list
I want to sort the array c. But I don't get the answer a,b,c,d. Instead I get a,b,d,c. What could I do, for sorting the whole array and not only one row?
EDIT: I want to sort the numbers. And the connected letters, should have the same order like the sorted numbers. sorry my question wasn't clear. Maybe I should join number and letters first. Like this:
[['a',1]['b',2]....
a = ['a','b','d','c']
b = [1,2,4,3]
c = [[],[]]
c[0]=a
c[1]=b
c[1].sort()
print(c)
A:
Let's take a look at what's going on here:
# Initialize the lists
a = ['a','b','d','c']
b = [1,2,4,3]
c = [[],[]]
# Assign the lists to positions in c
c[0]=a
c[1]=b
# Sort b, which was assigned to c[1]
c[1].sort()
print(c)
So, of course you could not expect a to get sorted. Try this instead:
# Sort a, which was assigned to c[0]
c[0].sort()
# Sort b, which was assigned to c[1]
c[1].sort()
print(c)
Or if c is of variable length:
# Sort every list in c
for l in c:
l.sort()
Edit: in response to your comment, the letters are not connected to the numbers in any way. If you want them to be connected, you need to join them in a structure like a tuple. Try:
>>> c = [ (1, 'a'), (2, 'b'), (4, 'd'), (3, 'c') ]
>>> c.sort()
>>> print c
[(1, 'a'), (2, 'b'), (3, 'c'), (4, 'd')]
By default, tuples will sort on their first element. Note that you could use any letters here in place of a, b, c, d, and the tuples would still sort the same (by number).
A:
This appears to be what you really want to do:
>>> a = ['a', 'z', 'd', 'c']
>>> b = [1, 2, 4, 3]
>>> c = zip(a, b)
>>> c
[('a', 1), ('z', 2), ('d', 4), ('c', 3)]
>>> import operator
>>> c.sort(key=operator.itemgetter(1))
# this would be equivalent: c.sort(key=lambda x: x[1])
>>> c
[('a', 1), ('z', 2), ('c', 3), ('d', 4)]
A:
>>> a = ['a','b','d','c']
>>> b = [1, 2, 4, 3]
>>> c = zip(a, b)
>>> c
[('a', 1), ('b', 2), ('d', 4), ('c', 3)]
>>> c.sort(key=lambda x: x[1])
>>> c
[('a', 1), ('b', 2), ('c', 3), ('d', 4)]
A:
[sorted(x) for x in c]
A:
The first thing that comes to mind for me on this is to use the numpy array, rather than the builtin list datatype.
Something like:
>>> from numpy import *
>>> a = array(['a', 'b', 'd', 'c'])
>>> a.sort()
>>> print a
['a' 'b' 'c' 'd']
>>> reshape(a, (2,2))
array([['a', 'b'],
['c', 'd']],
dtype='|S1')
A:
def sort_parallel(a, b):
ba = zip(b, a)
ba.sort()
return [e[1] for e in ba]
a = ['a','b','d','c']
b = [1,2,4,3]
print sort_parallel(a, b)
prints
['a', 'b', 'c', 'd']
A:
You could try (for Python 3.x):
def sort_a_based_on_b(a, b):
c = sorted(list(zip(b, a)))
return list(list(zip(*c))[1]) # Returns the sorted a
This returns the sorted a, based on the values in b.
a = ['a','b','d','c']
b = [1,2,4,3]
print(sort_a_based_on_b(a,b))
Prints ['a', 'b', 'c', 'd']
A:
In Python, an array (of the sort you are using) is called list. As for your problem, change c[1].sort() to c[0].sort() and your list of strings will be sorted instead of the list of ints contained in c[1].
A:
Roger Pate gave a good answer, but you said "but now he sorts the letters. I want to sort the numbers."
Here is a modified version of Roger Pate's answer that sorts c by the numbers. Is this what you want?
>>> def mykey(tup):
>>> return tup[1]
>>>
>>> a = ['a','b','d','c']
>>> b = [1, 2, 4, 3]
>>> c = zip(a, b)
>>> c
[('a', 1), ('b', 2), ('d', 4), ('c', 3)]
>>> c.sort(key=mykey)
>>> c
[('a', 1), ('b', 2), ('c', 3), ('d', 4)]
The "key" to the sort() method function is a function. The function returns the key you want to use. The mykey() function takes a tuple and returns its second value (value indexed by 1). Thus, .sort() will sort using the number part of the tuple. And the strings will still match the numbers. You could even split the list c again to recover lists a and b, and they will still match.
A:
you have to provide the custom comparison function for sort to use.using lambda it is pretty simple:
cmp = lambda x,y: (x[1], x[0]) < (y[1], y[0])
L.sort(cmp = cmp)
Lambda is all anonymous function, in this case it reverses the order of elements, such that second element becomes primary key, and the comparison is done using "<" operator.
A:
Is this what you're after?
>>> a = ['a','b','d','c']
>>> b = [1, 2, 4, 3]
>>> c = zip(b, a)
>>> c.sort()
>>> c = [(y, x) for (x, y) in c]
>>> print(c)
[('a', 1), ('b', 2), ('c', 3), ('d', 4)]
| Python: sort the list | I want to sort the array c. But I don't get the answer a,b,c,d. Instead I get a,b,d,c. What could I do, for sorting the whole array and not only one row?
EDIT: I want to sort the numbers. And the connected letters, should have the same order like the sorted numbers. sorry my question wasn't clear. Maybe I should join number and letters first. Like this:
[['a',1]['b',2]....
a = ['a','b','d','c']
b = [1,2,4,3]
c = [[],[]]
c[0]=a
c[1]=b
c[1].sort()
print(c)
| [
"Let's take a look at what's going on here:\n# Initialize the lists\na = ['a','b','d','c']\nb = [1,2,4,3]\nc = [[],[]]\n\n# Assign the lists to positions in c\nc[0]=a\nc[1]=b\n\n# Sort b, which was assigned to c[1]\nc[1].sort()\nprint(c)\n\nSo, of course you could not expect a to get sorted. Try this instead:\n# Sort a, which was assigned to c[0]\nc[0].sort()\n\n# Sort b, which was assigned to c[1]\nc[1].sort()\nprint(c)\n\nOr if c is of variable length:\n# Sort every list in c\nfor l in c:\n l.sort()\n\nEdit: in response to your comment, the letters are not connected to the numbers in any way. If you want them to be connected, you need to join them in a structure like a tuple. Try:\n>>> c = [ (1, 'a'), (2, 'b'), (4, 'd'), (3, 'c') ]\n>>> c.sort()\n>>> print c \n[(1, 'a'), (2, 'b'), (3, 'c'), (4, 'd')]\n\nBy default, tuples will sort on their first element. Note that you could use any letters here in place of a, b, c, d, and the tuples would still sort the same (by number).\n",
"This appears to be what you really want to do:\n>>> a = ['a', 'z', 'd', 'c']\n>>> b = [1, 2, 4, 3]\n>>> c = zip(a, b)\n>>> c\n[('a', 1), ('z', 2), ('d', 4), ('c', 3)]\n>>> import operator\n>>> c.sort(key=operator.itemgetter(1))\n# this would be equivalent: c.sort(key=lambda x: x[1])\n>>> c\n[('a', 1), ('z', 2), ('c', 3), ('d', 4)]\n\n",
">>> a = ['a','b','d','c']\n>>> b = [1, 2, 4, 3]\n>>> c = zip(a, b)\n>>> c\n[('a', 1), ('b', 2), ('d', 4), ('c', 3)]\n>>> c.sort(key=lambda x: x[1])\n>>> c\n[('a', 1), ('b', 2), ('c', 3), ('d', 4)]\n\n",
"[sorted(x) for x in c]\n\n",
"The first thing that comes to mind for me on this is to use the numpy array, rather than the builtin list datatype.\nSomething like:\n>>> from numpy import *\n>>> a = array(['a', 'b', 'd', 'c'])\n>>> a.sort()\n>>> print a\n['a' 'b' 'c' 'd']\n>>> reshape(a, (2,2))\narray([['a', 'b'],\n ['c', 'd']], \n dtype='|S1')\n\n",
"def sort_parallel(a, b):\n ba = zip(b, a)\n ba.sort()\n return [e[1] for e in ba]\n\na = ['a','b','d','c']\nb = [1,2,4,3]\n\nprint sort_parallel(a, b)\n\nprints\n['a', 'b', 'c', 'd']\n\n",
"You could try (for Python 3.x):\ndef sort_a_based_on_b(a, b):\n c = sorted(list(zip(b, a)))\n return list(list(zip(*c))[1]) # Returns the sorted a\n\nThis returns the sorted a, based on the values in b.\na = ['a','b','d','c']\nb = [1,2,4,3]\n\nprint(sort_a_based_on_b(a,b))\n\nPrints ['a', 'b', 'c', 'd']\n",
"In Python, an array (of the sort you are using) is called list. As for your problem, change c[1].sort() to c[0].sort() and your list of strings will be sorted instead of the list of ints contained in c[1].\n",
"Roger Pate gave a good answer, but you said \"but now he sorts the letters. I want to sort the numbers.\"\nHere is a modified version of Roger Pate's answer that sorts c by the numbers. Is this what you want?\n>>> def mykey(tup):\n>>> return tup[1]\n>>>\n>>> a = ['a','b','d','c']\n>>> b = [1, 2, 4, 3]\n>>> c = zip(a, b)\n>>> c\n[('a', 1), ('b', 2), ('d', 4), ('c', 3)]\n>>> c.sort(key=mykey)\n>>> c\n[('a', 1), ('b', 2), ('c', 3), ('d', 4)]\n\nThe \"key\" to the sort() method function is a function. The function returns the key you want to use. The mykey() function takes a tuple and returns its second value (value indexed by 1). Thus, .sort() will sort using the number part of the tuple. And the strings will still match the numbers. You could even split the list c again to recover lists a and b, and they will still match.\n",
"you have to provide the custom comparison function for sort to use.using lambda it is pretty simple:\n\n\ncmp = lambda x,y: (x[1], x[0]) < (y[1], y[0])\nL.sort(cmp = cmp)\n\n\nLambda is all anonymous function, in this case it reverses the order of elements, such that second element becomes primary key, and the comparison is done using \"<\" operator.\n",
"Is this what you're after?\n>>> a = ['a','b','d','c']\n>>> b = [1, 2, 4, 3]\n>>> c = zip(b, a)\n>>> c.sort()\n>>> c = [(y, x) for (x, y) in c]\n>>> print(c)\n[('a', 1), ('b', 2), ('c', 3), ('d', 4)]\n\n"
] | [
5,
3,
2,
1,
1,
1,
1,
0,
0,
0,
0
] | [] | [] | [
"list",
"python",
"sorting"
] | stackoverflow_0002059564_list_python_sorting.txt |
Q:
Qt winId() forcing 32bit values
Im trying to embed a display from an alien application (python OCC) into (Py)Qt using the winId of the widget. But when i pass it to OCC i get an overflow error.
Inspecting the winId qt returns its 4318283408 which is more than a 32bit number. Im running 64bits (osx) and both libraries are compiled for 64bit, but i have a hunch that OCC only likes 32bit numbers still. So my question is, is there any way to control the range of the winId that Qt return?
Thanks
Henrik
A:
Looking in Qt's source code, in the file src/gui/kernel/qwindowdefs.h, you'll find that WId is typedef'd to long for 64-bits OSX (it's int for 32-bits OSX). A long on 64-bits OSX is 8 bytes long (or 64 bits), and therefore 4318283408 is a valid value.
If you want to force winId() to return a 32 bits value, you will need to link to a 32-bits version of the Qt's library.
| Qt winId() forcing 32bit values | Im trying to embed a display from an alien application (python OCC) into (Py)Qt using the winId of the widget. But when i pass it to OCC i get an overflow error.
Inspecting the winId qt returns its 4318283408 which is more than a 32bit number. Im running 64bits (osx) and both libraries are compiled for 64bit, but i have a hunch that OCC only likes 32bit numbers still. So my question is, is there any way to control the range of the winId that Qt return?
Thanks
Henrik
| [
"Looking in Qt's source code, in the file src/gui/kernel/qwindowdefs.h, you'll find that WId is typedef'd to long for 64-bits OSX (it's int for 32-bits OSX). A long on 64-bits OSX is 8 bytes long (or 64 bits), and therefore 4318283408 is a valid value.\nIf you want to force winId() to return a 32 bits value, you will need to link to a 32-bits version of the Qt's library.\n"
] | [
0
] | [] | [] | [
"pyqt4",
"python",
"qt"
] | stackoverflow_0002053949_pyqt4_python_qt.txt |
Q:
How important are design patterns in web development?
What are the design patterns that I should be completely familiar with? And what is one easy example that each can be used for?
I am a web developer (I use Django, and is familiar with separation of logic), but I work at a Desktop-app company. They are always talking about singletons, and I forget...but it leaves me no clue!
A:
MVP or MVC
Model View Presenter or Model View Controller
More architecural patterns but neverless, they are a combination of design patterns.
A:
Forget Singleton. It's confusing and rarely necessary.
Learn State, Strategy and Command. They're used all the time.
State is for anything that has logic that depends on the state of the object. In short, every if-statement might possibly be better done via State. Seriously. Too many if-statements are a code smell and indicate that there's stateful processing that's sprawled all over the place.
Strategy is for any "plug-in" or "expansion" or "option" processing.
Command is for any extensible (and composable) set of actions. Backup, Restore. Table Drop, Create, Index, Populate. Validate, Load, Summarize, Report. Any of those command-like things that can be put together in different ways, different orders, etc., should probably be done with a formal Command design.
A:
Honestly, patterns are important but knowing when to use them is just as important. There is never going to be any set answer it is something you need to feel out for yourself. People that fight about it being an absolute where you should always use them or always not use them are incorrect. Design patterns are a tool. I would suggest looking at Amazon.com for a book in whatever language you are writing in that deals specifically with design patterns. I know there is one written for Ruby on Rails that is great though I don't remember the name, there is also one for Java called Head First Design Patterns, and on for C# written by Bob and Micah Martin that is excellent. Read whichever one of those that applies to the language you are most familiar with. Even if you don't use all of the patterns it is good to understand how they work and when they will be useful to use.
A:
Knowing design patterns won't be much use until you know why they are the best strategy for a given problem. Learning design patterns from the very beginning is probably fine, except you've missed all the "wrong" ways to solve that problem, which in turn means you may be missing subtle difference in when to use the given pattern and when to not use it.
The only thing worse than people who stick to their old ways and don't bother learning the proper way, is people who learn the proper way and don't bother learning why that way is proper. And they keep applying it to stuff that it shouldn't be applied to, because they just don't know better.
So my point is, if you're new at web development, don't be too caught up in the design pattern hype (though it's a good hype). Learn by doing stuff yourself. When you've reached a certain level, read up on design patterns and see where they could have been applied to have made your code better.
THAT is how you learn them properly. Not like being forced to run before you can walk.
A:
For web applications, understanding at least at a rudimentary level the patterns described in Patterns of Enterprise Application Architecture has proven valuable to me. Gang of Four patterns are worth knowing, too.
But I would argue that you simply don't need encyclopedic knowledge of patterns to get started. A cursory understanding will help you understand where to look when you start to encounter friction between your ideas/business problems and your code. I had a couple of weekend trips that allowed me to plow through these two books in their entirety, but I still find the detailed information in the patterns section more useful as a reference than as background knowledge.
Reading just the "Part 1" sections of the GoF or PoEAA will help you far more than learning three or four patterns in depth, because you'll know where to look when you encounter problems they describe. And you can look up the details of most of the patterns they describe online.
GoF patterns that I use directly or indirectly, often unconsciously, in web development, include: Observer, Command, Composite, State, Strategy. I usually don't use Singleton except as a client of logging and service locator/dependency injection tools. PoEAA patterns that I use regularly, usually unconsciously, or incidentally as a part of the data access strategy or web framework I'm using, are Active Record, Application Controller, Data Mapper, Domain Model, Gateway, Lazy Load, Layer Supertype, Page Controller, Template View, and Value Object. That's not exhaustive; these are just a few that popped into mind.
Most of those are probably more usefully learned by starting with an opinionated web development framework, like Rails, Django, or Castle Monorail, than in the abstract. After all, patterns were identified and extracted from thousands of successful app development experiences, not invented and then glued on because they sounded clever.
It's pretty easy to get overly excited by better-than-superficial knowledge gained on one or two patterns and then seeing "only nails" for every problem you see shortly thereafter and trying to hammer an ill-fitting pattern into a solution because you understand how it works.
So, learn patterns, yes; get a superficial overview of the motivations of all of the commonly used ones, but don't feel like you have to wait to write serious code until you understand some arbitrary list of them.
A:
MVVM is a newer one I have seen used with Silverlight. It's a bit much, but it seems effective.
| How important are design patterns in web development? | What are the design patterns that I should be completely familiar with? And what is one easy example that each can be used for?
I am a web developer (I use Django, and is familiar with separation of logic), but I work at a Desktop-app company. They are always talking about singletons, and I forget...but it leaves me no clue!
| [
"MVP or MVC\nModel View Presenter or Model View Controller\nMore architecural patterns but neverless, they are a combination of design patterns.\n",
"Forget Singleton. It's confusing and rarely necessary.\nLearn State, Strategy and Command. They're used all the time.\nState is for anything that has logic that depends on the state of the object. In short, every if-statement might possibly be better done via State. Seriously. Too many if-statements are a code smell and indicate that there's stateful processing that's sprawled all over the place.\nStrategy is for any \"plug-in\" or \"expansion\" or \"option\" processing.\nCommand is for any extensible (and composable) set of actions. Backup, Restore. Table Drop, Create, Index, Populate. Validate, Load, Summarize, Report. Any of those command-like things that can be put together in different ways, different orders, etc., should probably be done with a formal Command design. \n",
"Honestly, patterns are important but knowing when to use them is just as important. There is never going to be any set answer it is something you need to feel out for yourself. People that fight about it being an absolute where you should always use them or always not use them are incorrect. Design patterns are a tool. I would suggest looking at Amazon.com for a book in whatever language you are writing in that deals specifically with design patterns. I know there is one written for Ruby on Rails that is great though I don't remember the name, there is also one for Java called Head First Design Patterns, and on for C# written by Bob and Micah Martin that is excellent. Read whichever one of those that applies to the language you are most familiar with. Even if you don't use all of the patterns it is good to understand how they work and when they will be useful to use.\n",
"Knowing design patterns won't be much use until you know why they are the best strategy for a given problem. Learning design patterns from the very beginning is probably fine, except you've missed all the \"wrong\" ways to solve that problem, which in turn means you may be missing subtle difference in when to use the given pattern and when to not use it.\nThe only thing worse than people who stick to their old ways and don't bother learning the proper way, is people who learn the proper way and don't bother learning why that way is proper. And they keep applying it to stuff that it shouldn't be applied to, because they just don't know better.\nSo my point is, if you're new at web development, don't be too caught up in the design pattern hype (though it's a good hype). Learn by doing stuff yourself. When you've reached a certain level, read up on design patterns and see where they could have been applied to have made your code better.\nTHAT is how you learn them properly. Not like being forced to run before you can walk.\n",
"For web applications, understanding at least at a rudimentary level the patterns described in Patterns of Enterprise Application Architecture has proven valuable to me. Gang of Four patterns are worth knowing, too.\nBut I would argue that you simply don't need encyclopedic knowledge of patterns to get started. A cursory understanding will help you understand where to look when you start to encounter friction between your ideas/business problems and your code. I had a couple of weekend trips that allowed me to plow through these two books in their entirety, but I still find the detailed information in the patterns section more useful as a reference than as background knowledge.\nReading just the \"Part 1\" sections of the GoF or PoEAA will help you far more than learning three or four patterns in depth, because you'll know where to look when you encounter problems they describe. And you can look up the details of most of the patterns they describe online.\nGoF patterns that I use directly or indirectly, often unconsciously, in web development, include: Observer, Command, Composite, State, Strategy. I usually don't use Singleton except as a client of logging and service locator/dependency injection tools. PoEAA patterns that I use regularly, usually unconsciously, or incidentally as a part of the data access strategy or web framework I'm using, are Active Record, Application Controller, Data Mapper, Domain Model, Gateway, Lazy Load, Layer Supertype, Page Controller, Template View, and Value Object. That's not exhaustive; these are just a few that popped into mind.\nMost of those are probably more usefully learned by starting with an opinionated web development framework, like Rails, Django, or Castle Monorail, than in the abstract. After all, patterns were identified and extracted from thousands of successful app development experiences, not invented and then glued on because they sounded clever.\nIt's pretty easy to get overly excited by better-than-superficial knowledge gained on one or two patterns and then seeing \"only nails\" for every problem you see shortly thereafter and trying to hammer an ill-fitting pattern into a solution because you understand how it works.\nSo, learn patterns, yes; get a superficial overview of the motivations of all of the commonly used ones, but don't feel like you have to wait to write serious code until you understand some arbitrary list of them.\n",
"MVVM is a newer one I have seen used with Silverlight. It's a bit much, but it seems effective.\n"
] | [
11,
10,
2,
1,
1,
0
] | [] | [] | [
"design_patterns",
"oop",
"python"
] | stackoverflow_0002060341_design_patterns_oop_python.txt |
Q:
super() weirdness in Python 3
I know this has been discussed a number of times before, but there was never an explanation of what's going on "under the hood".
Can anyone provide a detailed explanation as to why commenting-in the last line of code causes an error to be raised? I know that that object.__init__ doesn't take any arguments, but why does the code work when the line is commented out?
class A:
def __init__(self, a):
print("A constructor")
super().__init__(a)
self.a = a
print("A constructor end")
class B:
def __init__(self, b):
print("B constructor")
super().__init__()
self.b = b
print("B constructor end")
class C(A, B):
def __init__(self, x):
super().__init__(x)
c = C(42)
#a = A(33)
A:
In Python 3 every method becomes a closure with a hidden value added for the "current class" being defined. This is accessed by super() (with no arguments).
Super returns an object which uses the class's Method Resolution Order (MRO), and for C instances this has B after A.
Without finding B in the MRO, super().__init__ in A will call object.__init__, to which you can't pass any parameters.
You can view the MRO for a class by looking at SomeClass.__mro__.
Though mostly talking about 2.x, you may want to read http://fuhm.net/super-harmful/.
| super() weirdness in Python 3 | I know this has been discussed a number of times before, but there was never an explanation of what's going on "under the hood".
Can anyone provide a detailed explanation as to why commenting-in the last line of code causes an error to be raised? I know that that object.__init__ doesn't take any arguments, but why does the code work when the line is commented out?
class A:
def __init__(self, a):
print("A constructor")
super().__init__(a)
self.a = a
print("A constructor end")
class B:
def __init__(self, b):
print("B constructor")
super().__init__()
self.b = b
print("B constructor end")
class C(A, B):
def __init__(self, x):
super().__init__(x)
c = C(42)
#a = A(33)
| [
"In Python 3 every method becomes a closure with a hidden value added for the \"current class\" being defined. This is accessed by super() (with no arguments).\nSuper returns an object which uses the class's Method Resolution Order (MRO), and for C instances this has B after A.\nWithout finding B in the MRO, super().__init__ in A will call object.__init__, to which you can't pass any parameters.\nYou can view the MRO for a class by looking at SomeClass.__mro__.\nThough mostly talking about 2.x, you may want to read http://fuhm.net/super-harmful/.\n"
] | [
6
] | [] | [] | [
"python",
"python_3.x",
"super"
] | stackoverflow_0002060475_python_python_3.x_super.txt |
Q:
Is there anything out there that can take screenshots of website content and crop out the layout?
Other ideas are also welcome. I am trying to take an excel file, using python to generate an xml for a javascript html webpage that will essentially display a gallery (or some sort of directory structure). The excel file would be pretty massive, but let us assume time isn't so crucial.
So far I can convert the tab delimited version of the excel spreadsheet into XML and I have all of the links... Now, I just need to able to open up a browser and take a screenshot and crop them the right way, or save certain portions of the web content some how....
I was thinking about using selenium as a web crawler then using autoit execute keyboard commands to save all the webpages, but that won't work for various reasons (also it would be extremely slow).
Ideas?
One example where I've seen a "smart crop" take place is in camtasia where they zoom in on certain parts of the screen where they think to focus would be. I think that could work to some degree. Then again I don't have any idea how to make such assumptions with a good deal of accuracy.
A:
You could probably use pywebkitgtk to render the HTML and then PIL to manipulate the image.
| Is there anything out there that can take screenshots of website content and crop out the layout? | Other ideas are also welcome. I am trying to take an excel file, using python to generate an xml for a javascript html webpage that will essentially display a gallery (or some sort of directory structure). The excel file would be pretty massive, but let us assume time isn't so crucial.
So far I can convert the tab delimited version of the excel spreadsheet into XML and I have all of the links... Now, I just need to able to open up a browser and take a screenshot and crop them the right way, or save certain portions of the web content some how....
I was thinking about using selenium as a web crawler then using autoit execute keyboard commands to save all the webpages, but that won't work for various reasons (also it would be extremely slow).
Ideas?
One example where I've seen a "smart crop" take place is in camtasia where they zoom in on certain parts of the screen where they think to focus would be. I think that could work to some degree. Then again I don't have any idea how to make such assumptions with a good deal of accuracy.
| [
"You could probably use pywebkitgtk to render the HTML and then PIL to manipulate the image.\n"
] | [
1
] | [] | [] | [
"automation",
"crop",
"image",
"python",
"screenshot"
] | stackoverflow_0002060865_automation_crop_image_python_screenshot.txt |
Q:
Copy Table data from one DB to another
For development I find myself needing to copy table information from one table to another quite often. I am just curious what are the easiest solutions to do this for Postgres. I have PGAdminIII but it looks like it really only support the long drawn out Backup/Restore.
Is there a python or bash script somewhere or something that I can just give it the basic infomation?
Here is DB1
Here is DB2
Copy Tables ...
Go!
I believe SQLYog did this for MySQL in Win32, but I am now on OSX and using Postgres.
A:
Kettle, aka pentaho data integration can do this for you.
http://sourceforge.net/projects/pentaho/files/Data%20Integration/
Download kettle and unzip.
Make sure you have a java runtime environment (1.5 and 1.6 will both work for the 3.2 stable version).
Run spoon.sh
Create a new job (file/new/job)
Define source and target connections (click on the view button above the tree, dbl click on the database connections node to open the connection wizard or do menu/wizard/create db connection wizard)
Do menu/wizard/copy tables wizard
follow the wizard steps
run job (play button on toolbar)
A:
If you're just moving between two PostgreSQL databases, a good way is to just use pg_dump and pg_restore in a pipe (or pg_dump and psql). Basically
pg_dump -Fc db1 | pg_restore -d db2 -c
(adjust switches as necessary for your environment, see the man pages)
It's tools you have already installed, and if you just want to transfer the data and not modify it, it'll be a lot faster than a full-blown ETL too like Kettle.
| Copy Table data from one DB to another | For development I find myself needing to copy table information from one table to another quite often. I am just curious what are the easiest solutions to do this for Postgres. I have PGAdminIII but it looks like it really only support the long drawn out Backup/Restore.
Is there a python or bash script somewhere or something that I can just give it the basic infomation?
Here is DB1
Here is DB2
Copy Tables ...
Go!
I believe SQLYog did this for MySQL in Win32, but I am now on OSX and using Postgres.
| [
"Kettle, aka pentaho data integration can do this for you. \nhttp://sourceforge.net/projects/pentaho/files/Data%20Integration/\n\nDownload kettle and unzip. \nMake sure you have a java runtime environment (1.5 and 1.6 will both work for the 3.2 stable version). \nRun spoon.sh\nCreate a new job (file/new/job)\nDefine source and target connections (click on the view button above the tree, dbl click on the database connections node to open the connection wizard or do menu/wizard/create db connection wizard)\nDo menu/wizard/copy tables wizard\nfollow the wizard steps\nrun job (play button on toolbar)\n\n",
"If you're just moving between two PostgreSQL databases, a good way is to just use pg_dump and pg_restore in a pipe (or pg_dump and psql). Basically\npg_dump -Fc db1 | pg_restore -d db2 -c\n\n(adjust switches as necessary for your environment, see the man pages)\nIt's tools you have already installed, and if you just want to transfer the data and not modify it, it'll be a lot faster than a full-blown ETL too like Kettle.\n"
] | [
7,
3
] | [] | [] | [
"linux",
"macos",
"postgresql",
"python"
] | stackoverflow_0002060823_linux_macos_postgresql_python.txt |
Q:
Opening multiple windows from a list in WxPython
I have a little program that goes to news aggregater's, gets the hrefs, and returns in a window. I want to have multiple windows open if multiple sites are choosen, right now, it will only go to the first one in a list, and completes perfectly. I assume I am not passing the the contents of the list properly to the next step in my program.
import wx
import urllib2
from BeautifulSoup import BeautifulSoup
import re
from pyparsing import makeHTMLTags, originalTextFor, SkipTo, Combine
import wx
import wx.html
global P
siteDict = {0:'http://www.reddit.com', 1:'http://www.digg.com',2:'http://www.stumbleupon.com', 3:'news.google.com'}
class citPanel(wx.Panel):
def __init__(self, parent, id):
wx.Panel.__init__(self, parent, id)
allSites = ['Reddit', 'Digg', 'StumbleUpon', 'Google News']
wx.StaticText(self, -1, "Choose the Sites you would like Charlie to Visit:", (45, 15))
self.sitList = wx.CheckListBox(self, 20, (60, 50), wx.DefaultSize, allSites)
class nextButton(wx.Button):
def __init__(self, parent, id, label, pos):
wx.Button.__init__(self, parent, id, label, pos)
class checkList(wx.Frame):
def __init__(self, parent, id, title):
wx.Frame.__init__(self, parent, id, title, size=(400, 300))
self.panel = citPanel(self, -1)
nextButton(self.panel, 30, 'Ok', (275, 50))
self.Bind(wx.EVT_BUTTON, self.Clicked)
self.Centre()
self.Show(True)
def Clicked(self, event):
checkedItems = [i for i in range(self.panel.sitList.GetCount()) if self.panel.sitList.IsChecked(i)]
print checkedItems
r = [siteDict[k] for k in checkedItems]
print r
for each in r:
pre = '<HTML><head><title>Page title</title></head>'
post = '</HTML>'
site = urllib2.urlopen(each)
html=site.read()
soup = BeautifulSoup(html)
tags = soup.findAll('a')
soup1 = BeautifulSoup(''.join(str(t) for t in tags))
print soup1.prettify()
aTag,aEnd = makeHTMLTags("A")
aTag = originalTextFor(aTag)
aEnd = originalTextFor(aEnd)
aLink = aTag + SkipTo(aEnd) + aEnd
aLink.setParseAction(lambda tokens : ''.join(tokens))
links = aLink.searchString(html)
out = []
out.append(pre)
out.extend([' '+lnk[0] for lnk in links])
out.append(post)
P= '\n'.join(out)
print type(P)
print P
class MyHtmlFrame(wx.Frame):
def __init__(self, parent, title):
wx.Frame.__init__(self, parent, -1, title)
html = wx.html.HtmlWindow(self)
if "gtk2" in wx.PlatformInfo:
html.SetStandardFonts()
html.SetPage(P)
app = wx.PySimpleApp()
frm = MyHtmlFrame(None, "Charlie")
frm.Show()
app.MainLoop()
#event.Skip()
#self.Destroy()
app = wx.App()
checkList(None, -1, 'Charlie')
app.MainLoop()
I have some print statements mixed in for debugging. So, any help, much appreciated. Also, if they all ended up on the same window, that would be fine too. Just trying to get past the only doing the first one
A:
Eeek! You're defining your MyHTMLFrame class -inside- an event handler function (not a good idea).
I can't run the script as I don't have the module PyParsing (always make samples that have as little dependencies as possible...)
Therefore, I'm not sure if this code runs, but it should give you the general idea. Here is the code modified, I've only changed a bit after the clicked() function
def Clicked(self, event):
checkedItems = [i for i in range(self.panel.sitList.GetCount()) if self.panel.sitList.IsChecked(i)]
print checkedItems
r = [siteDict[k] for k in checkedItems]
print r
for each in r:
pre = '<HTML><head><title>Page title</title></head>'
post = '</HTML>'
site = urllib2.urlopen(each)
html=site.read()
soup = BeautifulSoup(html)
tags = soup.findAll('a')
soup1 = BeautifulSoup(''.join(str(t) for t in tags))
print soup1.prettify()
aTag,aEnd = makeHTMLTags("A")
aTag = originalTextFor(aTag)
aEnd = originalTextFor(aEnd)
aLink = aTag + SkipTo(aEnd) + aEnd
aLink.setParseAction(lambda tokens : ''.join(tokens))
links = aLink.searchString(html)
out = []
out.append(pre)
out.extend([' '+lnk[0] for lnk in links])
out.append(post)
P= '\n'.join(out)
print type(P)
print P
# create the html frame, pass it in your string
frm = MyHtmlFrame(None, "Charlie", P)
frm.Show()
class MyHtmlFrame(wx.Frame):
def __init__(self, parent, title, page): # pass it in the page variable
wx.Frame.__init__(self, parent, -1, title)
html = wx.html.HtmlWindow(self)
if "gtk2" in wx.PlatformInfo:
html.SetStandardFonts()
html.SetPage(page)
app = wx.App()
checkList(None, -1, 'Charlie')
checkList.Show() # show first frame, which opens other windows
app.MainLoop()
ugh I hate indenting by 4 spaces to start code in StackOverflow. Hope this works for you!
A:
I am not familiar with WxPython but it appears that you have two MainLoops running.
I got your program to open two windows when I commented out the two lines as shown below:
class MyHtmlFrame(wx.Frame):
def __init__(self, parent, title):
wx.Frame.__init__(self, parent, -1, title)
html = wx.html.HtmlWindow(self)
if "gtk2" in wx.PlatformInfo:
html.SetStandardFonts()
html.SetPage(P)
#app = wx.PySimpleApp()
frm = MyHtmlFrame(None, "Charlie")
frm.Show()
#app.MainLoop()
| Opening multiple windows from a list in WxPython | I have a little program that goes to news aggregater's, gets the hrefs, and returns in a window. I want to have multiple windows open if multiple sites are choosen, right now, it will only go to the first one in a list, and completes perfectly. I assume I am not passing the the contents of the list properly to the next step in my program.
import wx
import urllib2
from BeautifulSoup import BeautifulSoup
import re
from pyparsing import makeHTMLTags, originalTextFor, SkipTo, Combine
import wx
import wx.html
global P
siteDict = {0:'http://www.reddit.com', 1:'http://www.digg.com',2:'http://www.stumbleupon.com', 3:'news.google.com'}
class citPanel(wx.Panel):
def __init__(self, parent, id):
wx.Panel.__init__(self, parent, id)
allSites = ['Reddit', 'Digg', 'StumbleUpon', 'Google News']
wx.StaticText(self, -1, "Choose the Sites you would like Charlie to Visit:", (45, 15))
self.sitList = wx.CheckListBox(self, 20, (60, 50), wx.DefaultSize, allSites)
class nextButton(wx.Button):
def __init__(self, parent, id, label, pos):
wx.Button.__init__(self, parent, id, label, pos)
class checkList(wx.Frame):
def __init__(self, parent, id, title):
wx.Frame.__init__(self, parent, id, title, size=(400, 300))
self.panel = citPanel(self, -1)
nextButton(self.panel, 30, 'Ok', (275, 50))
self.Bind(wx.EVT_BUTTON, self.Clicked)
self.Centre()
self.Show(True)
def Clicked(self, event):
checkedItems = [i for i in range(self.panel.sitList.GetCount()) if self.panel.sitList.IsChecked(i)]
print checkedItems
r = [siteDict[k] for k in checkedItems]
print r
for each in r:
pre = '<HTML><head><title>Page title</title></head>'
post = '</HTML>'
site = urllib2.urlopen(each)
html=site.read()
soup = BeautifulSoup(html)
tags = soup.findAll('a')
soup1 = BeautifulSoup(''.join(str(t) for t in tags))
print soup1.prettify()
aTag,aEnd = makeHTMLTags("A")
aTag = originalTextFor(aTag)
aEnd = originalTextFor(aEnd)
aLink = aTag + SkipTo(aEnd) + aEnd
aLink.setParseAction(lambda tokens : ''.join(tokens))
links = aLink.searchString(html)
out = []
out.append(pre)
out.extend([' '+lnk[0] for lnk in links])
out.append(post)
P= '\n'.join(out)
print type(P)
print P
class MyHtmlFrame(wx.Frame):
def __init__(self, parent, title):
wx.Frame.__init__(self, parent, -1, title)
html = wx.html.HtmlWindow(self)
if "gtk2" in wx.PlatformInfo:
html.SetStandardFonts()
html.SetPage(P)
app = wx.PySimpleApp()
frm = MyHtmlFrame(None, "Charlie")
frm.Show()
app.MainLoop()
#event.Skip()
#self.Destroy()
app = wx.App()
checkList(None, -1, 'Charlie')
app.MainLoop()
I have some print statements mixed in for debugging. So, any help, much appreciated. Also, if they all ended up on the same window, that would be fine too. Just trying to get past the only doing the first one
| [
"Eeek! You're defining your MyHTMLFrame class -inside- an event handler function (not a good idea). \nI can't run the script as I don't have the module PyParsing (always make samples that have as little dependencies as possible...)\nTherefore, I'm not sure if this code runs, but it should give you the general idea. Here is the code modified, I've only changed a bit after the clicked() function\n def Clicked(self, event):\n checkedItems = [i for i in range(self.panel.sitList.GetCount()) if self.panel.sitList.IsChecked(i)]\n print checkedItems\n r = [siteDict[k] for k in checkedItems]\n print r\n for each in r:\n pre = '<HTML><head><title>Page title</title></head>'\n post = '</HTML>'\n site = urllib2.urlopen(each)\n html=site.read()\n soup = BeautifulSoup(html)\n tags = soup.findAll('a')\n\n soup1 = BeautifulSoup(''.join(str(t) for t in tags))\n print soup1.prettify()\n\n aTag,aEnd = makeHTMLTags(\"A\")\n\n aTag = originalTextFor(aTag)\n aEnd = originalTextFor(aEnd)\n\n aLink = aTag + SkipTo(aEnd) + aEnd\n aLink.setParseAction(lambda tokens : ''.join(tokens))\n\n links = aLink.searchString(html)\n\n out = []\n out.append(pre)\n out.extend([' '+lnk[0] for lnk in links])\n out.append(post)\n\n P= '\\n'.join(out)\n print type(P)\n\n print P\n\n # create the html frame, pass it in your string\n frm = MyHtmlFrame(None, \"Charlie\", P)\n frm.Show()\n\n\n\nclass MyHtmlFrame(wx.Frame):\ndef __init__(self, parent, title, page): # pass it in the page variable\n wx.Frame.__init__(self, parent, -1, title)\n html = wx.html.HtmlWindow(self)\n if \"gtk2\" in wx.PlatformInfo:\n html.SetStandardFonts()\n\n html.SetPage(page)\n\n\n\napp = wx.App()\n\ncheckList(None, -1, 'Charlie') \ncheckList.Show() # show first frame, which opens other windows\napp.MainLoop()\n\nugh I hate indenting by 4 spaces to start code in StackOverflow. Hope this works for you!\n",
"I am not familiar with WxPython but it appears that you have two MainLoops running.\nI got your program to open two windows when I commented out the two lines as shown below:\n class MyHtmlFrame(wx.Frame):\n def __init__(self, parent, title):\n wx.Frame.__init__(self, parent, -1, title)\n html = wx.html.HtmlWindow(self)\n if \"gtk2\" in wx.PlatformInfo:\n html.SetStandardFonts()\n\n html.SetPage(P)\n\n\n #app = wx.PySimpleApp()\n frm = MyHtmlFrame(None, \"Charlie\")\n frm.Show()\n #app.MainLoop()\n\n"
] | [
1,
0
] | [] | [] | [
"python",
"wxpython"
] | stackoverflow_0002059786_python_wxpython.txt |
Q:
Yahoo OAuth question
I'm keep getting oauth_problem=consumer_key_unknown error when trying oauth https://api.login.yahoo.com/oauth/v2/get_request_token
I'm pretty sure my consumer key is correct because it works locally (Runs via 127.0.0.1). Just keep giving me oauth_problem=consumer_key_unknown when I try it on my server. Any ideas?
A:
is it sending the right domain in requireSession (4th argument should be something like 'http://mydomain.com/' which should match exactly what you used to sign up...
| Yahoo OAuth question | I'm keep getting oauth_problem=consumer_key_unknown error when trying oauth https://api.login.yahoo.com/oauth/v2/get_request_token
I'm pretty sure my consumer key is correct because it works locally (Runs via 127.0.0.1). Just keep giving me oauth_problem=consumer_key_unknown when I try it on my server. Any ideas?
| [
"is it sending the right domain in requireSession (4th argument should be something like 'http://mydomain.com/' which should match exactly what you used to sign up...\n"
] | [
0
] | [] | [] | [
"oauth",
"python",
"yahoo"
] | stackoverflow_0002061124_oauth_python_yahoo.txt |
Q:
Subclassing Decimal in Python
I want to use Decimal class in my Python program for doing financial calculations. Decimals to not work with floats - they need explicit conversion to strings first.
So i decided to subclass Decimal to be able to work with floats without explicit conversions.
m_Decimal.py:
# -*- coding: utf-8 -*-
import decimal
Decimal = decimal.Decimal
def floatCheck ( obj ) : # usually Decimal does not work with floats
return repr ( obj ) if isinstance ( obj, float ) else obj # this automatically converts floats to Decimal
class m_Decimal ( Decimal ) :
__integral = Decimal ( 1 )
def __new__ ( cls, value = 0 ) :
return Decimal.__new__ ( cls, floatCheck ( value ) )
def __str__ ( self ) :
return str ( self.quantize ( self.__integral ) if self == self.to_integral () else self.normalize () ) # http://docs.python.org/library/decimal.html#decimal-faq
def __mul__ ( self, other ) :
print (type(other))
Decimal.__mul__ ( self, other )
D = m_Decimal
print ( D(5000000)*D(2.2))
So now instead of writing D(5000000)*D(2.2) i should be able to write D(5000000)*2.2 without rasing exceptions.
I have several questions:
Will my decision cause me any troubles?
Reimplementing __mul__ doesn't work in case of D(5000000)*D(2.2), because the other argument is of type class '__main__.m_Decimal', but you can see in decimal module this:
decimal.py, line 5292:
def _convert_other(other, raiseit=False):
"""Convert other to Decimal.
Verifies that it's ok to use in an implicit construction.
"""
if isinstance(other, Decimal):
return other
if isinstance(other, (int, long)):
return Decimal(other)
if raiseit:
raise TypeError("Unable to convert %s to Decimal" % other)
return NotImplemented
The decimal module expects argument being Decimal or int. This means i should convert my m_Decimal object to string first, then to Decimal. But this is lot of waste - m_Decimal is descendant of Decimal - how can i use this to make the class faster (Decimal is already very slow).
When cDecimal will appear, will this subclassing work?
A:
Currently, it won't do what you want at all. You can't multiply your m_decimal by anything: it will always return None, due to a missing return statement:
def __mul__ ( self, other ) :
print (type(other))
return Decimal.__mul__ ( self, other )
Even with the return added in, you still can't do D(500000)*2.2, as the float still needs converting to a Decimal, before Decimal.mul will accept it. Also, repr is not appropriate here:
>>> repr(2.1)
'2.1000000000000001'
>>> str(2.1)
'2.1'
The way I would do it, is to make a classmethod, fromfloat
@classmethod
def fromfloat(cls, f):
return cls(str(f))
Then override the mul method to check for the type of other, and run m_Decimal.fromfloat() on it if it is a float:
class m_Decimal(Decimal):
@classmethod
def fromfloat(cls, f):
return cls(str(f))
def __mul__(self, other):
if isinstance(other, float):
other = m_Decimal.fromfloat(other)
return Decimal.__mul__(self,other)
It will then work exactly as you expect. I personally wouldn't override the new method, as it seems cleaner to me to use the fromfloat() method. But that's just my opinion.
Like Dirk said, you don't need to worry about conversion, as isinstance works with subclasses. The only problem you might have is that Decimal*m_Decimal will return a Decimal, rather than your subclass:
>>> Decimal(2) * m_Decimal(2) * 2.2
Traceback (most recent call last):
File "<pyshell#3>", line 1, in <module>
Decimal(2) * m_Decimal(2) * 2.2
TypeError: unsupported operand type(s) for *: 'Decimal' and 'float'
There are two ways to fix this. First is to add an explicit conversion to the m_Decimal's mul magicmethod:
def __mul__(self, other):
if isinstance(other, float):
other = m_Decimal.fromfloat(other)
return m_Decimal(Decimal.__mul__(self,other))
The other way, which I probably wouldn't recommend, is to "Monkeypatch" the decimal module:
decimal._Decimal = decimal.Decimal
decimal.Decimal = m_Decimal
A:
In my opinion you shouldn't use floats at all. Floats are not the right tool for a financial application. Anywhere you are using floats you should be able to use str or Decimal to ensure you are not losing precision.
For example.
User input, File input - obviously use str and convert to Decimal to do any math
Database - use decimal type if it is supported, otherwise use strings and convert to Decimal in your app.
If you insist on using floats, remember that python float is equivalent to double on many other platforms, so if you are storing them in a database for instance, make sure the database field is of type double
A:
Use cdecimal or decimal.py from 2.7 or 3.2. All of those have the from_float
class method:
class MyDecimal(Decimal):
def convert(self, v):
if isinstance(v, float):
return Decimal.from_float(v)
else:
return Decimal(v)
def __mul__(self, other):
other = self.convert(other)
return self.multiply(other)
| Subclassing Decimal in Python | I want to use Decimal class in my Python program for doing financial calculations. Decimals to not work with floats - they need explicit conversion to strings first.
So i decided to subclass Decimal to be able to work with floats without explicit conversions.
m_Decimal.py:
# -*- coding: utf-8 -*-
import decimal
Decimal = decimal.Decimal
def floatCheck ( obj ) : # usually Decimal does not work with floats
return repr ( obj ) if isinstance ( obj, float ) else obj # this automatically converts floats to Decimal
class m_Decimal ( Decimal ) :
__integral = Decimal ( 1 )
def __new__ ( cls, value = 0 ) :
return Decimal.__new__ ( cls, floatCheck ( value ) )
def __str__ ( self ) :
return str ( self.quantize ( self.__integral ) if self == self.to_integral () else self.normalize () ) # http://docs.python.org/library/decimal.html#decimal-faq
def __mul__ ( self, other ) :
print (type(other))
Decimal.__mul__ ( self, other )
D = m_Decimal
print ( D(5000000)*D(2.2))
So now instead of writing D(5000000)*D(2.2) i should be able to write D(5000000)*2.2 without rasing exceptions.
I have several questions:
Will my decision cause me any troubles?
Reimplementing __mul__ doesn't work in case of D(5000000)*D(2.2), because the other argument is of type class '__main__.m_Decimal', but you can see in decimal module this:
decimal.py, line 5292:
def _convert_other(other, raiseit=False):
"""Convert other to Decimal.
Verifies that it's ok to use in an implicit construction.
"""
if isinstance(other, Decimal):
return other
if isinstance(other, (int, long)):
return Decimal(other)
if raiseit:
raise TypeError("Unable to convert %s to Decimal" % other)
return NotImplemented
The decimal module expects argument being Decimal or int. This means i should convert my m_Decimal object to string first, then to Decimal. But this is lot of waste - m_Decimal is descendant of Decimal - how can i use this to make the class faster (Decimal is already very slow).
When cDecimal will appear, will this subclassing work?
| [
"Currently, it won't do what you want at all. You can't multiply your m_decimal by anything: it will always return None, due to a missing return statement:\n def __mul__ ( self, other ) :\n print (type(other))\n return Decimal.__mul__ ( self, other )\n\nEven with the return added in, you still can't do D(500000)*2.2, as the float still needs converting to a Decimal, before Decimal.mul will accept it. Also, repr is not appropriate here:\n>>> repr(2.1)\n'2.1000000000000001'\n>>> str(2.1)\n'2.1'\n\nThe way I would do it, is to make a classmethod, fromfloat\n @classmethod\n def fromfloat(cls, f):\n return cls(str(f))\n\nThen override the mul method to check for the type of other, and run m_Decimal.fromfloat() on it if it is a float:\nclass m_Decimal(Decimal):\n @classmethod\n def fromfloat(cls, f):\n return cls(str(f))\n\n def __mul__(self, other):\n if isinstance(other, float):\n other = m_Decimal.fromfloat(other)\n return Decimal.__mul__(self,other)\n\nIt will then work exactly as you expect. I personally wouldn't override the new method, as it seems cleaner to me to use the fromfloat() method. But that's just my opinion. \nLike Dirk said, you don't need to worry about conversion, as isinstance works with subclasses. The only problem you might have is that Decimal*m_Decimal will return a Decimal, rather than your subclass:\n>>> Decimal(2) * m_Decimal(2) * 2.2\n\nTraceback (most recent call last):\n File \"<pyshell#3>\", line 1, in <module>\n Decimal(2) * m_Decimal(2) * 2.2\nTypeError: unsupported operand type(s) for *: 'Decimal' and 'float'\n\nThere are two ways to fix this. First is to add an explicit conversion to the m_Decimal's mul magicmethod:\n def __mul__(self, other):\n if isinstance(other, float):\n other = m_Decimal.fromfloat(other)\n return m_Decimal(Decimal.__mul__(self,other))\n\nThe other way, which I probably wouldn't recommend, is to \"Monkeypatch\" the decimal module:\ndecimal._Decimal = decimal.Decimal\ndecimal.Decimal = m_Decimal\n\n",
"In my opinion you shouldn't use floats at all. Floats are not the right tool for a financial application. Anywhere you are using floats you should be able to use str or Decimal to ensure you are not losing precision.\nFor example.\nUser input, File input - obviously use str and convert to Decimal to do any math\nDatabase - use decimal type if it is supported, otherwise use strings and convert to Decimal in your app.\nIf you insist on using floats, remember that python float is equivalent to double on many other platforms, so if you are storing them in a database for instance, make sure the database field is of type double\n",
"Use cdecimal or decimal.py from 2.7 or 3.2. All of those have the from_float\nclass method:\n\nclass MyDecimal(Decimal):\n def convert(self, v):\n if isinstance(v, float):\n return Decimal.from_float(v)\n else:\n return Decimal(v)\n def __mul__(self, other):\n other = self.convert(other)\n return self.multiply(other)\n\n"
] | [
4,
1,
0
] | [] | [] | [
"decimal",
"python",
"subclassing"
] | stackoverflow_0002044427_decimal_python_subclassing.txt |
Q:
Downgrading to pyobjc 2.0 from pyobjc 2.2
I accidentally installed pyobjc 2.2 with easy-install pyobjc, and it's causing problems: When I try to import it I get the error
Incompatible library version: _objc.so requires version 10.0.0 or later, but libxml2.2.dylib provides version 9.0.0
I'm not interested in fixing that though, all I want is my pyobjc 2.0 back. I've tried removing pyobjc 2.2 and reinstalling python, and I've tried building 2.0 from the svn trunk (I get the error lipo: can't figure out the architecture of [random filename].out)
I imagine there must be a good way of doing this but it escapes me. Any insight would be appreciated.
Edit: Python 2.6 and OSX 10.5
A:
If you are using the Apple-supplied Python 2.5 on 10.5 Leopard, which comes with PyObjC 2.0 built-in, probably the easiest way to downgrade is to remove the 2.2 version from its site-packages directory, /Library/Python/2.5/site-packages. First, though, run the command:
easy_install -m pyobjc==2.2
which will edit the easy-install.pth file in that directory or you can edit the file yourself to remove the line for PyObjC 2.2. That should then revert back to the Apple-supplied version which is installed elsewhere.
If you are using another version of Python and installed PyObjC yourself, you still may be able to use easy_install to revert to it since, normally, easy_install does not remove previous versions when you upgrade. Try:
easy_install pyobjc==2.0
If that doesn't work, you may have to go to the PyObjC subversion repository and download a copy of the 2.0 branch and re-install from there:
svn co http://svn.red-bean.com/pyobjc/branches/pyobjc-20x-branch/
A:
I figured it out. The 2.5 pyobjc library is in /System/Library/Frameworks/Python.framework/Versions/2.5/...
and the command to install pyobjc for python 2.6 is
sudo port install py26-pyobjc2
Thanks anyways for the help!
| Downgrading to pyobjc 2.0 from pyobjc 2.2 | I accidentally installed pyobjc 2.2 with easy-install pyobjc, and it's causing problems: When I try to import it I get the error
Incompatible library version: _objc.so requires version 10.0.0 or later, but libxml2.2.dylib provides version 9.0.0
I'm not interested in fixing that though, all I want is my pyobjc 2.0 back. I've tried removing pyobjc 2.2 and reinstalling python, and I've tried building 2.0 from the svn trunk (I get the error lipo: can't figure out the architecture of [random filename].out)
I imagine there must be a good way of doing this but it escapes me. Any insight would be appreciated.
Edit: Python 2.6 and OSX 10.5
| [
"If you are using the Apple-supplied Python 2.5 on 10.5 Leopard, which comes with PyObjC 2.0 built-in, probably the easiest way to downgrade is to remove the 2.2 version from its site-packages directory, /Library/Python/2.5/site-packages. First, though, run the command:\neasy_install -m pyobjc==2.2\n\nwhich will edit the easy-install.pth file in that directory or you can edit the file yourself to remove the line for PyObjC 2.2. That should then revert back to the Apple-supplied version which is installed elsewhere.\nIf you are using another version of Python and installed PyObjC yourself, you still may be able to use easy_install to revert to it since, normally, easy_install does not remove previous versions when you upgrade. Try:\neasy_install pyobjc==2.0\n\nIf that doesn't work, you may have to go to the PyObjC subversion repository and download a copy of the 2.0 branch and re-install from there:\nsvn co http://svn.red-bean.com/pyobjc/branches/pyobjc-20x-branch/\n\n",
"I figured it out. The 2.5 pyobjc library is in /System/Library/Frameworks/Python.framework/Versions/2.5/...\nand the command to install pyobjc for python 2.6 is\nsudo port install py26-pyobjc2\n\nThanks anyways for the help!\n"
] | [
2,
1
] | [] | [] | [
"downgrade",
"macos",
"pyobjc",
"python"
] | stackoverflow_0002052013_downgrade_macos_pyobjc_python.txt |
Q:
machine readable language for writing notes
I'd like to write notes for class in plain text.
I was wondering if there was a markup language for doing this, where I could parse the notes for key terms, titles, page #s etc programmatically with a language such as Ruby or Python.
A:
In the Python world, reStructuredText is probably the most widely used markup language, and it's the result of a long-term and fairly rigorous design and development. It's the markup underlying the Sphinx documentation tool which, among other things, is used for the Python docs and many Python projects.
I also haven't seen a formal specification for other markup languages, at least not with the same thoroughness.
A:
LYX! I used lyx all last semester and it was great. It takes a little while to get used to (like a week). By the end of the first week I was formatting equations and matrices just as fast as my classmates could write them down. The only problem is diagrams, but if you have a sheet of paper handy or even a tablet, it shouldn't be a problem at all.
http://www.lyx.org/
Note: Lyx is a tex parser that translates code in real time. You could also just use tex, but then you might not format things right. You could also use the openoffice tex plugin, but that doesn't work as well as LYX, but it does make life easier with the plain text formatting. Also, the openoffice plugin is not current.
here's a link to that project ooolatex:
http://ooolatex.sourceforge.net/
| machine readable language for writing notes | I'd like to write notes for class in plain text.
I was wondering if there was a markup language for doing this, where I could parse the notes for key terms, titles, page #s etc programmatically with a language such as Ruby or Python.
| [
"In the Python world, reStructuredText is probably the most widely used markup language, and it's the result of a long-term and fairly rigorous design and development. It's the markup underlying the Sphinx documentation tool which, among other things, is used for the Python docs and many Python projects.\nI also haven't seen a formal specification for other markup languages, at least not with the same thoroughness.\n",
"LYX! I used lyx all last semester and it was great. It takes a little while to get used to (like a week). By the end of the first week I was formatting equations and matrices just as fast as my classmates could write them down. The only problem is diagrams, but if you have a sheet of paper handy or even a tablet, it shouldn't be a problem at all.\nhttp://www.lyx.org/\nNote: Lyx is a tex parser that translates code in real time. You could also just use tex, but then you might not format things right. You could also use the openoffice tex plugin, but that doesn't work as well as LYX, but it does make life easier with the plain text formatting. Also, the openoffice plugin is not current.\nhere's a link to that project ooolatex:\nhttp://ooolatex.sourceforge.net/\n"
] | [
4,
2
] | [] | [] | [
"markup",
"python",
"ruby"
] | stackoverflow_0002061806_markup_python_ruby.txt |
Q:
About 20 models in 1 django app
I have started work on a local app for myself that runs through the browser. Having recently gone through the django tutorial I'm thinking that it might be better to use django rather than just plain python.
There's one problem: I have at least 20 models and each will have many functions. Quite simply it's going to create one huge models file and probably huge views too. How do I split them up?
The models are all related so I can't simply make them into separate apps can I?
A:
This is a pretty common need... I can't imagine wading through a models.py file that's 10,000 lines long :-)
You can split up the models.py file (and views.py too) into a pacakge. In this case, your project tree will look like:
/my_proj
/myapp
/models
__init__.py
person.py
The __init__.py file makes the folder into a package. The only gotcha is to be sure to define an inner Meta class for your models that indicate the app_label for the model, otherwise Django will have trouble building your schema:
class Person(models.Model):
name = models.CharField(max_length=128)
class Meta:
app_label = 'myapp'
Once that's done, import the model in your __init__.py file so that Django and sync db will find it:
from person import Person
This way you can still do from myapp.models import Person
A:
"I have at least 20 models" -- this is probably more than one Django "app" and is more like a Django "project" with several small "apps"
I like to partition things around topics or subject areas that have a few (1 to 5) models. This becomes a Django "app" -- and is the useful unit of reusability.
The overall "project" is a collection of apps that presents the integrated thing built up of separate pieces.
This also helps for project management since each "app" can become a sprint with a release at th end.
A:
The models are all related so I cant's
simply make them into separate apps
can I?
You can separate them into separate apps. To use a model in one app from another app you just import it in the same way you would import django.contrib apps.
A:
Having 20 models in one app might be a sign that you should break it up in smaller ones.
The purpose of a Django app is to have a small single-purpose piece of code, that fits nicelly together.
So, if you had a e-commerce site, you might have a shopping_cart app, a billing app, and so on.
Keep in mind that there is really no problem in apps depending on each other (although it's always better if they can be decoupled), but you should not have an app doing two very distinct things.
The article Django tips: laying out an application might help you. As always, take everything you read with a grain of salt (including this answer).
A:
You can break up the models over multiple files. This goes for views as well.
A:
You can split them into separate files and simply have imports at the top of your main models.py field.
Whether you'd really want to is another question.
| About 20 models in 1 django app | I have started work on a local app for myself that runs through the browser. Having recently gone through the django tutorial I'm thinking that it might be better to use django rather than just plain python.
There's one problem: I have at least 20 models and each will have many functions. Quite simply it's going to create one huge models file and probably huge views too. How do I split them up?
The models are all related so I can't simply make them into separate apps can I?
| [
"This is a pretty common need... I can't imagine wading through a models.py file that's 10,000 lines long :-)\nYou can split up the models.py file (and views.py too) into a pacakge. In this case, your project tree will look like:\n/my_proj\n /myapp\n /models\n __init__.py\n person.py\n\nThe __init__.py file makes the folder into a package. The only gotcha is to be sure to define an inner Meta class for your models that indicate the app_label for the model, otherwise Django will have trouble building your schema:\nclass Person(models.Model):\n name = models.CharField(max_length=128)\n\n class Meta:\n app_label = 'myapp'\n\nOnce that's done, import the model in your __init__.py file so that Django and sync db will find it:\nfrom person import Person\n\nThis way you can still do from myapp.models import Person\n",
"\"I have at least 20 models\" -- this is probably more than one Django \"app\" and is more like a Django \"project\" with several small \"apps\"\nI like to partition things around topics or subject areas that have a few (1 to 5) models. This becomes a Django \"app\" -- and is the useful unit of reusability.\nThe overall \"project\" is a collection of apps that presents the integrated thing built up of separate pieces.\nThis also helps for project management since each \"app\" can become a sprint with a release at th end.\n",
"\nThe models are all related so I cant's\n simply make them into separate apps\n can I?\n\nYou can separate them into separate apps. To use a model in one app from another app you just import it in the same way you would import django.contrib apps.\n",
"Having 20 models in one app might be a sign that you should break it up in smaller ones.\nThe purpose of a Django app is to have a small single-purpose piece of code, that fits nicelly together.\nSo, if you had a e-commerce site, you might have a shopping_cart app, a billing app, and so on. \nKeep in mind that there is really no problem in apps depending on each other (although it's always better if they can be decoupled), but you should not have an app doing two very distinct things.\nThe article Django tips: laying out an application might help you. As always, take everything you read with a grain of salt (including this answer).\n",
"You can break up the models over multiple files. This goes for views as well. \n",
"You can split them into separate files and simply have imports at the top of your main models.py field. \nWhether you'd really want to is another question.\n"
] | [
76,
31,
16,
5,
0,
0
] | [] | [] | [
"django",
"django_models",
"python"
] | stackoverflow_0000859192_django_django_models_python.txt |
Q:
Filter array to show rows with a specific value in a specific column
Let's say i have a multidimensional list l:
l = [['a', 1],['b', 2],['c', 3],['a', 4]]
and I want to return another list consisting only of the rows that has 'a' in their first list element:
m = [['a', 1],['a', 4]]
What's a good and efficient way of doing this?
A:
Definitely a case for a list comprehension:
m = [row for row in l if 'a' in row[0]]
Here I'm taking your "having 'a' in the first element" literally, whence the use of the in operator. If you want to restrict this to "having 'a' as the first element" (a very different thing from what you actually wrote!-), then
m = [row for row in l if 'a' == row[0]]
is more like it;-).
A:
m = [i for i in l if i[0] == 'a']
A:
With the filter function:
m = filter(lambda x: x[0] == 'a', l)
or as a list comprehension:
m = [x for x in l where x[0] == 'a']
A:
What's wrong with just:
m = [i for i in l if i[0] == 'a']
Or:
m = filter(lambda x: x[0] == 'a', l)
I doubt the difference between these will be significant performance-wise. Use whichever is most convenient. I don't like lambdas, but the filter can be replaced with itertools.ifilter for larger lists if that's a problem, but you can also change the list comprehension to a generator (change the [] to ()) to achieve the same general result. Other than that, they're probably identical.
A:
[i for i in l if i[0]=='a']
btw, take a look at Python's list comprehension with conditions.
| Filter array to show rows with a specific value in a specific column | Let's say i have a multidimensional list l:
l = [['a', 1],['b', 2],['c', 3],['a', 4]]
and I want to return another list consisting only of the rows that has 'a' in their first list element:
m = [['a', 1],['a', 4]]
What's a good and efficient way of doing this?
| [
"Definitely a case for a list comprehension:\nm = [row for row in l if 'a' in row[0]]\n\nHere I'm taking your \"having 'a' in the first element\" literally, whence the use of the in operator. If you want to restrict this to \"having 'a' as the first element\" (a very different thing from what you actually wrote!-), then\nm = [row for row in l if 'a' == row[0]]\n\nis more like it;-).\n",
"m = [i for i in l if i[0] == 'a']\n\n",
"With the filter function:\nm = filter(lambda x: x[0] == 'a', l)\n\nor as a list comprehension:\nm = [x for x in l where x[0] == 'a']\n\n",
"What's wrong with just:\nm = [i for i in l if i[0] == 'a']\n\nOr:\nm = filter(lambda x: x[0] == 'a', l)\n\nI doubt the difference between these will be significant performance-wise. Use whichever is most convenient. I don't like lambdas, but the filter can be replaced with itertools.ifilter for larger lists if that's a problem, but you can also change the list comprehension to a generator (change the [] to ()) to achieve the same general result. Other than that, they're probably identical.\n",
"[i for i in l if i[0]=='a']\n\nbtw, take a look at Python's list comprehension with conditions.\n"
] | [
19,
1,
1,
0,
0
] | [] | [] | [
"list",
"python"
] | stackoverflow_0002062368_list_python.txt |
Q:
After doing a SQLAlchemy update(), is there a way to get the changed values?
After calling update(), I know that the return value has a .rowcount attribute that will reveal how many rows were changed. Is there a way to get the actual new values that they were changed to?
For example, if I do the SQLAlchemy equivalent of:
UPDATE t SET x=x+1 WHERE y=z
...is there a way to get the new value for x? Or do I have to do a SELECT?
A:
The ResultProxy has two methods, last_updated_params() which returns a dictionary of every bind parameter value sent with the statement execution, as well as a collection postfetch_cols(), a list of columns for which an inline SQL expression was embedded in the UPDATE (for which you'd have to post-SELECT the values). These collections are only populated for single-statement executions, not "executemany" calls which pass multiple sets of parameters along.
| After doing a SQLAlchemy update(), is there a way to get the changed values? | After calling update(), I know that the return value has a .rowcount attribute that will reveal how many rows were changed. Is there a way to get the actual new values that they were changed to?
For example, if I do the SQLAlchemy equivalent of:
UPDATE t SET x=x+1 WHERE y=z
...is there a way to get the new value for x? Or do I have to do a SELECT?
| [
"The ResultProxy has two methods, last_updated_params() which returns a dictionary of every bind parameter value sent with the statement execution, as well as a collection postfetch_cols(), a list of columns for which an inline SQL expression was embedded in the UPDATE (for which you'd have to post-SELECT the values). These collections are only populated for single-statement executions, not \"executemany\" calls which pass multiple sets of parameters along.\n"
] | [
3
] | [] | [] | [
"python",
"sql",
"sqlalchemy"
] | stackoverflow_0002059315_python_sql_sqlalchemy.txt |
Q:
How to use "class" the word as parameter function calls in python
I am writing an XML generator per my manager's request. For less typings' sake, I decided using ElementTree as parser and SimpleXMLWriter as writer.
The result XML require attributes named "class". e.g.
<Node class="oops"></Node>
As the official tutorial suggested, to write an XML node just use this method:
w.element("meta", name="generator", value="my application 1.0")
So I wrote:
w.element("Node", class="oops")
python fails yawning SyntaxError. Any help?
A:
I guess SimpleXMLWriter developers meant this solution:
w.element("Node", None, {'class': 'oops'})
or
w.element("Node", attrib={'class': 'oops'})
A:
What steveha has written is true. As in any language, keywords can't be used for different purposes.
What you can do, if you must use "class" is this:
w.element("Node", **{'class': 'oops'})
A:
class is a reserved word in Python. You just can't use it for a variable name, any more than you can have a variable called class in C++.
The usual abbreviation for class is either klass or cls.
Here is an official list of reserved words in Python:
http://docs.python.org/reference/lexical_analysis.html#keywords
| How to use "class" the word as parameter function calls in python | I am writing an XML generator per my manager's request. For less typings' sake, I decided using ElementTree as parser and SimpleXMLWriter as writer.
The result XML require attributes named "class". e.g.
<Node class="oops"></Node>
As the official tutorial suggested, to write an XML node just use this method:
w.element("meta", name="generator", value="my application 1.0")
So I wrote:
w.element("Node", class="oops")
python fails yawning SyntaxError. Any help?
| [
"I guess SimpleXMLWriter developers meant this solution:\nw.element(\"Node\", None, {'class': 'oops'})\n\nor \nw.element(\"Node\", attrib={'class': 'oops'})\n\n",
"What steveha has written is true. As in any language, keywords can't be used for different purposes.\nWhat you can do, if you must use \"class\" is this:\nw.element(\"Node\", **{'class': 'oops'})\n\n",
"class is a reserved word in Python. You just can't use it for a variable name, any more than you can have a variable called class in C++.\nThe usual abbreviation for class is either klass or cls.\nHere is an official list of reserved words in Python:\nhttp://docs.python.org/reference/lexical_analysis.html#keywords\n"
] | [
7,
5,
3
] | [] | [] | [
"elementtree",
"python"
] | stackoverflow_0002062683_elementtree_python.txt |
Q:
if there any better way to read bb function souce code.i was very faint
in python ,if
a.py
from b import bb
bb()
b.py
from c import cc
def bb():
do someting else
cc()
c.py
from d import dd
def cc():
do someting else
dd()
d.py
from e import ee
def dd():
do someting else
ee()
e.py
from f import ff
def ee():
do someting else
ff()
to Understood bb function,i must open 5 file,i was very faint .
if there any better way to read bb function.(a tools to read source code better)
thanks
A:
The best way to import the ff function from the f module would be to use an import statement in your program:
from f import ff
ff(...)
Or you could use the form:
import f
f.ff(...)
EDIT:
If you are looking for tools to better read/navigate through the source code, I recommend creating a tags file for your source code tree (using either ctags or ptags.py).
You then point a capable editor (like Vim or Emacs) to that file, and use the editor's features to navigate your way through the code. For instance, using Vim, Ctrl-] jumps to the definition of the symbol under the cursor.
What editor are you using?
A:
Whoever wrote the code for file a.py should have just written
a.py
from f import ff
I mean isn't that what OO and modules are supposed to do: make code reusable?
Or maybe this is an example of obfuscation by tiresomeness.
A:
If you're not already using an IDE, you might like to give bpython a try
| if there any better way to read bb function souce code.i was very faint | in python ,if
a.py
from b import bb
bb()
b.py
from c import cc
def bb():
do someting else
cc()
c.py
from d import dd
def cc():
do someting else
dd()
d.py
from e import ee
def dd():
do someting else
ee()
e.py
from f import ff
def ee():
do someting else
ff()
to Understood bb function,i must open 5 file,i was very faint .
if there any better way to read bb function.(a tools to read source code better)
thanks
| [
"The best way to import the ff function from the f module would be to use an import statement in your program:\nfrom f import ff\nff(...)\n\nOr you could use the form:\nimport f\nf.ff(...)\n\nEDIT:\nIf you are looking for tools to better read/navigate through the source code, I recommend creating a tags file for your source code tree (using either ctags or ptags.py). \nYou then point a capable editor (like Vim or Emacs) to that file, and use the editor's features to navigate your way through the code. For instance, using Vim, Ctrl-] jumps to the definition of the symbol under the cursor.\nWhat editor are you using?\n",
"Whoever wrote the code for file a.py should have just written\na.py\nfrom f import ff\nI mean isn't that what OO and modules are supposed to do: make code reusable?\nOr maybe this is an example of obfuscation by tiresomeness.\n",
"If you're not already using an IDE, you might like to give bpython a try\n"
] | [
2,
0,
0
] | [] | [] | [
"python"
] | stackoverflow_0002048163_python.txt |
Q:
Why scipy.io.wavfile.read does not return a tuple?
I am trying to read a *.wav file using scipy. I do the following:
import scipy
x = scipy.io.wavfile.read('/usr/share/sounds/purple/receive.wav')
As a result of this code I get:
Traceback (most recent call last):
File "test3.py", line 2, in <module>
x = scipy.io.wavfile.read('/usr/share/sounds/purple/receive.wav')
AttributeError: 'module' object has no attribute 'io'
Does anybody know what is wrong here? Thank you in advance.
A:
As the error says, scipy module does not have 'io'.
io.wavfile is a submodule, you need to from scipy.io import wavfile and then do wavfile.read("/usr/share/sounds/purple/receive.wav")
This gives me an error with the file you are using as an example, however...
| Why scipy.io.wavfile.read does not return a tuple? | I am trying to read a *.wav file using scipy. I do the following:
import scipy
x = scipy.io.wavfile.read('/usr/share/sounds/purple/receive.wav')
As a result of this code I get:
Traceback (most recent call last):
File "test3.py", line 2, in <module>
x = scipy.io.wavfile.read('/usr/share/sounds/purple/receive.wav')
AttributeError: 'module' object has no attribute 'io'
Does anybody know what is wrong here? Thank you in advance.
| [
"As the error says, scipy module does not have 'io'.\nio.wavfile is a submodule, you need to from scipy.io import wavfile and then do wavfile.read(\"/usr/share/sounds/purple/receive.wav\")\nThis gives me an error with the file you are using as an example, however...\n"
] | [
8
] | [] | [] | [
"python",
"scipy",
"wav"
] | stackoverflow_0002063046_python_scipy_wav.txt |
Q:
python windows vista/7 uac and copying (only reading) files? permissions/interaction of UAC?
I'm currently making a program for a lan center that scans a users hard drive, and copies/archives certain save game files into a zip and uploads them to a FTP server. But I've created a lot of the program at this point and just had a major issue that I had not tested for spring to mind:
How does Vista/7's UAC permissions account for copying of these save game files? - As far as I'm aware, if a program tries to save a game to the C:\Program Files directory, it catches the call, redirects the file to another folder meant for such changes...the C:\Users directory as I recall?
So if this is the case, if my python program tries to copy from the c:\Program Files directory, will it also redirect and copy the appropriate information where applicable? Will I need to somehow invoke UAC to get folder permissions for a read-only event? I've tried googling the info for the workings of UAC but my google-fu isn't exactly up to par lately. Am I going to need to write an entirely new section of code to work around UAC or will it "just work™"?
IF it's not going to "just work™" what am I going to need to do to get permissions to access the files I need to copy/archive? I'm asking primarily because I don't have a vista/7 install to test against. =/
A:
If your program is running as elevated admin, then it will not redirect to c:\users folder.
You can run the program as elevated admin by embedding a manifest to the file.
see http://en.wikipedia.org/wiki/User_Account_Control
for details on tasks that trigger the UAC prompt.
Also note that 64 bit Windows 7 does not support File System Redirection.
| python windows vista/7 uac and copying (only reading) files? permissions/interaction of UAC? | I'm currently making a program for a lan center that scans a users hard drive, and copies/archives certain save game files into a zip and uploads them to a FTP server. But I've created a lot of the program at this point and just had a major issue that I had not tested for spring to mind:
How does Vista/7's UAC permissions account for copying of these save game files? - As far as I'm aware, if a program tries to save a game to the C:\Program Files directory, it catches the call, redirects the file to another folder meant for such changes...the C:\Users directory as I recall?
So if this is the case, if my python program tries to copy from the c:\Program Files directory, will it also redirect and copy the appropriate information where applicable? Will I need to somehow invoke UAC to get folder permissions for a read-only event? I've tried googling the info for the workings of UAC but my google-fu isn't exactly up to par lately. Am I going to need to write an entirely new section of code to work around UAC or will it "just work™"?
IF it's not going to "just work™" what am I going to need to do to get permissions to access the files I need to copy/archive? I'm asking primarily because I don't have a vista/7 install to test against. =/
| [
"If your program is running as elevated admin, then it will not redirect to c:\\users folder. \nYou can run the program as elevated admin by embedding a manifest to the file.\nsee http://en.wikipedia.org/wiki/User_Account_Control\nfor details on tasks that trigger the UAC prompt.\nAlso note that 64 bit Windows 7 does not support File System Redirection.\n"
] | [
0
] | [] | [] | [
"python",
"uac",
"windows_7",
"windows_vista"
] | stackoverflow_0002060672_python_uac_windows_7_windows_vista.txt |
Q:
Cambodian keyboard for Windows and Linux?
Before I created http://khmerlc.org/khmerkeyweb/ with javascript that allow user input
cambodia unicode user can switch from English to khmer(cambodia)
I am going to build an application called khmerkey for desktop (both can run window,linux).
I will use python.
the User interface it's very simple, just:
With two options(allow user to switch from khmer to english) or access switch by shortcut key.
Anybody know any informations related to my goal.
Is it easy to deploy it with python ( some tips)?
Reference:
Unicode_chart_Khmer
http://en.wikipedia.org/wiki/Template:Unicode_chart_Khmer
http://www.unicode.org/charts/PDF/U1780.pdf
Thanks
A:
Hooking keys and sendkeys is different way for Windows and Linux, so you have to do it seperately.
In Windows, you can use combination of PyHook and SendKeys
For Linux, I have no idea now, I will update this when I found something.
| Cambodian keyboard for Windows and Linux? | Before I created http://khmerlc.org/khmerkeyweb/ with javascript that allow user input
cambodia unicode user can switch from English to khmer(cambodia)
I am going to build an application called khmerkey for desktop (both can run window,linux).
I will use python.
the User interface it's very simple, just:
With two options(allow user to switch from khmer to english) or access switch by shortcut key.
Anybody know any informations related to my goal.
Is it easy to deploy it with python ( some tips)?
Reference:
Unicode_chart_Khmer
http://en.wikipedia.org/wiki/Template:Unicode_chart_Khmer
http://www.unicode.org/charts/PDF/U1780.pdf
Thanks
| [
"Hooking keys and sendkeys is different way for Windows and Linux, so you have to do it seperately.\nIn Windows, you can use combination of PyHook and SendKeys\nFor Linux, I have no idea now, I will update this when I found something.\n"
] | [
1
] | [] | [] | [
"python"
] | stackoverflow_0002063412_python.txt |
Q:
python lotus notes: odbc connect error
I am developing a client server application for a cross-database system.
I am using Eclipse IDE with Python 2.5 and PyODBC2.5; need to read content from a Lotus Notes database, so run some basic query like - SELECT peronname FROM tablename.
'import pyodbc' is ok - python see it!
But when I try to run
conn = pyodbc.connect("DRIVER={Lotus NotesSQL Driver};SERVER=localhost;UID=John
Meyer;PWD=yellowbird;DATABASE=mydb.nsf")
it gives the error
pyodbc.Error: ('IM002', '[IM002] [Microsoft][ODBC Driver Manager] Data
source name not found and no default driver specified (0) (SQLDriverConnectW)')
[01S00] [Microsoft][ODBC Driver Manager] Invalid connection string attribute (0)
Any suggestions - what should be missing here? All comments and suggestions are highly appreciated.
A:
I think it's odd that you want to try accessing Lotus Notes data vie SQL. When I have interfaced Notes and Python in the past, I always used the Lotus Note COM object to access data. After all, Notes is a document database like CouchDB, not a relational database.
A:
I almost forgot to post the solution here...
We have managed to put NotesSQL to work through ODBC with python to access data from our Lotus Notes *.NSF files (database). It works as queries using the same type of queries syntax you would need normally use to get the data when working on MS-Access to grab the info inside the Lotus Notes *.nsf file.
So we got access to the data via SQL using ODBC.
| python lotus notes: odbc connect error | I am developing a client server application for a cross-database system.
I am using Eclipse IDE with Python 2.5 and PyODBC2.5; need to read content from a Lotus Notes database, so run some basic query like - SELECT peronname FROM tablename.
'import pyodbc' is ok - python see it!
But when I try to run
conn = pyodbc.connect("DRIVER={Lotus NotesSQL Driver};SERVER=localhost;UID=John
Meyer;PWD=yellowbird;DATABASE=mydb.nsf")
it gives the error
pyodbc.Error: ('IM002', '[IM002] [Microsoft][ODBC Driver Manager] Data
source name not found and no default driver specified (0) (SQLDriverConnectW)')
[01S00] [Microsoft][ODBC Driver Manager] Invalid connection string attribute (0)
Any suggestions - what should be missing here? All comments and suggestions are highly appreciated.
| [
"I think it's odd that you want to try accessing Lotus Notes data vie SQL. When I have interfaced Notes and Python in the past, I always used the Lotus Note COM object to access data. After all, Notes is a document database like CouchDB, not a relational database.\n",
"I almost forgot to post the solution here...\nWe have managed to put NotesSQL to work through ODBC with python to access data from our Lotus Notes *.NSF files (database). It works as queries using the same type of queries syntax you would need normally use to get the data when working on MS-Access to grab the info inside the Lotus Notes *.nsf file.\nSo we got access to the data via SQL using ODBC.\n"
] | [
0,
0
] | [] | [] | [
"connect",
"lotus",
"lotus_notes",
"odbc",
"python"
] | stackoverflow_0001610781_connect_lotus_lotus_notes_odbc_python.txt |
Q:
Accessing XML comment located before the root element
Please help me to resolve my problem with lxml.
How can I get "Comment 1" from this file?
<?xml version="1.0" encoding="windows-1251" standalone="yes" ?>
<!--Comment 1-->
<a>
<!--Comment 2-->
</a>
A:
Docs: the lxml tutorial, and search for "Comments"
Code:
import lxml.etree as et
text = """\
<?xml version="1.0" encoding="windows-1251" standalone="yes" ?>
<!--Comment 1a-->
<!--Comment 1b-->
<a> waffle
<!--Comment 2-->
blah blah
</a>
<!--Comment 3a-->
<!--Comment 3b-->
"""
print "\n=== %s ===" % et.__name__
root = et.fromstring(text)
for pre in (True, False):
for comment in root.itersiblings(tag=et.Comment, preceding=pre):
print pre, comment
for elem in root.iter():
print
print isinstance(elem.tag, basestring), elem.__class__.__name__, repr(elem.tag), repr(elem.text), repr(elem.tail)
Output:
=== lxml.etree ===
True <!--Comment 1b-->
True <!--Comment 1a-->
False <!--Comment 3a-->
False <!--Comment 3b-->
True _Element 'a' ' waffle\n ' None
False _Comment <built-in function Comment> 'Comment 2' '\n blah blah\n'
Comments: doesn't work with xml.etree.cElementTree
A:
>>> from lxml import etree
>>> tree = etree.parse('filename.xml')
>>> root = tree.getroot()
>>> print root.getprevious()
<!--Comment 1-->
Or to be sure (there might be more than one):
>>> for i in root.itersiblings(tag=etree.Comment, preceding=True):
... print i
...
<!--Comment 1-->
Use the .text attribute if you want to extract the text of the comment.
| Accessing XML comment located before the root element | Please help me to resolve my problem with lxml.
How can I get "Comment 1" from this file?
<?xml version="1.0" encoding="windows-1251" standalone="yes" ?>
<!--Comment 1-->
<a>
<!--Comment 2-->
</a>
| [
"Docs: the lxml tutorial, and search for \"Comments\"\nCode:\nimport lxml.etree as et\n\ntext = \"\"\"\\\n<?xml version=\"1.0\" encoding=\"windows-1251\" standalone=\"yes\" ?>\n<!--Comment 1a-->\n<!--Comment 1b-->\n<a> waffle\n <!--Comment 2-->\n blah blah\n</a>\n<!--Comment 3a-->\n<!--Comment 3b-->\n\"\"\"\nprint \"\\n=== %s ===\" % et.__name__\nroot = et.fromstring(text)\n\nfor pre in (True, False):\n for comment in root.itersiblings(tag=et.Comment, preceding=pre):\n print pre, comment\n\nfor elem in root.iter():\n print\n print isinstance(elem.tag, basestring), elem.__class__.__name__, repr(elem.tag), repr(elem.text), repr(elem.tail)\n\nOutput:\n=== lxml.etree ===\nTrue <!--Comment 1b-->\nTrue <!--Comment 1a-->\nFalse <!--Comment 3a-->\nFalse <!--Comment 3b-->\n\nTrue _Element 'a' ' waffle\\n ' None\n\nFalse _Comment <built-in function Comment> 'Comment 2' '\\n blah blah\\n'\n\nComments: doesn't work with xml.etree.cElementTree\n",
">>> from lxml import etree\n>>> tree = etree.parse('filename.xml')\n>>> root = tree.getroot()\n>>> print root.getprevious()\n<!--Comment 1-->\n\nOr to be sure (there might be more than one):\n>>> for i in root.itersiblings(tag=etree.Comment, preceding=True):\n... print i\n...\n<!--Comment 1-->\n\nUse the .text attribute if you want to extract the text of the comment.\n"
] | [
11,
6
] | [] | [] | [
"comments",
"lxml",
"python",
"xml"
] | stackoverflow_0002063274_comments_lxml_python_xml.txt |
Q:
Qt Python: QTextEdit - display input
I have a QTextEdit... it works with 'clear()' when a pushbutton calls 'CleanComments' to clean the input done by the user. Here is the code:
def CleanComments(self):
self.textEditInput.clear()
def showInput(self):
print "show input: %s" % self.textEditInput.show()
def buildEditInput(self):
self.textEditInput = QtGui.QTextEdit(self.boxForm)
self.textEditInput.setGeometry(QtCore.QRect(10, 300, 500, 100))
The only problem is, that when 'showInput' is called to display the content on QTextEdit using "show()", it gives "" show input: 'None' "". So, what is missing here?
All comments and suggestions are highly appreciated.
A:
To get the contents of a QTextEdit as a simple string, use the toPlainText() method.
print "show input: %s" % self.textEditInput.toPlainText()
There is also the toHtml() method. For even more options, you can work directly with the QTextDocument from QTextEdit.document().
A:
Your showInput method is printing the return from the show() method, which returns None. If you want to print the current text in the edit, use:
print "show input: %s" % self.textEditInput.text()
A:
Method show from widget is used to display the widget on a screen. For example if you have main window, you call show to display it to user. If you wish to retrieve data from some edit, be it line edit or text edit, you should use text() method. Like this:
def showInput(self):
print "show input: %s" % self.textEditInput.text()
| Qt Python: QTextEdit - display input | I have a QTextEdit... it works with 'clear()' when a pushbutton calls 'CleanComments' to clean the input done by the user. Here is the code:
def CleanComments(self):
self.textEditInput.clear()
def showInput(self):
print "show input: %s" % self.textEditInput.show()
def buildEditInput(self):
self.textEditInput = QtGui.QTextEdit(self.boxForm)
self.textEditInput.setGeometry(QtCore.QRect(10, 300, 500, 100))
The only problem is, that when 'showInput' is called to display the content on QTextEdit using "show()", it gives "" show input: 'None' "". So, what is missing here?
All comments and suggestions are highly appreciated.
| [
"To get the contents of a QTextEdit as a simple string, use the toPlainText() method.\nprint \"show input: %s\" % self.textEditInput.toPlainText()\n\nThere is also the toHtml() method. For even more options, you can work directly with the QTextDocument from QTextEdit.document().\n",
"Your showInput method is printing the return from the show() method, which returns None. If you want to print the current text in the edit, use:\nprint \"show input: %s\" % self.textEditInput.text()\n\n",
"Method show from widget is used to display the widget on a screen. For example if you have main window, you call show to display it to user. If you wish to retrieve data from some edit, be it line edit or text edit, you should use text() method. Like this:\ndef showInput(self):\n print \"show input: %s\" % self.textEditInput.text()\n\n"
] | [
5,
0,
0
] | [] | [] | [
"python",
"qt",
"qtextedit"
] | stackoverflow_0002063633_python_qt_qtextedit.txt |
Q:
"Parseltongue": get Ruby to Speak a bit of Python?
Just for interest really - community wiki - how much Python can we get Ruby to understand ?
[ Probably be just as interesting to do the reverse as well].
The experiment (such as it is) perhaps to see how much can be written in Ruby-Cross-Python scripts that will result in identical outputs. The only 'cheat' I guess being allowed here is the too allow Ruby statements to precede the eventual 'common' script. [like the 'len' definition below].
For instance, this works in both:
a=[1,2,3]
mystring="hello"
bobby="hello"*3
epoch=1270123200
map={}
map['supamu']='egusu'
map['dedu']='paroto'
keys=map.keys()
values=map.values()
And doing this in Ruby:
class Object
def len(object)
object.size
end
end
class Object
def str(object)
object.to_s
end
end
Means this now works in both:
a=[1,2,3]
mystring="hello"
len(a)
len(mystring)
str(123)
I think the trouble will come with conditionals and loops, due to different syntax requirements. (the ':' at the end of Python lines for instance...)
A:
To answer the question fully would probably need a bit of analysis. The control structures in both languages are defined to make our lives easier and the codes more readable when we program, but they could be realised with methods like it was in smalltalk. Iterations and conditionals (except the "case" statement) similarly as it was described in this blog: Emulating Smalltalk’s Conditionals in Ruby. For example an "if" would look something like this:
(an_object.nil?).
if_true { puts "true" }.
if_false { puts "false" }
I would suggest to cope with the iteration and conditionals by creation of an extension of the objects in both languages, which define the control structures as methods. This way it would possible to write a code with control structures which run in both languages.
But there other things, which lays deeper in the language design, which would be harder to cope with. In python every instance variable is public, in ruby they are private. What are the differences in changing self..?
Maybe if we started to reduce and omit the syntactical things to method calls we would end up with a very simple syntax... with something similar to smalltalk.
| "Parseltongue": get Ruby to Speak a bit of Python? | Just for interest really - community wiki - how much Python can we get Ruby to understand ?
[ Probably be just as interesting to do the reverse as well].
The experiment (such as it is) perhaps to see how much can be written in Ruby-Cross-Python scripts that will result in identical outputs. The only 'cheat' I guess being allowed here is the too allow Ruby statements to precede the eventual 'common' script. [like the 'len' definition below].
For instance, this works in both:
a=[1,2,3]
mystring="hello"
bobby="hello"*3
epoch=1270123200
map={}
map['supamu']='egusu'
map['dedu']='paroto'
keys=map.keys()
values=map.values()
And doing this in Ruby:
class Object
def len(object)
object.size
end
end
class Object
def str(object)
object.to_s
end
end
Means this now works in both:
a=[1,2,3]
mystring="hello"
len(a)
len(mystring)
str(123)
I think the trouble will come with conditionals and loops, due to different syntax requirements. (the ':' at the end of Python lines for instance...)
| [
"To answer the question fully would probably need a bit of analysis. The control structures in both languages are defined to make our lives easier and the codes more readable when we program, but they could be realised with methods like it was in smalltalk. Iterations and conditionals (except the \"case\" statement) similarly as it was described in this blog: Emulating Smalltalk’s Conditionals in Ruby. For example an \"if\" would look something like this:\n(an_object.nil?).\n if_true { puts \"true\" }.\n if_false { puts \"false\" }\n\nI would suggest to cope with the iteration and conditionals by creation of an extension of the objects in both languages, which define the control structures as methods. This way it would possible to write a code with control structures which run in both languages.\nBut there other things, which lays deeper in the language design, which would be harder to cope with. In python every instance variable is public, in ruby they are private. What are the differences in changing self..?\nMaybe if we started to reduce and omit the syntactical things to method calls we would end up with a very simple syntax... with something similar to smalltalk.\n"
] | [
1
] | [] | [] | [
"multilingual",
"python",
"ruby"
] | stackoverflow_0002063962_multilingual_python_ruby.txt |
Q:
Executing python code from script and getting interpreter-style output
I need to execute code from my python script and take interpreter-style output like it's done here.
I am creating website on GAE using django, it must run user-entered code and print interpreter-style output as text.
A:
there is code.InteractiveInterpreter available, but I think you can take an inspiration in the following simpler example:
import code
exprs = [
'd = {}',
'd',
'd["x"] = 1',
'd',
]
for e in exprs:
print '>>> %s' % e
cmd = code.compile_command(e)
r = eval(cmd)
if r:
print repr(r)
producing the following output:
>>> d = {}
>>> d
{}
>>> d["x"] = 1
>>> d
{'x': 1}
A:
There is an open-source console for app engine that does what you want (if I understood the question correctly). Have a look at it: http://con.appspot.com/console/
Instructions to integrate it with your application are available here.
| Executing python code from script and getting interpreter-style output | I need to execute code from my python script and take interpreter-style output like it's done here.
I am creating website on GAE using django, it must run user-entered code and print interpreter-style output as text.
| [
"there is code.InteractiveInterpreter available, but I think you can take an inspiration in the following simpler example:\nimport code\n\nexprs = [\n 'd = {}',\n 'd',\n 'd[\"x\"] = 1',\n 'd',\n ]\n\nfor e in exprs:\n print '>>> %s' % e\n cmd = code.compile_command(e)\n r = eval(cmd)\n if r:\n print repr(r)\n\nproducing the following output:\n>>> d = {}\n>>> d\n{}\n>>> d[\"x\"] = 1\n>>> d\n{'x': 1}\n\n",
"There is an open-source console for app engine that does what you want (if I understood the question correctly). Have a look at it: http://con.appspot.com/console/\nInstructions to integrate it with your application are available here.\n"
] | [
1,
0
] | [] | [] | [
"python"
] | stackoverflow_0002064491_python.txt |
Q:
Python not all in operation
How do I check if a list is a subset of a bigger list.
i.e.
a = [1,2,3] is a subset of b = [1,2,3,4,5,6]
Can I do something like
if a all in b
A:
http://docs.python.org/library/stdtypes.html#set.issubset
set(a).issubset(set(b))
A:
>>> a = set([1, 2, 3])
>>> b = set([1, 2, 3, 4, 5, 6])
>>> a.issubset(b)
True
or
>>> a = [1, 2, 3]
>>> b = [1, 2, 3, 4, 5, 6]
>>> all(map(lambda x: x in b, a))
True
>>> a = [1, 2, 3, 9]
>>> all(map(lambda x: x in b, a))
False
or (if the number of elements is important)
>>> a = [1, 1, 2, 3]
>>> all(map(lambda x: a.count(x) <= b.count(x), a))
False
A:
mostly like the other answers, but I do prefer the generator syntax here, seems more natural and it's lazily evaluated:
if all(x in b for x in a):
pass
if you care about the number of repeated elements, this option seems nice, and you could optimize it sorting c and using bisect:
def all_in(a, b)
try:
c = b[:]
for x in a: c.remove[x]
return True
except:
return False
| Python not all in operation | How do I check if a list is a subset of a bigger list.
i.e.
a = [1,2,3] is a subset of b = [1,2,3,4,5,6]
Can I do something like
if a all in b
| [
"http://docs.python.org/library/stdtypes.html#set.issubset\nset(a).issubset(set(b))\n\n",
">>> a = set([1, 2, 3])\n>>> b = set([1, 2, 3, 4, 5, 6])\n>>> a.issubset(b)\nTrue\n\nor\n>>> a = [1, 2, 3]\n>>> b = [1, 2, 3, 4, 5, 6]\n>>> all(map(lambda x: x in b, a))\nTrue\n>>> a = [1, 2, 3, 9]\n>>> all(map(lambda x: x in b, a))\nFalse\n\nor (if the number of elements is important)\n>>> a = [1, 1, 2, 3]\n>>> all(map(lambda x: a.count(x) <= b.count(x), a))\nFalse\n\n",
"mostly like the other answers, but I do prefer the generator syntax here, seems more natural and it's lazily evaluated:\nif all(x in b for x in a):\n pass\n\nif you care about the number of repeated elements, this option seems nice, and you could optimize it sorting c and using bisect:\ndef all_in(a, b)\n try:\n c = b[:]\n for x in a: c.remove[x]\n return True\n except:\n return False\n\n"
] | [
12,
5,
2
] | [] | [] | [
"python",
"set"
] | stackoverflow_0002064389_python_set.txt |
Q:
multiprocessing.Process subclass works on Linux but not Windows
I'm trying to get python-gasp working on Windows, but when I do import gasp; gasp.begin_graphics() I get the following traceback:
File "C:\Python26\lib\site-packages\gasp\backend.py", line 142, in create_screen
screen.updater.start()
File "C:\Python26\lib\multiprocessing\process.py", line 104, in start
self._popen = Popen(self)
File "C:\Python26\lib\multiprocessing\forking.py", line 239, in __init__
dump(process_obj, to_child, HIGHEST_PROTOCOL)
File "C:\Python26\lib\multiprocessing\forking.py", line 162, in dump
ForkingPickler(file, protocol).dump(obj)
File "C:\Python26\lib\pickle.py", line 224, in dump
self.save(obj)
File "C:\Python26\lib\pickle.py", line 331, in save
self.save_reduce(obj=obj, *rv)
File "C:\Python26\lib\pickle.py", line 419, in save_reduce
save(state)
File "C:\Python26\lib\pickle.py", line 286, in save
f(self, obj) # Call unbound method with explicit self
File "C:\Python26\lib\pickle.py", line 649, in save_dict
self._batch_setitems(obj.iteritems())
File "C:\Python26\lib\pickle.py", line 681, in _batch_setitems
save(v)
File "C:\Python26\lib\pickle.py", line 286, in save
f(self, obj) # Call unbound method with explicit self
File "C:\Python26\lib\pickle.py", line 725, in save_inst
save(stuff)
File "C:\Python26\lib\pickle.py", line 286, in save
f(self, obj) # Call unbound method with explicit self
File "C:\Python26\lib\pickle.py", line 649, in save_dict
self._batch_setitems(obj.iteritems())
File "C:\Python26\lib\pickle.py", line 681, in _batch_setitems
save(v)
File "C:\Python26\lib\pickle.py", line 331, in save
self.save_reduce(obj=obj, *rv)
File "C:\Python26\lib\pickle.py", line 396, in save_reduce
save(cls)
File "C:\Python26\lib\pickle.py", line 286, in save
f(self, obj) # Call unbound method with explicit self
File "C:\Python26\lib\pickle.py", line 748, in save_global
(obj, module, name))
PicklingError: Can't pickle <class 'multiprocessing.process._MainProcess'>: it's not found as multiprocessing.process._MainProcess
Any idea why I'm getting this error on Windows XP but not on Ubuntu Linux 9.04?
It looks like screen.updater is an instance of Updater(multiprocessing.Process) (def), if that helps. The file in question is at http://bazaar.launchpad.net/~gasp-dev/gasp-core/main/annotate/head%3A/gasp/backend.py
A:
Your Updater class has a member screen, which itself has a member process which receives the value of multiprocessing.current_process().
When you call updater.start(), it tries to pickle the updater. This only happens on Windows because Linux uses fork() instead of pickling. However, the current-process object cannot be pickled and the exception is raised.
To fix this, you can remove the process member.
| multiprocessing.Process subclass works on Linux but not Windows | I'm trying to get python-gasp working on Windows, but when I do import gasp; gasp.begin_graphics() I get the following traceback:
File "C:\Python26\lib\site-packages\gasp\backend.py", line 142, in create_screen
screen.updater.start()
File "C:\Python26\lib\multiprocessing\process.py", line 104, in start
self._popen = Popen(self)
File "C:\Python26\lib\multiprocessing\forking.py", line 239, in __init__
dump(process_obj, to_child, HIGHEST_PROTOCOL)
File "C:\Python26\lib\multiprocessing\forking.py", line 162, in dump
ForkingPickler(file, protocol).dump(obj)
File "C:\Python26\lib\pickle.py", line 224, in dump
self.save(obj)
File "C:\Python26\lib\pickle.py", line 331, in save
self.save_reduce(obj=obj, *rv)
File "C:\Python26\lib\pickle.py", line 419, in save_reduce
save(state)
File "C:\Python26\lib\pickle.py", line 286, in save
f(self, obj) # Call unbound method with explicit self
File "C:\Python26\lib\pickle.py", line 649, in save_dict
self._batch_setitems(obj.iteritems())
File "C:\Python26\lib\pickle.py", line 681, in _batch_setitems
save(v)
File "C:\Python26\lib\pickle.py", line 286, in save
f(self, obj) # Call unbound method with explicit self
File "C:\Python26\lib\pickle.py", line 725, in save_inst
save(stuff)
File "C:\Python26\lib\pickle.py", line 286, in save
f(self, obj) # Call unbound method with explicit self
File "C:\Python26\lib\pickle.py", line 649, in save_dict
self._batch_setitems(obj.iteritems())
File "C:\Python26\lib\pickle.py", line 681, in _batch_setitems
save(v)
File "C:\Python26\lib\pickle.py", line 331, in save
self.save_reduce(obj=obj, *rv)
File "C:\Python26\lib\pickle.py", line 396, in save_reduce
save(cls)
File "C:\Python26\lib\pickle.py", line 286, in save
f(self, obj) # Call unbound method with explicit self
File "C:\Python26\lib\pickle.py", line 748, in save_global
(obj, module, name))
PicklingError: Can't pickle <class 'multiprocessing.process._MainProcess'>: it's not found as multiprocessing.process._MainProcess
Any idea why I'm getting this error on Windows XP but not on Ubuntu Linux 9.04?
It looks like screen.updater is an instance of Updater(multiprocessing.Process) (def), if that helps. The file in question is at http://bazaar.launchpad.net/~gasp-dev/gasp-core/main/annotate/head%3A/gasp/backend.py
| [
"Your Updater class has a member screen, which itself has a member process which receives the value of multiprocessing.current_process().\nWhen you call updater.start(), it tries to pickle the updater. This only happens on Windows because Linux uses fork() instead of pickling. However, the current-process object cannot be pickled and the exception is raised.\nTo fix this, you can remove the process member.\n"
] | [
2
] | [] | [] | [
"gasp",
"multiprocessing",
"pickle",
"python",
"windows"
] | stackoverflow_0002064533_gasp_multiprocessing_pickle_python_windows.txt |
Q:
Using wget with subprocess
I'm trying to use wget with subprocess.
my attempts worked until I tried to download the page to a specified directory with this code:
url = 'google.com'
location = '/home/patrick/downloads'
args = ['wget', 'r', 'l 1' 'p' 'P %s' % location, url]
output = Popen(args, stdout=PIPE)
if I run this code in /home/patrick I get index.html in /home/patrick and not in /home/patrick/downloads.
Can you help me?
Thanks ;)
A:
You need to have hyphens and location should be just another argument:
args = ['wget', '-r', '-l', '1', '-p', '-P', location, url]
A:
Edit: popen from os intends to replace os.popen module. Hence, using os.popen is not recommended
Initially I thought it was popen from os.
If you are using popen from os
#wget 'http://google.com/' -r -l 1 -p -P /Users/abhinay/Downloads
from os import popen
url = 'google.com'
location = '/Users/abhinay/Downloads'
args = ['wget %s', '-r', '-l 1', '-p', '-P %s' % location, url]
output = popen(' '.join(args))
and using Popen from subprocess
#wget 'http://google.com/' -r -l 1 -p -P Downloads/google
from subprocess import Popen
url = 'google.com'
location = '/Users/abhinay/Downloads'
#as suggested by @SilentGhost the `location` and `url` should be separate argument
args = ['wget', '-r', '-l', '1', '-p', '-P', location, url]
output = Popen(args, stdout=PIPE)
Let me know if I'm missing something.
Thx!
| Using wget with subprocess | I'm trying to use wget with subprocess.
my attempts worked until I tried to download the page to a specified directory with this code:
url = 'google.com'
location = '/home/patrick/downloads'
args = ['wget', 'r', 'l 1' 'p' 'P %s' % location, url]
output = Popen(args, stdout=PIPE)
if I run this code in /home/patrick I get index.html in /home/patrick and not in /home/patrick/downloads.
Can you help me?
Thanks ;)
| [
"You need to have hyphens and location should be just another argument:\nargs = ['wget', '-r', '-l', '1', '-p', '-P', location, url]\n\n",
"Edit: popen from os intends to replace os.popen module. Hence, using os.popen is not recommended\nInitially I thought it was popen from os.\nIf you are using popen from os\n#wget 'http://google.com/' -r -l 1 -p -P /Users/abhinay/Downloads\n\nfrom os import popen\n\nurl = 'google.com'\nlocation = '/Users/abhinay/Downloads'\nargs = ['wget %s', '-r', '-l 1', '-p', '-P %s' % location, url]\n\noutput = popen(' '.join(args))\n\nand using Popen from subprocess\n#wget 'http://google.com/' -r -l 1 -p -P Downloads/google\n\nfrom subprocess import Popen\n\nurl = 'google.com'\nlocation = '/Users/abhinay/Downloads'\n#as suggested by @SilentGhost the `location` and `url` should be separate argument\nargs = ['wget', '-r', '-l', '1', '-p', '-P', location, url]\n\noutput = Popen(args, stdout=PIPE)\n\nLet me know if I'm missing something.\nThx!\n"
] | [
4,
0
] | [] | [] | [
"python",
"subprocess"
] | stackoverflow_0002065060_python_subprocess.txt |
Q:
UDP packet encryption
This appears to be reasonably trivial if using the ssl module for TCP communication, but how would encrypted communication be done via UDP?
Can the ssl module still be used? if so, what steps would need to be performed for the client and server to be in a position where data can be sent to-and-fro as normal?
A:
DTLS is a TLS (aka SSL) derivative designed for use over datagram transports, like UDP.
OpenSSL supports DTLS starting in 0.9.8, using DTLSv1_METHOD instead of SSLv23_METHOD or TLSv1_METHOD or similar.
A:
You could use pyCrypto or ezPyCrypto to manually encrypt/decrypt the packets.
| UDP packet encryption | This appears to be reasonably trivial if using the ssl module for TCP communication, but how would encrypted communication be done via UDP?
Can the ssl module still be used? if so, what steps would need to be performed for the client and server to be in a position where data can be sent to-and-fro as normal?
| [
"DTLS is a TLS (aka SSL) derivative designed for use over datagram transports, like UDP.\nOpenSSL supports DTLS starting in 0.9.8, using DTLSv1_METHOD instead of SSLv23_METHOD or TLSv1_METHOD or similar.\n",
"You could use pyCrypto or ezPyCrypto to manually encrypt/decrypt the packets.\n"
] | [
4,
1
] | [] | [] | [
"python",
"ssl",
"udp"
] | stackoverflow_0002065218_python_ssl_udp.txt |
Q:
How should Django Apps bundle static media?
Background:
I'm starting to use Django for the first time, which is also my first foray into web development. I just got stuck on the whole "serving static media" problem. After spending a while looking at all the documentation and StackOverflow questions, I think I understand how it's supposed to work (i.e. MEDIA_ROOT, MEDIA_URL, updating the urls file, etc).
My Question:
Ok, so here's the part I'm not sure about. Django applications are supposed to be "pluggable", i.e. I can move an application from one project to another. So, how should these applications bundle static media?
For example, let's say I have a "foo" application, which has templates that load some css/image files. Where am I supposed to put these files, so that they'll automatically get served once I include the application?
The only solution I see, is that installing an application has to include the extra step of copying its static media to some place on your own server that serves that media.
Is this the accepted way to do it? It includes an extra step, but maybe that's standard when dealing with web-dev (I'm new so I don't really know).
Also, if this is the way, is there a standard way to collect all my static media to make it easy to know what I need to serve? (I.e., is it standard to have a folder named "media" or something inside the app?).
Thanks,
A:
Convention is to put static media in either media/appname/ or static/appname/ within the app (similar to templates).
For using apps in your project that come with media, I strongly recommend using django-staticfiles. It will automatically serve media (including media within apps) in development through a view that replaces django.views.static.serve, and it comes with a build_static management command that will copy media from all apps into a single directory for serving in production.
Update: django-staticfiles has become part of Django 1.3. It now expects app media to live in a "static/" subdirectory of the app, not "media/". And the management command is now "collectstatic."
A:
The only app I know of that deals with this without any intervention is the rather wonderful django-debug-toolbar, though it's arguable that this isn't a great example, since it's an app specifically designed for debug mode only.
The way it deals with it is that it serves its media through Django itself - see the source for urls.py:
url(r'^%s/m/(.*)$' % _PREFIX, 'debug_toolbar.views.debug_media'),
In general, this is a bad idea (you don't want to serve static files through Django), per this comment from the documentation:
[Serving static files through Django] is inefficient and
insecure. Do not use this in a
production setting. Use this only for
development.
Obviously, the django-debug-toolbar is only used for development, so I think its method of deployment makes sense, but this is very much an exception.
In general, the best way I know to do it is to create symbolic links wherever your media is stored to the media inside your app code. For example, create a folder called media within your app, and then require users installing your app to either add a symbolic link from their media directory, or copy the whole thing.
A:
i usually put apps media in ./apps/appname/static (my apps resides in an apps subfolder)
then i have something similar in the vhost in apache :
AliasMatch ^/apps/([^/]+)/static/(.*) /home/django/projectname/apps/$1/static/$2
<DirectoryMatch "^/home/django/projectname/apps/([^/]+)/static/*">
Order deny,allow
Options -Indexes
deny from all
Options +FollowSymLinks
<FilesMatch "\.(flv|gif|jpg|jpeg|png|ico|swf|js|css|pdf|txt|htm|html|json)$">
allow from all
</FilesMatch>
</DirectoryMatch>
i also have this in my urls.py for dev server (use only for debug) :
def statics_wrapper(request, **dict):
from django.views import static
return static.serve(request, dict['path'], document_root = os.path.join(settings.BASE_DIR, 'apps', dict['app'], 'static'), show_indexes=True)
urlpatterns += patterns('', (r'^apps/(?P<app>[^/]+)/static/(?P<path>.+)$', statics_wrapper))
this is very handy because statics url are simply mapped to filesystem, eg :
http://wwww.ecample.com/apps/calendar/static/js/calendar.js resides in [BASE_DIR]/apps/calendar/static/js/calendar.js
hope this helps
| How should Django Apps bundle static media? | Background:
I'm starting to use Django for the first time, which is also my first foray into web development. I just got stuck on the whole "serving static media" problem. After spending a while looking at all the documentation and StackOverflow questions, I think I understand how it's supposed to work (i.e. MEDIA_ROOT, MEDIA_URL, updating the urls file, etc).
My Question:
Ok, so here's the part I'm not sure about. Django applications are supposed to be "pluggable", i.e. I can move an application from one project to another. So, how should these applications bundle static media?
For example, let's say I have a "foo" application, which has templates that load some css/image files. Where am I supposed to put these files, so that they'll automatically get served once I include the application?
The only solution I see, is that installing an application has to include the extra step of copying its static media to some place on your own server that serves that media.
Is this the accepted way to do it? It includes an extra step, but maybe that's standard when dealing with web-dev (I'm new so I don't really know).
Also, if this is the way, is there a standard way to collect all my static media to make it easy to know what I need to serve? (I.e., is it standard to have a folder named "media" or something inside the app?).
Thanks,
| [
"Convention is to put static media in either media/appname/ or static/appname/ within the app (similar to templates).\nFor using apps in your project that come with media, I strongly recommend using django-staticfiles. It will automatically serve media (including media within apps) in development through a view that replaces django.views.static.serve, and it comes with a build_static management command that will copy media from all apps into a single directory for serving in production.\nUpdate: django-staticfiles has become part of Django 1.3. It now expects app media to live in a \"static/\" subdirectory of the app, not \"media/\". And the management command is now \"collectstatic.\"\n",
"The only app I know of that deals with this without any intervention is the rather wonderful django-debug-toolbar, though it's arguable that this isn't a great example, since it's an app specifically designed for debug mode only.\nThe way it deals with it is that it serves its media through Django itself - see the source for urls.py:\nurl(r'^%s/m/(.*)$' % _PREFIX, 'debug_toolbar.views.debug_media'),\n\nIn general, this is a bad idea (you don't want to serve static files through Django), per this comment from the documentation:\n\n[Serving static files through Django] is inefficient and\n insecure. Do not use this in a\n production setting. Use this only for\n development.\n\nObviously, the django-debug-toolbar is only used for development, so I think its method of deployment makes sense, but this is very much an exception.\nIn general, the best way I know to do it is to create symbolic links wherever your media is stored to the media inside your app code. For example, create a folder called media within your app, and then require users installing your app to either add a symbolic link from their media directory, or copy the whole thing.\n",
"i usually put apps media in ./apps/appname/static (my apps resides in an apps subfolder)\nthen i have something similar in the vhost in apache :\nAliasMatch ^/apps/([^/]+)/static/(.*) /home/django/projectname/apps/$1/static/$2\n<DirectoryMatch \"^/home/django/projectname/apps/([^/]+)/static/*\">\n Order deny,allow\n Options -Indexes\n deny from all\n Options +FollowSymLinks\n <FilesMatch \"\\.(flv|gif|jpg|jpeg|png|ico|swf|js|css|pdf|txt|htm|html|json)$\">\n allow from all\n </FilesMatch>\n</DirectoryMatch>\n\ni also have this in my urls.py for dev server (use only for debug) :\ndef statics_wrapper(request, **dict):\n from django.views import static\n return static.serve(request, dict['path'], document_root = os.path.join(settings.BASE_DIR, 'apps', dict['app'], 'static'), show_indexes=True)\nurlpatterns += patterns('', (r'^apps/(?P<app>[^/]+)/static/(?P<path>.+)$', statics_wrapper))\n\nthis is very handy because statics url are simply mapped to filesystem, eg :\nhttp://wwww.ecample.com/apps/calendar/static/js/calendar.js resides in [BASE_DIR]/apps/calendar/static/js/calendar.js\nhope this helps\n"
] | [
9,
2,
2
] | [] | [] | [
"django",
"python",
"web_applications"
] | stackoverflow_0002063923_django_python_web_applications.txt |
Q:
Parsing, securing python expression before passing it to eval()
I want to take an input from the user may be like foo() > 90 and boo() == 9 or do() > 100 and use eval on the server side to to evaluate this expression.
For security I want to restrict user to add limited functions and operators by keeping a check (against some data-structure) before I pass it to eval function.
PS: Input comes from a web page
Thanks
A:
Basically the only way to do this is to parse it yourself. You navigate the parse tree to guarantee that each part is in a whitelist of perfectly benign and safe operations, making the entire expression safe by construction. Ned Batchelder's answer is actually a (simple) form of this. You could pass it to eval() after that, although, what would be the point? You could compute the value of each subexpression as part of verification (this is especially a good idea because it makes your parser resistant to changes in Python syntax and so on). This whitelist must be extremely tiny, and there are a lot of things that you might think are okay, but aren't (e.g. general call operator; getattr function). You have to be very careful.
A blacklist is absolutely out of the question (such as the suggestion to "reject suspicious entries"). Reject anything that is not obviously good. If you don't, it will be trivial to work around your filter and give an expression that does something bad, barring the unlikely possibility that your code is better than any other blacklisting filter for Python ever created.
There have been attempts at restricting Python execution, one is the infamous and now-disabled (because it didn't work) rexec module (and company), and another is PyPy's sandbox. This second option doesn't do exactly what you asked for, but it's certainly worth looking into. It's probably what I would use-- it just means that it won't be as easy as eval(safematize(user_input)).
A:
the more secure way is to do everything at the back end. Users just key in the necessary parameters. For example you can prompt them to key in numeric values for foo(), boo() and do(). Then at the back end, pass these values to appropriate functions to do the calculations.
A:
Perhaps the simplest check would be to look at all the words in the expression, and check them against a whitelist. Reject the expression if any of the words isn't on the whitelist.
import re
expr = "foo() > 90 and boo() == 9 or do() > 100"
whitelist = "and or foo boo do".split()
for word in re.findall(r"[a-zA-Z_]\w+", expr):
if word not in whitelist:
raise Exception("Warning! Warning!")
This works because you have a limited domain that you need users to be able to express themselves in, and also because I don't think there's a way to cause damage with eval without using identifiers.
You'll have to be careful that your whitelist doesn't inadvertently include possibly malicious Python identifiers, though.
A:
You need to lock down the input format, or it will be a gaping security hole. Either implement a full blown parser, as lpthnc suggests, with a reasonable set of operations (but no more), or at least use a regular expression (or several regex patterns in a matching hierarchy and/or loop) to strip out recognized patterns, and reject suspicious entries as "not allowed".
| Parsing, securing python expression before passing it to eval() | I want to take an input from the user may be like foo() > 90 and boo() == 9 or do() > 100 and use eval on the server side to to evaluate this expression.
For security I want to restrict user to add limited functions and operators by keeping a check (against some data-structure) before I pass it to eval function.
PS: Input comes from a web page
Thanks
| [
"Basically the only way to do this is to parse it yourself. You navigate the parse tree to guarantee that each part is in a whitelist of perfectly benign and safe operations, making the entire expression safe by construction. Ned Batchelder's answer is actually a (simple) form of this. You could pass it to eval() after that, although, what would be the point? You could compute the value of each subexpression as part of verification (this is especially a good idea because it makes your parser resistant to changes in Python syntax and so on). This whitelist must be extremely tiny, and there are a lot of things that you might think are okay, but aren't (e.g. general call operator; getattr function). You have to be very careful.\nA blacklist is absolutely out of the question (such as the suggestion to \"reject suspicious entries\"). Reject anything that is not obviously good. If you don't, it will be trivial to work around your filter and give an expression that does something bad, barring the unlikely possibility that your code is better than any other blacklisting filter for Python ever created.\nThere have been attempts at restricting Python execution, one is the infamous and now-disabled (because it didn't work) rexec module (and company), and another is PyPy's sandbox. This second option doesn't do exactly what you asked for, but it's certainly worth looking into. It's probably what I would use-- it just means that it won't be as easy as eval(safematize(user_input)).\n",
"the more secure way is to do everything at the back end. Users just key in the necessary parameters. For example you can prompt them to key in numeric values for foo(), boo() and do(). Then at the back end, pass these values to appropriate functions to do the calculations. \n",
"Perhaps the simplest check would be to look at all the words in the expression, and check them against a whitelist. Reject the expression if any of the words isn't on the whitelist.\nimport re\n\nexpr = \"foo() > 90 and boo() == 9 or do() > 100\"\nwhitelist = \"and or foo boo do\".split()\nfor word in re.findall(r\"[a-zA-Z_]\\w+\", expr):\n if word not in whitelist:\n raise Exception(\"Warning! Warning!\")\n\nThis works because you have a limited domain that you need users to be able to express themselves in, and also because I don't think there's a way to cause damage with eval without using identifiers.\nYou'll have to be careful that your whitelist doesn't inadvertently include possibly malicious Python identifiers, though.\n",
"You need to lock down the input format, or it will be a gaping security hole. Either implement a full blown parser, as lpthnc suggests, with a reasonable set of operations (but no more), or at least use a regular expression (or several regex patterns in a matching hierarchy and/or loop) to strip out recognized patterns, and reject suspicious entries as \"not allowed\".\n"
] | [
3,
1,
1,
1
] | [] | [] | [
"python"
] | stackoverflow_0002065331_python.txt |
Q:
how to avoid storing different type of objects in the same place when they represent the same but with a different data structure
This is in my opinion an abstract problem and I hope I can explain it well. I happened to find the same kind of problem in a completely different project and now I have it again and I would like to avoid it if possible.
I'm creating some classes to simplify some tasks for some specific requirements we have in some projects at work.
I have a class that creates objects which maps the values from webcontrols to an object properties similar to this
http://msdn.microsoft.com/en-us/library/aa478957.aspx
The problem I have it's sometimes I have to store a non container object in a place (in an object's attribute) and sometimes I have to a store a container object in the same place for storing the values of a webcontrol (a webcontrol can sometimes hold several values like a checkboxlist). I dont like this at all, because some time ago when working in a non commercial compiler, when parsing and generating the intermediate code I had sometimes to store a container in a place, and sometimes I had to store a non container in the same place, and having to ask in other parts of the code if what you are reading is this type of object, or this another type of object, it is something really annoying and it mess up the code. Is there any tips about what it would be better to do to avoid this kind of situations or nothing can be done to avoid it sometimes?
A:
I'm not sure I understand your question, but maybe Visitor pattern is what you are looking for?
A:
Sounds like composite pattern to me. Composite will provide an interface for treating containers of objects and leaf objects (those that are not containers) the same.
A:
This is the Polymorphism problem.
"sometimes I have to store a non container object in a ... an object's attribute and sometimes I have to a store a container object in the same place"
You have two things which should be made polymorphic.
The easiest way to fix this is to use a container always. When you want to store a single non-container object, you "wrap" it in a container that contains just the one object.
Then you always have containers. Sometimes the container has one object, sometimes it has more than one.
| how to avoid storing different type of objects in the same place when they represent the same but with a different data structure | This is in my opinion an abstract problem and I hope I can explain it well. I happened to find the same kind of problem in a completely different project and now I have it again and I would like to avoid it if possible.
I'm creating some classes to simplify some tasks for some specific requirements we have in some projects at work.
I have a class that creates objects which maps the values from webcontrols to an object properties similar to this
http://msdn.microsoft.com/en-us/library/aa478957.aspx
The problem I have it's sometimes I have to store a non container object in a place (in an object's attribute) and sometimes I have to a store a container object in the same place for storing the values of a webcontrol (a webcontrol can sometimes hold several values like a checkboxlist). I dont like this at all, because some time ago when working in a non commercial compiler, when parsing and generating the intermediate code I had sometimes to store a container in a place, and sometimes I had to store a non container in the same place, and having to ask in other parts of the code if what you are reading is this type of object, or this another type of object, it is something really annoying and it mess up the code. Is there any tips about what it would be better to do to avoid this kind of situations or nothing can be done to avoid it sometimes?
| [
"I'm not sure I understand your question, but maybe Visitor pattern is what you are looking for?\n",
"Sounds like composite pattern to me. Composite will provide an interface for treating containers of objects and leaf objects (those that are not containers) the same.\n",
"This is the Polymorphism problem.\n\"sometimes I have to store a non container object in a ... an object's attribute and sometimes I have to a store a container object in the same place\"\nYou have two things which should be made polymorphic.\nThe easiest way to fix this is to use a container always. When you want to store a single non-container object, you \"wrap\" it in a container that contains just the one object.\nThen you always have containers. Sometimes the container has one object, sometimes it has more than one.\n"
] | [
1,
1,
1
] | [] | [] | [
"algorithm",
"asp.net",
"design_patterns",
"ironpython",
"python"
] | stackoverflow_0002064284_algorithm_asp.net_design_patterns_ironpython_python.txt |
Q:
wxFrame with title bar but non resizable
hai guyz
I need to create a login window
for that window i need a title bar for dragging but it should not be a resized
I need a fixed size for this window
A:
frame = wx.Frame(self, title="something", size=(480, 320), style=wx.CAPTION)
You can "mix and match" styles, which can be seen here: http://docs.wxwidgets.org/2.6/wx_wxframe.html
e.g. in my example, no "close box" is shown, so:
frame = wx.Frame(self, title="something", size=(480, 320), style=wx.CAPTION | wx.CLOSE_BOX)
would fix it. (Note: you need wx.SOMETHING, not wxSOMETHING)
| wxFrame with title bar but non resizable | hai guyz
I need to create a login window
for that window i need a title bar for dragging but it should not be a resized
I need a fixed size for this window
| [
"frame = wx.Frame(self, title=\"something\", size=(480, 320), style=wx.CAPTION)\n\nYou can \"mix and match\" styles, which can be seen here: http://docs.wxwidgets.org/2.6/wx_wxframe.html\ne.g. in my example, no \"close box\" is shown, so:\nframe = wx.Frame(self, title=\"something\", size=(480, 320), style=wx.CAPTION | wx.CLOSE_BOX)\n\nwould fix it. (Note: you need wx.SOMETHING, not wxSOMETHING)\n"
] | [
4
] | [] | [] | [
"python",
"wxpython"
] | stackoverflow_0002064856_python_wxpython.txt |
Q:
Linear Fit to Planet Positions
An astounding alignment occurs 2048/5/28 with the inner 5 planets
having heliocentric longitudes (in degrees):
248.229, 66.631, 246.967, 249.605, 67.684.
The planets are at most 0.875 degrees from the line (through Sol)
with slope 67.823 degrees. In this case, the method sought (PA) would give:
PA(248.229, 66.631, 246.967, 249.605, 67.684) = (67.823, 0.875)
I have tried two simple algorithms which both fail on the case:
2003/9/9: 340.256, 180.320, 346.156, 342.316, 150.285
One method gives slope=127.867, deviation=51.019 and the other 271.867, 85.251.
I think a correct method would give s=163.466, d=7.515.
The main problem is that planets on opposite sides of Sol can be (nearly) on the same line.
Python or javascript appreciated.
Yay I figured out how to edit! Or not.
def score3(wList):
wSize = len(wList)
#print wList
first = wList[0]
d1 = first - 90.0
if d1 < 0.0: d1 += 360.0
d2 = first + 90.0
if d2 > 360.0: d1 -= 360.0
if d1 > d2: d1,d2 = d2,d1
sum = 0.0
for wx in range(0,wSize):
curr = wList[wx]
if (curr > d1) and (curr < d2):
new = curr
else:
new = (curr + 180.0) % 360.0
wList[wx] = new
sum += new
#print '%7.3f --> %7.3f' % (curr, new)
avg = sum / wSize
#print avg, wList
score = 0.0
for wx in range(0,wSize):
curr = wList[wx]
diff = curr - avg
if diff < 0: diff = - diff
score += diff
score /= wSize
return avg, score
A:
Dumb as dirt method didn't work for reasons that should have been obvious: your data can be pathological for any choice of half-plane to map to. I'm going to recommend a least squares approach, but you do need to deal with the radial ambiguity.
That means the function that you are looking to minimize is:
\sum (forceAngleIntoQuandrantI(a_i - A))^2
or something equivalent. That is, the planet can never lie more than 90 degrees from the proposed line.
Now, if you use a forcing routine like I showed initially (you can still find that in the edit history for this answer), the problem is no longer analytical and you'll have to use an iterative approach (see Bisection Method for a simple approach). Or you can note that sin^2(theta) is monotonically increasing in quadrants I,IV and symmetric about the +- 90 degree line and minimize
\sum sin^4(a_i - A)
without clipping using the analytical methods described in the MathWorld link (or look at wikipdia if you prefer).
| Linear Fit to Planet Positions | An astounding alignment occurs 2048/5/28 with the inner 5 planets
having heliocentric longitudes (in degrees):
248.229, 66.631, 246.967, 249.605, 67.684.
The planets are at most 0.875 degrees from the line (through Sol)
with slope 67.823 degrees. In this case, the method sought (PA) would give:
PA(248.229, 66.631, 246.967, 249.605, 67.684) = (67.823, 0.875)
I have tried two simple algorithms which both fail on the case:
2003/9/9: 340.256, 180.320, 346.156, 342.316, 150.285
One method gives slope=127.867, deviation=51.019 and the other 271.867, 85.251.
I think a correct method would give s=163.466, d=7.515.
The main problem is that planets on opposite sides of Sol can be (nearly) on the same line.
Python or javascript appreciated.
Yay I figured out how to edit! Or not.
def score3(wList):
wSize = len(wList)
#print wList
first = wList[0]
d1 = first - 90.0
if d1 < 0.0: d1 += 360.0
d2 = first + 90.0
if d2 > 360.0: d1 -= 360.0
if d1 > d2: d1,d2 = d2,d1
sum = 0.0
for wx in range(0,wSize):
curr = wList[wx]
if (curr > d1) and (curr < d2):
new = curr
else:
new = (curr + 180.0) % 360.0
wList[wx] = new
sum += new
#print '%7.3f --> %7.3f' % (curr, new)
avg = sum / wSize
#print avg, wList
score = 0.0
for wx in range(0,wSize):
curr = wList[wx]
diff = curr - avg
if diff < 0: diff = - diff
score += diff
score /= wSize
return avg, score
| [
"Dumb as dirt method didn't work for reasons that should have been obvious: your data can be pathological for any choice of half-plane to map to. I'm going to recommend a least squares approach, but you do need to deal with the radial ambiguity.\nThat means the function that you are looking to minimize is:\n\\sum (forceAngleIntoQuandrantI(a_i - A))^2\n\nor something equivalent. That is, the planet can never lie more than 90 degrees from the proposed line. \nNow, if you use a forcing routine like I showed initially (you can still find that in the edit history for this answer), the problem is no longer analytical and you'll have to use an iterative approach (see Bisection Method for a simple approach). Or you can note that sin^2(theta) is monotonically increasing in quadrants I,IV and symmetric about the +- 90 degree line and minimize\n\\sum sin^4(a_i - A) \n\nwithout clipping using the analytical methods described in the MathWorld link (or look at wikipdia if you prefer).\n"
] | [
0
] | [] | [] | [
"javascript",
"python"
] | stackoverflow_0002065550_javascript_python.txt |
Q:
Does Pythoncard have an on change event?
I want to do some validation whenever the value of a textfield changes. I don't see an on change event mentioned in the documentation though.
A:
Pythoncard is built on wxPython, and wxPython has a text change event. I know nothing about Pythoncard, but in wxPython one would use:
t1 = wx.TextCtrl(self, -1, "some text", size=(125, -1)) # to make the text control
self.Bind(wx.EVT_TEXT, self.OnText, t1) # your OnText method handles the event
For events, there's wx.EVT_TEXT, wx.EVT_CHAR, wx.EVT_TEXT_ENTER, and more details about these can be found in the wxPython docs, and also usage examples in the wxPython demo if you happen to have that. Also, wxPython has several types of the text entry controls, and I'm assuming that you're using the wxTextCtrl, though the docs should have info on the others as well.
A:
I think the textUpdate event is what your looking for.
http://pythoncard.sourceforge.net/framework/components/TextField.html
| Does Pythoncard have an on change event? | I want to do some validation whenever the value of a textfield changes. I don't see an on change event mentioned in the documentation though.
| [
"Pythoncard is built on wxPython, and wxPython has a text change event. I know nothing about Pythoncard, but in wxPython one would use:\n t1 = wx.TextCtrl(self, -1, \"some text\", size=(125, -1)) # to make the text control\n self.Bind(wx.EVT_TEXT, self.OnText, t1) # your OnText method handles the event\n\nFor events, there's wx.EVT_TEXT, wx.EVT_CHAR, wx.EVT_TEXT_ENTER, and more details about these can be found in the wxPython docs, and also usage examples in the wxPython demo if you happen to have that. Also, wxPython has several types of the text entry controls, and I'm assuming that you're using the wxTextCtrl, though the docs should have info on the others as well.\n",
"I think the textUpdate event is what your looking for.\nhttp://pythoncard.sourceforge.net/framework/components/TextField.html\n"
] | [
1,
1
] | [] | [] | [
"event_handling",
"events",
"pycard",
"python",
"pythoncard"
] | stackoverflow_0000984263_event_handling_events_pycard_python_pythoncard.txt |
Q:
How to capture keystrokes with a Python daemon?
I'm trying to write a POS-style application for a Sheevaplug that does the following:
Captures input from a card reader (as I understand, most mag card readers emulate keyboard input, so basically I'm looking to capture that)
Doesn't require X
Runs in the background (daemon)
I've seen examples of code that will wait for STDIN, but that won't work because this is a background process with no login, not even a monitor actually.
I also found this snippet elsewhere on this site:
from struct import unpack
port = open("/dev/input/event1","rb")
while 1:
a,b,c,d = unpack("4B",port.read(4))
print a,b,c,d
Which, while being the closest thing to what I need so far, only generates a series of numbers, all of which are different with no way that I know of to translate them into useful values.
Clearly, I'm missing something here, but I don't know what it is. Can someone please how to get the rest of the way?
A:
Section 5 of the Linux kernel input documentation describes what each of the values in the event interface means.
A:
the format is explained in the kernel documentation in section 5. Event Interface.
| How to capture keystrokes with a Python daemon? | I'm trying to write a POS-style application for a Sheevaplug that does the following:
Captures input from a card reader (as I understand, most mag card readers emulate keyboard input, so basically I'm looking to capture that)
Doesn't require X
Runs in the background (daemon)
I've seen examples of code that will wait for STDIN, but that won't work because this is a background process with no login, not even a monitor actually.
I also found this snippet elsewhere on this site:
from struct import unpack
port = open("/dev/input/event1","rb")
while 1:
a,b,c,d = unpack("4B",port.read(4))
print a,b,c,d
Which, while being the closest thing to what I need so far, only generates a series of numbers, all of which are different with no way that I know of to translate them into useful values.
Clearly, I'm missing something here, but I don't know what it is. Can someone please how to get the rest of the way?
| [
"Section 5 of the Linux kernel input documentation describes what each of the values in the event interface means.\n",
"the format is explained in the kernel documentation in section 5. Event Interface.\n"
] | [
2,
1
] | [] | [] | [
"capture",
"keyboard",
"linux",
"python"
] | stackoverflow_0002066049_capture_keyboard_linux_python.txt |
Q:
Assigning one of multiple values based on what exists
In Perl, if I want to assign $myVar a value of $var1, $var2, or $var3, based on which one evaluates to true, I would code the following:
$myVar = $var1 || $var2 || $var3;
I am working on separate projects in both Python and PHP, and I have not figured out how to code this situation as concisely in either language.
What is the best way to code this in Python?
What is the best way to code this in PHP?
A:
Perl 'autovivifies' variables upon first reference (as far as I remember). Python will raise a NameError if a variable doesn't exist. However, you can do something like this.
var1 = var2 = var3 = None
# code that might change the value of three variables mentioned above
myvar = var1 or var2 or var3
Generally speaking, checking if a variable is defined (and altering the control flow based on that) is a bad thing in Python. You should use a dictionary and keys.
A:
In Python, I believe you can say
myVar = var1 or var2 or var3
The Python documentation describes x or y as
if x is false, then y, else x
Edit: theatrus brings up an interesting point - I hadn't even considered that the variables might not be defined. I found this discussion on the matter:
Python doesn't have a specific
function to test whether a variable is
defined, since all variables are
expected to have been defined before
use - even if initially just assigned
the None object. Attempting to access
a variable that hasn't previously been
defined will raise an exception.
It is generally considered unusual in
Python not to know whether a variable
has already been defined. But if you
are nevertheless in this situation,
you can make sure that a given
variable is in fact defined (as None,
if nothing else) by attempting to
access it inside a 'try' block and
assigning it the None object should it
raise a NameError exception.
So, if you're not guaranteed that the variables exist, and you want to check one by one for both existence and truthiness, you could be in for some messy code.
A:
In PHP you can use isset() to test to see if the variable is set and not null. To achieve what you are looking for you can check whether $var1, $var2 or $var3 is set, and then set the value to $myVar
But beware depending on the condition of which you want to set your $myVar to, this would evaluate to true:
$str = '';
var_dump(isset($str)); // TRUE
A:
In PHP you could do this (assumes the variables are set):
$vars = array($var1, $var2, $var3);
foreach ($vars as $var) {
if ($myvar = $var) {
break;
}
}
Or, to make it slightly more perly :) :
foreach(array($var1,$var2,$var3)as$var)if($myvar=$var)break;
A:
There are also conditional expressions in Python added in Python 2.5:
x = true_value if condition else false_value
I cannot speak to PHP.
One thing to keep in mind with both languages is that trying to evaluate a variable that does not exist is always going to throw an error. With Python, you could work around this by catching the NameError exception that will occur if you attempt this and fallback to a default:
>>> try:
... myVar = var1 or var2 or var3
... except NameError:
... myVar = 'default'
...
>>> myVar
'default'
So if var1, var2, or var3 are either not set, then myVar will receive the fallback value of "default". Otherwise, you'll get the value of whichever var of the set evaluated to True.
| Assigning one of multiple values based on what exists | In Perl, if I want to assign $myVar a value of $var1, $var2, or $var3, based on which one evaluates to true, I would code the following:
$myVar = $var1 || $var2 || $var3;
I am working on separate projects in both Python and PHP, and I have not figured out how to code this situation as concisely in either language.
What is the best way to code this in Python?
What is the best way to code this in PHP?
| [
"Perl 'autovivifies' variables upon first reference (as far as I remember). Python will raise a NameError if a variable doesn't exist. However, you can do something like this. \nvar1 = var2 = var3 = None\n# code that might change the value of three variables mentioned above\nmyvar = var1 or var2 or var3\n\nGenerally speaking, checking if a variable is defined (and altering the control flow based on that) is a bad thing in Python. You should use a dictionary and keys.\n",
"In Python, I believe you can say\nmyVar = var1 or var2 or var3\n\nThe Python documentation describes x or y as \n\nif x is false, then y, else x\n\nEdit: theatrus brings up an interesting point - I hadn't even considered that the variables might not be defined. I found this discussion on the matter:\n\nPython doesn't have a specific\n function to test whether a variable is\n defined, since all variables are\n expected to have been defined before\n use - even if initially just assigned\n the None object. Attempting to access\n a variable that hasn't previously been\n defined will raise an exception.\nIt is generally considered unusual in\n Python not to know whether a variable\n has already been defined. But if you\n are nevertheless in this situation,\n you can make sure that a given\n variable is in fact defined (as None,\n if nothing else) by attempting to\n access it inside a 'try' block and\n assigning it the None object should it\n raise a NameError exception.\n\nSo, if you're not guaranteed that the variables exist, and you want to check one by one for both existence and truthiness, you could be in for some messy code.\n",
"In PHP you can use isset() to test to see if the variable is set and not null. To achieve what you are looking for you can check whether $var1, $var2 or $var3 is set, and then set the value to $myVar\nBut beware depending on the condition of which you want to set your $myVar to, this would evaluate to true:\n$str = '';\nvar_dump(isset($str)); // TRUE\n\n",
"In PHP you could do this (assumes the variables are set):\n$vars = array($var1, $var2, $var3);\nforeach ($vars as $var) {\n if ($myvar = $var) {\n break;\n }\n}\n\nOr, to make it slightly more perly :) :\nforeach(array($var1,$var2,$var3)as$var)if($myvar=$var)break;\n\n",
"There are also conditional expressions in Python added in Python 2.5:\nx = true_value if condition else false_value\n\nI cannot speak to PHP.\nOne thing to keep in mind with both languages is that trying to evaluate a variable that does not exist is always going to throw an error. With Python, you could work around this by catching the NameError exception that will occur if you attempt this and fallback to a default:\n>>> try: \n... myVar = var1 or var2 or var3\n... except NameError:\n... myVar = 'default'\n... \n>>> myVar\n'default'\n\nSo if var1, var2, or var3 are either not set, then myVar will receive the fallback value of \"default\". Otherwise, you'll get the value of whichever var of the set evaluated to True.\n"
] | [
3,
2,
1,
1,
0
] | [] | [] | [
"perl",
"php",
"python"
] | stackoverflow_0002058544_perl_php_python.txt |
Q:
Complex Django query over foreign keys
I have two models in the same application. The application is called "News", and it has two classes in its model called "Article" and "Category".
class Category(models.Model):
name = models.CharField(_("Name"), max_length=100)
slug = models.SlugField(_("Slug"), max_length=100, unique=True)
class Article(models.Model):
category = models.ForeignKey(Category, verbose_name=_("Category"))
archived = models.BooleanField(_("Archive this?"), default=False)
I want to create a query that shows me all of the articles which are archived but grouped by category.
How would I accomplish this efficiently?
A:
Article.objects.filter(archived=True).order_by('category')
i am editing this to get more info to try and help out.
given:
cat1
art1
art2-archived
art3
cat2
art4
art5
art6-archived
cat3
art7-archived
art8-archived
art9
what would you want your queryset to contain?
A:
c = Category.objects.filter(article__archived=True)
A:
Isn't this what you want?
class Article(models.Model):
category = models.ForeignKey(Category, related_name='articles')
archived = models.BooleanField(default=False)
categories = Category.objects.select_related("articles").filter(articles__archived=True)
| Complex Django query over foreign keys | I have two models in the same application. The application is called "News", and it has two classes in its model called "Article" and "Category".
class Category(models.Model):
name = models.CharField(_("Name"), max_length=100)
slug = models.SlugField(_("Slug"), max_length=100, unique=True)
class Article(models.Model):
category = models.ForeignKey(Category, verbose_name=_("Category"))
archived = models.BooleanField(_("Archive this?"), default=False)
I want to create a query that shows me all of the articles which are archived but grouped by category.
How would I accomplish this efficiently?
| [
"Article.objects.filter(archived=True).order_by('category')\n\ni am editing this to get more info to try and help out. \ngiven:\n\ncat1\n\n\nart1\nart2-archived\nart3\n\ncat2\n\n\nart4\nart5\nart6-archived\n\ncat3\n\n\nart7-archived\nart8-archived\nart9\n\n\nwhat would you want your queryset to contain?\n",
"\n\n\nc = Category.objects.filter(article__archived=True)\n\n\n\n",
"Isn't this what you want?\nclass Article(models.Model):\n category = models.ForeignKey(Category, related_name='articles')\n archived = models.BooleanField(default=False)\n\ncategories = Category.objects.select_related(\"articles\").filter(articles__archived=True)\n\n"
] | [
3,
3,
2
] | [] | [] | [
"django",
"django_orm",
"python"
] | stackoverflow_0002028440_django_django_orm_python.txt |
Q:
Dynamic form field generation in Django templates
I am having a problem figuring out how to solve this problem the Django and (probably) the Python way. I am sending a hash to a template that contains the following values
{'date': '2009-12-30', 'locations': [{u'lat': 43.514000000000003, u'lng': -79.844032999999996, u'place': u'1053 Bowring Cres, Milton, ON L9T, CA', u'description': u'Home base'}, {u'lat': 43.730550000000001, u'lng': -79.805334000000002, u'place': u'50 Dawnridge Trl, Brampton, ON L6Z, CA', u'description': u'Southfork'}]}
I then pass this data to my template and I need to do the following:
create a form
pre-populate a number of form fields related to the values inside 'locations'
if I have less than 5 'locations' add in a number of blank form fields until I have 5
Here's the code that pulls in and generates the data -- it grabs info from CouchDB
def get_by_id(self, username, search_id):
if username and search_id:
info = db.get(search_id)
if info['user'] == username:
return {'date': info['date'],
'locations': json.loads(info['locations'])}
I suppose I could somehow manipulate what is in info['locations'] to add in an ID, but I've been struggling with understanding how Python handles iterating through the JSON.
Here's the code in template I'm using to create the form. my_search contains the data I've shown above
<form method="post" action="/locations">
<input type="hidden" name="search_id" value="{{ search_id }}">
<table>
<tr>
<th>Location</th>
<th>Description</th>
</tr>
{% for location in my_search.locations %}
<tr>
<td><input type="text" name="location" id="id_location"
value="{{ location.place }}"></td>
<td><input type="text" name="description" id="id_description"
value="{{ location.description }}"></td>
</tr>
{% endfor %}
</table>
<input type="submit" value="Update Plan">
</form>
Thoughts on how to (a) easily add in a unique ID and (b) add in the missing blank form field pairs if I have less than 5 locations would be greatly appreciated.
A:
if info['user'] == username:
locations = (json.loads(info['locations']) +
[{'place': '', 'description': ''}] * 5)[:5]
return {'date': info['date'], 'locations': locations}
A:
(a)
id="id_location_{{ forloop.counter }}"
| Dynamic form field generation in Django templates | I am having a problem figuring out how to solve this problem the Django and (probably) the Python way. I am sending a hash to a template that contains the following values
{'date': '2009-12-30', 'locations': [{u'lat': 43.514000000000003, u'lng': -79.844032999999996, u'place': u'1053 Bowring Cres, Milton, ON L9T, CA', u'description': u'Home base'}, {u'lat': 43.730550000000001, u'lng': -79.805334000000002, u'place': u'50 Dawnridge Trl, Brampton, ON L6Z, CA', u'description': u'Southfork'}]}
I then pass this data to my template and I need to do the following:
create a form
pre-populate a number of form fields related to the values inside 'locations'
if I have less than 5 'locations' add in a number of blank form fields until I have 5
Here's the code that pulls in and generates the data -- it grabs info from CouchDB
def get_by_id(self, username, search_id):
if username and search_id:
info = db.get(search_id)
if info['user'] == username:
return {'date': info['date'],
'locations': json.loads(info['locations'])}
I suppose I could somehow manipulate what is in info['locations'] to add in an ID, but I've been struggling with understanding how Python handles iterating through the JSON.
Here's the code in template I'm using to create the form. my_search contains the data I've shown above
<form method="post" action="/locations">
<input type="hidden" name="search_id" value="{{ search_id }}">
<table>
<tr>
<th>Location</th>
<th>Description</th>
</tr>
{% for location in my_search.locations %}
<tr>
<td><input type="text" name="location" id="id_location"
value="{{ location.place }}"></td>
<td><input type="text" name="description" id="id_description"
value="{{ location.description }}"></td>
</tr>
{% endfor %}
</table>
<input type="submit" value="Update Plan">
</form>
Thoughts on how to (a) easily add in a unique ID and (b) add in the missing blank form field pairs if I have less than 5 locations would be greatly appreciated.
| [
"if info['user'] == username:\n locations = (json.loads(info['locations']) +\n [{'place': '', 'description': ''}] * 5)[:5]\n\n return {'date': info['date'], 'locations': locations}\n\n",
"(a)\nid=\"id_location_{{ forloop.counter }}\"\n\n"
] | [
2,
2
] | [] | [] | [
"django",
"python",
"templates"
] | stackoverflow_0002066181_django_python_templates.txt |
Q:
how to concatenate lists in python?
I'm trying to insert a String into a list.
I got this error:
TypeError: can only concatenate list (not "tuple") to list
because I tried this:
var1 = 'ThisIsAString' # My string I want to insert in the following list
file_content = open('myfile.txt').readlines()
new_line_insert = file_content[:10] + list(var1) + rss_xml[11:]
open('myfile.txt', 'w').writelines(new_line_insert)
The content of myfile.txt is saved in "file_content" as a list.
I want to insert the String var1 after the 10th line, thats why I did
file_content[:10] + list(var1) + rss_xml[11:]
but the list(var1) doesn't work. How can I make this code work?
Thanks!
A:
try
file_content[:10] + [var1] + rss_xml[11:]
A:
Lists have an insert method, so you could just use that:
file_content.insert(10, var1)
A:
It's important to note the "list(var1)" is trying to convert var1 to a list. Since var1 is a string, it will be something like:
>>> list('this')
['t', 'h', 'i', 's']
Or, in other words, it converts the string to a list of characters. This is different from creating a list where var1 is an element, which is most easily accomplished by putting the "[]" around the element:
>>> ['this']
['this']
A:
file_content = file_content[:10]
file_content.append(var1)
file_content.extend(rss_xml[11:])
| how to concatenate lists in python? | I'm trying to insert a String into a list.
I got this error:
TypeError: can only concatenate list (not "tuple") to list
because I tried this:
var1 = 'ThisIsAString' # My string I want to insert in the following list
file_content = open('myfile.txt').readlines()
new_line_insert = file_content[:10] + list(var1) + rss_xml[11:]
open('myfile.txt', 'w').writelines(new_line_insert)
The content of myfile.txt is saved in "file_content" as a list.
I want to insert the String var1 after the 10th line, thats why I did
file_content[:10] + list(var1) + rss_xml[11:]
but the list(var1) doesn't work. How can I make this code work?
Thanks!
| [
"try\nfile_content[:10] + [var1] + rss_xml[11:]\n\n",
"Lists have an insert method, so you could just use that:\nfile_content.insert(10, var1)\n\n",
"It's important to note the \"list(var1)\" is trying to convert var1 to a list. Since var1 is a string, it will be something like:\n\n>>> list('this')\n['t', 'h', 'i', 's']\n\nOr, in other words, it converts the string to a list of characters. This is different from creating a list where var1 is an element, which is most easily accomplished by putting the \"[]\" around the element:\n\n>>> ['this']\n['this']\n\n",
"file_content = file_content[:10]\nfile_content.append(var1)\nfile_content.extend(rss_xml[11:])\n\n"
] | [
9,
3,
2,
1
] | [] | [] | [
"python"
] | stackoverflow_0002066213_python.txt |
Q:
Python syntax and legibility for sequential steps that are sub-items
I like Python's whitespace formatting and legibility. But can you, or is there a common/standard way of delimiting blocks of code that are not to be indented, ie do not belong in nested loops?
I have two parts of a procedure that belong inside a main header. Something like step 2 has parts 2.1 and parts 2.2.
Commenting so far I have something like:
# Section 2
<code>
# Section 2.1
<code>
# Section 2.2
<code>
But I would prefer something like:
# Section 2
<code>
# Section 2.1
<code>
# Section 2.2
<code>
But neither 2.1 nor 2.2 are sub-loops and I know this is illegal. They just run in sequence but are logical steps (to me) that fall under the 2 header so when I look at my code I know what part of the program they are.
How do you handle these cases when coding?
A:
Put them in separate functions.
A:
You should not have long functions in Python. Take whitespace dilemmas as a hint.
A:
What's wrong with function definitions?
def section1( ... ):
def section2( ... ):
def overall( ... ):
section1()
section2()
If it's so huge that indentation is required, perhaps it's too huge.
Also, you can abuse the with statement to "force" indentation.
A:
You might try splitting this up into multiple functions:
def section2():
section21()
section22()
or something similar. I find using functions not only for purposes of reuse but also organizationally makes my code much more readable and easy to maintain. If the functions need to share a significant amount of data, you might consider making them methods of a class.
A:
I use comments in my code to help me recognize their logical relationship to one-another. If I think that there is some sort of a natural order emerging, I might refactor my code in some way to recognize that, but I never try to mis-use Python's indentation. That's just not what it is meant for. It is syntactical rather than semantic.
A:
I'm surprised you'd consider indenting your code like this even in languages that allow it. How do your team members feel about this? I'd find it very confusing to have indented code that didn't correspond to a block.
| Python syntax and legibility for sequential steps that are sub-items | I like Python's whitespace formatting and legibility. But can you, or is there a common/standard way of delimiting blocks of code that are not to be indented, ie do not belong in nested loops?
I have two parts of a procedure that belong inside a main header. Something like step 2 has parts 2.1 and parts 2.2.
Commenting so far I have something like:
# Section 2
<code>
# Section 2.1
<code>
# Section 2.2
<code>
But I would prefer something like:
# Section 2
<code>
# Section 2.1
<code>
# Section 2.2
<code>
But neither 2.1 nor 2.2 are sub-loops and I know this is illegal. They just run in sequence but are logical steps (to me) that fall under the 2 header so when I look at my code I know what part of the program they are.
How do you handle these cases when coding?
| [
"Put them in separate functions.\n",
"You should not have long functions in Python. Take whitespace dilemmas as a hint.\n",
"What's wrong with function definitions?\ndef section1( ... ):\n\ndef section2( ... ):\n\ndef overall( ... ):\n section1()\n section2()\n\nIf it's so huge that indentation is required, perhaps it's too huge.\nAlso, you can abuse the with statement to \"force\" indentation.\n",
"You might try splitting this up into multiple functions:\ndef section2():\n section21()\n section22()\n\nor something similar. I find using functions not only for purposes of reuse but also organizationally makes my code much more readable and easy to maintain. If the functions need to share a significant amount of data, you might consider making them methods of a class.\n",
"I use comments in my code to help me recognize their logical relationship to one-another. If I think that there is some sort of a natural order emerging, I might refactor my code in some way to recognize that, but I never try to mis-use Python's indentation. That's just not what it is meant for. It is syntactical rather than semantic.\n",
"I'm surprised you'd consider indenting your code like this even in languages that allow it. How do your team members feel about this? I'd find it very confusing to have indented code that didn't correspond to a block.\n"
] | [
5,
4,
3,
1,
1,
1
] | [] | [] | [
"python",
"syntax"
] | stackoverflow_0002066595_python_syntax.txt |
Q:
Unknown Authn provider: wsgi ... fail!
I have working wsgi authentication on another server, however a second server is not accepting the same configuration and errors upon reload with the message:
Syntax error on line 12 of /etc/apache2/sites-enabled/mydomain.com
Unknown Authn provider: wsgi
... fail
Here is the relevant portion of the config file (line 12 is WSGIAuthUserScript ...)
<Location /adirectory/>
AuthType Basic
AuthName "Answer me these questions two"
AuthBasicProvider wsgi
WSGIAuthUserScript /home/auser/domains/mydomain.com/apache/auth_test.wsgi
Require valid-user
</location>
WSGIPassAuthorization On
And the auth_test.wsgi file:
def check_password(environ, user, password):
if user == 'someusername':
if password == 'asecretpassword':
return True
return False
return None
mod-wsgi.conf and mod-wsgi.load are both enabled. Of course there must be /something/ different, but I am at a loss.
A:
It turned out to be a wsgi version difference.
| Unknown Authn provider: wsgi ... fail! | I have working wsgi authentication on another server, however a second server is not accepting the same configuration and errors upon reload with the message:
Syntax error on line 12 of /etc/apache2/sites-enabled/mydomain.com
Unknown Authn provider: wsgi
... fail
Here is the relevant portion of the config file (line 12 is WSGIAuthUserScript ...)
<Location /adirectory/>
AuthType Basic
AuthName "Answer me these questions two"
AuthBasicProvider wsgi
WSGIAuthUserScript /home/auser/domains/mydomain.com/apache/auth_test.wsgi
Require valid-user
</location>
WSGIPassAuthorization On
And the auth_test.wsgi file:
def check_password(environ, user, password):
if user == 'someusername':
if password == 'asecretpassword':
return True
return False
return None
mod-wsgi.conf and mod-wsgi.load are both enabled. Of course there must be /something/ different, but I am at a loss.
| [
"It turned out to be a wsgi version difference.\n"
] | [
1
] | [] | [] | [
"apache",
"mod_wsgi",
"python",
"wsgi"
] | stackoverflow_0002065761_apache_mod_wsgi_python_wsgi.txt |
Q:
Accessing parallel arrays in Django templates?
My view code looks basically like this:
context = Context()
context['some_values'] = ['a', 'b', 'c', 'd', 'e', 'f']
context['other_values'] = [4, 8, 15, 16, 23, 42]
I would like my template code to look like this:
{% for some in some_values %}
{% with index as forloop.counter0 %}
{{ some }} : {{ other_values.index }} <br/>
{% endwith %}
{% endfor %}
And I would expect this to output:
a : 4 <br/>
b : 8 <br/>
c : 15 <br/>
d : 16 <br/>
e : 23 <br/>
f : 42 <br/>
Is this possible? I'm finding that my "with" statement is actually working, but then using that variable as a reference isn't working. I suspect that for {{ other_values.index }} it's doing other_values['index'] instead of other_values[index]. Is this possible?
A:
zip(some_values, other_values), then use it in template
from itertools import izip
some_values = ['a', 'b', 'c', 'd', 'e', 'f']
other_values = [4, 8, 15, 16, 23, 42]
context['zipped_values'] = izip(some_values, other_values)
{% for some, other in zipped_values %}
{{ some }}: {{ other }} <br/>
{% endfor %}
| Accessing parallel arrays in Django templates? | My view code looks basically like this:
context = Context()
context['some_values'] = ['a', 'b', 'c', 'd', 'e', 'f']
context['other_values'] = [4, 8, 15, 16, 23, 42]
I would like my template code to look like this:
{% for some in some_values %}
{% with index as forloop.counter0 %}
{{ some }} : {{ other_values.index }} <br/>
{% endwith %}
{% endfor %}
And I would expect this to output:
a : 4 <br/>
b : 8 <br/>
c : 15 <br/>
d : 16 <br/>
e : 23 <br/>
f : 42 <br/>
Is this possible? I'm finding that my "with" statement is actually working, but then using that variable as a reference isn't working. I suspect that for {{ other_values.index }} it's doing other_values['index'] instead of other_values[index]. Is this possible?
| [
"zip(some_values, other_values), then use it in template\nfrom itertools import izip\nsome_values = ['a', 'b', 'c', 'd', 'e', 'f']\nother_values = [4, 8, 15, 16, 23, 42]\ncontext['zipped_values'] = izip(some_values, other_values)\n\n{% for some, other in zipped_values %}\n {{ some }}: {{ other }} <br/>\n{% endfor %}\n\n"
] | [
8
] | [] | [] | [
"django",
"django_templates",
"python"
] | stackoverflow_0002067036_django_django_templates_python.txt |
Q:
Does Django logs usernames internally
All..
I have a Django site and to access it all the users have to go through the login page.
My question is when a user is given a access through the login page to enter the site.Does Django logs the username in any of the Django internal tables....
Thanks.......
A:
Yes, the last_login column of the user's record in table auth_user is updated with the date/time of the successful login.
| Does Django logs usernames internally | All..
I have a Django site and to access it all the users have to go through the login page.
My question is when a user is given a access through the login page to enter the site.Does Django logs the username in any of the Django internal tables....
Thanks.......
| [
"Yes, the last_login column of the user's record in table auth_user is updated with the date/time of the successful login.\n"
] | [
2
] | [] | [] | [
"django",
"logging",
"python"
] | stackoverflow_0002067185_django_logging_python.txt |
Q:
django select query--how do I make this?
class Content(models.Model):
.....stuff here
class Score(models.Model):
content = models.OneToOneField(Content, primary_key=True)
real_score = models.IntegerField(default=0)
This is my database schema. As you can see, each Content has a score.
How do I do this:
Select all from Content where Content's Score is 1?
A:
Content.objects.filter(score__real_score=1)
| django select query--how do I make this? | class Content(models.Model):
.....stuff here
class Score(models.Model):
content = models.OneToOneField(Content, primary_key=True)
real_score = models.IntegerField(default=0)
This is my database schema. As you can see, each Content has a score.
How do I do this:
Select all from Content where Content's Score is 1?
| [
"Content.objects.filter(score__real_score=1)\n"
] | [
5
] | [] | [] | [
"database",
"django",
"mysql",
"python"
] | stackoverflow_0002067268_database_django_mysql_python.txt |
Q:
PYTHONPATH issue on a Production server and Namespace challenge
I'm really confused by some errors I'm getting as I'm trying to put an App into production. Everything works fine on the development machine, but I can't syncdb or enter the Django shell on the Production server.
I'm getting an error when forum.models.py is attempts to import forum.managers.py because the models aren't in the namespace yet.
I think it could be a PYTHONPATH issue, but it has a weird Chicken or Egg aspect to it. I don't understand why TagManager is not in the NameSpace.
TagManager is imported via:
from forum.managers import *
Which is executed before the the TagManager class is called.
$ python2.5 manage.py syncdb
Traceback (most recent call last):
File "manage.py", line 11, in
execute_manager(settings)
File "/home/app_name/webapps/app_name/lib/python2.5/django/core/management/init.py", line 362, in execute_manager
utility.execute()
File "/home/app_name/webapps/app_name/lib/python2.5/django/core/management/init.py", line 303, in execute
self.fetch_command(subcommand).run_from_argv(self.argv)
File "/home/app_name/webapps/app_name/lib/python2.5/django/core/management/base.py", line 195, in run_from_argv
self.execute(*args, **options.dict)
File "/home/app_name/webapps/app_name/lib/python2.5/django/core/management/base.py", line 221, in execute
self.validate()
File "/home/app_name/webapps/app_name/lib/python2.5/django/core/management/base.py", line 249, in validate
num_errors = get_validation_errors(s, app)
File "/home/app_name/webapps/app_name/lib/python2.5/django/core/management/validation.py", line 28, in get_validation_errors
for (app_name, error) in get_app_errors().items():
File "/home/app_name/webapps/app_name/lib/python2.5/django/db/models/loading.py", line 131, in get_app_errors
self._populate()
File "/home/app_name/webapps/app_name/lib/python2.5/django/db/models/loading.py", line 58, in _populate
self.load_app(app_name, True)
File "/home/app_name/webapps/app_name/lib/python2.5/django/db/models/loading.py", line 74, in load_app
models = import_module('.models', app_name)
File "/home/app_name/webapps/app_name/lib/python2.5/django/utils/importlib.py", line 35, in import_module
import(name)
File "/home/app_name/webapps/app_name/django_app/../django_app/forum/models.py", line 18, in
from forum.managers import *
File "/home/app_name/webapps/app_name/django_app/forum/managers.py", line 6, in
from forum.models import *
File "/home/app_name/webapps/app_name/django_app/../django_app/forum/models.py", line 43, in
class Tag(models.Model):
File "/home/app_name/webapps/app_name/django_app/../django_app/forum/models.py", line 53, in Tag
objects = TagManager()
NameError: name 'TagManager' is not defined
Python 2.5.4 (r254:67916, Aug 5 2009, 12:42:40)
[GCC 4.1.2 20080704 (Red Hat 4.1.2-44)] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> import os
>>> os.environ['DJANGO_SETTINGS_MODULE'] = 'django_app.settings'
>>>
>>> import sys
>>> import pprint
>>> pprint.pprint(sys.path)
['',
'/home/app_name/webapps/app_name/lib/python2.5',
'/home/app_name/lib/python2.5/markdown2-1.0.1.16-py2.5.egg',
'/home/app_name/lib/python2.5/html5lib-0.11.1-py2.5.egg',
'/home/app_name/lib/python2.5',
'/usr/local/lib/python25.zip',
'/usr/local/lib/python2.5',
'/usr/local/lib/python2.5/plat-linux2',
'/usr/local/lib/python2.5/lib-tk',
'/usr/local/lib/python2.5/lib-dynload',
'/usr/local/lib/python2.5/site-packages',
'/usr/local/lib/python2.5/site-packages/PIL']
>>> sys.path = ['/home/app_name/webapps/app_name/django_app','/home/app_name/webapps/app_name','/home/app_name/webapps/app_name/lib/python2.5'] + sys.path
>>> pprint.pprint(sys.path)['/home/app_name/webapps/app_name/django_app',
'/home/app_name/webapps/app_name',
'/home/app_name/webapps/app_name/lib/python2.5',
'',
'/home/app_name/webapps/app_name/lib/python2.5',
'/home/app_name/lib/python2.5/markdown2-1.0.1.16-py2.5.egg',
'/home/app_name/lib/python2.5/html5lib-0.11.1-py2.5.egg',
'/home/app_name/lib/python2.5',
'/usr/local/lib/python25.zip',
'/usr/local/lib/python2.5',
'/usr/local/lib/python2.5/plat-linux2',
'/usr/local/lib/python2.5/lib-tk',
'/usr/local/lib/python2.5/lib-dynload',
'/usr/local/lib/python2.5/site-packages',
'/usr/local/lib/python2.5/site-packages/PIL']
>>> from forum.managers import *
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "/home/app_name/webapps/app_name/django_app/forum/managers.py", line 6, in <module>
from forum.models import *
File "/home/app_name/webapps/app_name/django_app/../django_app/forum/models.py", line 43, in <module>
class Tag(models.Model):
File "/home/app_name/webapps/app_name/django_app/../django_app/forum/models.py", line 53, in Tag
objects = TagManager()
NameError: name 'TagManager' is not defined
>>> from forum.models import *
>>> from forum.managers import *
>>> objects = TagManager()
>>> objects
<forum.managers.TagManager object at 0x9b9fdac>
>>>
A:
Your problem is you do:
from forum.managers import * (at line 18 models.py)
from forum.models import * (at line 6 managers.py)
How can that ever work? Try flattening this out (do the imports by hand copying and pasting into a new file) and you'll see why, by the time it executes the line "objects = TagManager()" it cannot possibly have executed the part of the managers module where TagManager is defined, unless it was defined before line 18.
Some general tips:
Avoid the * imports whenever possible (it makes python programs harder to read if nothing else)
If you have circular imports like that, try to break them up. Often in one module you can move the import into a function call, or you can refactor some elements into a third module that both can import from. You can also try moving the import lower in the module, which sometimes works.
| PYTHONPATH issue on a Production server and Namespace challenge | I'm really confused by some errors I'm getting as I'm trying to put an App into production. Everything works fine on the development machine, but I can't syncdb or enter the Django shell on the Production server.
I'm getting an error when forum.models.py is attempts to import forum.managers.py because the models aren't in the namespace yet.
I think it could be a PYTHONPATH issue, but it has a weird Chicken or Egg aspect to it. I don't understand why TagManager is not in the NameSpace.
TagManager is imported via:
from forum.managers import *
Which is executed before the the TagManager class is called.
$ python2.5 manage.py syncdb
Traceback (most recent call last):
File "manage.py", line 11, in
execute_manager(settings)
File "/home/app_name/webapps/app_name/lib/python2.5/django/core/management/init.py", line 362, in execute_manager
utility.execute()
File "/home/app_name/webapps/app_name/lib/python2.5/django/core/management/init.py", line 303, in execute
self.fetch_command(subcommand).run_from_argv(self.argv)
File "/home/app_name/webapps/app_name/lib/python2.5/django/core/management/base.py", line 195, in run_from_argv
self.execute(*args, **options.dict)
File "/home/app_name/webapps/app_name/lib/python2.5/django/core/management/base.py", line 221, in execute
self.validate()
File "/home/app_name/webapps/app_name/lib/python2.5/django/core/management/base.py", line 249, in validate
num_errors = get_validation_errors(s, app)
File "/home/app_name/webapps/app_name/lib/python2.5/django/core/management/validation.py", line 28, in get_validation_errors
for (app_name, error) in get_app_errors().items():
File "/home/app_name/webapps/app_name/lib/python2.5/django/db/models/loading.py", line 131, in get_app_errors
self._populate()
File "/home/app_name/webapps/app_name/lib/python2.5/django/db/models/loading.py", line 58, in _populate
self.load_app(app_name, True)
File "/home/app_name/webapps/app_name/lib/python2.5/django/db/models/loading.py", line 74, in load_app
models = import_module('.models', app_name)
File "/home/app_name/webapps/app_name/lib/python2.5/django/utils/importlib.py", line 35, in import_module
import(name)
File "/home/app_name/webapps/app_name/django_app/../django_app/forum/models.py", line 18, in
from forum.managers import *
File "/home/app_name/webapps/app_name/django_app/forum/managers.py", line 6, in
from forum.models import *
File "/home/app_name/webapps/app_name/django_app/../django_app/forum/models.py", line 43, in
class Tag(models.Model):
File "/home/app_name/webapps/app_name/django_app/../django_app/forum/models.py", line 53, in Tag
objects = TagManager()
NameError: name 'TagManager' is not defined
Python 2.5.4 (r254:67916, Aug 5 2009, 12:42:40)
[GCC 4.1.2 20080704 (Red Hat 4.1.2-44)] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> import os
>>> os.environ['DJANGO_SETTINGS_MODULE'] = 'django_app.settings'
>>>
>>> import sys
>>> import pprint
>>> pprint.pprint(sys.path)
['',
'/home/app_name/webapps/app_name/lib/python2.5',
'/home/app_name/lib/python2.5/markdown2-1.0.1.16-py2.5.egg',
'/home/app_name/lib/python2.5/html5lib-0.11.1-py2.5.egg',
'/home/app_name/lib/python2.5',
'/usr/local/lib/python25.zip',
'/usr/local/lib/python2.5',
'/usr/local/lib/python2.5/plat-linux2',
'/usr/local/lib/python2.5/lib-tk',
'/usr/local/lib/python2.5/lib-dynload',
'/usr/local/lib/python2.5/site-packages',
'/usr/local/lib/python2.5/site-packages/PIL']
>>> sys.path = ['/home/app_name/webapps/app_name/django_app','/home/app_name/webapps/app_name','/home/app_name/webapps/app_name/lib/python2.5'] + sys.path
>>> pprint.pprint(sys.path)['/home/app_name/webapps/app_name/django_app',
'/home/app_name/webapps/app_name',
'/home/app_name/webapps/app_name/lib/python2.5',
'',
'/home/app_name/webapps/app_name/lib/python2.5',
'/home/app_name/lib/python2.5/markdown2-1.0.1.16-py2.5.egg',
'/home/app_name/lib/python2.5/html5lib-0.11.1-py2.5.egg',
'/home/app_name/lib/python2.5',
'/usr/local/lib/python25.zip',
'/usr/local/lib/python2.5',
'/usr/local/lib/python2.5/plat-linux2',
'/usr/local/lib/python2.5/lib-tk',
'/usr/local/lib/python2.5/lib-dynload',
'/usr/local/lib/python2.5/site-packages',
'/usr/local/lib/python2.5/site-packages/PIL']
>>> from forum.managers import *
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "/home/app_name/webapps/app_name/django_app/forum/managers.py", line 6, in <module>
from forum.models import *
File "/home/app_name/webapps/app_name/django_app/../django_app/forum/models.py", line 43, in <module>
class Tag(models.Model):
File "/home/app_name/webapps/app_name/django_app/../django_app/forum/models.py", line 53, in Tag
objects = TagManager()
NameError: name 'TagManager' is not defined
>>> from forum.models import *
>>> from forum.managers import *
>>> objects = TagManager()
>>> objects
<forum.managers.TagManager object at 0x9b9fdac>
>>>
| [
"Your problem is you do:\nfrom forum.managers import * (at line 18 models.py)\nfrom forum.models import * (at line 6 managers.py)\nHow can that ever work? Try flattening this out (do the imports by hand copying and pasting into a new file) and you'll see why, by the time it executes the line \"objects = TagManager()\" it cannot possibly have executed the part of the managers module where TagManager is defined, unless it was defined before line 18.\nSome general tips:\n\nAvoid the * imports whenever possible (it makes python programs harder to read if nothing else)\nIf you have circular imports like that, try to break them up. Often in one module you can move the import into a function call, or you can refactor some elements into a third module that both can import from. You can also try moving the import lower in the module, which sometimes works.\n\n"
] | [
1
] | [] | [] | [
"django",
"production",
"python",
"pythonpath"
] | stackoverflow_0002066426_django_production_python_pythonpath.txt |
Q:
Django: iterating over the options in a custom select field
I'm using a custom MM/YY field and widget based on this example. I want to iterate over the individual month and year options defined in the widget class in order to apply "selected='selected'" to the MM/YY value that corresponds with the MM/YY value stored in the database. This seems like such a messy way of doing this, so if you have any better ideas please post them here.
class MonthYearWidget(forms.MultiWidget):
def __init__(self, attrs=None):
months = (
('01', 'Jan (01)'),
('02', 'Feb (02)'),
('03', 'Mar (03)'),
('04', 'Apr (04)'),
('05', 'May (05)'),
('06', 'Jun (06)'),
('07', 'Jul (07)'),
('08', 'Aug (08)'),
('09', 'Sep (09)'),
('10', 'Oct (10)'),
('11', 'Nov (11)'),
('12', 'Dec (12)'),
)
year = int(datetime.date.today().year)
year_digits = range(year, year+10)
years = [(year, year) for year in year_digits]
widgets = (forms.Select(attrs=attrs, choices=months), forms.Select(attrs=attrs, choices=years))
super(MonthYearWidget, self).__init__(widgets, attrs)
def decompress(self, value):
if value:
return [value.month, value.year]
return [None, None]
def render(self, name, value, attrs=None):
try:
value = datetime.date(month=int(value[0]), year=int(value[1]), day=1)
except:
value = ''
return super(MonthYearWidget, self).render(name, value, attrs)
class MonthYearField(forms.MultiValueField):
def __init__(self, *args, **kwargs):
forms.MultiValueField.__init__(self, *args, **kwargs)
self.fields = (forms.CharField(), forms.CharField(),)
def compress(self, data_list):
if data_list:
return datetime.date(year=int(data_list[1]), month=int(data_list[0]), day=1)
return datetime.date.today()
and then here's where I'm stuck, in the template. I can't figure out what the name of the iterable list for the months and years is (if there is one). Finding that iterable list is the problem; I already plan to use an ifequal statement to determine which option the "selected='selected'" should apply to. I have only tried to iterate over the months so far.
<form action="#" method="POST">
{% csrf_token %}
<p>{{ form.from_email.label_tag }}: {{ form.from_email }}</p>
<p>{{ form.working_month.label_tag }}:
<select name="working_month_0" id="id_working_month_0">
{% for i in form.working_month.data_list %}
<option value="{{ i }}">{{ option.from_email }}</option>
{% endfor %}
</select>
<p><input type="submit" value="Change Settings Now" /></p>
</form>
Thanks in advance for any guidance you all can provide.
EDIT: Here is the generic view:
def option_edit(request,option_id):
try:
option = Option.objects.get(pk=option_id)
except Option.DoesNotExist:
raise Http404
return create_update.update_object(
request,
form_class = OptionForm,
template_name = 'options.html',
template_object_name = 'option',
object_id = option_id,
post_save_redirect = '/some/address/' + option_id + '/edit/'
)
... and the form class:
class OptionForm(ModelForm):
class Meta:
model = Option
working_month = MonthYearField(widget=MonthYearWidget)
I think the model is relevant, too:
class Option(models.Model):
from_email = models.EmailField()
working_month = models.DateField()
Do I have to create a custom model field in addition to the custom form field, or can I use this setup?
A:
The magic of django forms is that you don't need to do all that. By calling the form's select field by name, it will render it and select the right option as based on initial/instance data passed into the form on instantation.
{{form.working_month}}
If you're still having troubles, can you post the form class as well?
Good luck!
EDIT
In looking at the first comment on the link you posted, this issue is addressed. The commenter included this code
def __init__(self, *args, **kwargs):
forms.MultiValueField.__init__(self, *args, **kwargs)
self.fields = (forms.CharField(), forms.CharField(),)
A:
A slight variation of your problem is solved here
http://skyl.org/log/post/skyl/2010/01/subclass-django-forms-widgets-radiofieldrenderer-and-django-forms-widgets-radioselect-for-custom-rendering-of-individual-choices/
| Django: iterating over the options in a custom select field | I'm using a custom MM/YY field and widget based on this example. I want to iterate over the individual month and year options defined in the widget class in order to apply "selected='selected'" to the MM/YY value that corresponds with the MM/YY value stored in the database. This seems like such a messy way of doing this, so if you have any better ideas please post them here.
class MonthYearWidget(forms.MultiWidget):
def __init__(self, attrs=None):
months = (
('01', 'Jan (01)'),
('02', 'Feb (02)'),
('03', 'Mar (03)'),
('04', 'Apr (04)'),
('05', 'May (05)'),
('06', 'Jun (06)'),
('07', 'Jul (07)'),
('08', 'Aug (08)'),
('09', 'Sep (09)'),
('10', 'Oct (10)'),
('11', 'Nov (11)'),
('12', 'Dec (12)'),
)
year = int(datetime.date.today().year)
year_digits = range(year, year+10)
years = [(year, year) for year in year_digits]
widgets = (forms.Select(attrs=attrs, choices=months), forms.Select(attrs=attrs, choices=years))
super(MonthYearWidget, self).__init__(widgets, attrs)
def decompress(self, value):
if value:
return [value.month, value.year]
return [None, None]
def render(self, name, value, attrs=None):
try:
value = datetime.date(month=int(value[0]), year=int(value[1]), day=1)
except:
value = ''
return super(MonthYearWidget, self).render(name, value, attrs)
class MonthYearField(forms.MultiValueField):
def __init__(self, *args, **kwargs):
forms.MultiValueField.__init__(self, *args, **kwargs)
self.fields = (forms.CharField(), forms.CharField(),)
def compress(self, data_list):
if data_list:
return datetime.date(year=int(data_list[1]), month=int(data_list[0]), day=1)
return datetime.date.today()
and then here's where I'm stuck, in the template. I can't figure out what the name of the iterable list for the months and years is (if there is one). Finding that iterable list is the problem; I already plan to use an ifequal statement to determine which option the "selected='selected'" should apply to. I have only tried to iterate over the months so far.
<form action="#" method="POST">
{% csrf_token %}
<p>{{ form.from_email.label_tag }}: {{ form.from_email }}</p>
<p>{{ form.working_month.label_tag }}:
<select name="working_month_0" id="id_working_month_0">
{% for i in form.working_month.data_list %}
<option value="{{ i }}">{{ option.from_email }}</option>
{% endfor %}
</select>
<p><input type="submit" value="Change Settings Now" /></p>
</form>
Thanks in advance for any guidance you all can provide.
EDIT: Here is the generic view:
def option_edit(request,option_id):
try:
option = Option.objects.get(pk=option_id)
except Option.DoesNotExist:
raise Http404
return create_update.update_object(
request,
form_class = OptionForm,
template_name = 'options.html',
template_object_name = 'option',
object_id = option_id,
post_save_redirect = '/some/address/' + option_id + '/edit/'
)
... and the form class:
class OptionForm(ModelForm):
class Meta:
model = Option
working_month = MonthYearField(widget=MonthYearWidget)
I think the model is relevant, too:
class Option(models.Model):
from_email = models.EmailField()
working_month = models.DateField()
Do I have to create a custom model field in addition to the custom form field, or can I use this setup?
| [
"The magic of django forms is that you don't need to do all that. By calling the form's select field by name, it will render it and select the right option as based on initial/instance data passed into the form on instantation.\n{{form.working_month}}\n\nIf you're still having troubles, can you post the form class as well?\nGood luck!\nEDIT\nIn looking at the first comment on the link you posted, this issue is addressed. The commenter included this code\ndef __init__(self, *args, **kwargs):\n forms.MultiValueField.__init__(self, *args, **kwargs)\n self.fields = (forms.CharField(), forms.CharField(),)\n\n",
"A slight variation of your problem is solved here\nhttp://skyl.org/log/post/skyl/2010/01/subclass-django-forms-widgets-radiofieldrenderer-and-django-forms-widgets-radioselect-for-custom-rendering-of-individual-choices/\n"
] | [
2,
0
] | [] | [] | [
"django",
"django_forms",
"django_templates",
"python"
] | stackoverflow_0001975411_django_django_forms_django_templates_python.txt |
Q:
Get a C reference to an embedded python function by name?
Assuming I have some embedded python code containing a function foo, what is the best way to get a reference to that function (for use with PyObject_CallObject)?
One way is to have some function register each function along with the function name either manually or through use of reflection. This seems like overkill.
Another way is to create a "loader" function that takes the function name and returns a reference to the function. Better, but I still have to register the loader function with C.
Am I missing a better way to do this with or without having to write any additional python code?
A:
Read the section in the documentation about embedding Python. I guess you have a reference to the module containing the function.
At the end there is an example which shows how to get a function reference out of an object.
pFunc = PyObject_GetAttrString(pModule, argv[2]);
/* pFunc is a new reference */
if (pFunc && PyCallable_Check(pFunc)) {
...
}
Py_XDECREF(pFunc);
| Get a C reference to an embedded python function by name? | Assuming I have some embedded python code containing a function foo, what is the best way to get a reference to that function (for use with PyObject_CallObject)?
One way is to have some function register each function along with the function name either manually or through use of reflection. This seems like overkill.
Another way is to create a "loader" function that takes the function name and returns a reference to the function. Better, but I still have to register the loader function with C.
Am I missing a better way to do this with or without having to write any additional python code?
| [
"Read the section in the documentation about embedding Python. I guess you have a reference to the module containing the function.\nAt the end there is an example which shows how to get a function reference out of an object.\npFunc = PyObject_GetAttrString(pModule, argv[2]);\n/* pFunc is a new reference */\n\nif (pFunc && PyCallable_Check(pFunc)) {\n ...\n}\nPy_XDECREF(pFunc);\n\n"
] | [
1
] | [] | [] | [
"c",
"embedded_language",
"python"
] | stackoverflow_0002067496_c_embedded_language_python.txt |
Q:
Utilities or libraries for finding most closely matched binary file
I would like to be able to compare a binary file X to a directory of other binary files and find which other file is most similar to X. The nature of the data is such that identical chunks will exist between files, but possibly shifted in location. The files are all 1MB in size, and there are about 200 of them. I would like to be have something quick enough to analyze these in a few minutes or less on a modern desktop computer.
I've googled a bit and found a few different binary diff utilities, but none of them seem appropriate for my application.
For example there is bsdiff, which looks like it creates some a patch file which is optimized for size. Or vbindiff which just displays the differences graphically, but those don't really seem to help me figure out if one file is more similar to X than another file.
If there is not a tool that I can use directly for this purpose, is there a good library someone could recommend for writing my own utility? Python would be preferable, but I'm flexible.
A:
Here's a simple perl script which more or less tries to do exactly that.
Edit: Also have a look at the following stackoverflow thread.
| Utilities or libraries for finding most closely matched binary file | I would like to be able to compare a binary file X to a directory of other binary files and find which other file is most similar to X. The nature of the data is such that identical chunks will exist between files, but possibly shifted in location. The files are all 1MB in size, and there are about 200 of them. I would like to be have something quick enough to analyze these in a few minutes or less on a modern desktop computer.
I've googled a bit and found a few different binary diff utilities, but none of them seem appropriate for my application.
For example there is bsdiff, which looks like it creates some a patch file which is optimized for size. Or vbindiff which just displays the differences graphically, but those don't really seem to help me figure out if one file is more similar to X than another file.
If there is not a tool that I can use directly for this purpose, is there a good library someone could recommend for writing my own utility? Python would be preferable, but I'm flexible.
| [
"Here's a simple perl script which more or less tries to do exactly that.\nEdit: Also have a look at the following stackoverflow thread.\n"
] | [
0
] | [] | [] | [
"diff",
"python",
"utility"
] | stackoverflow_0002067628_diff_python_utility.txt |
Q:
deploying django to UserDir
I would like to deploy my django pet-project on our student server. We have apache2 with UserDir mod and I don't have access to apache2 config files. How do I deploy? :-D
I come from PHP background and I deploy my PHP scripts by uploading them to my public_html dir and everything shows up on http://ourserver.com/~myusername. I read django documentation and it says I should add <Location>some stuff</Location> to our apache config file. I don't have access to it, so I tried putting it in .htaccess in my public_html dir and that didn't work. I googled a lot and I think I read somewhere you can't put <Location> in .htaccess, but now I can't find that quote.
So, anybody here deployed django to UserDir without harassing apache admins?
edit:
I tested mod_python as Graham Dumpleton advised here, and I can use mod_python without problems. Also, I found error log and here is what error log says when I put <Location>some stuff</Location> in .htaccess:
"[Thu Oct 01 21:33:19 2009] [alert] [client 188.129.74.66] /path/to/my/.htaccess: <Location not allowed here"
So, it seems like I really can't put <Location> into .htaccess. So, what are my options?
A:
If mod_python installed, first see if you can actually use it without needing administrator to do anything. Read:
http://www.dscpl.com.au/wiki/ModPython/Articles/GettingModPythonWorking
Unless you are a trusted user or administrators don't know what they are doing, they shouldn't be allowing you to use mod_python because your code will run as Apache user and if anyone else also running applications same way, you could interfere with each others applications and data. In other words it isn't secure and shouldn't be used in shared hosting environments where multiple users on same Apache instance.
UPDATE 1
On the basis that you now have mod_python working, you should be able to replace contents of mptest.py with something like:
import os
os.environ['DJANGO_SETTINGS_MODULE'] = 'mysite.settings'
import sys
sys.path.insert(0, '/some/path/to/project/area/mysite')
sys.path.insert(0, '/some/path/to/project/area')
from django.core.handlers.modpython import handler as _handler
def handler(req):
req.get_options()['django.root'] = '/~myusername/mptest.py'
return _handler(req)
Obviously, various paths and values in that should be changed per your naming.
The site would be accessed as '/~myusername/mptest.py'.
At this point you will find out silly using mod_python is where you don't have control of Apache. This is because when you change code in your site, you will need to ask the administrators to restart Apache for you for your changes to be picked up.
Using mod_wsgi in its daemon mode with you as owner of daemon process would be much better, but if they are already running mod_python I wouldn't be recommending they load both modules at same time as mod_python issues screw up use of mod_wsgi in some cases and if they haven't installed Python properly, you are just likely to have lots of issues and so not worth the trouble.
In short, using mod_python in shared hosting environment where you have no control of Apache is silly and insecure.
All the same, have documented how to run Django out of per user directory as I don't think it has been documented anywhere previously.
A:
Are mod_python or mod_wsgi enabled on the base Apache? You'll need that as a minimum.
A:
Would you be allowed to run your own long-running server process on some port other than 80? This might allow you to serve Django content either with a Django test server or your own copy of Apache with local configuration files.
A:
Have you tried using <Directory> instead of <Location>? If that isn't blocked by local policy you should be able to do something like this:
<Directory /path/to/your/home/public_html>
# mod_python stuff here
</Directory>
I'd go with either mod_wsgi or fastcgi if you're on good terms with your admin. If that's the case, however, you should simply be able to give your admin the mod_wsgi config since it supports update-based reloading and running as an alternate user. He should be able to set it up to simply run a single wsgi file under your account - something like this, possibly with an allow from all depending on how security is configured:
<Directory /home/you/public_html>
WSGIApplicationGroup PROJECT
WSGIDaemonProcess YOU threads=15 processes=2 python-path=/home/YOU/.virtualenvs/PROJECT-env/lib/python2.6/site-packages
WSGIProcessGroup YOUR_GROUP
WSGIScriptAlias / /home/YOU/PROJECT/deploy/PROJECT.wsgi
</Directory>
As an aside, the above assumes the use of the awesome, highly-recommended virtualenv and virtualenvwrapper to create a local python sandbox in your home directory. This will massively simplify life running as a non-admin or when you have more than one project. If you don't use virtualenv the python-path above can be removed entirely.
A:
If mod_fcgi is configured, you can use that. See http://docs.djangoproject.com/en/dev/howto/deployment/fastcgi/
| deploying django to UserDir | I would like to deploy my django pet-project on our student server. We have apache2 with UserDir mod and I don't have access to apache2 config files. How do I deploy? :-D
I come from PHP background and I deploy my PHP scripts by uploading them to my public_html dir and everything shows up on http://ourserver.com/~myusername. I read django documentation and it says I should add <Location>some stuff</Location> to our apache config file. I don't have access to it, so I tried putting it in .htaccess in my public_html dir and that didn't work. I googled a lot and I think I read somewhere you can't put <Location> in .htaccess, but now I can't find that quote.
So, anybody here deployed django to UserDir without harassing apache admins?
edit:
I tested mod_python as Graham Dumpleton advised here, and I can use mod_python without problems. Also, I found error log and here is what error log says when I put <Location>some stuff</Location> in .htaccess:
"[Thu Oct 01 21:33:19 2009] [alert] [client 188.129.74.66] /path/to/my/.htaccess: <Location not allowed here"
So, it seems like I really can't put <Location> into .htaccess. So, what are my options?
| [
"If mod_python installed, first see if you can actually use it without needing administrator to do anything. Read:\nhttp://www.dscpl.com.au/wiki/ModPython/Articles/GettingModPythonWorking\nUnless you are a trusted user or administrators don't know what they are doing, they shouldn't be allowing you to use mod_python because your code will run as Apache user and if anyone else also running applications same way, you could interfere with each others applications and data. In other words it isn't secure and shouldn't be used in shared hosting environments where multiple users on same Apache instance.\n\nUPDATE 1\nOn the basis that you now have mod_python working, you should be able to replace contents of mptest.py with something like:\nimport os\nos.environ['DJANGO_SETTINGS_MODULE'] = 'mysite.settings'\n\nimport sys\nsys.path.insert(0, '/some/path/to/project/area/mysite')\nsys.path.insert(0, '/some/path/to/project/area')\n\nfrom django.core.handlers.modpython import handler as _handler\n\ndef handler(req):\n req.get_options()['django.root'] = '/~myusername/mptest.py'\n return _handler(req)\n\nObviously, various paths and values in that should be changed per your naming.\nThe site would be accessed as '/~myusername/mptest.py'.\nAt this point you will find out silly using mod_python is where you don't have control of Apache. This is because when you change code in your site, you will need to ask the administrators to restart Apache for you for your changes to be picked up.\nUsing mod_wsgi in its daemon mode with you as owner of daemon process would be much better, but if they are already running mod_python I wouldn't be recommending they load both modules at same time as mod_python issues screw up use of mod_wsgi in some cases and if they haven't installed Python properly, you are just likely to have lots of issues and so not worth the trouble.\nIn short, using mod_python in shared hosting environment where you have no control of Apache is silly and insecure.\nAll the same, have documented how to run Django out of per user directory as I don't think it has been documented anywhere previously.\n",
"Are mod_python or mod_wsgi enabled on the base Apache? You'll need that as a minimum.\n",
"Would you be allowed to run your own long-running server process on some port other than 80? This might allow you to serve Django content either with a Django test server or your own copy of Apache with local configuration files.\n",
"Have you tried using <Directory> instead of <Location>? If that isn't blocked by local policy you should be able to do something like this:\n<Directory /path/to/your/home/public_html>\n# mod_python stuff here\n</Directory>\n\nI'd go with either mod_wsgi or fastcgi if you're on good terms with your admin. If that's the case, however, you should simply be able to give your admin the mod_wsgi config since it supports update-based reloading and running as an alternate user. He should be able to set it up to simply run a single wsgi file under your account - something like this, possibly with an allow from all depending on how security is configured:\n<Directory /home/you/public_html>\nWSGIApplicationGroup PROJECT\nWSGIDaemonProcess YOU threads=15 processes=2 python-path=/home/YOU/.virtualenvs/PROJECT-env/lib/python2.6/site-packages\nWSGIProcessGroup YOUR_GROUP\nWSGIScriptAlias / /home/YOU/PROJECT/deploy/PROJECT.wsgi\n</Directory>\n\nAs an aside, the above assumes the use of the awesome, highly-recommended virtualenv and virtualenvwrapper to create a local python sandbox in your home directory. This will massively simplify life running as a non-admin or when you have more than one project. If you don't use virtualenv the python-path above can be removed entirely.\n",
"If mod_fcgi is configured, you can use that. See http://docs.djangoproject.com/en/dev/howto/deployment/fastcgi/\n"
] | [
1,
0,
0,
0,
0
] | [] | [] | [
"apache",
"django",
"python"
] | stackoverflow_0001491102_apache_django_python.txt |
Q:
How to fetch some data conditionally with Python and Beautiful Soup
Sorry if you feel like this has been asked but I have read the related questions and being quite new to Python I could not find how to write this request in a clean manner.
For now I have this minimal Python code:
from mechanize import Browser
from BeautifulSoup import BeautifulSoup
import re
import urllib2
br = Browser()
br.open("http://www.atpworldtour.com/Rankings/Singles.aspx")
filename = "rankings.html"
FILE = open(filename,"w")
html = br.response().read();
soup = BeautifulSoup(html);
links = soup.findAll('a', href=re.compile("Players"));
for link in links:
print link['href'];
FILE.writelines(html);
It retrieves all the link where the href contains the word player.
Now the HTML I need to parse looks something like this:
<tr>
<td>1</td>
<td><a href="/Tennis/Players/Top-Players/Roger-Federer.aspx">Federer, Roger</a> (SUI)</td>
<td><a href="/Tennis/Players/Top-Players/Roger-Federer.aspx?t=rb">10,550</a></td>
<td>0</td>
<td><a href="/Tennis/Players/Top-Players/Roger-Federer.aspx?t=pa&m=s">19</a></td>
</tr>
The 1 contains the rank of the player.
I would like to be able to retrieve this data in a dictionary:
rank
name of the player
link to the detailed page (here /Tennis/Players/Top-Players/Roger-Federer.aspx)
Could you give me some pointers or if this is easy enough help me to build the piece of code ? I am not sure about how to formulate the request in Beautiful Soup.
Anthony
A:
Searching for the players using your method will work, but will return 3 results per player. Easier to search for the table itself, and then iterate over the rows (except the header):
table=soup.find('table', 'bioTableAlt')
for row in table.findAll('tr')[1:]:
cells = row.findAll('td')
#retreieve data from cells...
To get the data you need:
rank = cells[0].string
player = cells[1].a.string
link = cells[1].a['href']
| How to fetch some data conditionally with Python and Beautiful Soup | Sorry if you feel like this has been asked but I have read the related questions and being quite new to Python I could not find how to write this request in a clean manner.
For now I have this minimal Python code:
from mechanize import Browser
from BeautifulSoup import BeautifulSoup
import re
import urllib2
br = Browser()
br.open("http://www.atpworldtour.com/Rankings/Singles.aspx")
filename = "rankings.html"
FILE = open(filename,"w")
html = br.response().read();
soup = BeautifulSoup(html);
links = soup.findAll('a', href=re.compile("Players"));
for link in links:
print link['href'];
FILE.writelines(html);
It retrieves all the link where the href contains the word player.
Now the HTML I need to parse looks something like this:
<tr>
<td>1</td>
<td><a href="/Tennis/Players/Top-Players/Roger-Federer.aspx">Federer, Roger</a> (SUI)</td>
<td><a href="/Tennis/Players/Top-Players/Roger-Federer.aspx?t=rb">10,550</a></td>
<td>0</td>
<td><a href="/Tennis/Players/Top-Players/Roger-Federer.aspx?t=pa&m=s">19</a></td>
</tr>
The 1 contains the rank of the player.
I would like to be able to retrieve this data in a dictionary:
rank
name of the player
link to the detailed page (here /Tennis/Players/Top-Players/Roger-Federer.aspx)
Could you give me some pointers or if this is easy enough help me to build the piece of code ? I am not sure about how to formulate the request in Beautiful Soup.
Anthony
| [
"Searching for the players using your method will work, but will return 3 results per player. Easier to search for the table itself, and then iterate over the rows (except the header):\ntable=soup.find('table', 'bioTableAlt')\nfor row in table.findAll('tr')[1:]:\n cells = row.findAll('td')\n #retreieve data from cells...\n\nTo get the data you need:\n rank = cells[0].string\n player = cells[1].a.string\n link = cells[1].a['href']\n\n"
] | [
3
] | [] | [] | [
"beautifulsoup",
"python"
] | stackoverflow_0002067710_beautifulsoup_python.txt |
Q:
Efficient method to store Python dictionary on disk?
What is the most efficient method to store a Python dictionary on the disk? The only methods I know of right now are plain-text and the pickle module.
Edit: Sorry for not being very clear. By efficient I meant fastest execution speed. The dictionary will contain mutable objects that will hold information to be parsed and modified.
A:
shelve is pretty nice as well
or this persistent dictionary recipe
for a convenient method that keeps your objects synchronized with storage, there's the ORM SQLAlchemy for python
if you just need a way to store string values by some key, theres the dbm.ndbm and dbm.gnu modules.
if you need a hyper efficient, distributed key value cache, something like memcached for python...
A:
JSON and YAML work well, also.
Depends on what you mean by "efficient"? Size of file? Time required? Amount of code you need to write?
You have the timeit module available to determine what meets your specific criteria for "efficient".
| Efficient method to store Python dictionary on disk? | What is the most efficient method to store a Python dictionary on the disk? The only methods I know of right now are plain-text and the pickle module.
Edit: Sorry for not being very clear. By efficient I meant fastest execution speed. The dictionary will contain mutable objects that will hold information to be parsed and modified.
| [
"shelve is pretty nice as well\nor this persistent dictionary recipe\nfor a convenient method that keeps your objects synchronized with storage, there's the ORM SQLAlchemy for python\nif you just need a way to store string values by some key, theres the dbm.ndbm and dbm.gnu modules.\nif you need a hyper efficient, distributed key value cache, something like memcached for python...\n",
"JSON and YAML work well, also. \nDepends on what you mean by \"efficient\"? Size of file? Time required? Amount of code you need to write?\nYou have the timeit module available to determine what meets your specific criteria for \"efficient\".\n"
] | [
9,
2
] | [] | [] | [
"dictionary",
"disk",
"pickle",
"python"
] | stackoverflow_0002067749_dictionary_disk_pickle_python.txt |
Q:
python list of dicts how to merge key:value where values are same?
Python newb here looking for some assistance...
For a variable number of dicts in a python list like:
list_dicts = [
{'id':'001', 'name':'jim', 'item':'pencil', 'price':'0.99'},
{'id':'002', 'name':'mary', 'item':'book', 'price':'15.49'},
{'id':'002', 'name':'mary', 'item':'tape', 'price':'7.99'},
{'id':'003', 'name':'john', 'item':'pen', 'price':'3.49'},
{'id':'003', 'name':'john', 'item':'stapler', 'price':'9.49'},
{'id':'003', 'name':'john', 'item':'scissors', 'price':'12.99'},
]
I'm trying to find the best way to group dicts where the value of key "id" is equal, then add/merge any unique key:value and create a new list of dicts like:
list_dicts2 = [
{'id':'001', 'name':'jim', 'item1':'pencil', 'price1':'0.99'},
{'id':'002', 'name':'mary', 'item1':'book', 'price1':'15.49', 'item2':'tape', 'price2':'7.99'},
{'id':'003', 'name':'john', 'item1':'pen', 'price1':'3.49', 'item2':'stapler', 'price2':'9.49', 'item3':'scissors', 'price3':'12.99'},
]
So far, I've figured out how to group the dicts in the list with:
myList = itertools.groupby(list_dicts, operator.itemgetter('id'))
But I'm struggling with how to build the new list of dicts to:
1) Add the extra keys and values to the first dict instance that has the same "id"
2) Set the new name for "item" and "price" keys (e.g. "item1", "item2", "item3"). This seems clunky to me, is there a better way?
3) Loop over each "id" match to build up a string for later output
I've chosen to return a new list of dicts only because of the convenience of passing a dict to a templating function where setting variables by a descriptive key is helpful (there are many vars). If there is a cleaner more concise way to accomplish this, I'd be curious to learn. Again, I'm pretty new to Python and in working with data structures like this.
A:
Try to avoid complex nested data structures. I believe people tend to
grok them only while they are intensively using the data structure. After the
program is finished, or is set aside for a while, the data structure quickly
becomes mystifying.
Objects can be used to retain or even add richness to the data structure in a saner, more organized way. For instance, it appears the item and price always go together. So the two pieces of data might as well be paired in an object:
class Item(object):
def __init__(self,name,price):
self.name=name
self.price=price
Similarly, a person seems to have an id and name and a set of possessions:
class Person(object):
def __init__(self,id,name,*items):
self.id=id
self.name=name
self.items=set(items)
If you buy into the idea of using classes like these, then your list_dicts could become
list_people = [
Person('001','jim',Item('pencil',0.99)),
Person('002','mary',Item('book',15.49)),
Person('002','mary',Item('tape',7.99)),
Person('003','john',Item('pen',3.49)),
Person('003','john',Item('stapler',9.49)),
Person('003','john',Item('scissors',12.99)),
]
Then, to merge the people based on id, you could use Python's reduce function,
along with take_items, which takes (merges) the items from one person and gives them to another:
def take_items(person,other):
'''
person takes other's items.
Note however, that although person may be altered, other remains the same --
other does not lose its items.
'''
person.items.update(other.items)
return person
Putting it all together:
import itertools
import operator
class Item(object):
def __init__(self,name,price):
self.name=name
self.price=price
def __str__(self):
return '{0} {1}'.format(self.name,self.price)
class Person(object):
def __init__(self,id,name,*items):
self.id=id
self.name=name
self.items=set(items)
def __str__(self):
return '{0} {1}: {2}'.format(self.id,self.name,map(str,self.items))
list_people = [
Person('001','jim',Item('pencil',0.99)),
Person('002','mary',Item('book',15.49)),
Person('002','mary',Item('tape',7.99)),
Person('003','john',Item('pen',3.49)),
Person('003','john',Item('stapler',9.49)),
Person('003','john',Item('scissors',12.99)),
]
def take_items(person,other):
'''
person takes other's items.
Note however, that although person may be altered, other remains the same --
other does not lose its items.
'''
person.items.update(other.items)
return person
list_people2 = [reduce(take_items,g)
for k,g in itertools.groupby(list_people, lambda person: person.id)]
for person in list_people2:
print(person)
A:
I imagine it would be easier to combine the items in list_dicts into something that looks more like this:
list_dicts2 = [{'id':1, 'name':'jim', 'items':[{'itemname':'pencil','price':'0.99'}], {'id':2, 'name':'mary', 'items':[{'itemname':'book','price':'15.49'}, {'itemname':'tape','price':'7.99'}]]
You could also use a list of tuples for 'items' or perhaps a named tuple.
A:
This looks very much like a homework problem.
As the above poster mentioned, there are a few more appropriate data structures for this kind of data, some variant on the following might be reasonable:
[ ('001', 'jim', [('pencil', '0.99')]),
('002', 'mary', [('book', '15.49'), ('tape', '7.99')]),
('003', 'john', [('pen', '3.49'), ('stapler', '9.49'), ('scissors', '12.99')])]
This can be made with the relatively simple:
list2 = []
for id,iter in itertools.groupby(list_dicts,operator.itemgetter('id')):
idList = list(iter)
list2.append((id,idList[0]['name'],[(z['item'],z['price']) for z in idList]))
The interesting thing about this question is the difficulty in extracting 'name' when using groupby, without iterating past the item.
To get back to the original goal though, you could use code like this (as the OP suggested):
list3 = []
for id,name,itemList in list2:
newitem = dict({'id':id,'name':name})
for index,items in enumerate(itemList):
newitem['item'+str(index+1)] = items[0]
newitem['price'+str(index+1)] = items[1]
list3.append(newitem)
| python list of dicts how to merge key:value where values are same? | Python newb here looking for some assistance...
For a variable number of dicts in a python list like:
list_dicts = [
{'id':'001', 'name':'jim', 'item':'pencil', 'price':'0.99'},
{'id':'002', 'name':'mary', 'item':'book', 'price':'15.49'},
{'id':'002', 'name':'mary', 'item':'tape', 'price':'7.99'},
{'id':'003', 'name':'john', 'item':'pen', 'price':'3.49'},
{'id':'003', 'name':'john', 'item':'stapler', 'price':'9.49'},
{'id':'003', 'name':'john', 'item':'scissors', 'price':'12.99'},
]
I'm trying to find the best way to group dicts where the value of key "id" is equal, then add/merge any unique key:value and create a new list of dicts like:
list_dicts2 = [
{'id':'001', 'name':'jim', 'item1':'pencil', 'price1':'0.99'},
{'id':'002', 'name':'mary', 'item1':'book', 'price1':'15.49', 'item2':'tape', 'price2':'7.99'},
{'id':'003', 'name':'john', 'item1':'pen', 'price1':'3.49', 'item2':'stapler', 'price2':'9.49', 'item3':'scissors', 'price3':'12.99'},
]
So far, I've figured out how to group the dicts in the list with:
myList = itertools.groupby(list_dicts, operator.itemgetter('id'))
But I'm struggling with how to build the new list of dicts to:
1) Add the extra keys and values to the first dict instance that has the same "id"
2) Set the new name for "item" and "price" keys (e.g. "item1", "item2", "item3"). This seems clunky to me, is there a better way?
3) Loop over each "id" match to build up a string for later output
I've chosen to return a new list of dicts only because of the convenience of passing a dict to a templating function where setting variables by a descriptive key is helpful (there are many vars). If there is a cleaner more concise way to accomplish this, I'd be curious to learn. Again, I'm pretty new to Python and in working with data structures like this.
| [
"Try to avoid complex nested data structures. I believe people tend to\ngrok them only while they are intensively using the data structure. After the\nprogram is finished, or is set aside for a while, the data structure quickly\nbecomes mystifying.\nObjects can be used to retain or even add richness to the data structure in a saner, more organized way. For instance, it appears the item and price always go together. So the two pieces of data might as well be paired in an object:\nclass Item(object):\n def __init__(self,name,price):\n self.name=name\n self.price=price\n\nSimilarly, a person seems to have an id and name and a set of possessions:\nclass Person(object):\n def __init__(self,id,name,*items):\n self.id=id\n self.name=name\n self.items=set(items)\n\nIf you buy into the idea of using classes like these, then your list_dicts could become\nlist_people = [\n Person('001','jim',Item('pencil',0.99)),\n Person('002','mary',Item('book',15.49)),\n Person('002','mary',Item('tape',7.99)),\n Person('003','john',Item('pen',3.49)),\n Person('003','john',Item('stapler',9.49)),\n Person('003','john',Item('scissors',12.99)), \n]\n\nThen, to merge the people based on id, you could use Python's reduce function,\nalong with take_items, which takes (merges) the items from one person and gives them to another:\ndef take_items(person,other):\n '''\n person takes other's items.\n Note however, that although person may be altered, other remains the same --\n other does not lose its items. \n '''\n person.items.update(other.items)\n return person\n\nPutting it all together:\nimport itertools\nimport operator\n\nclass Item(object):\n def __init__(self,name,price):\n self.name=name\n self.price=price\n def __str__(self):\n return '{0} {1}'.format(self.name,self.price)\n\nclass Person(object):\n def __init__(self,id,name,*items):\n self.id=id\n self.name=name\n self.items=set(items)\n def __str__(self):\n return '{0} {1}: {2}'.format(self.id,self.name,map(str,self.items))\n\nlist_people = [\n Person('001','jim',Item('pencil',0.99)),\n Person('002','mary',Item('book',15.49)),\n Person('002','mary',Item('tape',7.99)),\n Person('003','john',Item('pen',3.49)),\n Person('003','john',Item('stapler',9.49)),\n Person('003','john',Item('scissors',12.99)), \n]\n\ndef take_items(person,other):\n '''\n person takes other's items.\n Note however, that although person may be altered, other remains the same --\n other does not lose its items. \n '''\n person.items.update(other.items)\n return person\n\nlist_people2 = [reduce(take_items,g)\n for k,g in itertools.groupby(list_people, lambda person: person.id)]\nfor person in list_people2:\n print(person)\n\n",
"I imagine it would be easier to combine the items in list_dicts into something that looks more like this:\nlist_dicts2 = [{'id':1, 'name':'jim', 'items':[{'itemname':'pencil','price':'0.99'}], {'id':2, 'name':'mary', 'items':[{'itemname':'book','price':'15.49'}, {'itemname':'tape','price':'7.99'}]]\nYou could also use a list of tuples for 'items' or perhaps a named tuple.\n",
"This looks very much like a homework problem.\nAs the above poster mentioned, there are a few more appropriate data structures for this kind of data, some variant on the following might be reasonable:\n[ ('001', 'jim', [('pencil', '0.99')]), \n('002', 'mary', [('book', '15.49'), ('tape', '7.99')]), \n('003', 'john', [('pen', '3.49'), ('stapler', '9.49'), ('scissors', '12.99')])]\n\nThis can be made with the relatively simple:\nlist2 = []\nfor id,iter in itertools.groupby(list_dicts,operator.itemgetter('id')):\n idList = list(iter)\n list2.append((id,idList[0]['name'],[(z['item'],z['price']) for z in idList]))\n\nThe interesting thing about this question is the difficulty in extracting 'name' when using groupby, without iterating past the item.\nTo get back to the original goal though, you could use code like this (as the OP suggested):\nlist3 = []\nfor id,name,itemList in list2:\n newitem = dict({'id':id,'name':name})\n for index,items in enumerate(itemList):\n newitem['item'+str(index+1)] = items[0]\n newitem['price'+str(index+1)] = items[1]\n list3.append(newitem)\n\n"
] | [
10,
0,
0
] | [] | [] | [
"dictionary",
"list",
"merge",
"python"
] | stackoverflow_0002067627_dictionary_list_merge_python.txt |
Q:
Broken Pipe from subprocess.Popen.communciate() with stdin
I'm having a strange issue when using subprocess.Popen.communicate(). For background, I want to execute an application from my python script. When I run the program from the command line, I do it like this (UNIX):
$ echo "input text" | /path/to/myapp
From my script, I also want to pipe the input into the application. So, I tried the following. But I get a "broken pipe" error when I try to send the input with communicate():
>>> cmd = ['/path/to/myapp']
>>> p = subprocess.Popen(cmd, stdout=subprocess.PIPE, stderr=subprocess.STDOUT, stdin=subprocess.PIPE)
>>> out,err = p.communicate('input text')
Traceback (most recent call last):
File "", line 1, in
File "/usr/lib/python2.5/subprocess.py", line 670, in communicate
return self._communicate(input)
File "/usr/lib/python2.5/subprocess.py", line 1223, in _communicate
bytes_written = self._write_no_intr(self.stdin.fileno(), buffer(input, input_offset, 512))
File "/usr/lib/python2.5/subprocess.py", line 1003, in _write_no_intr
return os.write(fd, s)
OSError: [Errno 32] Broken pipe
To make matters stranger, if I leave out the input data, I don't get any errors. However, this isn't really a good workaround because the application needs input to work.
>>> p = subprocess.Popen(cmd, stdout=subprocess.PIPE, stderr=subprocess.STDOUT, stdin=subprocess.PIPE)
>>> out,err = p.communicate()
>>> print out
[error from myapp regarding lack of input]
Any idea what I'm missing?
A:
Your observation suggests that myapp is terminating without reading (all of the) input. Not knowing anything about myapp, that's hard to confirm, but consider for example
$ echo 'hello world' | tr 'l' 'L'
heLLo worLd
now...:
>>> cmd = ['/usr/bin/tr']
>>> p = subprocess.Popen(cmd, stdout=subprocess.PIPE, stderr=subprocess.STDOUT, stdin=subprocess.PIPE)
>>> out,err = p.communicate('hello world')
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "/usr/lib/python2.5/subprocess.py", line 668, in communicate
return self._communicate(input)
File "/usr/lib/python2.5/subprocess.py", line 1218, in _communicate
bytes_written = self._write_no_intr(self.stdin.fileno(), buffer(input, input_offset, 512))
File "/usr/lib/python2.5/subprocess.py", line 997, in _write_no_intr
return os.write(fd, s)
OSError: [Errno 32] Broken pipe
because...:
>>> p = subprocess.Popen(cmd, stdout=subprocess.PIPE, stdin=subprocess.PIPE)
>>> /usr/bin/tr: missing operand
Try `/usr/bin/tr --help' for more information.
and if we fix the bug:
>>> cmd = ['/usr/bin/tr', 'l', 'L']
>>> p = subprocess.Popen(cmd, stdout=subprocess.PIPE, stdin=subprocess.PIPE)
>>> out,err = p.communicate('hello world')>>> print out
heLLo worLd
>>> print err
None
...it fixes everything. What happens if you omit the stderr redirection -- do you perchance see any error messages from myapp...?
| Broken Pipe from subprocess.Popen.communciate() with stdin | I'm having a strange issue when using subprocess.Popen.communicate(). For background, I want to execute an application from my python script. When I run the program from the command line, I do it like this (UNIX):
$ echo "input text" | /path/to/myapp
From my script, I also want to pipe the input into the application. So, I tried the following. But I get a "broken pipe" error when I try to send the input with communicate():
>>> cmd = ['/path/to/myapp']
>>> p = subprocess.Popen(cmd, stdout=subprocess.PIPE, stderr=subprocess.STDOUT, stdin=subprocess.PIPE)
>>> out,err = p.communicate('input text')
Traceback (most recent call last):
File "", line 1, in
File "/usr/lib/python2.5/subprocess.py", line 670, in communicate
return self._communicate(input)
File "/usr/lib/python2.5/subprocess.py", line 1223, in _communicate
bytes_written = self._write_no_intr(self.stdin.fileno(), buffer(input, input_offset, 512))
File "/usr/lib/python2.5/subprocess.py", line 1003, in _write_no_intr
return os.write(fd, s)
OSError: [Errno 32] Broken pipe
To make matters stranger, if I leave out the input data, I don't get any errors. However, this isn't really a good workaround because the application needs input to work.
>>> p = subprocess.Popen(cmd, stdout=subprocess.PIPE, stderr=subprocess.STDOUT, stdin=subprocess.PIPE)
>>> out,err = p.communicate()
>>> print out
[error from myapp regarding lack of input]
Any idea what I'm missing?
| [
"Your observation suggests that myapp is terminating without reading (all of the) input. Not knowing anything about myapp, that's hard to confirm, but consider for example\n$ echo 'hello world' | tr 'l' 'L'\nheLLo worLd\n\nnow...:\n>>> cmd = ['/usr/bin/tr']\n>>> p = subprocess.Popen(cmd, stdout=subprocess.PIPE, stderr=subprocess.STDOUT, stdin=subprocess.PIPE)\n>>> out,err = p.communicate('hello world')\nTraceback (most recent call last):\n File \"<stdin>\", line 1, in <module>\n File \"/usr/lib/python2.5/subprocess.py\", line 668, in communicate\n return self._communicate(input)\n File \"/usr/lib/python2.5/subprocess.py\", line 1218, in _communicate\n bytes_written = self._write_no_intr(self.stdin.fileno(), buffer(input, input_offset, 512))\n File \"/usr/lib/python2.5/subprocess.py\", line 997, in _write_no_intr\n return os.write(fd, s)\nOSError: [Errno 32] Broken pipe\n\nbecause...:\n>>> p = subprocess.Popen(cmd, stdout=subprocess.PIPE, stdin=subprocess.PIPE)\n>>> /usr/bin/tr: missing operand\nTry `/usr/bin/tr --help' for more information.\n\nand if we fix the bug:\n>>> cmd = ['/usr/bin/tr', 'l', 'L']\n>>> p = subprocess.Popen(cmd, stdout=subprocess.PIPE, stdin=subprocess.PIPE)\n>>> out,err = p.communicate('hello world')>>> print out\nheLLo worLd\n>>> print err\nNone\n\n...it fixes everything. What happens if you omit the stderr redirection -- do you perchance see any error messages from myapp...?\n"
] | [
3
] | [] | [] | [
"python"
] | stackoverflow_0002067852_python.txt |
Q:
Passing arguments into SUDS client statement
I am using SUDS (Like SOAP) to test WSDL files. The methods contain types that are linked to further functions. I am not sure how to access the variables stored in the types that are displayed. Some sample code is below:
from suds.client import Client
client=Client('http://eample.wsdl')
print client
response is:
Ports (1):
(PTZ)
Methods (4):
AbsoluteMove(ns4:ReferenceToken ProfileToken, ns4:PTZVector Destination, ns4:PTZSpeed Speed, )
Types (303):
ns4:PTZSpeed
I am able to get access to these functions. I cannot find any documentation on how to test functions in SUDS. I want to test to see if functions work and checking their return values. Does anyone know how to do this?
I used the command below to display all child functions.
client.factory.create('AbsoluteMove.PTZSpeed.Speed.PanTilt')
I main problem is basically passing values into the functions and getting return values.
I have tried to pass the arguments but the parameters have attributes stored in the attributes. Below shows the layout for the structure of the parameters I'm trying to access.
(AbsoluteMove){
ProfileToken = None
Destination =
(PTZVector){
PanTilt =
(Vector2D){
_x = ""
_y = ""
_space = ""
}
Zoom =
(Vector1D){
_x = ""
_space = ""
}
}
Speed =
(PTZSpeed){
PanTilt =
(Vector2D){
_x = ""
_y = ""
_space = ""
}
Zoom =
(Vector1D){
_x = ""
_space = ""
The parameters are more complex than just entering simple values.
A:
Try to invoke the method on the service:
from suds.client import Client
client=Client('http://eample.wsdl')
res = client.service.AbsoluteMove(profile_token, destination, speed)
print res
You'll need to determine what values to put in for those arguments to the AbsoluteMove method.
A:
Client.factory.create is for the instantiation of object types that are internal to the service you are utilizing. If you're just doing a method call (which it seems you are), invoke it directly.
| Passing arguments into SUDS client statement | I am using SUDS (Like SOAP) to test WSDL files. The methods contain types that are linked to further functions. I am not sure how to access the variables stored in the types that are displayed. Some sample code is below:
from suds.client import Client
client=Client('http://eample.wsdl')
print client
response is:
Ports (1):
(PTZ)
Methods (4):
AbsoluteMove(ns4:ReferenceToken ProfileToken, ns4:PTZVector Destination, ns4:PTZSpeed Speed, )
Types (303):
ns4:PTZSpeed
I am able to get access to these functions. I cannot find any documentation on how to test functions in SUDS. I want to test to see if functions work and checking their return values. Does anyone know how to do this?
I used the command below to display all child functions.
client.factory.create('AbsoluteMove.PTZSpeed.Speed.PanTilt')
I main problem is basically passing values into the functions and getting return values.
I have tried to pass the arguments but the parameters have attributes stored in the attributes. Below shows the layout for the structure of the parameters I'm trying to access.
(AbsoluteMove){
ProfileToken = None
Destination =
(PTZVector){
PanTilt =
(Vector2D){
_x = ""
_y = ""
_space = ""
}
Zoom =
(Vector1D){
_x = ""
_space = ""
}
}
Speed =
(PTZSpeed){
PanTilt =
(Vector2D){
_x = ""
_y = ""
_space = ""
}
Zoom =
(Vector1D){
_x = ""
_space = ""
The parameters are more complex than just entering simple values.
| [
"Try to invoke the method on the service:\nfrom suds.client import Client\nclient=Client('http://eample.wsdl')\nres = client.service.AbsoluteMove(profile_token, destination, speed)\nprint res\n\nYou'll need to determine what values to put in for those arguments to the AbsoluteMove method.\n",
"Client.factory.create is for the instantiation of object types that are internal to the service you are utilizing. If you're just doing a method call (which it seems you are), invoke it directly.\n"
] | [
3,
1
] | [] | [] | [
"python",
"soap",
"suds"
] | stackoverflow_0002065088_python_soap_suds.txt |
Q:
time complexity of variable loops
i want to try to calculate the O(n) of my program (in python). there are two problems:
1: i have a very basic knowledge of O(n) [aka: i know O(n) has to do with time and calculations]
and
2: all of the loops in my program are not set to any particular value. they are based on the input data.
A:
The n in O(n) means precisely the input size. So, if I have this code:
def findmax(l):
maybemax = 0
for i in l:
if i > maybemax:
maybemax = i
return maybemax
Then I'd say that the complexity is O(n) -- how long it takes is proportional to the input size (since the loop loops as many times as the length of l).
If I had
def allbigger(l, m):
for el in l:
for el2 in m:
if el < el2:
return False
return True
then, in the worst case (that is, when I return True), I have one loop of length len(l) and inside it, one of length len(m), so I say that it's O(l * m) or O(n^2) if the lists are expected to be about the same length.
A:
Try this out to start, then head to wiki:
Plain English Explanation of Big O Notation
| time complexity of variable loops | i want to try to calculate the O(n) of my program (in python). there are two problems:
1: i have a very basic knowledge of O(n) [aka: i know O(n) has to do with time and calculations]
and
2: all of the loops in my program are not set to any particular value. they are based on the input data.
| [
"The n in O(n) means precisely the input size. So, if I have this code:\ndef findmax(l):\n maybemax = 0\n for i in l:\n if i > maybemax:\n maybemax = i\n return maybemax\n\nThen I'd say that the complexity is O(n) -- how long it takes is proportional to the input size (since the loop loops as many times as the length of l).\nIf I had\ndef allbigger(l, m):\n for el in l:\n for el2 in m:\n if el < el2:\n return False\n return True\n\nthen, in the worst case (that is, when I return True), I have one loop of length len(l) and inside it, one of length len(m), so I say that it's O(l * m) or O(n^2) if the lists are expected to be about the same length.\n",
"Try this out to start, then head to wiki:\n\nPlain English Explanation of Big O Notation\n\n"
] | [
4,
1
] | [] | [] | [
"algorithm",
"big_o",
"python"
] | stackoverflow_0002068591_algorithm_big_o_python.txt |
Q:
mysqldb pulls whole query result in one chunk always even if I just do a fetchone?
So if I do
import MySQLdb
conn = MySQLdb.connect(...)
cur = conn.cursor()
cur.execute("SELECT * FROM HUGE_TABLE")
print "hello?"
print cur.fetchone()
It looks to me that MySQLdb gets the entire huge table before it gets to the "print".
I previously assumed it did some sort of "cursor/state" lazy retrieval in the background,
but it doesn't look like it to me.
Is this right? If so is it because it has to be this way or is this due to a limitation
of the MySQL wire protocol? Does this mean that java/hibernate behave the same way?
I guess I need to use the "limit 1" MySQL clauses and relatives if I want to walk through
a large table without pulling in the whole thing at once? Or no? Thanks in advance.
A:
In the _mysql module, use the following call:
conn.use_result()
That tells the connection you want to fetch rows one by one, leaving the remainder on the server (but leaving the cursor open).
The alternative (and the default) is:
conn.store_result()
This tells the connection to fetch the entire result set after executing the query, and subsequent fetches will just iterate through the result set, which is now in memory in your Python app. If your result set is very large, you should consider using LIMIT to restrict it to something you can handle.
Note that MySQL does not allow another query to be run until you have fetched all the rows from the one you have left open.
In the MySQLdb module, the equivalent is to use one of these two different cursor objects from MySQLdb.cusrors:
CursorUseResultMixIn
CursorStoreResultMixIn
A:
This is correct in every other language I've used. The fetchone is just going to only retrieve the first row of the resultset which in this case is the entire database. It's more of a convenience method than anything, it's designed to be easier to use if you KNOW that there's only one result coming down or you only care about the first.
A:
oursql is an alternative MySQL DB-API interface that exposes a few more of the lower-level details, and also provides other facilities for dealing with large datasets.
| mysqldb pulls whole query result in one chunk always even if I just do a fetchone? | So if I do
import MySQLdb
conn = MySQLdb.connect(...)
cur = conn.cursor()
cur.execute("SELECT * FROM HUGE_TABLE")
print "hello?"
print cur.fetchone()
It looks to me that MySQLdb gets the entire huge table before it gets to the "print".
I previously assumed it did some sort of "cursor/state" lazy retrieval in the background,
but it doesn't look like it to me.
Is this right? If so is it because it has to be this way or is this due to a limitation
of the MySQL wire protocol? Does this mean that java/hibernate behave the same way?
I guess I need to use the "limit 1" MySQL clauses and relatives if I want to walk through
a large table without pulling in the whole thing at once? Or no? Thanks in advance.
| [
"In the _mysql module, use the following call:\nconn.use_result()\n\nThat tells the connection you want to fetch rows one by one, leaving the remainder on the server (but leaving the cursor open).\nThe alternative (and the default) is:\nconn.store_result()\n\nThis tells the connection to fetch the entire result set after executing the query, and subsequent fetches will just iterate through the result set, which is now in memory in your Python app. If your result set is very large, you should consider using LIMIT to restrict it to something you can handle.\nNote that MySQL does not allow another query to be run until you have fetched all the rows from the one you have left open.\nIn the MySQLdb module, the equivalent is to use one of these two different cursor objects from MySQLdb.cusrors:\n\nCursorUseResultMixIn\nCursorStoreResultMixIn\n\n",
"This is correct in every other language I've used. The fetchone is just going to only retrieve the first row of the resultset which in this case is the entire database. It's more of a convenience method than anything, it's designed to be easier to use if you KNOW that there's only one result coming down or you only care about the first. \n",
"oursql is an alternative MySQL DB-API interface that exposes a few more of the lower-level details, and also provides other facilities for dealing with large datasets.\n"
] | [
4,
0,
0
] | [] | [] | [
"mysql",
"python"
] | stackoverflow_0002067529_mysql_python.txt |
Q:
Python Function Reference
There're tons of apps/widgets for PHP function reference and even for Ruby but I'm shocked to find there is nothing available for a popular language like Python (besides the official online documentation ofcourse).
Is there really not a single handy reference widget/app available for Python? I have 'Pocket Reference' book, but a dashboard widget would be so handy!
A:
Python libraries have (or should have) built in documentation through docstrings. Also, python code is (mostly) very readable, and reading the source (.py or even .c) is actually the preferred way for many developers to get the information they're looking for, especially since some corner cases may not even be documented.
I've caught myself looking through the source now and then, as if it's a natural step in looking up functionality, either because I'm curious how they solve the problem, or because I reckon it's faster than googling obscure problems and reading SO questions.
A:
So it's (often) not very pretty at all, but it's possible that the pydoc command line tool, or pydoc in webserver mode, could help you here. Here's an article on pydoc to help you get started
A:
The interactive interpreter is a fantastic reference tool. dir(<identifier) lists all the attributes of a module, class, or function help(<identifier>) gives you help about same.
pydoc at the command line is another great tool. It does for Python what man gives you for commands, plus it even includes a web server you can start up to see the documentation in your browser.
| Python Function Reference | There're tons of apps/widgets for PHP function reference and even for Ruby but I'm shocked to find there is nothing available for a popular language like Python (besides the official online documentation ofcourse).
Is there really not a single handy reference widget/app available for Python? I have 'Pocket Reference' book, but a dashboard widget would be so handy!
| [
"Python libraries have (or should have) built in documentation through docstrings. Also, python code is (mostly) very readable, and reading the source (.py or even .c) is actually the preferred way for many developers to get the information they're looking for, especially since some corner cases may not even be documented.\nI've caught myself looking through the source now and then, as if it's a natural step in looking up functionality, either because I'm curious how they solve the problem, or because I reckon it's faster than googling obscure problems and reading SO questions.\n",
"So it's (often) not very pretty at all, but it's possible that the pydoc command line tool, or pydoc in webserver mode, could help you here. Here's an article on pydoc to help you get started\n",
"\nThe interactive interpreter is a fantastic reference tool. dir(<identifier) lists all the attributes of a module, class, or function help(<identifier>) gives you help about same.\npydoc at the command line is another great tool. It does for Python what man gives you for commands, plus it even includes a web server you can start up to see the documentation in your browser.\n\n"
] | [
1,
0,
0
] | [
"I develop on Mac OS.\nI have all the Python documentation directly available through a desktop app.\nThe app is called Safari. I bookmark http://docs.python.org/index.html\nIt's available as a desktop app.\n"
] | [
-1
] | [
"documentation",
"macos",
"python",
"reference",
"widget"
] | stackoverflow_0002068486_documentation_macos_python_reference_widget.txt |
Q:
Serving up snippets of html and using urlfetch
I'm trying to "modularize" a section of an appengine website where a profile is requested as a small hunk of pre-rendered html
Sending a request to /userInfo?id=4992 sends down some html like:
<div>
(image of john) John
Information about this user
</div>
So, from my google appengine code, I need to be able to repeatedly fetch results from this URL when displaying a group of people.
The only way I can do it now is send down a collection of <iframes> like
<iframe src="/userInfo?id=4992"></iframe>
<iframe src="/userInfo?id=4993"></iframe>
<iframe src="/userInfo?id=4994"></iframe>
The iframes work to request the data.
I tried using urlfetch.fetch() but it keeps timing out on me.
Am I doing this right? I thought this would be handy-dandy (url that serves up a snippet of html) but it turns out its looking like a design error.
A:
You're currently serializing urlfetch requests, which ends up summing their wait times and may easily push you beyond your latency deadline. I'm afraid that you'll need to switch to async urlfetch requests -- an advanced technique which may suit your architecture better!
| Serving up snippets of html and using urlfetch | I'm trying to "modularize" a section of an appengine website where a profile is requested as a small hunk of pre-rendered html
Sending a request to /userInfo?id=4992 sends down some html like:
<div>
(image of john) John
Information about this user
</div>
So, from my google appengine code, I need to be able to repeatedly fetch results from this URL when displaying a group of people.
The only way I can do it now is send down a collection of <iframes> like
<iframe src="/userInfo?id=4992"></iframe>
<iframe src="/userInfo?id=4993"></iframe>
<iframe src="/userInfo?id=4994"></iframe>
The iframes work to request the data.
I tried using urlfetch.fetch() but it keeps timing out on me.
Am I doing this right? I thought this would be handy-dandy (url that serves up a snippet of html) but it turns out its looking like a design error.
| [
"You're currently serializing urlfetch requests, which ends up summing their wait times and may easily push you beyond your latency deadline. I'm afraid that you'll need to switch to async urlfetch requests -- an advanced technique which may suit your architecture better!\n"
] | [
1
] | [] | [] | [
"google_app_engine",
"python",
"urlfetch"
] | stackoverflow_0002069465_google_app_engine_python_urlfetch.txt |
Q:
read multiple files using multiprocessing
I need to read some very huge text files (100+ Mb), process every lines with regex and store the data into a structure. My structure inherits from defaultdict, it has a read(self) method that read self.file_name file.
Look at this very simple (but not real) example, I'm not using regex, but I'm splitting lines:
import multiprocessing
from collections import defaultdict
def SingleContainer():
return list()
class Container(defaultdict):
"""
this class store odd line in self["odd"] and even line in self["even"].
It is stupid, but it's only an example. In the real case the class
has additional methods that do computation on readen data.
"""
def __init__(self,file_name):
if type(file_name) != str:
raise AttributeError, "%s is not a string" % file_name
defaultdict.__init__(self,SingleContainer)
self.file_name = file_name
self.readen_lines = 0
def read(self):
f = open(self.file_name)
print "start reading file %s" % self.file_name
for line in f:
self.readen_lines += 1
values = line.split()
key = {0: "even", 1: "odd"}[self.readen_lines %2]
self[key].append(values)
print "readen %d lines from file %s" % (self.readen_lines, self.file_name)
def do(file_name):
container = Container(file_name)
container.read()
return container.items()
if __name__ == "__main__":
file_names = ["r1_200909.log", "r1_200910.log"]
pool = multiprocessing.Pool(len(file_names))
result = pool.map(do,file_names)
pool.close()
pool.join()
print "Finish"
At the end I need to join every results in a single Container. It is important that the order of the lines is preserved. My approach is too slow when returning values. Better solution?
I'm using python 2.6 on Linux
A:
You're probably hitting two problems.
One of them was mentioned: you're reading multiple files at once. Those reads will end up being interleaved, causing disk thrashing. You want to read whole files at once, and then only multithread the computation on the data.
Second, you're hitting the overhead of Python's multiprocessing module. It's not actually using threads, but instead starting multiple processes and serializing the results through a pipe. That's very slow for bulk data--in fact, it seems to be slower than the work you're doing in the thread (at least in the example). This is the real-world problem caused by the GIL.
If I modify do() to return None instead of container.items() to disable the extra data copy, this example is faster than a single thread, as long as the files are already cached:
Two threads: 0.36elapsed 168%CPU
One thread (replace pool.map with map): 0:00.52elapsed 98%CPU
Unfortunately, the GIL problem is fundamental and can't be worked around from inside Python.
A:
Multiprocessing is more suited to CPU- or memory-oriented processes since the seek time of rotational drives kills performance when switching between files. Either load your log files into a fast flash drive or some sort of memory disk (physical or virtual), or give up on multiprocessing.
A:
You're creating a pool with as many workers as files. That may be too many. Usually, I aim to have the number of workers around the same as the number of cores.
The simple fact is that your final step is going to be a single process merging all the results together. There is no avoiding this, given your problem description. This is known as a barrier synchronization: all tasks have to reach the same point before any can proceed.
You should probably run this program multiple times, or in a loop, passing a different value to multiprocessing.Pool() each time, starting at 1 and going to the number of cores. Time each run, and see which worker count does best.
The result will depend on how CPU-intensive (as opposed to disk-intensive) your task is. I would not be surprised if 2 were best if your task is about half CPU and half disk, even on an 8-core machine.
| read multiple files using multiprocessing | I need to read some very huge text files (100+ Mb), process every lines with regex and store the data into a structure. My structure inherits from defaultdict, it has a read(self) method that read self.file_name file.
Look at this very simple (but not real) example, I'm not using regex, but I'm splitting lines:
import multiprocessing
from collections import defaultdict
def SingleContainer():
return list()
class Container(defaultdict):
"""
this class store odd line in self["odd"] and even line in self["even"].
It is stupid, but it's only an example. In the real case the class
has additional methods that do computation on readen data.
"""
def __init__(self,file_name):
if type(file_name) != str:
raise AttributeError, "%s is not a string" % file_name
defaultdict.__init__(self,SingleContainer)
self.file_name = file_name
self.readen_lines = 0
def read(self):
f = open(self.file_name)
print "start reading file %s" % self.file_name
for line in f:
self.readen_lines += 1
values = line.split()
key = {0: "even", 1: "odd"}[self.readen_lines %2]
self[key].append(values)
print "readen %d lines from file %s" % (self.readen_lines, self.file_name)
def do(file_name):
container = Container(file_name)
container.read()
return container.items()
if __name__ == "__main__":
file_names = ["r1_200909.log", "r1_200910.log"]
pool = multiprocessing.Pool(len(file_names))
result = pool.map(do,file_names)
pool.close()
pool.join()
print "Finish"
At the end I need to join every results in a single Container. It is important that the order of the lines is preserved. My approach is too slow when returning values. Better solution?
I'm using python 2.6 on Linux
| [
"You're probably hitting two problems.\nOne of them was mentioned: you're reading multiple files at once. Those reads will end up being interleaved, causing disk thrashing. You want to read whole files at once, and then only multithread the computation on the data.\nSecond, you're hitting the overhead of Python's multiprocessing module. It's not actually using threads, but instead starting multiple processes and serializing the results through a pipe. That's very slow for bulk data--in fact, it seems to be slower than the work you're doing in the thread (at least in the example). This is the real-world problem caused by the GIL.\nIf I modify do() to return None instead of container.items() to disable the extra data copy, this example is faster than a single thread, as long as the files are already cached:\nTwo threads: 0.36elapsed 168%CPU\nOne thread (replace pool.map with map): 0:00.52elapsed 98%CPU\nUnfortunately, the GIL problem is fundamental and can't be worked around from inside Python.\n",
"Multiprocessing is more suited to CPU- or memory-oriented processes since the seek time of rotational drives kills performance when switching between files. Either load your log files into a fast flash drive or some sort of memory disk (physical or virtual), or give up on multiprocessing.\n",
"You're creating a pool with as many workers as files. That may be too many. Usually, I aim to have the number of workers around the same as the number of cores.\nThe simple fact is that your final step is going to be a single process merging all the results together. There is no avoiding this, given your problem description. This is known as a barrier synchronization: all tasks have to reach the same point before any can proceed.\nYou should probably run this program multiple times, or in a loop, passing a different value to multiprocessing.Pool() each time, starting at 1 and going to the number of cores. Time each run, and see which worker count does best.\nThe result will depend on how CPU-intensive (as opposed to disk-intensive) your task is. I would not be surprised if 2 were best if your task is about half CPU and half disk, even on an 8-core machine.\n"
] | [
5,
0,
0
] | [] | [] | [
"multiprocessing",
"performance",
"python"
] | stackoverflow_0002068645_multiprocessing_performance_python.txt |
Q:
Help in Converting Small Python Code to PHP
please i need some help in converting a python code to a php syntax
the code is for generating an alphanumeric code using alpha encoding
the code :
def mkcpl(x):
x = ord(x)
set="0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz"
for c in set:
d = ord(c)^x
if chr(d) in set:
return 0,c,chr(d)
if chr(0xff^d) in set:
return 1,c,chr(0xff^d)
raise Exception,"No encoding found for %#02x"%x
def mkalphadecryptloader(shcode):
s="hAAAAX5AAAAHPPPPPPPPa"
shcode=list(shcode)
shcode.reverse()
shcode = "".join(shcode)
shcode += "\x90"*((-len(shcode))%4)
for b in range(len(shcode)/4):
T,C,D = 0,"",""
for i in range(4):
t,c,d = mkcpl(shcode[4*b+i])
T += t << i
C = c+C
D = d+D
s += "h%sX5%sP" % (C,D)
if T > 0:
s += "TY"
T = (2*T^T)%16
for i in range(4):
if T & 1:
s += "19"
T >>= 1
if T == 0:
break
s += "I"
return s+"\xff\xe4"
any help would be really appreciated ...
A:
i will help you a little. For the rest of it, please read up on the documentation.
function mkcpl($x){
$x=ord($x);
$set="0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz";
$set=str_split($set);
foreach($set as $c){
$d=ord($c)^$x;
if( in_array( chr($d) ,$set ) ){
return array(0,$c,chr($d));
}
if ( in_array( chr(0xff^d) ,$set ) ){
return array(0,$c,chr(0xff^$d));
}
}
}
function mkalphadecryptloader($shcode){
$s="hAAAAX5AAAAHPPPPPPPPa";
# you could use strrev()
$shcode=str_split($shcode);
$shcode=array_reverse($shcode);
$shcode=implode("",$shcode);
# continue on... read the documentation
}
print_r(mkcpl("A"));
mkalphadecryptloader("abc");
Python: PHP
len() - length of string/array. strlen(),count()
range() - generate range of numbers for($i=0;$i<=number;$i++)
<< <<
the rest of them, like +=, == etc are pretty much the same across the 2 languages.
A:
the rest of them, like +=, == etc are
pretty much the same across the 2
languages.
Careful; in PHP string concatenation is accomplished using .= not +=. If you try to use += PHP will try to evaluate the expression mathematically (probably returning a null) and you'll be pulling your hair out trying to figure out what's wrong with your script.
| Help in Converting Small Python Code to PHP | please i need some help in converting a python code to a php syntax
the code is for generating an alphanumeric code using alpha encoding
the code :
def mkcpl(x):
x = ord(x)
set="0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz"
for c in set:
d = ord(c)^x
if chr(d) in set:
return 0,c,chr(d)
if chr(0xff^d) in set:
return 1,c,chr(0xff^d)
raise Exception,"No encoding found for %#02x"%x
def mkalphadecryptloader(shcode):
s="hAAAAX5AAAAHPPPPPPPPa"
shcode=list(shcode)
shcode.reverse()
shcode = "".join(shcode)
shcode += "\x90"*((-len(shcode))%4)
for b in range(len(shcode)/4):
T,C,D = 0,"",""
for i in range(4):
t,c,d = mkcpl(shcode[4*b+i])
T += t << i
C = c+C
D = d+D
s += "h%sX5%sP" % (C,D)
if T > 0:
s += "TY"
T = (2*T^T)%16
for i in range(4):
if T & 1:
s += "19"
T >>= 1
if T == 0:
break
s += "I"
return s+"\xff\xe4"
any help would be really appreciated ...
| [
"i will help you a little. For the rest of it, please read up on the documentation.\nfunction mkcpl($x){\n $x=ord($x);\n $set=\"0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz\";\n $set=str_split($set);\n foreach($set as $c){\n $d=ord($c)^$x;\n if( in_array( chr($d) ,$set ) ){\n return array(0,$c,chr($d));\n }\n if ( in_array( chr(0xff^d) ,$set ) ){\n return array(0,$c,chr(0xff^$d));\n }\n }\n}\n\nfunction mkalphadecryptloader($shcode){\n $s=\"hAAAAX5AAAAHPPPPPPPPa\";\n # you could use strrev()\n $shcode=str_split($shcode);\n $shcode=array_reverse($shcode);\n $shcode=implode(\"\",$shcode);\n # continue on... read the documentation\n}\n\nprint_r(mkcpl(\"A\"));\nmkalphadecryptloader(\"abc\");\n\n\n\nPython: PHP\n\nlen() - length of string/array. strlen(),count() \nrange() - generate range of numbers for($i=0;$i<=number;$i++)\n<< <<\n\nthe rest of them, like +=, == etc are pretty much the same across the 2 languages.\n",
"\nthe rest of them, like +=, == etc are\n pretty much the same across the 2\n languages.\n\nCareful; in PHP string concatenation is accomplished using .= not +=. If you try to use += PHP will try to evaluate the expression mathematically (probably returning a null) and you'll be pulling your hair out trying to figure out what's wrong with your script.\n"
] | [
4,
0
] | [] | [] | [
"php",
"python"
] | stackoverflow_0002069352_php_python.txt |
Q:
'Invalid Key' error from Paramiko
I'm trying to set up Fabric for deploying my Python web application and Paramiko is barfing on my private RSA key. I had been using my key successfully for 6 months, so I know it's good. In case having a passphrase was the problem, I just made a new key with no passphrase and still get the error. Help?
A:
I don't know if this helps you but here's how I set my SSH user/key in fabric.
env.user = "username"
env.key_filename = "/path/to/ssh/keyfile"
And it seems to work fine.
| 'Invalid Key' error from Paramiko | I'm trying to set up Fabric for deploying my Python web application and Paramiko is barfing on my private RSA key. I had been using my key successfully for 6 months, so I know it's good. In case having a passphrase was the problem, I just made a new key with no passphrase and still get the error. Help?
| [
"I don't know if this helps you but here's how I set my SSH user/key in fabric.\nenv.user = \"username\"\nenv.key_filename = \"/path/to/ssh/keyfile\"\n\nAnd it seems to work fine.\n"
] | [
1
] | [] | [] | [
"fabric",
"paramiko",
"python",
"ssh"
] | stackoverflow_0002045880_fabric_paramiko_python_ssh.txt |
Q:
ImportError: cannot import name NumpyTest
I am trying to read a *.wav file using scipy. I do it in the following way:
import scipy.io
x = scipy.io.wavfile.read('/usr/share/sounds/purple/receive.wav')
As a result I get the following error message:
Traceback (most recent call last):
File "test3.py", line 1, in <module>
import scipy.io
File "/usr/lib/python2.5/site-packages/scipy/io/__init__.py", line 23, in <module>
from numpy.testing import NumpyTest
ImportError: cannot import name NumpyTest
Does anybody know why scipy cannot import NumpyTest and how it can be fixed?
A:
Looks like you have upgraded your numpy version but haven't installed a corresponding scipy version.
A:
Do you have numpy installed? The package is most likely called numpy or python-numpy if you are running Linux
If your OS package manager does not have numpy package, download it from here
| ImportError: cannot import name NumpyTest | I am trying to read a *.wav file using scipy. I do it in the following way:
import scipy.io
x = scipy.io.wavfile.read('/usr/share/sounds/purple/receive.wav')
As a result I get the following error message:
Traceback (most recent call last):
File "test3.py", line 1, in <module>
import scipy.io
File "/usr/lib/python2.5/site-packages/scipy/io/__init__.py", line 23, in <module>
from numpy.testing import NumpyTest
ImportError: cannot import name NumpyTest
Does anybody know why scipy cannot import NumpyTest and how it can be fixed?
| [
"Looks like you have upgraded your numpy version but haven't installed a corresponding scipy version.\n",
"Do you have numpy installed? The package is most likely called numpy or python-numpy if you are running Linux\nIf your OS package manager does not have numpy package, download it from here\n"
] | [
1,
0
] | [] | [] | [
"importerror",
"numpy",
"python",
"scipy",
"wav"
] | stackoverflow_0002063124_importerror_numpy_python_scipy_wav.txt |
Q:
In optparse module - command line option parser, how to confirm if an option was not provided?
From Python docs:
"Option.dest : If the option’s action implies writing or modifying a value somewhere, this tells optparse where to write it: dest names an attribute of the options object that optparse builds as it parses the command line."
Can we put some check on the name of the attribute (dest) to check if it's value was provided? Say, I want to perform some action to determine it's value when no value is provided for it in CLI, as I don't have a fixed default value.
Checking against 'None' does not work.
A:
You could use a default value of None for such options, which cannot be entered on the command line. Then you can check like
if opts.optional_value is None:
# action for option not given
else:
# use value from command line
| In optparse module - command line option parser, how to confirm if an option was not provided? | From Python docs:
"Option.dest : If the option’s action implies writing or modifying a value somewhere, this tells optparse where to write it: dest names an attribute of the options object that optparse builds as it parses the command line."
Can we put some check on the name of the attribute (dest) to check if it's value was provided? Say, I want to perform some action to determine it's value when no value is provided for it in CLI, as I don't have a fixed default value.
Checking against 'None' does not work.
| [
"You could use a default value of None for such options, which cannot be entered on the command line. Then you can check like\nif opts.optional_value is None:\n # action for option not given\nelse:\n # use value from command line\n\n"
] | [
1
] | [] | [] | [
"python"
] | stackoverflow_0002069998_python.txt |
Q:
Python parallel processing libraries
Python seems to have many different packages available to assist one in parallel processing on an SMP based system or across a cluster. I'm interested in building a client server system in which a server maintains a queue of jobs and clients (local or remote) connect and run jobs until the queue is empty. Of the packages listed above, which is recommended and why?
Edit: In particular, I have written a simulator which takes in a few inputs and processes things for awhile. I need to collect enough samples from the simulation to estimate a mean within a user specified confidence interval. To speed things up, I want to be able to run simulations on many different systems, each of which report back to the server at some interval with the samples that they have collected. The server then calculates the confidence interval and determines whether the client process needs to continue. After enough samples have been gathered, the server terminates all client simulations, reconfigures the simulation based on past results, and repeats the processes.
With this need for intercommunication between the client and server processes, I question whether batch-scheduling is a viable solution. Sorry I should have been more clear to begin with.
A:
Have a go with ParallelPython. Seems easy to use, and should provide the jobs and queues interface that you want.
A:
There are also now two different Python wrappers around the map/reduce framework Hadoop:
http://code.google.com/p/happy/
http://wiki.github.com/klbostee/dumbo
Map/Reduce is a nice development pattern with lots of recipes for solving common patterns of problems.
If you don't already have a cluster, Hadoop itself is nice because it has full job scheduling, automatic data distribution of data across the cluster (i.e. HDFS), etc.
A:
Given that you tagged your question "scientific-computing", and mention a cluster, some kind of MPI wrapper seems the obvious choice, if the goal is to develop parallel applications as one might guess from the title. Then again, the text in your question suggests you want to develop a batch scheduler. So I don't really know which question you're asking.
A:
The simplest way to do this would probably just to output the intermediate samples to separate files (or a database) as they finish, and have a process occasionally poll these output files to see if they're sufficient or if more jobs need to be submitted.
| Python parallel processing libraries | Python seems to have many different packages available to assist one in parallel processing on an SMP based system or across a cluster. I'm interested in building a client server system in which a server maintains a queue of jobs and clients (local or remote) connect and run jobs until the queue is empty. Of the packages listed above, which is recommended and why?
Edit: In particular, I have written a simulator which takes in a few inputs and processes things for awhile. I need to collect enough samples from the simulation to estimate a mean within a user specified confidence interval. To speed things up, I want to be able to run simulations on many different systems, each of which report back to the server at some interval with the samples that they have collected. The server then calculates the confidence interval and determines whether the client process needs to continue. After enough samples have been gathered, the server terminates all client simulations, reconfigures the simulation based on past results, and repeats the processes.
With this need for intercommunication between the client and server processes, I question whether batch-scheduling is a viable solution. Sorry I should have been more clear to begin with.
| [
"Have a go with ParallelPython. Seems easy to use, and should provide the jobs and queues interface that you want.\n",
"There are also now two different Python wrappers around the map/reduce framework Hadoop:\nhttp://code.google.com/p/happy/\nhttp://wiki.github.com/klbostee/dumbo\nMap/Reduce is a nice development pattern with lots of recipes for solving common patterns of problems.\nIf you don't already have a cluster, Hadoop itself is nice because it has full job scheduling, automatic data distribution of data across the cluster (i.e. HDFS), etc.\n",
"Given that you tagged your question \"scientific-computing\", and mention a cluster, some kind of MPI wrapper seems the obvious choice, if the goal is to develop parallel applications as one might guess from the title. Then again, the text in your question suggests you want to develop a batch scheduler. So I don't really know which question you're asking.\n",
"The simplest way to do this would probably just to output the intermediate samples to separate files (or a database) as they finish, and have a process occasionally poll these output files to see if they're sufficient or if more jobs need to be submitted. \n"
] | [
2,
1,
0,
0
] | [] | [] | [
"cluster_computing",
"python",
"scientific_computing"
] | stackoverflow_0002051984_cluster_computing_python_scientific_computing.txt |
Q:
python app to exe not working on WinSRV2003
I created little app for sending out emails when something is wrong with server. Used py2exe to create exe file. While it is works absolutely fine on Win7 i have problems with running it on WinSRV2003. I do not believe that it has something to do with code itself.
Please see imports below
import pyodbc, sys, smtplib, os
from datetime import date
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText
from email.mime.base import MIMEBase
import email.iterators
import email.generator
setup.py file:
from distutils.core import setup
import py2exe
import modulefinder
modulefinder.AddPackagePath("mail.mime", "base")
modulefinder.AddPackagePath("mail.mime", "multipart")
modulefinder.AddPackagePath("mail.mime", "nonmultipart")
modulefinder.AddPackagePath("mail.mime", "audio")
modulefinder.AddPackagePath("mail.mime", "image")
modulefinder.AddPackagePath("mail.mime", "message")
modulefinder.AddPackagePath("mail.mime", "application")
setup(console=['capfile_tester.py'],
options = { "py2exe": { "includes": "decimal, datetime, email" } })
And also one line from py2exe output that might be interesting
The following modules appear to be missing
['_scproxy']
Error message when trying to start it:
This application has failed to start because application configuration is incorrect. Reinstalling the application may fix this problem.
What came to my mind is could it missing some registry keys taht would allow app to run?
A:
I'd say this is a missing DLL's problem. You should check and see the DLL's your application bundles ( or presumes to exist on the target computer ). I think you can do that with the depends.exe that comes with Visual Studio.
EDIT: I just remembered. Make sure you run py2exe with a Python 2.5 installation. The 2.6 had some bugs and that made the exe not work on several machines.
A:
A search on _scproxy seems to indicate that _scproxy is a new module in 2.6. Perhaps somehow Python 2.5 is involved? py2exe is supposed to make a completely self-contained executable, so I don't see how that's possible, though.
Another possibility is that _scproxy depends on a dll that isn't available in Windows 2003? Have you tried running your program without py2exe on Win2003?
A:
Googling for your "this application has failed to start..." message suggests strongly this is a DLL problem, probably with msvcp80.dll and friends. This is a very common occurrence with recent Windows/Python/py2exe given how MS keeps changing MSVCC libraries etc. Different Python versions are linked with different libraries and if they aren't pre-installed on your target machine you can get problems like this. Sometimes installing the appropriate redistributable package from MS works.
Note that the py2exe warnings, in this case about _scproxy, can almost always be ignored. It's very common to get what amount to spurious reports of missing modules like that. 95% of the time we can ignore them, even when we see literally dozens of modules "missing".
A:
I had a similar problem where COM objects were involved. Maybe that's the case here, too. This description solved my problems. My software would then run on different Windows versions, which it before would not.
| python app to exe not working on WinSRV2003 | I created little app for sending out emails when something is wrong with server. Used py2exe to create exe file. While it is works absolutely fine on Win7 i have problems with running it on WinSRV2003. I do not believe that it has something to do with code itself.
Please see imports below
import pyodbc, sys, smtplib, os
from datetime import date
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText
from email.mime.base import MIMEBase
import email.iterators
import email.generator
setup.py file:
from distutils.core import setup
import py2exe
import modulefinder
modulefinder.AddPackagePath("mail.mime", "base")
modulefinder.AddPackagePath("mail.mime", "multipart")
modulefinder.AddPackagePath("mail.mime", "nonmultipart")
modulefinder.AddPackagePath("mail.mime", "audio")
modulefinder.AddPackagePath("mail.mime", "image")
modulefinder.AddPackagePath("mail.mime", "message")
modulefinder.AddPackagePath("mail.mime", "application")
setup(console=['capfile_tester.py'],
options = { "py2exe": { "includes": "decimal, datetime, email" } })
And also one line from py2exe output that might be interesting
The following modules appear to be missing
['_scproxy']
Error message when trying to start it:
This application has failed to start because application configuration is incorrect. Reinstalling the application may fix this problem.
What came to my mind is could it missing some registry keys taht would allow app to run?
| [
"I'd say this is a missing DLL's problem. You should check and see the DLL's your application bundles ( or presumes to exist on the target computer ). I think you can do that with the depends.exe that comes with Visual Studio.\nEDIT: I just remembered. Make sure you run py2exe with a Python 2.5 installation. The 2.6 had some bugs and that made the exe not work on several machines.\n",
"A search on _scproxy seems to indicate that _scproxy is a new module in 2.6. Perhaps somehow Python 2.5 is involved? py2exe is supposed to make a completely self-contained executable, so I don't see how that's possible, though.\nAnother possibility is that _scproxy depends on a dll that isn't available in Windows 2003? Have you tried running your program without py2exe on Win2003?\n",
"Googling for your \"this application has failed to start...\" message suggests strongly this is a DLL problem, probably with msvcp80.dll and friends. This is a very common occurrence with recent Windows/Python/py2exe given how MS keeps changing MSVCC libraries etc. Different Python versions are linked with different libraries and if they aren't pre-installed on your target machine you can get problems like this. Sometimes installing the appropriate redistributable package from MS works.\nNote that the py2exe warnings, in this case about _scproxy, can almost always be ignored. It's very common to get what amount to spurious reports of missing modules like that. 95% of the time we can ignore them, even when we see literally dozens of modules \"missing\".\n",
"I had a similar problem where COM objects were involved. Maybe that's the case here, too. This description solved my problems. My software would then run on different Windows versions, which it before would not.\n"
] | [
1,
1,
1,
1
] | [] | [] | [
"py2exe",
"python",
"windows",
"windows_server_2003"
] | stackoverflow_0001707323_py2exe_python_windows_windows_server_2003.txt |
Q:
A clean algorithm for sorting a objects according to defined dependencies?
Given a list of classes inheriting from this base:
class Plugin(object):
run_after_plugins = ()
run_before_plugins = ()
...and the following rules:
Plugins can provide a list of plugins that they must run after.
Plugins can provide a list of plugins that they must run before.
The list of plugins may or may not contain all plugins that have been specified in ordering constraints.
Can anyone provide a nice clean algorithm for ordering a list of plugins? It will need to detect circular dependencies as well....
def order_plugins(plugins):
pass
I've come up with a few versions but nothing particuarlly neat: I'm sure some of you Art of Computer Programming types will relish the challenge :)
[note: question given in Python but it's clearly not only a Python question: pseudocode in any language would do]
A:
This is called topological sorting.
The canonical application of
topological sorting (topological
order) is in scheduling a sequence of
jobs or tasks; topological sorting
algorithms were first studied in the
early 1960s in the context of the PERT
technique for scheduling in project
management (Jarnagin 1960). The jobs
are represented by vertices, and there
is an edge from x to y if job x must
be completed before job y can be
started (for example, when washing
clothes, the washing machine must
finish before we put the clothes to
dry). Then, a topological sort gives
an order in which to perform the jobs.
A:
Here is Python code that does topological sorting.
A:
This is called topological sorting.
Doing this involves several steps:
First build a graph of all choosen plugins as vertices and their dependencies as edges. Run before/after deps boil down to the same type of edges.
Next build a transitiv hull: Look at all plugins and add all missing dependencies. Repeat this until the set does not change any more.
Last step: Choose a vertice without incoming edges and do a DFS (or BFS) search. This algorithms can be enriched with cycle detection.
A:
If you define the __lt__ and associated methods on Plugin based on whether or not they should be run before or after then it could be possible to find a sane ordering with sorted(). Cycles would still be a problem though.
A:
If you want to give good diagnostics for the case that there are cycles, have a look at http://en.wikipedia.org/wiki/Strongly_connected_component. I think that if you use a version of a Strongly connected component like the one outlined in http://www.cs.sunysb.edu/~skiena/373/notes/lecture16/lecture16.html you can get it to print out the strongly connected components in topological sort order.
| A clean algorithm for sorting a objects according to defined dependencies? | Given a list of classes inheriting from this base:
class Plugin(object):
run_after_plugins = ()
run_before_plugins = ()
...and the following rules:
Plugins can provide a list of plugins that they must run after.
Plugins can provide a list of plugins that they must run before.
The list of plugins may or may not contain all plugins that have been specified in ordering constraints.
Can anyone provide a nice clean algorithm for ordering a list of plugins? It will need to detect circular dependencies as well....
def order_plugins(plugins):
pass
I've come up with a few versions but nothing particuarlly neat: I'm sure some of you Art of Computer Programming types will relish the challenge :)
[note: question given in Python but it's clearly not only a Python question: pseudocode in any language would do]
| [
"This is called topological sorting.\n\nThe canonical application of\n topological sorting (topological\n order) is in scheduling a sequence of\n jobs or tasks; topological sorting\n algorithms were first studied in the\n early 1960s in the context of the PERT\n technique for scheduling in project\n management (Jarnagin 1960). The jobs\n are represented by vertices, and there\n is an edge from x to y if job x must\n be completed before job y can be\n started (for example, when washing\n clothes, the washing machine must\n finish before we put the clothes to\n dry). Then, a topological sort gives\n an order in which to perform the jobs.\n\n",
"Here is Python code that does topological sorting.\n",
"This is called topological sorting.\nDoing this involves several steps:\nFirst build a graph of all choosen plugins as vertices and their dependencies as edges. Run before/after deps boil down to the same type of edges.\nNext build a transitiv hull: Look at all plugins and add all missing dependencies. Repeat this until the set does not change any more.\nLast step: Choose a vertice without incoming edges and do a DFS (or BFS) search. This algorithms can be enriched with cycle detection.\n",
"If you define the __lt__ and associated methods on Plugin based on whether or not they should be run before or after then it could be possible to find a sane ordering with sorted(). Cycles would still be a problem though.\n",
"If you want to give good diagnostics for the case that there are cycles, have a look at http://en.wikipedia.org/wiki/Strongly_connected_component. I think that if you use a version of a Strongly connected component like the one outlined in http://www.cs.sunysb.edu/~skiena/373/notes/lecture16/lecture16.html you can get it to print out the strongly connected components in topological sort order.\n"
] | [
8,
2,
1,
0,
0
] | [] | [] | [
"algorithm",
"python"
] | stackoverflow_0002065897_algorithm_python.txt |
Q:
How do I pass a python list in the post query?
I want to send some strings in a list in a POST call. eg:
www.example.com/?post_data = A list of strings
The python code receives the data as a single string (Instead of a list of strings). How do I post it as a list of strings?
A:
There's no such thing as a "list of strings" in a URL (or in practically anything in HTTP - if you specify multiple values for the same header, they come out as a single delimited value in most web app frameworks IME). It's just a single string. I suggest you delimit the strings in some way (e.g. comma-separated) and then parse them out again at the other end.
A:
TRY JSON(JavaScript Object Notation) it's available in the python package.
Find out here: http://docs.python.org/library/json.html
You can Encode your list to an array represented in JSON and append to the post argument. Later decode it back to list...
A:
Are you talking about this?
post_data= ",".join( list_of_strings )
A:
If the big string you're receiving is merely delimited then you could try splitting it. See Splitting strings.
To clarify, you get the delimited list of the strings, split that list into a python list, and voila!, you have a python list...
A:
It depends on your server to format the incoming arguments.
for example, when zope gets a request like this:
http://www.zope.org?ids:list=1&ids:list=2
you can get the the ids as a list. But this feature depends on the server. If your server does not support some kind of parsing and validating your input, you have to implement it by yourself. Or you use zope.
A:
If you can't or don't want to simply separate them with a comma and you want to send them in a more list-ish way.
I have a list of numbers that I want to pass and I use a PHP webservice on the other end, I don't want to rebuild my webservice since I'v used a common multiselect element that Zend Framework provided.
This example works fine for me and my little integers and it would with your strings, I actualy don't perform the urllib.quote(s), I just do a str(s).
Import urllib
import urllib
Your list of stings:
string_list = ['A', 'list', 'of', 'strings', 'and', 'öthér', '.&st,u?ff,']
Join together the list of strings with 'post_data[]=', also urlencode the string
post_data = '&'.join('post_data[]='+urllib.quote(s) for s in string_list)
Posts to http://example.com/
urllib.urlopen('http://example.com/',post_data)
A:
Data passed to a POST statement is (as far as I understood) encoded as key-value pairs, using the application/x-www-form-urlencoded encoding.
So, I'll assume that you represent your list of string as the following dictionnary :
>>> my_string_list= { 's1': 'I',
... 's2': 'love',
... 's3': 'python'
... }
Then, passing it as argument to POST is as difficult as reading the documentation of urllib.
>>> import urllib
>>> print urllib.urlopen( 'http://www.google.fr/search',
urllib.urlencode( my_string_list )
).read()
Note that google does not use POST for its search queries, but you will see the error reported by google.
If you run WireShark while typing the code above, you will see the data of the POST being passed as :
s3=python&s2=love&s1=I
A:
A data structure like django.utils.datastructures.MultiValueDict is a clean way to represent such data. AFAIK it preserves order.
>>> d = MultiValueDict({'name': ['Adrian', 'Simon'], 'position': ['Developer']})
>>> d['name']
'Simon'
>>> d.getlist('name')
['Adrian', 'Simon']
>>> d.get('lastname', 'nonexistent')
'nonexistent'
>>> d.setlist('lastname', ['Holovaty', 'Willison'])
Django is using django.http.QueryDict (subclass of MultiValueDict) to turn a query string into python primitives and back.
from django.http import QueryDict
qs = 'post_data=a&post_data=b&post_data=c'
query_dict = QueryDict(qs)
assert query_dict['post_data'] == 'c'
assert query_dict.getlist('post_data') == ['a', 'b', 'c']
assert query_dict.urlencode() == qs
You should be able to copy these classes and use them in your project. (I haven't checked all dependencies though)
| How do I pass a python list in the post query? | I want to send some strings in a list in a POST call. eg:
www.example.com/?post_data = A list of strings
The python code receives the data as a single string (Instead of a list of strings). How do I post it as a list of strings?
| [
"There's no such thing as a \"list of strings\" in a URL (or in practically anything in HTTP - if you specify multiple values for the same header, they come out as a single delimited value in most web app frameworks IME). It's just a single string. I suggest you delimit the strings in some way (e.g. comma-separated) and then parse them out again at the other end.\n",
"TRY JSON(JavaScript Object Notation) it's available in the python package.\nFind out here: http://docs.python.org/library/json.html\nYou can Encode your list to an array represented in JSON and append to the post argument. Later decode it back to list...\n",
"Are you talking about this?\npost_data= \",\".join( list_of_strings )\n\n",
"If the big string you're receiving is merely delimited then you could try splitting it. See Splitting strings.\nTo clarify, you get the delimited list of the strings, split that list into a python list, and voila!, you have a python list...\n",
"It depends on your server to format the incoming arguments.\nfor example, when zope gets a request like this:\nhttp://www.zope.org?ids:list=1&ids:list=2\nyou can get the the ids as a list. But this feature depends on the server. If your server does not support some kind of parsing and validating your input, you have to implement it by yourself. Or you use zope.\n",
"If you can't or don't want to simply separate them with a comma and you want to send them in a more list-ish way.\nI have a list of numbers that I want to pass and I use a PHP webservice on the other end, I don't want to rebuild my webservice since I'v used a common multiselect element that Zend Framework provided.\nThis example works fine for me and my little integers and it would with your strings, I actualy don't perform the urllib.quote(s), I just do a str(s).\nImport urllib\nimport urllib\n\nYour list of stings:\nstring_list = ['A', 'list', 'of', 'strings', 'and', 'öthér', '.&st,u?ff,']\n\nJoin together the list of strings with 'post_data[]=', also urlencode the string\npost_data = '&'.join('post_data[]='+urllib.quote(s) for s in string_list)\n\nPosts to http://example.com/\nurllib.urlopen('http://example.com/',post_data)\n\n",
"Data passed to a POST statement is (as far as I understood) encoded as key-value pairs, using the application/x-www-form-urlencoded encoding.\nSo, I'll assume that you represent your list of string as the following dictionnary :\n>>> my_string_list= { 's1': 'I', \n... 's2': 'love', \n... 's3': 'python' \n... } \n\nThen, passing it as argument to POST is as difficult as reading the documentation of urllib.\n>>> import urllib\n>>> print urllib.urlopen( 'http://www.google.fr/search', \n urllib.urlencode( my_string_list ) \n ).read()\n\nNote that google does not use POST for its search queries, but you will see the error reported by google.\nIf you run WireShark while typing the code above, you will see the data of the POST being passed as : \n s3=python&s2=love&s1=I\n\n",
"A data structure like django.utils.datastructures.MultiValueDict is a clean way to represent such data. AFAIK it preserves order.\n>>> d = MultiValueDict({'name': ['Adrian', 'Simon'], 'position': ['Developer']})\n>>> d['name']\n'Simon'\n>>> d.getlist('name')\n['Adrian', 'Simon']\n>>> d.get('lastname', 'nonexistent')\n'nonexistent'\n>>> d.setlist('lastname', ['Holovaty', 'Willison'])\n\nDjango is using django.http.QueryDict (subclass of MultiValueDict) to turn a query string into python primitives and back.\nfrom django.http import QueryDict\n\nqs = 'post_data=a&post_data=b&post_data=c'\n\nquery_dict = QueryDict(qs)\n\nassert query_dict['post_data'] == 'c'\nassert query_dict.getlist('post_data') == ['a', 'b', 'c']\nassert query_dict.urlencode() == qs\n\nYou should be able to copy these classes and use them in your project. (I haven't checked all dependencies though)\n"
] | [
8,
5,
3,
2,
2,
2,
1,
0
] | [] | [] | [
"python",
"web_services"
] | stackoverflow_0000349369_python_web_services.txt |
Q:
How can I make my Python code stay under 80 characters a line?
I have written some Python in which some lines exceed 80 characters in length, which is a threshold I need to stay under. How can I adapt my code to reduce line lengths?
A:
My current editor (Kate) has been configured to introduce a line break on word boundaries whenever the line length reaches or exceeds 80 characters. This makes it immediately obvious that I've overstepped the bounds. In addition, there is a red line marking the 80 character position, giving me advance warning of when the line is going to flow over. These let me plan logical lines that will fit on multiple physical lines.
As for how to actually fit them, there are several mechanisms. You can end the line with a \ , but this is error prone.
# works
print 4 + \
2
# doesn't work
print 4 + \
2
The difference? The difference is invisible-- there was a whitespace character after the backslash in the second case. Oops!
What should be done instead? Well, surround it in parentheses.
print (4 +
2)
No \ needed. This actually works universally, you will never ever need \ . Even for attribute access boundaries!
print (foo
.bar())
For strings, you can add them explicitly, or implicitly using C-style joining.
# all of these do exactly the same thing
print ("123"
"456")
print ("123" +
"456")
print "123456"
Finally, anything that will be in any form of bracket ((), []. {}), not just parentheses in particular, can have a line break placed anywhere. So, for example, you can use a list literal over multiple lines just fine, so long as elements are separated by a comma.
All this and more can be found in the official documentation for Python. Also, a quick note, PEP-8 specifies 79 characters as the limit, not 80-- if you have 80 characters, you are already over it.
A:
I would add two points to the previous answers:
Strings can be automatically concatenated, which is very convenient:
this_is_a_long_string = ("lkjlkj lkj lkj mlkj mlkj mlkj mlkj mlkj mlkj "
"rest of the string: no string addition is necessary!"
" You can do it many times!")
Note that this is efficient: this does not result in string concatenations calculated when the code is run: instead, this is directly considered as a single long string literal, so it is efficient.
A little caveat related to Devin's answer: the "parenthesis" syntax actually does not "work universally". For instance, d[42] = "H22G" cannot be written as
(d
[42] = "H2G2")
Parentheses can be used around "calculated" expression (which does not include an assignment (=) like above).
Another example was the following code, which used to generate a syntax error (at some point before Python 3.9):
with (open("..... very long file name .....")
as input_file):
In fact, parentheses cannot be put around any statement, more generally (only expressions).
In these cases, one can either use the "" syntax, or, better (since "" is to be avoided if possible), split the code over multiple statements.
A:
If the code exceeding 80 chars is a function call (or definition), break the argument line. Python will recognise the parenthesis, and sees that as one line.
function(arg, arg, arg, arg,
arg, arg, arg...)
If the code exceeding 80 chars is a line of code that isn't naturally breakable, you can use the backslash \ to "escape" the newline.
some.weird.namespace.thing.that.is.long = ','.join(strings) + \
'another string'
You can also use the parenthesis to your advantage.
some.weird.namespace.thing.that.is.long = (','.join(strings) +
'another string')
All types of set brackets {} (dict/set), [] (list), () (tuples) can be broken across several lines without problems. This allows for nicer formatting.
mydict = {
'key': 'value',
'yes': 'no'
}
A:
Idiomatic Python says:
Use backslashes as a last resort
So, if using parentheses () is possible, avoid backslashes.
If you have a a.train.wreck.that.spans.across.a.dozen.cars.and-multiple.lines.across.the.whole.trainyard.and.several.states() do something like:
lines = a.train.wreck.that.spans.across.a.dozen.cars.and-multiple.lines
lines.across.the.whole.trainyard.and.several.states()
Or, preferably, refactor your code. Please.
| How can I make my Python code stay under 80 characters a line? | I have written some Python in which some lines exceed 80 characters in length, which is a threshold I need to stay under. How can I adapt my code to reduce line lengths?
| [
"My current editor (Kate) has been configured to introduce a line break on word boundaries whenever the line length reaches or exceeds 80 characters. This makes it immediately obvious that I've overstepped the bounds. In addition, there is a red line marking the 80 character position, giving me advance warning of when the line is going to flow over. These let me plan logical lines that will fit on multiple physical lines.\nAs for how to actually fit them, there are several mechanisms. You can end the line with a \\ , but this is error prone.\n# works\nprint 4 + \\\n 2\n\n# doesn't work\nprint 4 + \\ \n 2\n\nThe difference? The difference is invisible-- there was a whitespace character after the backslash in the second case. Oops!\nWhat should be done instead? Well, surround it in parentheses.\nprint (4 + \n 2)\n\nNo \\ needed. This actually works universally, you will never ever need \\ . Even for attribute access boundaries!\nprint (foo\n .bar())\n\nFor strings, you can add them explicitly, or implicitly using C-style joining.\n# all of these do exactly the same thing\nprint (\"123\"\n \"456\")\nprint (\"123\" + \n \"456\")\nprint \"123456\"\n\nFinally, anything that will be in any form of bracket ((), []. {}), not just parentheses in particular, can have a line break placed anywhere. So, for example, you can use a list literal over multiple lines just fine, so long as elements are separated by a comma.\nAll this and more can be found in the official documentation for Python. Also, a quick note, PEP-8 specifies 79 characters as the limit, not 80-- if you have 80 characters, you are already over it.\n",
"I would add two points to the previous answers:\nStrings can be automatically concatenated, which is very convenient:\nthis_is_a_long_string = (\"lkjlkj lkj lkj mlkj mlkj mlkj mlkj mlkj mlkj \"\n \"rest of the string: no string addition is necessary!\"\n \" You can do it many times!\")\n\nNote that this is efficient: this does not result in string concatenations calculated when the code is run: instead, this is directly considered as a single long string literal, so it is efficient.\nA little caveat related to Devin's answer: the \"parenthesis\" syntax actually does not \"work universally\". For instance, d[42] = \"H22G\" cannot be written as\n(d\n [42] = \"H2G2\")\n\nParentheses can be used around \"calculated\" expression (which does not include an assignment (=) like above).\nAnother example was the following code, which used to generate a syntax error (at some point before Python 3.9):\nwith (open(\"..... very long file name .....\")\n as input_file):\n\nIn fact, parentheses cannot be put around any statement, more generally (only expressions).\nIn these cases, one can either use the \"\" syntax, or, better (since \"\" is to be avoided if possible), split the code over multiple statements.\n",
"If the code exceeding 80 chars is a function call (or definition), break the argument line. Python will recognise the parenthesis, and sees that as one line.\nfunction(arg, arg, arg, arg,\n arg, arg, arg...)\n\nIf the code exceeding 80 chars is a line of code that isn't naturally breakable, you can use the backslash \\ to \"escape\" the newline.\nsome.weird.namespace.thing.that.is.long = ','.join(strings) + \\\n 'another string'\n\nYou can also use the parenthesis to your advantage.\nsome.weird.namespace.thing.that.is.long = (','.join(strings) +\n 'another string')\n\nAll types of set brackets {} (dict/set), [] (list), () (tuples) can be broken across several lines without problems. This allows for nicer formatting.\nmydict = {\n 'key': 'value',\n 'yes': 'no'\n}\n\n",
"Idiomatic Python says:\n\nUse backslashes as a last resort\n\nSo, if using parentheses () is possible, avoid backslashes.\nIf you have a a.train.wreck.that.spans.across.a.dozen.cars.and-multiple.lines.across.the.whole.trainyard.and.several.states() do something like:\nlines = a.train.wreck.that.spans.across.a.dozen.cars.and-multiple.lines\nlines.across.the.whole.trainyard.and.several.states()\n\nOr, preferably, refactor your code. Please.\n"
] | [
62,
23,
22,
19
] | [] | [] | [
"pep8",
"python"
] | stackoverflow_0002070684_pep8_python.txt |
Q:
Example for using Python Twisted with File Descriptors
I'm looking to use twisted to control communication across Linux pipes (os.pipe()) and fifos (os.mkfifo()) between a master process and a set of slave processes. While I'm positive tat it's possible to use twisted for these types of file descriptors (after all, twisted is great for tcp sockets which *nix abstracts away as file descriptors), I cannot find any examples of this type of usage. Anyone have any links, sample code, or advice?
A:
You can use reactor.spawnProcess to set up arbitrary file descriptor mappings between a parent process and a child process it spawns. For example, to run a program and give it two extra output descriptors (in addition to stdin, stdout, and stderr) with which it can send bytes back to the parent process, you would do something like this:
reactor.spawnProcess(protocol, executable, args,
childFDs={0: 'w', 1: 'r', 2: 'r', 3: 'r', 4: 'r'})
The reactor will take care of creating the pipes for you, and will call childDataReceived on the ProcessProtocol you pass in when data is read from them. See the spawnProcess API docs for details.
If you're also using Twisted on the child end, then you mostly want to be looking at twisted.internet.stdio. stdiodemo.py and stdin.py in the core examples will show you how to use that module.
A:
It does not have anything built-in for asynchronous I/O. Someone wrote a libaio wrapper for it, but it has not been touched for a long time, and I have no idea if it still works.
In the worst case you could use select to see if there's anything available to read, but that won't help you with writing.
| Example for using Python Twisted with File Descriptors | I'm looking to use twisted to control communication across Linux pipes (os.pipe()) and fifos (os.mkfifo()) between a master process and a set of slave processes. While I'm positive tat it's possible to use twisted for these types of file descriptors (after all, twisted is great for tcp sockets which *nix abstracts away as file descriptors), I cannot find any examples of this type of usage. Anyone have any links, sample code, or advice?
| [
"You can use reactor.spawnProcess to set up arbitrary file descriptor mappings between a parent process and a child process it spawns. For example, to run a program and give it two extra output descriptors (in addition to stdin, stdout, and stderr) with which it can send bytes back to the parent process, you would do something like this:\nreactor.spawnProcess(protocol, executable, args,\n childFDs={0: 'w', 1: 'r', 2: 'r', 3: 'r', 4: 'r'})\n\nThe reactor will take care of creating the pipes for you, and will call childDataReceived on the ProcessProtocol you pass in when data is read from them. See the spawnProcess API docs for details.\nIf you're also using Twisted on the child end, then you mostly want to be looking at twisted.internet.stdio. stdiodemo.py and stdin.py in the core examples will show you how to use that module.\n",
"It does not have anything built-in for asynchronous I/O. Someone wrote a libaio wrapper for it, but it has not been touched for a long time, and I have no idea if it still works.\nIn the worst case you could use select to see if there's anything available to read, but that won't help you with writing.\n"
] | [
12,
-3
] | [] | [] | [
"file_descriptor",
"mkfifo",
"pipe",
"python",
"twisted"
] | stackoverflow_0002069262_file_descriptor_mkfifo_pipe_python_twisted.txt |
Q:
why i get this traceback?
This is part of my code:
if ind_1<>0:
rbrcol=[]
brdod1=[]
for i in range(27):
if Add_Cyc_1[1,i]!=0:
rbrcol.append(Add_Cyc_1[0,i])
brdod1.append(Add_Cyc_1[1,i])
Probrani_1=vstack((rbrcol,brdod1))
pok=0
for i in (rbrcol):
pok+=1
broj1=0
for j in range(21):
if SYS_STATE_1[i,j]==0:
broj1+=1
if broj1 <= Probrani_1[1,pok-1]:
SYS_STATE_1[i,j]=123456
And when i run program i get this:
Traceback (most recent call last):
File "C:/Python26/pokusaj2.py", line 157, in <module>
for i in (rbrcol):
NameError: name 'rbrcol' is not defined
What i do wrong???
A:
I think the real problem is the if at the very top. Your indenting is incorrect - the code as written won't run because the line after the if is not indented.
Assuming it is indented in the original code, then rbrcol is not initialized if ind_1 is 0 and as ghostdog says if the if statement never fires, then rbrcol would not be set at all.
A:
just as the error says, "rbrcol" doesn't have value. check your for loop
for i in range(27):
if Add_Cyc_1[1,i]!=0: <----- this part doesn't get through
rbrcol.append(Add_Cyc_1[0,i])
brdod1.append(Add_Cyc_1[1,i])
Probrani_1=vstack((rbrcol,brdod1))
also, what is Add_Cyc_1 ? To assign multidimension list
Add_Cyc_1[1,i] should be Add_Cyc_1[1][i]
further, this
if ind_1<>0: <<--- if this is not true, then rbrcol will not be defined
rbrcol=[] << --- <> should be != , although <> its also valid, but now ppl use !=
brdod1=[]
| why i get this traceback? | This is part of my code:
if ind_1<>0:
rbrcol=[]
brdod1=[]
for i in range(27):
if Add_Cyc_1[1,i]!=0:
rbrcol.append(Add_Cyc_1[0,i])
brdod1.append(Add_Cyc_1[1,i])
Probrani_1=vstack((rbrcol,brdod1))
pok=0
for i in (rbrcol):
pok+=1
broj1=0
for j in range(21):
if SYS_STATE_1[i,j]==0:
broj1+=1
if broj1 <= Probrani_1[1,pok-1]:
SYS_STATE_1[i,j]=123456
And when i run program i get this:
Traceback (most recent call last):
File "C:/Python26/pokusaj2.py", line 157, in <module>
for i in (rbrcol):
NameError: name 'rbrcol' is not defined
What i do wrong???
| [
"I think the real problem is the if at the very top. Your indenting is incorrect - the code as written won't run because the line after the if is not indented.\nAssuming it is indented in the original code, then rbrcol is not initialized if ind_1 is 0 and as ghostdog says if the if statement never fires, then rbrcol would not be set at all.\n",
"just as the error says, \"rbrcol\" doesn't have value. check your for loop\nfor i in range(27):\n if Add_Cyc_1[1,i]!=0: <----- this part doesn't get through\n rbrcol.append(Add_Cyc_1[0,i]) \n brdod1.append(Add_Cyc_1[1,i]) \n Probrani_1=vstack((rbrcol,brdod1))\n\nalso, what is Add_Cyc_1 ? To assign multidimension list\nAdd_Cyc_1[1,i] should be Add_Cyc_1[1][i]\n\nfurther, this\nif ind_1<>0: <<--- if this is not true, then rbrcol will not be defined\n rbrcol=[] << --- <> should be != , although <> its also valid, but now ppl use !=\n brdod1=[]\n\n"
] | [
4,
2
] | [] | [] | [
"python"
] | stackoverflow_0002071895_python.txt |
Q:
Access models in other project in a Django view cause "table doesn't exist" error
Base project structure
baseproject
baseapp
models.py
class BaseModel(models.Model)
...
Other project structure:
project
app
views.py
urls.py
project.app.views.py
import os
os.environ['DJANGO_SETTINGS_MODULE'] = 'project.settings'
from django.conf import settings
from baseproject.baseapp.models import BaseModel
print BaseModel.objects.count()
it raised "Table 'project.baseapp_baemodel' doesn't exist" error when run from command line: "python views.py".
import os
os.environ['DJANGO_SETTINGS_MODULE'] = 'baseproject.settings'
from django.conf import settings
from baseproject.baseapp.models import BaseModel
print BaseModel.objects.count()
After changed project.settings to baseproject.settings, it works in command line.
import os
os.environ['DJANGO_SETTINGS_MODULE'] = 'baseproject.settings'
from django.conf import settings
from baseproject.baseapp.models import BaseModel
def someview(request):
count = BaseModel.objects.count()
return render_to_response(...)
But it still raised "Table 'project.baseapp_baemodel' doesn't exist" error when access the view by opening corresponding url in browser.
What's wrong in above code?
A:
You are fighting against the framework here, and you'll be better off if you rethink your architecture. Django is built around the assumption that a project = a given set of INSTALLED_APPS, and the project settings name a database to which those apps are synced. It's not clear here what problem you have with just doing things that way, but whatever you're trying to achieve, it can be achieved without trying to import models from an app that is not in your current project's INSTALLED_APPS. That is never going to work reliably.
If there's an app you want in both projects, you should put it on your PYTHONPATH (or in virtualenvs) so both projects can access it, and put it in the INSTALLED_APPS of both projects. If you also need its data shared between the projects, you might be able to point both projects at the same database (though you'd need to be careful of other conflicting app names that you might not want to share data). Or you could use the multi-database support that's now in Django trunk to have the one project use the other project's database only for that one app.
My guess is if you back up a step and explain what you're trying to do, there are even better solutions available than those.
| Access models in other project in a Django view cause "table doesn't exist" error | Base project structure
baseproject
baseapp
models.py
class BaseModel(models.Model)
...
Other project structure:
project
app
views.py
urls.py
project.app.views.py
import os
os.environ['DJANGO_SETTINGS_MODULE'] = 'project.settings'
from django.conf import settings
from baseproject.baseapp.models import BaseModel
print BaseModel.objects.count()
it raised "Table 'project.baseapp_baemodel' doesn't exist" error when run from command line: "python views.py".
import os
os.environ['DJANGO_SETTINGS_MODULE'] = 'baseproject.settings'
from django.conf import settings
from baseproject.baseapp.models import BaseModel
print BaseModel.objects.count()
After changed project.settings to baseproject.settings, it works in command line.
import os
os.environ['DJANGO_SETTINGS_MODULE'] = 'baseproject.settings'
from django.conf import settings
from baseproject.baseapp.models import BaseModel
def someview(request):
count = BaseModel.objects.count()
return render_to_response(...)
But it still raised "Table 'project.baseapp_baemodel' doesn't exist" error when access the view by opening corresponding url in browser.
What's wrong in above code?
| [
"You are fighting against the framework here, and you'll be better off if you rethink your architecture. Django is built around the assumption that a project = a given set of INSTALLED_APPS, and the project settings name a database to which those apps are synced. It's not clear here what problem you have with just doing things that way, but whatever you're trying to achieve, it can be achieved without trying to import models from an app that is not in your current project's INSTALLED_APPS. That is never going to work reliably.\nIf there's an app you want in both projects, you should put it on your PYTHONPATH (or in virtualenvs) so both projects can access it, and put it in the INSTALLED_APPS of both projects. If you also need its data shared between the projects, you might be able to point both projects at the same database (though you'd need to be careful of other conflicting app names that you might not want to share data). Or you could use the multi-database support that's now in Django trunk to have the one project use the other project's database only for that one app.\nMy guess is if you back up a step and explain what you're trying to do, there are even better solutions available than those.\n"
] | [
8
] | [] | [] | [
"django",
"model",
"python"
] | stackoverflow_0002069254_django_model_python.txt |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.