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:
Why is my spawned process still causing IntelliJ to wait?
I'm trying to start a server as part of an Ant artifact.
Here are the relevant lines:
<exec dir="." executable="cmd.exe" spawn="true">
<arg line="/c c:\Java\james-2.3.2\bin\debug.bat" />
</exec>
If I start it with ant from the command line, a process is spawned and I get a command prompt and everything seems fine. However, if I start it from IntelliJ 6, my IDE, the build stays alive until I kill the server.
Here's the line IntelliJ uses to start ant:
C:\Java\jdk1.6.0_02\bin\java -Xmx128m -Dant.home=C:\Java\apache-ant-1.7.1 -Dfile.encoding=UTF-8 -classpath "C:\Java\apache-ant-1.7.1\lib\ant-antlr.jar;C:\Java\apache-ant-1.7.1\lib\ant-apache-bcel.jar;C:\Java\apache-ant-1.7.1\lib\ant-apache-bsf.jar;C:\Java\apache-ant-1.7.1\lib\ant-apache-log4j.jar;C:\Java\apache-ant-1.7.1\lib\ant-apache-oro.jar;C:\Java\apache-ant-1.7.1\lib\ant-apache-regexp.jar;C:\Java\apache-ant-1.7.1\lib\ant-apache-resolver.jar;C:\Java\apache-ant-1.7.1\lib\ant-commons-logging.jar;C:\Java\apache-ant-1.7.1\lib\ant-commons-net.jar;C:\Java\apache-ant-1.7.1\lib\ant-jai.jar;C:\Java\apache-ant-1.7.1\lib\ant-javamail.jar;C:\Java\apache-ant-1.7.1\lib\ant-jdepend.jar;C:\Java\apache-ant-1.7.1\lib\ant-jmf.jar;C:\Java\apache-ant-1.7.1\lib\ant-jsch.jar;C:\Java\apache-ant-1.7.1\lib\ant-junit.jar;C:\Java\apache-ant-1.7.1\lib\ant-launcher.jar;C:\Java\apache-ant-1.7.1\lib\ant-netrexx.jar;C:\Java\apache-ant-1.7.1\lib\ant-nodeps.jar;C:\Java\apache-ant-1.7.1\lib\ant-starteam.jar;C:\Java\apache-ant-1.7.1\lib\ant-stylebook.jar;C:\Java\apache-ant-1.7.1\lib\ant-swing.jar;C:\Java\apache-ant-1.7.1\lib\ant-testutil.jar;C:\Java\apache-ant-1.7.1\lib\ant-trax.jar;C:\Java\apache-ant-1.7.1\lib\ant-weblogic.jar;C:\Java\apache-ant-1.7.1\lib\ant.jar;C:\Java\apache-ant-1.7.1\lib\xercesImpl.jar;C:\Java\apache-ant-1.7.1\lib\xml-apis.jar;C:\Java\jdk1.6.0_02\lib\tools.jar;C:\Program Files\JetBrains\IntelliJ IDEA 6.0\lib\idea_rt.jar" com.intellij.rt.ant.execution.AntMain2 -logger com.intellij.rt.ant.execution.IdeaAntLogger2 -inputhandler com.intellij.rt.ant.execution.IdeaInputHandler -buildfile C:\Java\Projects\CcMailer\ccmailer.xml jar
I suspect the inputhandler parameter has something to do with the problem, but if I run it myself the problem is not reproduced. Either way, I have only limited control over what IntelliJ does.
My question is: how does IntelliJ even know the process is running? The Ant process is long gone. Is there a way to start a subprocess in a more sneaky way, so that IntelliJ won't even know there's anything to wait around for?
Here's what I've tried so far: I tried using the start command, like this:
<exec dir="." executable="cmd.exe" spawn="true">
<arg line="/c start cmd /c c:\Java\james-2.3.2\bin\debug.bat" />
</exec>
I also tried using python, with code like this:
import os.path
import subprocess
subprocess.Popen(["cmd.exe", "/c", "debug.bat"], stdin=open(os.path.devnull), stdout=open(os.path.devnull, "w"), stderr=subprocess.STDOUT)
To no avail. The build window always stays up until I kill the server.
Any ideas?
A:
I've given up on figuring this out, so instead I set up an XML RPC server that does the starting and stopping, and the startup/shutdown scripts make an XML RPC call.
Code for the server (simplified):
from __future__ import with_statement
from threading import Lock
from SimpleXMLRPCServer import SimpleXMLRPCServer
server = SimpleXMLRPCServer(("localhost", 8000), allow_none=True)
server.register_introspection_functions()
class JamesController(object):
def __init__(self):
self.lock = Lock()
self.started = False
def start(self):
# starting code using subprocess
def stop(self):
# stopping code
server.register_instance(JamesController())
server.serve_forever()
And then the start/stop scripts become something like:
import xmlrpclib
s = xmlrpclib.Server('http://localhost:8000')
s.start()
It's clunky, and requires some time.sleep() calls sprinkled, but it gets the job done.
|
Why is my spawned process still causing IntelliJ to wait?
|
I'm trying to start a server as part of an Ant artifact.
Here are the relevant lines:
<exec dir="." executable="cmd.exe" spawn="true">
<arg line="/c c:\Java\james-2.3.2\bin\debug.bat" />
</exec>
If I start it with ant from the command line, a process is spawned and I get a command prompt and everything seems fine. However, if I start it from IntelliJ 6, my IDE, the build stays alive until I kill the server.
Here's the line IntelliJ uses to start ant:
C:\Java\jdk1.6.0_02\bin\java -Xmx128m -Dant.home=C:\Java\apache-ant-1.7.1 -Dfile.encoding=UTF-8 -classpath "C:\Java\apache-ant-1.7.1\lib\ant-antlr.jar;C:\Java\apache-ant-1.7.1\lib\ant-apache-bcel.jar;C:\Java\apache-ant-1.7.1\lib\ant-apache-bsf.jar;C:\Java\apache-ant-1.7.1\lib\ant-apache-log4j.jar;C:\Java\apache-ant-1.7.1\lib\ant-apache-oro.jar;C:\Java\apache-ant-1.7.1\lib\ant-apache-regexp.jar;C:\Java\apache-ant-1.7.1\lib\ant-apache-resolver.jar;C:\Java\apache-ant-1.7.1\lib\ant-commons-logging.jar;C:\Java\apache-ant-1.7.1\lib\ant-commons-net.jar;C:\Java\apache-ant-1.7.1\lib\ant-jai.jar;C:\Java\apache-ant-1.7.1\lib\ant-javamail.jar;C:\Java\apache-ant-1.7.1\lib\ant-jdepend.jar;C:\Java\apache-ant-1.7.1\lib\ant-jmf.jar;C:\Java\apache-ant-1.7.1\lib\ant-jsch.jar;C:\Java\apache-ant-1.7.1\lib\ant-junit.jar;C:\Java\apache-ant-1.7.1\lib\ant-launcher.jar;C:\Java\apache-ant-1.7.1\lib\ant-netrexx.jar;C:\Java\apache-ant-1.7.1\lib\ant-nodeps.jar;C:\Java\apache-ant-1.7.1\lib\ant-starteam.jar;C:\Java\apache-ant-1.7.1\lib\ant-stylebook.jar;C:\Java\apache-ant-1.7.1\lib\ant-swing.jar;C:\Java\apache-ant-1.7.1\lib\ant-testutil.jar;C:\Java\apache-ant-1.7.1\lib\ant-trax.jar;C:\Java\apache-ant-1.7.1\lib\ant-weblogic.jar;C:\Java\apache-ant-1.7.1\lib\ant.jar;C:\Java\apache-ant-1.7.1\lib\xercesImpl.jar;C:\Java\apache-ant-1.7.1\lib\xml-apis.jar;C:\Java\jdk1.6.0_02\lib\tools.jar;C:\Program Files\JetBrains\IntelliJ IDEA 6.0\lib\idea_rt.jar" com.intellij.rt.ant.execution.AntMain2 -logger com.intellij.rt.ant.execution.IdeaAntLogger2 -inputhandler com.intellij.rt.ant.execution.IdeaInputHandler -buildfile C:\Java\Projects\CcMailer\ccmailer.xml jar
I suspect the inputhandler parameter has something to do with the problem, but if I run it myself the problem is not reproduced. Either way, I have only limited control over what IntelliJ does.
My question is: how does IntelliJ even know the process is running? The Ant process is long gone. Is there a way to start a subprocess in a more sneaky way, so that IntelliJ won't even know there's anything to wait around for?
Here's what I've tried so far: I tried using the start command, like this:
<exec dir="." executable="cmd.exe" spawn="true">
<arg line="/c start cmd /c c:\Java\james-2.3.2\bin\debug.bat" />
</exec>
I also tried using python, with code like this:
import os.path
import subprocess
subprocess.Popen(["cmd.exe", "/c", "debug.bat"], stdin=open(os.path.devnull), stdout=open(os.path.devnull, "w"), stderr=subprocess.STDOUT)
To no avail. The build window always stays up until I kill the server.
Any ideas?
|
[
"I've given up on figuring this out, so instead I set up an XML RPC server that does the starting and stopping, and the startup/shutdown scripts make an XML RPC call.\nCode for the server (simplified):\nfrom __future__ import with_statement\n\nfrom threading import Lock\nfrom SimpleXMLRPCServer import SimpleXMLRPCServer\n\nserver = SimpleXMLRPCServer((\"localhost\", 8000), allow_none=True)\nserver.register_introspection_functions()\n\nclass JamesController(object):\n def __init__(self):\n self.lock = Lock()\n self.started = False\n\n def start(self):\n # starting code using subprocess\n\n def stop(self):\n # stopping code\n\n\nserver.register_instance(JamesController())\nserver.serve_forever()\n\nAnd then the start/stop scripts become something like:\nimport xmlrpclib\n\ns = xmlrpclib.Server('http://localhost:8000')\ns.start()\n\nIt's clunky, and requires some time.sleep() calls sprinkled, but it gets the job done.\n"
] |
[
0
] |
[] |
[] |
[
"ant",
"intellij_idea",
"python",
"subprocess"
] |
stackoverflow_0002402635_ant_intellij_idea_python_subprocess.txt
|
Q:
Memory usage with Django + SQLite3
I've got a very large SQLite table with over 500,000 rows with about 15 columns (mostly floats). I'm wanting to transfer data from the SQLite DB to a Django app (which could be backed by many RDBMs, but Postgres in my case). Everything works OK, but as the iteration continues, memory usage jumps by 2-3 meg a second for the Python process. I've tried using 'del' to delete the EVEMapDenormalize and row objects at the end of each iteration, but the bloat continues. Here's an excerpt, any ideas?
class Importer_mapDenormalize(SQLImporter):
def run_importer(self, conn):
c = conn.cursor()
for row in c.execute('select * from mapDenormalize'):
mapdenorm, created = EVEMapDenormalize.objects.get_or_create(id=row['itemID'])
mapdenorm.x = row['x']
mapdenorm.y = row['y']
mapdenorm.z = row['z']
if row['typeID']:
mapdenorm.type = EVEInventoryType.objects.get(id=row['typeID'])
if row['groupID']:
mapdenorm.group = EVEInventoryGroup.objects.get(id=row['groupID'])
if row['solarSystemID']:
mapdenorm.solar_system = EVESolarSystem.objects.get(id=row['solarSystemID'])
if row['constellationID']:
mapdenorm.constellation = EVEConstellation.objects.get(id=row['constellationID'])
if row['regionID']:
mapdenorm.region = EVERegion.objects.get(id=row['regionID'])
mapdenorm.save()
c.close()
I'm not at all interested in wrapping this SQLite DB with the Django ORM. I'd just really like to figure out how to get the data transferred without sucking all of my RAM.
A:
Silly me, this was addressed in the Django FAQ.
Needed to clear the DB query cache while in DEBUG mode.
from django import db
db.reset_queries()
A:
I think a select * from mapDenormalize and loading the result into memory will always be a bad idea. My advise is - spread script into chunks. Use LIMIT to get data in portions.
Get first portion, work with it, close to cursor, and then get the next portion.
|
Memory usage with Django + SQLite3
|
I've got a very large SQLite table with over 500,000 rows with about 15 columns (mostly floats). I'm wanting to transfer data from the SQLite DB to a Django app (which could be backed by many RDBMs, but Postgres in my case). Everything works OK, but as the iteration continues, memory usage jumps by 2-3 meg a second for the Python process. I've tried using 'del' to delete the EVEMapDenormalize and row objects at the end of each iteration, but the bloat continues. Here's an excerpt, any ideas?
class Importer_mapDenormalize(SQLImporter):
def run_importer(self, conn):
c = conn.cursor()
for row in c.execute('select * from mapDenormalize'):
mapdenorm, created = EVEMapDenormalize.objects.get_or_create(id=row['itemID'])
mapdenorm.x = row['x']
mapdenorm.y = row['y']
mapdenorm.z = row['z']
if row['typeID']:
mapdenorm.type = EVEInventoryType.objects.get(id=row['typeID'])
if row['groupID']:
mapdenorm.group = EVEInventoryGroup.objects.get(id=row['groupID'])
if row['solarSystemID']:
mapdenorm.solar_system = EVESolarSystem.objects.get(id=row['solarSystemID'])
if row['constellationID']:
mapdenorm.constellation = EVEConstellation.objects.get(id=row['constellationID'])
if row['regionID']:
mapdenorm.region = EVERegion.objects.get(id=row['regionID'])
mapdenorm.save()
c.close()
I'm not at all interested in wrapping this SQLite DB with the Django ORM. I'd just really like to figure out how to get the data transferred without sucking all of my RAM.
|
[
"Silly me, this was addressed in the Django FAQ.\nNeeded to clear the DB query cache while in DEBUG mode. \nfrom django import db \ndb.reset_queries()\n\n",
"I think a select * from mapDenormalize and loading the result into memory will always be a bad idea. My advise is - spread script into chunks. Use LIMIT to get data in portions.\nGet first portion, work with it, close to cursor, and then get the next portion.\n"
] |
[
3,
1
] |
[] |
[] |
[
"django",
"python",
"sqlite"
] |
stackoverflow_0002417572_django_python_sqlite.txt
|
Q:
What's the correct way to extract a regexp match in Python?
I have found two ways to extract matches in Python:
1.
def extract_matches(regexp, text):
matches = re.match(regexp, text)
if matches:
return matches.group(1)
2.
def extract_matches(regexp, text):
try:
return re.findall(regexp, text)[0]
except IndexError:
return None
Which one would you suggest me to use? And do you know any other ways to do this?
Thanks, Boda Cydo.
A:
I would more often use re.search (which returns any match, not just one constrained to start at the beginning of the string as re.match does!) if I'm looking for just one match, re.finditer if I want to loop over all matches. Never re.findall if I'm going after only one match though, that's wasted effort with no upside!
|
What's the correct way to extract a regexp match in Python?
|
I have found two ways to extract matches in Python:
1.
def extract_matches(regexp, text):
matches = re.match(regexp, text)
if matches:
return matches.group(1)
2.
def extract_matches(regexp, text):
try:
return re.findall(regexp, text)[0]
except IndexError:
return None
Which one would you suggest me to use? And do you know any other ways to do this?
Thanks, Boda Cydo.
|
[
"I would more often use re.search (which returns any match, not just one constrained to start at the beginning of the string as re.match does!) if I'm looking for just one match, re.finditer if I want to loop over all matches. Never re.findall if I'm going after only one match though, that's wasted effort with no upside!\n"
] |
[
6
] |
[] |
[] |
[
"python",
"regex"
] |
stackoverflow_0002418312_python_regex.txt
|
Q:
How do I emulate keyboard-interactive ssh login with paramiko?
I'm trying to automate a ssh connection and control of a network device, that for some reason, only allows keyboard-interactive authentication. It doesn't appear that paramiko supports this by default or with the standard sshclient() object.
I've spent the past couple of days going through the paramiko documentation trying to figure this out, and this is the closest that I've been able to get working.
import paramiko
import socket
def ihandler(title,instructions,prompt_list):
return 'pass'
if __name__=="__main__":
paramiko.common.logging.basicConfig(level=paramiko.common.DEBUG)
s=socket.socket()
s.connect(('localhost',22))
t=paramiko.Transport(s)
t.set_log_channel("paramiko.transport")
t.start_client()
t.auth_password('user','pass')
t.auth_interactive ('user',ihandler)
Any help would be greatly appreciated.
|
How do I emulate keyboard-interactive ssh login with paramiko?
|
I'm trying to automate a ssh connection and control of a network device, that for some reason, only allows keyboard-interactive authentication. It doesn't appear that paramiko supports this by default or with the standard sshclient() object.
I've spent the past couple of days going through the paramiko documentation trying to figure this out, and this is the closest that I've been able to get working.
import paramiko
import socket
def ihandler(title,instructions,prompt_list):
return 'pass'
if __name__=="__main__":
paramiko.common.logging.basicConfig(level=paramiko.common.DEBUG)
s=socket.socket()
s.connect(('localhost',22))
t=paramiko.Transport(s)
t.set_log_channel("paramiko.transport")
t.start_client()
t.auth_password('user','pass')
t.auth_interactive ('user',ihandler)
Any help would be greatly appreciated.
|
[] |
[] |
[
"What you want is pxssh from the pxpect project. Look at the sshls.py and ssh_tunnel.py examples.\nhttp://www.noah.org/wiki/Pexpect\n"
] |
[
-1
] |
[
"authentication",
"paramiko",
"python",
"ssh"
] |
stackoverflow_0002254673_authentication_paramiko_python_ssh.txt
|
Q:
How to digitally sign a message with M2Crypto using the keys within a DER format certificate
I am working on a project to implement digital signatures of outgoing messages and decided to use M2Crypto for that.
I have a certificate (in DER format) from which I extract the keys to sign the message. For some reason I keep getting an ugly segmentation fault error when I call the "sign_update" method.
Given the previous examples I have read here, I am clearly missing something.
Here is the example I am working on:
from M2Crypto.X509 import *
cert = load_cert( 'certificate.cer', format=1 )
Pub_key = cert.get_pubkey()
Pub_key.reset_context(md='sha1')
Pub_key.sign_init()
Pub_key.sign_update( "This should be good." )
print Pub_key.sign_final()
Thanks in advance for the help,
Pablo
A:
One obvious thing jumps at me: you say your certificate is in DER format, but you are passing format=0 to load_cert() which means PEM. See X509 module variables. Maybe not what is causing your issue, though (I would expect you'd get an exception if you mix the cert type).
Update After some more thought, I think you are trying to do the wrong thing here, which is why it is crashing (although it of course should not crash but raise an exception). You can't sign a message using the public key from a certificate. That would be like doing digital forgery.
Think of it this way. You receive my certificate, which contains my public key. You can use the public key to encrypt a message to me. Only I will be able to decrypt using my private key. You can sign the message using your private key, and I can use your public key to verify your signature.
A:
There is no private key file, thats why it crashes and I can not sign it.
|
How to digitally sign a message with M2Crypto using the keys within a DER format certificate
|
I am working on a project to implement digital signatures of outgoing messages and decided to use M2Crypto for that.
I have a certificate (in DER format) from which I extract the keys to sign the message. For some reason I keep getting an ugly segmentation fault error when I call the "sign_update" method.
Given the previous examples I have read here, I am clearly missing something.
Here is the example I am working on:
from M2Crypto.X509 import *
cert = load_cert( 'certificate.cer', format=1 )
Pub_key = cert.get_pubkey()
Pub_key.reset_context(md='sha1')
Pub_key.sign_init()
Pub_key.sign_update( "This should be good." )
print Pub_key.sign_final()
Thanks in advance for the help,
Pablo
|
[
"One obvious thing jumps at me: you say your certificate is in DER format, but you are passing format=0 to load_cert() which means PEM. See X509 module variables. Maybe not what is causing your issue, though (I would expect you'd get an exception if you mix the cert type).\nUpdate After some more thought, I think you are trying to do the wrong thing here, which is why it is crashing (although it of course should not crash but raise an exception). You can't sign a message using the public key from a certificate. That would be like doing digital forgery.\nThink of it this way. You receive my certificate, which contains my public key. You can use the public key to encrypt a message to me. Only I will be able to decrypt using my private key. You can sign the message using your private key, and I can use your public key to verify your signature.\n",
"There is no private key file, thats why it crashes and I can not sign it.\n"
] |
[
2,
0
] |
[] |
[] |
[
"digital_certificate",
"digital_signature",
"m2crypto",
"python"
] |
stackoverflow_0002401397_digital_certificate_digital_signature_m2crypto_python.txt
|
Q:
Problem importing pylab in Ubuntu 8.1
I have installed numpy1.3,scipy 0.7.1,matplotlib 0.99.1.1 and python 2.5
when I import pylab I get the following error. Someone please help.
/var/lib/python-support/python2.5/gtk-2.0/gtk/__init__.py:72: GtkWarning: could not open display
warnings.warn(str(e), _gtk.Warning)
/usr/lib/python2.5/site-packages/matplotlib/backends/backend_gtk.py:44: GtkWarning: gdk_cursor_new_for_display: assertion `GDK_IS_DISPLAY (display)' failed
cursors.MOVE : gdk.Cursor(gdk.FLEUR),
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "/usr/lib/python2.5/site-packages/pylab.py", line 1, in <module>
from matplotlib.pylab import *
File "/usr/lib/python2.5/site-packages/matplotlib/pylab.py", line 247, in <module>
from matplotlib.pyplot import *
File "/usr/lib/python2.5/site-packages/matplotlib/pyplot.py", line 78, in <module>
new_figure_manager, draw_if_interactive, show = pylab_setup()
File "/usr/lib/python2.5/site-packages/matplotlib/backends/__init__.py", line 25, in pylab_setup
globals(),locals(),[backend_name])
File "/usr/lib/python2.5/site-packages/matplotlib/backends/backend_gtkagg.py", line 10, in <module>
from matplotlib.backends.backend_gtk import gtk, FigureManagerGTK, FigureCanvasGTK,\
File "/usr/lib/python2.5/site-packages/matplotlib/backends/backend_gtk.py", line 44, in <module>
cursors.MOVE : gdk.Cursor(gdk.FLEUR),
RuntimeError: could not create GdkCursor object
A:
try using a different backend for plotting than Gtk.
Open the python console and type:
>>> import matplotlib
>>> matplotlib.matplotlib_fname()
This will print a file name. Edit this file and modify the section 'Backend' and change Gtk or GtkAgg with any other (see the documentation in the same file), until you get it working.
You can find more information about backends here.
As for why you get an error when you try to use that backend, it depends on how you have installed the libraries and what you have installed on your computer. I would recommend to install matplotlib with synaptic/yum and selecting all optional dependencies.
|
Problem importing pylab in Ubuntu 8.1
|
I have installed numpy1.3,scipy 0.7.1,matplotlib 0.99.1.1 and python 2.5
when I import pylab I get the following error. Someone please help.
/var/lib/python-support/python2.5/gtk-2.0/gtk/__init__.py:72: GtkWarning: could not open display
warnings.warn(str(e), _gtk.Warning)
/usr/lib/python2.5/site-packages/matplotlib/backends/backend_gtk.py:44: GtkWarning: gdk_cursor_new_for_display: assertion `GDK_IS_DISPLAY (display)' failed
cursors.MOVE : gdk.Cursor(gdk.FLEUR),
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "/usr/lib/python2.5/site-packages/pylab.py", line 1, in <module>
from matplotlib.pylab import *
File "/usr/lib/python2.5/site-packages/matplotlib/pylab.py", line 247, in <module>
from matplotlib.pyplot import *
File "/usr/lib/python2.5/site-packages/matplotlib/pyplot.py", line 78, in <module>
new_figure_manager, draw_if_interactive, show = pylab_setup()
File "/usr/lib/python2.5/site-packages/matplotlib/backends/__init__.py", line 25, in pylab_setup
globals(),locals(),[backend_name])
File "/usr/lib/python2.5/site-packages/matplotlib/backends/backend_gtkagg.py", line 10, in <module>
from matplotlib.backends.backend_gtk import gtk, FigureManagerGTK, FigureCanvasGTK,\
File "/usr/lib/python2.5/site-packages/matplotlib/backends/backend_gtk.py", line 44, in <module>
cursors.MOVE : gdk.Cursor(gdk.FLEUR),
RuntimeError: could not create GdkCursor object
|
[
"try using a different backend for plotting than Gtk. \nOpen the python console and type:\n>>> import matplotlib\n>>> matplotlib.matplotlib_fname()\n\nThis will print a file name. Edit this file and modify the section 'Backend' and change Gtk or GtkAgg with any other (see the documentation in the same file), until you get it working.\nYou can find more information about backends here.\nAs for why you get an error when you try to use that backend, it depends on how you have installed the libraries and what you have installed on your computer. I would recommend to install matplotlib with synaptic/yum and selecting all optional dependencies.\n"
] |
[
8
] |
[] |
[] |
[
"python"
] |
stackoverflow_0002418583_python.txt
|
Q:
Applying style sheets in pyqt
If i apply a property to a parent widget it is automatically applied for child widgets too.. Is there any way of preventing this?? For example if i set background color as white in a dialog the button,combo boxes and scroll bars looks white as it lacks it native look(have to say it's unpleasant & ugly).. Is there any way that i can apply the stylesheets only to a parent widget not to it's children???
Experts help please..
A:
Found a solution..
Instead of using
self.groupBox.setStyleSheet("background-color: rgb(255, 255, 255);\n"
"border:1px solid rgb(255, 170, 255);")
use specifically using selector types..
self.groupBox.setStyleSheet("QGroupBox { background-color: rgb(255, 255,\
255); border:1px solid rgb(255, 170, 255); }")
This solves the problem..
|
Applying style sheets in pyqt
|
If i apply a property to a parent widget it is automatically applied for child widgets too.. Is there any way of preventing this?? For example if i set background color as white in a dialog the button,combo boxes and scroll bars looks white as it lacks it native look(have to say it's unpleasant & ugly).. Is there any way that i can apply the stylesheets only to a parent widget not to it's children???
Experts help please..
|
[
"Found a solution..\nInstead of using \nself.groupBox.setStyleSheet(\"background-color: rgb(255, 255, 255);\\n\"\n \"border:1px solid rgb(255, 170, 255);\")\n\nuse specifically using selector types..\nself.groupBox.setStyleSheet(\"QGroupBox { background-color: rgb(255, 255,\\\n255); border:1px solid rgb(255, 170, 255); }\")\n\nThis solves the problem.. \n"
] |
[
14
] |
[] |
[] |
[
"pyqt",
"pyqt4",
"python",
"qt4",
"stylesheet"
] |
stackoverflow_0002404317_pyqt_pyqt4_python_qt4_stylesheet.txt
|
Q:
How do I pass a list parameter as multiple link-named elements instead of as an array in SOAPpy?
I am trying to pass multiple instances of an element to a web servile that has the following wsdl
<complexType name="OAMCommand">
<sequence>
<element name="m-strName" type="xsd:string" minOccurs="1" maxOccurs="1"/>
<element name="m-argVector" type="xsd:string" minOccurs="0" maxOccurs="unbounded"/>
</sequence>
</complexType>
This is my code in python for the client
oamCmdStruct = SOAPpy.structType()
oamCmdStruct._addItem('m-strName','set-log-level')
oamCmdStruct._addItem('m-argVector', logLevel)
oamCmdStruct._addItem('m-argVector', loggerName)
self.serverConnection.executeCommand({'in-cmd':oamCmdStruct}
Here is the output I get from SOAPpy that gets rejected by the web service, it creates an array for the 2 m-argVector elements.
<xsd:in-cmd>
<m-strName xsi:type="xsd:string">set-log-level</m-strName>
<m-argVector SOAP-ENC:arrayType="xsd:string[2]" xsi:type="SOAP-ENC:Array">
<item>WARN_LOG_LEVEL</item>
<item>netborder</item>
</m-argVector>
</xsd:in-cmd>
Here is the output that another client sends that works. No array, just two elements that have the same name.
<SoapOAM:executeCommand>
<in-cmd>
<m-strName>set-log-level</m-strName>
<m-argVector>ERROR_LOG_LEVEL</m-argVector>
<m-argVector>netborder.media</m-argVector>
</in-cmd>
</SoapOAM:executeCommand>
How can I modify my SOAPpy code to generate the xml output like the one above ?
EDIT:
I tried the following code in python
oamCmdStruct = SOAPpy.structType( data = {"m-strName":"set-log-level",
"m-argVector": logLevel,
"m-argVector": loggerName})
But this is what the XML output from SOAPpy looked like
<xsd:in-cmd>
<m-strName xsi:type="xsd:string">set-log-level</m-strName>
<m-argVector xsi:type="xsd:string">loggerName</m-argVector>
</xsd:in-cmd>
The value for logLevel gets overwritten by loggerName instead of creating 2 entries...
A:
After trying a few different librairies (suds, soaplib), I finally dug into the SOAPpy code.
In order to remove the arrays from my SOAP requests, I modified the dump_list() function in the SOAPBuilder class of the SOAPpy library.
# COMMENT: We dont want arrays in SOAP-XML so I commented out the following lines
# if typed:
# self.out.append(
# '<%s %sarrayType="%s[%d]" %stype="%sArray"%s%s%s%s%s%s>\n' %
# (tag, ens, t, len(data), ins, ens, ndecl, edecl, idecl,
# self.genroot(ns_map), id, a))
#if typed:
# try: elemsname = obj._elemsname
# except: elemsname = "item"
#else:
elemsname = tag
for i in data:
self.dump(i, elemsname, not same_type, ns_map)
#if typed: self.out.append('</%s>\n' % tag)
This change gives me the following output for my SOAP XML request.
<SOAP-ENV:Body>
<ns1:executeCommand xmlns:ns1="urn:SoapOAM">
<xsd:in-cmd>
<m-strName xsi:type="xsd:string">set-log-level</m-strName>
<m-argVector>ERROR_LOG_LEVEL</m-argVector>
<m-argVector>netborder</m-argVector>
</xsd:in-cmd>
</ns1:executeCommand>
</SOAP-ENV:Body>
|
How do I pass a list parameter as multiple link-named elements instead of as an array in SOAPpy?
|
I am trying to pass multiple instances of an element to a web servile that has the following wsdl
<complexType name="OAMCommand">
<sequence>
<element name="m-strName" type="xsd:string" minOccurs="1" maxOccurs="1"/>
<element name="m-argVector" type="xsd:string" minOccurs="0" maxOccurs="unbounded"/>
</sequence>
</complexType>
This is my code in python for the client
oamCmdStruct = SOAPpy.structType()
oamCmdStruct._addItem('m-strName','set-log-level')
oamCmdStruct._addItem('m-argVector', logLevel)
oamCmdStruct._addItem('m-argVector', loggerName)
self.serverConnection.executeCommand({'in-cmd':oamCmdStruct}
Here is the output I get from SOAPpy that gets rejected by the web service, it creates an array for the 2 m-argVector elements.
<xsd:in-cmd>
<m-strName xsi:type="xsd:string">set-log-level</m-strName>
<m-argVector SOAP-ENC:arrayType="xsd:string[2]" xsi:type="SOAP-ENC:Array">
<item>WARN_LOG_LEVEL</item>
<item>netborder</item>
</m-argVector>
</xsd:in-cmd>
Here is the output that another client sends that works. No array, just two elements that have the same name.
<SoapOAM:executeCommand>
<in-cmd>
<m-strName>set-log-level</m-strName>
<m-argVector>ERROR_LOG_LEVEL</m-argVector>
<m-argVector>netborder.media</m-argVector>
</in-cmd>
</SoapOAM:executeCommand>
How can I modify my SOAPpy code to generate the xml output like the one above ?
EDIT:
I tried the following code in python
oamCmdStruct = SOAPpy.structType( data = {"m-strName":"set-log-level",
"m-argVector": logLevel,
"m-argVector": loggerName})
But this is what the XML output from SOAPpy looked like
<xsd:in-cmd>
<m-strName xsi:type="xsd:string">set-log-level</m-strName>
<m-argVector xsi:type="xsd:string">loggerName</m-argVector>
</xsd:in-cmd>
The value for logLevel gets overwritten by loggerName instead of creating 2 entries...
|
[
"After trying a few different librairies (suds, soaplib), I finally dug into the SOAPpy code.\nIn order to remove the arrays from my SOAP requests, I modified the dump_list() function in the SOAPBuilder class of the SOAPpy library.\n# COMMENT: We dont want arrays in SOAP-XML so I commented out the following lines\n# if typed:\n# self.out.append(\n# '<%s %sarrayType=\"%s[%d]\" %stype=\"%sArray\"%s%s%s%s%s%s>\\n' %\n# (tag, ens, t, len(data), ins, ens, ndecl, edecl, idecl,\n# self.genroot(ns_map), id, a))\n\n#if typed:\n# try: elemsname = obj._elemsname\n# except: elemsname = \"item\"\n#else:\nelemsname = tag\n\nfor i in data:\n self.dump(i, elemsname, not same_type, ns_map)\n\n#if typed: self.out.append('</%s>\\n' % tag)\n\nThis change gives me the following output for my SOAP XML request.\n<SOAP-ENV:Body>\n<ns1:executeCommand xmlns:ns1=\"urn:SoapOAM\">\n<xsd:in-cmd>\n<m-strName xsi:type=\"xsd:string\">set-log-level</m-strName>\n<m-argVector>ERROR_LOG_LEVEL</m-argVector>\n<m-argVector>netborder</m-argVector>\n</xsd:in-cmd>\n</ns1:executeCommand>\n</SOAP-ENV:Body>\n\n"
] |
[
1
] |
[] |
[] |
[
"python",
"soap",
"soappy",
"wsdl"
] |
stackoverflow_0002336961_python_soap_soappy_wsdl.txt
|
Q:
stop django from taking out javascript/frames?
Very newbie question, but please be gentle with me. Our site uses Django CMS and we're trying to insert some javascript into particular stories, but it appears Django is stripping out any javascript or iframes we put in there as soon as we save the story. How do we allow javascript to be used in stories? Is it being deliberately excluded, or do we need to code this function into the site?
Any help would be incredibly appreciated.
A:
Django is probably automatically escaping the content the javascript / html as the template renders the content. It does this for security purposes.
The solution depends on which version of django you're running, whether you'll be rendering any content from untrusted sources, how the templates are put together and perhaps the view that prepares the content for the template.
A:
Django doesn't strip out javascript, because it is client side agnostic.
How are you inserting javascript into your website? If you are trying to put it into database (like ) it will escaped.
A:
Read through the docs on automatic HTML escaping:
http://docs.djangoproject.com/en/1.1/topics/templates/#id2
|
stop django from taking out javascript/frames?
|
Very newbie question, but please be gentle with me. Our site uses Django CMS and we're trying to insert some javascript into particular stories, but it appears Django is stripping out any javascript or iframes we put in there as soon as we save the story. How do we allow javascript to be used in stories? Is it being deliberately excluded, or do we need to code this function into the site?
Any help would be incredibly appreciated.
|
[
"Django is probably automatically escaping the content the javascript / html as the template renders the content. It does this for security purposes.\nThe solution depends on which version of django you're running, whether you'll be rendering any content from untrusted sources, how the templates are put together and perhaps the view that prepares the content for the template.\n",
"Django doesn't strip out javascript, because it is client side agnostic.\nHow are you inserting javascript into your website? If you are trying to put it into database (like ) it will escaped.\n",
"Read through the docs on automatic HTML escaping:\nhttp://docs.djangoproject.com/en/1.1/topics/templates/#id2\n"
] |
[
2,
0,
0
] |
[] |
[] |
[
"django",
"django_templates",
"python"
] |
stackoverflow_0002416677_django_django_templates_python.txt
|
Q:
Sending a List through an URL
I have a list that I need to send through a URL to a third party vendor. I don't know what language they are using.
The list prints out like this:
[u'1', u'6', u'5']
I know that the u encodes the string in utf-8 right? So a couple of questions.
Can I send a list through a URL?
Will the u's show up on the other end when going through the URL?
If so, how do I remove them?
I am not sure what keywords to search to help me out, so any resources would be helpful too.
A:
Can I send a list through a URL?
No. A URL is just text. If you want a way to package structured information in it, you'll have to agree that with the provider you're talking to.
One standard encoding for structure in URLs, that might or might not be what you need, is the use of multiple parameters with the same name in a query string. This format comes from HTML form submissions:
http://www.example.com/script?par=1&par=6&par=5
might be considered to represent a parameter par with a three-item list as its value. Or maybe not, it's up to the receiver to decide. For example in a PHP application you would have had to name the parameter par[] to get it to accept the array value.
I know that the u encodes the string in utf-8 right?
No. a u'...' string is a native Unicode string, where each index represents a whole character and not a byte in any particular encoding. If you want UTF-8 bytes, write u'...'.encode('utf-8') before URL-encoding. UTF-8 is a good default choice, but again: what encoding the receiving side wants is up to that application.
Will the u's show up on the other end when going through the URL?
u is part of the literal representation of the string, just the same as the ' quotes themselves. They are not part of the string value and would not be echoed by print or when joined into other strings, unless you deliberately asked for the literal representation by calling repr.
A:
u'' is not utf-8, its python unicode strings for python 2.x
To send it through url, you need to encode them with utf8 like .encode('utf-8'), and also need to urlencode, and list cannot send it through URL, you need to make it as string.
Basically, you need to do it in following steps
python list -> unicode string -> utf8 string -> url encode -> send it through proper urllib api
A:
Incorrect. unicode literals use Python's internal encoding, decided when it was compiled.
You can't send anything "through" URLs. Pick a protocol instead. And encode before sending, probably to UTF-8.
|
Sending a List through an URL
|
I have a list that I need to send through a URL to a third party vendor. I don't know what language they are using.
The list prints out like this:
[u'1', u'6', u'5']
I know that the u encodes the string in utf-8 right? So a couple of questions.
Can I send a list through a URL?
Will the u's show up on the other end when going through the URL?
If so, how do I remove them?
I am not sure what keywords to search to help me out, so any resources would be helpful too.
|
[
"\nCan I send a list through a URL?\n\nNo. A URL is just text. If you want a way to package structured information in it, you'll have to agree that with the provider you're talking to.\nOne standard encoding for structure in URLs, that might or might not be what you need, is the use of multiple parameters with the same name in a query string. This format comes from HTML form submissions:\nhttp://www.example.com/script?par=1&par=6&par=5\n\nmight be considered to represent a parameter par with a three-item list as its value. Or maybe not, it's up to the receiver to decide. For example in a PHP application you would have had to name the parameter par[] to get it to accept the array value.\n\nI know that the u encodes the string in utf-8 right?\n\nNo. a u'...' string is a native Unicode string, where each index represents a whole character and not a byte in any particular encoding. If you want UTF-8 bytes, write u'...'.encode('utf-8') before URL-encoding. UTF-8 is a good default choice, but again: what encoding the receiving side wants is up to that application.\n\nWill the u's show up on the other end when going through the URL?\n\nu is part of the literal representation of the string, just the same as the ' quotes themselves. They are not part of the string value and would not be echoed by print or when joined into other strings, unless you deliberately asked for the literal representation by calling repr.\n",
"u'' is not utf-8, its python unicode strings for python 2.x\nTo send it through url, you need to encode them with utf8 like .encode('utf-8'), and also need to urlencode, and list cannot send it through URL, you need to make it as string.\nBasically, you need to do it in following steps\npython list -> unicode string -> utf8 string -> url encode -> send it through proper urllib api\n",
"Incorrect. unicode literals use Python's internal encoding, decided when it was compiled.\nYou can't send anything \"through\" URLs. Pick a protocol instead. And encode before sending, probably to UTF-8.\n"
] |
[
5,
1,
0
] |
[] |
[] |
[
"python",
"string",
"unicode",
"url"
] |
stackoverflow_0002417611_python_string_unicode_url.txt
|
Q:
Avoiding duplicated data in PostgreSQL database in Python
I am working on PostgreSQL and psycopg2. Trying
to get feed data which is updated every after 10 mins
and keep this feeds contents in PostgreSQL database.My target is to retrieve
and print those data from that table.
But facing problem as duplicate data is also stored in the database every time I run that script due to insertion operation on table.
To get out off this problem ,I made primary key constraint of column location_title in table Locations-musiq1 where I intend to store my feed data.But facing error.
Here is my code:
import psycopg2
import sys
import feedparser
import codecs
import psycopg2.extensions
# Parsing data from Geofeed location feeds
data = feedparser.parse("some URL")
psycopg2.extensions.register_type(psycopg2.extensions.UNICODE)
try:
conn=psycopg2.connect("dbname='name' user='postgres' host='localhost' password='abcds'")
conn.set_client_encoding('UNICODE')
except:
print "I am unable to connect to the database, exiting."
sys.exit()
cur=conn.cursor()
for i in range(len(data['entries'])):
cur.execute("INSERT INTO locations_musiq1(location, location_title) VALUES (%s, %s)", (data.entries[i].title,data.entries[i].summary))
conn.commit()
cur.execute("SELECT * FROM locations_musiq1;")
cur.fetchone()
for row in cur:
print ' '.join(row[1:])
cur.close()
conn.close()
My error after changing "locations_musiq1" tables column "location_title" as primary key is:
Traceback (most recent call last):
File "F:\JavaWorkspace\Test\src\postgr_example.py", line 28, in
cur.execute("INSERT INTO locations_musiq1(location, location_title) VALUES (%s, %s)", (data.entries[i].title,data.entries[i].summary))
psycopg2.IntegrityError: duplicate key value violates unique constraint "locations_musiq1_pkey"
Can anybody have any idea to get out of this problem ?..Thanks in advance..
A:
Your code only has INSERT, so what do you think is going to happen when you fetch the same data for a second time?
Your update is failing because you're trying to insert a row which has an identical field value to one that already exists in a column with a unique constraint.
You either need to match entries in from the feed to your table and INSERT, UPDATE, DELETE as appropriate. Where appropriate is defined by the feed data and the reasons for you synchronising. Or you empty your table and populate it from the feed each time.
What are you trying to achieve?
A:
You could try something like this:
cur.execute("""
INSERT INTO locations_musiq1(location, location_title)
SELECT %s, %s WHERE NOT EXISTS
(SELECT location_title FROM locations_musiq1 WHERE location_title=%s);
""", (data.entries[i].title, data.entries[i].summary, data.entries[i].summary))
A:
Rahman. You are asking a second question in your comment that should probably be made into its own question instead.
Anyhow to return the results in a specified order, you need an order by clause. I don't see a timestamp column here but I assume that your feed data is formatted in XML. You could order by some xpath expression. But if you just want them in the order they were inserted, you can sort by the hidden system column xmin, which is the transaction id of the insert operation.
See documentation on system columns.
|
Avoiding duplicated data in PostgreSQL database in Python
|
I am working on PostgreSQL and psycopg2. Trying
to get feed data which is updated every after 10 mins
and keep this feeds contents in PostgreSQL database.My target is to retrieve
and print those data from that table.
But facing problem as duplicate data is also stored in the database every time I run that script due to insertion operation on table.
To get out off this problem ,I made primary key constraint of column location_title in table Locations-musiq1 where I intend to store my feed data.But facing error.
Here is my code:
import psycopg2
import sys
import feedparser
import codecs
import psycopg2.extensions
# Parsing data from Geofeed location feeds
data = feedparser.parse("some URL")
psycopg2.extensions.register_type(psycopg2.extensions.UNICODE)
try:
conn=psycopg2.connect("dbname='name' user='postgres' host='localhost' password='abcds'")
conn.set_client_encoding('UNICODE')
except:
print "I am unable to connect to the database, exiting."
sys.exit()
cur=conn.cursor()
for i in range(len(data['entries'])):
cur.execute("INSERT INTO locations_musiq1(location, location_title) VALUES (%s, %s)", (data.entries[i].title,data.entries[i].summary))
conn.commit()
cur.execute("SELECT * FROM locations_musiq1;")
cur.fetchone()
for row in cur:
print ' '.join(row[1:])
cur.close()
conn.close()
My error after changing "locations_musiq1" tables column "location_title" as primary key is:
Traceback (most recent call last):
File "F:\JavaWorkspace\Test\src\postgr_example.py", line 28, in
cur.execute("INSERT INTO locations_musiq1(location, location_title) VALUES (%s, %s)", (data.entries[i].title,data.entries[i].summary))
psycopg2.IntegrityError: duplicate key value violates unique constraint "locations_musiq1_pkey"
Can anybody have any idea to get out of this problem ?..Thanks in advance..
|
[
"Your code only has INSERT, so what do you think is going to happen when you fetch the same data for a second time?\nYour update is failing because you're trying to insert a row which has an identical field value to one that already exists in a column with a unique constraint.\nYou either need to match entries in from the feed to your table and INSERT, UPDATE, DELETE as appropriate. Where appropriate is defined by the feed data and the reasons for you synchronising. Or you empty your table and populate it from the feed each time.\nWhat are you trying to achieve?\n",
"You could try something like this:\ncur.execute(\"\"\"\n INSERT INTO locations_musiq1(location, location_title) \n SELECT %s, %s WHERE NOT EXISTS \n (SELECT location_title FROM locations_musiq1 WHERE location_title=%s);\n \"\"\", (data.entries[i].title, data.entries[i].summary, data.entries[i].summary))\n\n",
"Rahman. You are asking a second question in your comment that should probably be made into its own question instead.\nAnyhow to return the results in a specified order, you need an order by clause. I don't see a timestamp column here but I assume that your feed data is formatted in XML. You could order by some xpath expression. But if you just want them in the order they were inserted, you can sort by the hidden system column xmin, which is the transaction id of the insert operation.\nSee documentation on system columns.\n"
] |
[
2,
2,
1
] |
[] |
[] |
[
"postgresql",
"psycopg2",
"python"
] |
stackoverflow_0002415884_postgresql_psycopg2_python.txt
|
Q:
Installing mod_python on Snow Leopard
I'd rather not use Macports. Simply cause Macport replaces (installs another Apache in /opt/local/bin) the default installation of Apache. And that would mean having ports install/replace PHP too. I'd rather use the default installation included in Snow Leopard.
Been searching the net, and all I get is old instructions using Darwin Ports (older version of Macports) or instruction for Leopard (which hasn't panned out for me).
Can anyone point me in the right direction? Thanks.
PS: By the way mod_python for 1.6 or 3.1 is fine.
A:
First of all, it seems that the mod_python development has somewhat stalled. I've read comments that, for wsgi-capable applications like Trac or Django, mod_wsgi is sufficient. Mod_wsgi compiles without problems on Snow Leopard (of course you need the Developer tools installed).
Of course, Macports or Fink is always an alternative. However, as opposed to Leopard where the supplied Apache and Python binaries were rather old, the Snow Leopard ones are current and 64-bit as well. Another advantage of using the Apple supplied binaries is that they get automatic security updates with the usual Apple Software Update. Last but not least you have better OS integration with using the standard supplied Apache.
A:
fink is the alternative distribution to MacPorts. Given you're installing a module, it would most likely update your Apache instance as well.
Sounds like you'll probably need to build Apache (to get the header files/libraries you need to link to) and mod_python.
A:
If you still want to avoid macports, I recommend checking out the mod_python trunk. I was actually able to build it with apache2 and Python 2.5 successfully without having to tweak the source of any of all the previously reported issues
svn co https://svn.apache.org/repos/asf/quetzalcoatl/mod_python/trunk mod_python-trunk
Macports is great if you are starting with a clean slate. But often you are just migrating systems (migrations assistant never gets the mod_python over) or even just upgrading the OS (had to rebuild mod_python for snow leopard)
:)
|
Installing mod_python on Snow Leopard
|
I'd rather not use Macports. Simply cause Macport replaces (installs another Apache in /opt/local/bin) the default installation of Apache. And that would mean having ports install/replace PHP too. I'd rather use the default installation included in Snow Leopard.
Been searching the net, and all I get is old instructions using Darwin Ports (older version of Macports) or instruction for Leopard (which hasn't panned out for me).
Can anyone point me in the right direction? Thanks.
PS: By the way mod_python for 1.6 or 3.1 is fine.
|
[
"First of all, it seems that the mod_python development has somewhat stalled. I've read comments that, for wsgi-capable applications like Trac or Django, mod_wsgi is sufficient. Mod_wsgi compiles without problems on Snow Leopard (of course you need the Developer tools installed).\nOf course, Macports or Fink is always an alternative. However, as opposed to Leopard where the supplied Apache and Python binaries were rather old, the Snow Leopard ones are current and 64-bit as well. Another advantage of using the Apple supplied binaries is that they get automatic security updates with the usual Apple Software Update. Last but not least you have better OS integration with using the standard supplied Apache.\n",
"fink is the alternative distribution to MacPorts. Given you're installing a module, it would most likely update your Apache instance as well.\nSounds like you'll probably need to build Apache (to get the header files/libraries you need to link to) and mod_python.\n",
"If you still want to avoid macports, I recommend checking out the mod_python trunk. I was actually able to build it with apache2 and Python 2.5 successfully without having to tweak the source of any of all the previously reported issues\nsvn co https://svn.apache.org/repos/asf/quetzalcoatl/mod_python/trunk mod_python-trunk\nMacports is great if you are starting with a clean slate. But often you are just migrating systems (migrations assistant never gets the mod_python over) or even just upgrading the OS (had to rebuild mod_python for snow leopard)\n:)\n"
] |
[
2,
0,
0
] |
[] |
[] |
[
"mod_python",
"osx_snow_leopard",
"python"
] |
stackoverflow_0001616431_mod_python_osx_snow_leopard_python.txt
|
Q:
How to only pay the dependency penalty for the implementation you use in Python?
I have a fairly simple set of functionality for which I have multiple implementations, e.g., a datastore that could be backed by Redis, MongoDB, or PostgreSQL. How should I structure/write my code so that code that wants to use one of these implementations only needs the dependencies for that implementation, e.g., they don't need to have psycopg2 installed if they are using the Redis backend.
Here's an example. Assume the following module, example.py.
class RedisExample(object):
try:
import redis
except ImportError:
print("You need to install redis-py.")
def __init__(self):
super(RedisExample, self).__init__()
class UnsatisfiedExample(object):
try:
import flibbertigibbet
except ImportError:
print("You need to install flibbertigibbet-py")
def __init__(self):
super(UnsatisfiedExample, self).__init__()
Here's my Python shell experience:
>>> import example
You need to install flibbertigibbet-py
Alternately:
>>> from example import RedisExample
You need to install flibbertigibbet-py
I'd really rather I didn't get that error until I tried to instantiate an UnsatisfiedExample. Is there any sort of common way to approach this problem? I've thought about making example a package with each backend getting its own module and using a factory function, but I wanted to make sure I wasn't missing something better.
Thanks.
A:
Can't you simply put the import statement in the __init__ method of each class? Then it won't be run until you try to make an instance:
class UnsatisfiedExample(object):
def __init__(self):
try:
import flibbertigibbet
except ImportError:
raise RuntimeError("You need to install flibbertigibbet-py")
super(UnsatisfiedExample, self).__init__()
A:
import is just another statement, like for or with. Put it in an if statement, possibly behind an abstraction class.
|
How to only pay the dependency penalty for the implementation you use in Python?
|
I have a fairly simple set of functionality for which I have multiple implementations, e.g., a datastore that could be backed by Redis, MongoDB, or PostgreSQL. How should I structure/write my code so that code that wants to use one of these implementations only needs the dependencies for that implementation, e.g., they don't need to have psycopg2 installed if they are using the Redis backend.
Here's an example. Assume the following module, example.py.
class RedisExample(object):
try:
import redis
except ImportError:
print("You need to install redis-py.")
def __init__(self):
super(RedisExample, self).__init__()
class UnsatisfiedExample(object):
try:
import flibbertigibbet
except ImportError:
print("You need to install flibbertigibbet-py")
def __init__(self):
super(UnsatisfiedExample, self).__init__()
Here's my Python shell experience:
>>> import example
You need to install flibbertigibbet-py
Alternately:
>>> from example import RedisExample
You need to install flibbertigibbet-py
I'd really rather I didn't get that error until I tried to instantiate an UnsatisfiedExample. Is there any sort of common way to approach this problem? I've thought about making example a package with each backend getting its own module and using a factory function, but I wanted to make sure I wasn't missing something better.
Thanks.
|
[
"Can't you simply put the import statement in the __init__ method of each class? Then it won't be run until you try to make an instance:\nclass UnsatisfiedExample(object):\n def __init__(self):\n try:\n import flibbertigibbet\n except ImportError:\n raise RuntimeError(\"You need to install flibbertigibbet-py\")\n super(UnsatisfiedExample, self).__init__()\n\n",
"import is just another statement, like for or with. Put it in an if statement, possibly behind an abstraction class.\n"
] |
[
5,
4
] |
[] |
[] |
[
"dependencies",
"import",
"python"
] |
stackoverflow_0002410580_dependencies_import_python.txt
|
Q:
Some doubts on implementing custom error pages in Web2Py
I'm trying to implement a decorator for custom error pages in web2py
as per one of the haiti Todos. Ref -
http://web2py.com/AlterEgo/default/show/75
I'm trying to keep it as a module in /modules directory so that I can
import it into the controllers and place the decorator appropriately.
I have kept error handling decorator as
/modules/onerror.py
and am importing it like this from a controller say (or.py)-
exec('from applications.%s.modules.onerror import onerror as onerror'
% request.application)
HTTP object wasn't available in onerror.py so i did a -
from gluon.http import *
But then I readlized that the request object is also not available to
the decorator as in the line -
filename=os.path.join(request.folder,'views/errors/error%i.html'%status)
I have some doubts -
Is /modules directory a good place to keep such a reusable component?
Are the modules in the /modules directory automatically loaded as a
new web2py instance is created? If so how can I access them in a
controller?
Is there a way I can pass the request object to this decorator from
my controller? Hints are welcome.
My current onerror.py - http://paste.pocoo.org/show/186165/
The way I'm trying to use in a controller - http://paste.pocoo.org/show/186167/
Let me know if I'm doing it in an unobvious way.
A:
Solved through the web2py users mailing list.
you can also use: onerror = load_import('onerror').onerror
HTTP object wasn't available in onerror.py so i did a -
from gluon.http import *
python modules are normal python modules in web2py as well. They only see
python keywords unless you import them. web2py has 5 special objects
(request, response, session, cache, T) and your app has others (db,
auth, crud). Because they are instantiated at every request, they
cannot import by the module, they have to be passed explicitly to the
functions in the module. Mind that while this is awkward this is what
other frameworks ask to do all the time for all functions. web2py
saves you this for models and controllers.
But then I realized that the request object is also not available to
the decorator as in the line -
filename=os.path.join(request.folder,'views/errors/error
%i.html'%status)
I have some doubts -
1. Are the modules in the /modules directory automatically loaded as a
new web2py instance is created? If so how can I access them?
No. They are normal python modules. You have to import them to use
them.
Is there a way I can pass the request object to this decorator from
my controller? Hints are welcome.
You need a meta decorator def meta_decoration(something):
def actual_decorator(f,something=something):
do_whatever_you_want()
return f()
return decorator @meta_decorator(request) def function_to_be_decorated(): return dict() Anyway you do not need this
decorator. Look into routes.examples.py for routes_onerror. There is
a simple way to do what you want.
|
Some doubts on implementing custom error pages in Web2Py
|
I'm trying to implement a decorator for custom error pages in web2py
as per one of the haiti Todos. Ref -
http://web2py.com/AlterEgo/default/show/75
I'm trying to keep it as a module in /modules directory so that I can
import it into the controllers and place the decorator appropriately.
I have kept error handling decorator as
/modules/onerror.py
and am importing it like this from a controller say (or.py)-
exec('from applications.%s.modules.onerror import onerror as onerror'
% request.application)
HTTP object wasn't available in onerror.py so i did a -
from gluon.http import *
But then I readlized that the request object is also not available to
the decorator as in the line -
filename=os.path.join(request.folder,'views/errors/error%i.html'%status)
I have some doubts -
Is /modules directory a good place to keep such a reusable component?
Are the modules in the /modules directory automatically loaded as a
new web2py instance is created? If so how can I access them in a
controller?
Is there a way I can pass the request object to this decorator from
my controller? Hints are welcome.
My current onerror.py - http://paste.pocoo.org/show/186165/
The way I'm trying to use in a controller - http://paste.pocoo.org/show/186167/
Let me know if I'm doing it in an unobvious way.
|
[
"Solved through the web2py users mailing list.\n\nyou can also use: onerror = load_import('onerror').onerror \n\nHTTP object wasn't available in onerror.py so i did a - \n from gluon.http import * \n\npython modules are normal python modules in web2py as well. They only see\n python keywords unless you import them. web2py has 5 special objects \n (request, response, session, cache, T) and your app has others (db, \n auth, crud). Because they are instantiated at every request, they \n cannot import by the module, they have to be passed explicitly to the \n functions in the module. Mind that while this is awkward this is what \n other frameworks ask to do all the time for all functions. web2py \n saves you this for models and controllers. \n\nBut then I realized that the request object is also not available to \n the decorator as in the line - \n filename=os.path.join(request.folder,'views/errors/error \n %i.html'%status) \n I have some doubts - \n 1. Are the modules in the /modules directory automatically loaded as a \n new web2py instance is created? If so how can I access them? \n\nNo. They are normal python modules. You have to import them to use \n them. \n\n\nIs there a way I can pass the request object to this decorator from \n my controller? Hints are welcome. \n\n\nYou need a meta decorator def meta_decoration(something): \n def actual_decorator(f,something=something): \n do_whatever_you_want() \n return f() \n return decorator @meta_decorator(request) def function_to_be_decorated(): return dict() Anyway you do not need this\n decorator. Look into routes.examples.py for routes_onerror. There is\n a simple way to do what you want.\n\n"
] |
[
1
] |
[] |
[] |
[
"python",
"web2py"
] |
stackoverflow_0002391297_python_web2py.txt
|
Q:
Difference between `is` and `==`?
Possible Duplicate:
Python ‘==’ vs ‘is’ comparing strings, ‘is’ fails sometimes, why?
In Python, what is the difference between these two statements:
if x is "odp":
if x == "odp":
A:
The == operator tests for equality
The is keyword tests for object identity; whether we are talking about the same object. Note that multiple variables may refer to the same object.
A:
The is operator compares the identity while the == operator compares the value. Essentially x is y is the same as id(x) == id(y)
A:
For implementation reasons, "odp" is a bad example, but you should not use is unless you want the possibility of two identical strings to evaluate to false:
>>> lorem1 = "lorem ipsum dolor sit amet"
>>> lorem2 = " ".join(["lorem", "ipsum", "dolor", "sit", "amet"])
>>> lorem1 == lorem2
True
>>> lorem1 is lorem2
False
As others have said, is tests identity, not equality. In this case, I have two separate strings with the same contents. However, you should not depend on this either:
>>> odp1 = "odp"
>>> odp2 = "".join(["o", "d", "p"])
>>> odp1 == odp2
True
>>> odp1 is odp2
True
In other words, you should never use is to compare strings.
P.S.
In Python 2.7.10 >>> odp1 is odp2 returns False.
A:
See here
The operators is and is not test for object identity: x is y is true if and only if x and y are the same object. x is not y yields the inverse truth value
|
Difference between `is` and `==`?
|
Possible Duplicate:
Python ‘==’ vs ‘is’ comparing strings, ‘is’ fails sometimes, why?
In Python, what is the difference between these two statements:
if x is "odp":
if x == "odp":
|
[
"The == operator tests for equality \nThe is keyword tests for object identity; whether we are talking about the same object. Note that multiple variables may refer to the same object.\n",
"The is operator compares the identity while the == operator compares the value. Essentially x is y is the same as id(x) == id(y)\n",
"For implementation reasons, \"odp\" is a bad example, but you should not use is unless you want the possibility of two identical strings to evaluate to false:\n>>> lorem1 = \"lorem ipsum dolor sit amet\"\n>>> lorem2 = \" \".join([\"lorem\", \"ipsum\", \"dolor\", \"sit\", \"amet\"])\n>>> lorem1 == lorem2\nTrue\n>>> lorem1 is lorem2\nFalse\n\nAs others have said, is tests identity, not equality. In this case, I have two separate strings with the same contents. However, you should not depend on this either:\n>>> odp1 = \"odp\"\n>>> odp2 = \"\".join([\"o\", \"d\", \"p\"])\n>>> odp1 == odp2\nTrue\n>>> odp1 is odp2\nTrue \n\nIn other words, you should never use is to compare strings.\nP.S. \nIn Python 2.7.10 >>> odp1 is odp2 returns False.\n",
"See here\n\nThe operators is and is not test for object identity: x is y is true if and only if x and y are the same object. x is not y yields the inverse truth value\n\n"
] |
[
3,
2,
1,
0
] |
[] |
[] |
[
"python",
"syntax"
] |
stackoverflow_0002419361_python_syntax.txt
|
Q:
How do I retrieve a modules path when I have a class from that module
In python, If I have a class foo, I can call foo.__module__ to get a string with the name of the module it is part of.
If I have a module bar, I can call bar.__file__ to get a string with the path where the module was loaded from.
How, when I only have class foo can I get the path of the module it is part of? (foo.__module__ returns a string, not an instance of the module it names)
A:
sys.modules is a mapping from module name to module:
sys.modules[foo.__module__].__file__
A:
For such introspection tasks, I always recommend using Python standard library's inspect module: it can handle some corner cases &c and makes the whole process much smoother. For your specific task, inspect.getsourcefile can be handy -- e.g., consider...:
>>> from sched import scheduler as someclass
>>> import inspect
>>> inspect.getsourcefile(someclass)
'/Library/Frameworks/Python.framework/Versions/2.6/lib/python2.6/sched.py'
this always tries to give you the .py file rather than sometimes the .py file and sometimes a .pyc file instead -- not a big deal, but one more useful "regularity".
|
How do I retrieve a modules path when I have a class from that module
|
In python, If I have a class foo, I can call foo.__module__ to get a string with the name of the module it is part of.
If I have a module bar, I can call bar.__file__ to get a string with the path where the module was loaded from.
How, when I only have class foo can I get the path of the module it is part of? (foo.__module__ returns a string, not an instance of the module it names)
|
[
"sys.modules is a mapping from module name to module:\nsys.modules[foo.__module__].__file__\n\n",
"For such introspection tasks, I always recommend using Python standard library's inspect module: it can handle some corner cases &c and makes the whole process much smoother. For your specific task, inspect.getsourcefile can be handy -- e.g., consider...:\n>>> from sched import scheduler as someclass\n>>> import inspect\n>>> inspect.getsourcefile(someclass)\n'/Library/Frameworks/Python.framework/Versions/2.6/lib/python2.6/sched.py'\n\nthis always tries to give you the .py file rather than sometimes the .py file and sometimes a .pyc file instead -- not a big deal, but one more useful \"regularity\".\n"
] |
[
6,
3
] |
[] |
[] |
[
"python"
] |
stackoverflow_0002417639_python.txt
|
Q:
Decorator class to test for required class variables
First of all I don't know if this is the right approach. I want to write a decorator class that will be used with methods of other class. Before running the method I'd like to check if all required class variables are initialized. The ideal case would be something similar to this:
class Test(object):
def __init__(self, f):
self.f = f
# some magic
def __call__(self):
self.f.magically_get_variable(required)
# do some checks and execute method or throw an exception
class Data(object):
def __init__(self, a, b):
self.a = a
@test
def sum(self):
required('self.a', 'self.b')
return self.a + self.b
If this is not the way it should be done please advise me how to do it properly.
A:
I'd say decorators are a bit unfit here for the purpose of checking if a variable exists.
Think about what you're planning to do if the required variables are not supplied: raise an exception (it's in your comment).
I'd say (based on the code above):
def sum(self):
return self.a + self.b
And let it fail if self.a or self.b is not supplied (it will raise a NameError exception, you can catch that if you like, and you could raise your own then if you want.)
A:
If you insist on checking before the decorated method's body starts, the following is one reasonable way to do it...:
import functools
class test(object):
def __init__(self, requiredvars):
self.reqs = requiredvars.split()
def __call__(self, f):
@functools.wraps(f)
def wrapper(wself, *a, **k):
missing = set()
for v in self.reqs:
if not hasattr(wself, v):
missing.add(v)
if missing:
msg = 'missing fields: %s' % ','.join(sorted(missing))
raise valueerror, msg
return f(wself, *a, **k)
return wrapper
class data(object):
def __init__(self, a, b):
self.a = a
@test('a b')
def sum(self):
return self.a + self.b
d = data(23, 42)
d.sum()
This emits, as you apparently desire,
Traceback (most recent call last):
File "rev.py", line 29, in <module>
d.sum()
File "rev.py", line 16, in wrapper
raise ValueError, msg
ValueError: Missing fields: b
|
Decorator class to test for required class variables
|
First of all I don't know if this is the right approach. I want to write a decorator class that will be used with methods of other class. Before running the method I'd like to check if all required class variables are initialized. The ideal case would be something similar to this:
class Test(object):
def __init__(self, f):
self.f = f
# some magic
def __call__(self):
self.f.magically_get_variable(required)
# do some checks and execute method or throw an exception
class Data(object):
def __init__(self, a, b):
self.a = a
@test
def sum(self):
required('self.a', 'self.b')
return self.a + self.b
If this is not the way it should be done please advise me how to do it properly.
|
[
"I'd say decorators are a bit unfit here for the purpose of checking if a variable exists.\nThink about what you're planning to do if the required variables are not supplied: raise an exception (it's in your comment). \nI'd say (based on the code above):\ndef sum(self):\n return self.a + self.b\n\nAnd let it fail if self.a or self.b is not supplied (it will raise a NameError exception, you can catch that if you like, and you could raise your own then if you want.)\n",
"If you insist on checking before the decorated method's body starts, the following is one reasonable way to do it...:\nimport functools\n\nclass test(object):\n def __init__(self, requiredvars):\n self.reqs = requiredvars.split()\n\n def __call__(self, f):\n @functools.wraps(f)\n def wrapper(wself, *a, **k):\n missing = set()\n for v in self.reqs:\n if not hasattr(wself, v):\n missing.add(v)\n if missing:\n msg = 'missing fields: %s' % ','.join(sorted(missing))\n raise valueerror, msg\n return f(wself, *a, **k)\n return wrapper\n\nclass data(object):\n def __init__(self, a, b):\n self.a = a\n\n @test('a b')\n def sum(self):\n return self.a + self.b\n\nd = data(23, 42)\nd.sum()\n\nThis emits, as you apparently desire,\nTraceback (most recent call last):\n File \"rev.py\", line 29, in <module>\n d.sum()\n File \"rev.py\", line 16, in wrapper\n raise ValueError, msg\nValueError: Missing fields: b\n\n"
] |
[
1,
0
] |
[] |
[] |
[
"decorator",
"python"
] |
stackoverflow_0002419196_decorator_python.txt
|
Q:
How to get the content of a Html page in Python
I have downloaded the web page into an html file. I am wondering what's the simplest way to get the content of that page. By content, I mean I need the strings that a browser would display.
To be clear:
Input:
<html><head><title>Page title</title></head>
<body><p id="firstpara" align="center">This is paragraph <b>one</b>.
<p id="secondpara" align="blah">This is paragraph <b>two</b>.
</html>
Output:
Page title This is paragraph one. This is paragraph two.
putting together:
from BeautifulSoup import BeautifulSoup
import re
def removeHtmlTags(page):
p = re.compile(r'''<(?:"[^"]*"['"]*|'[^']*'['"]*|[^'">])+>''')
return p.sub('', page)
def removeHtmlTags2(page):
soup = BeautifulSoup(page)
return ''.join(soup.findAll(text=True))
Related
Python HTML removal
Extracting text from HTML file using Python
What is a light python library that can eliminate HTML tags? (and only text)
Remove HTML tags in AppEngine Python Env (equivalent to Ruby’s Sanitize)
RegEx match open tags except XHTML self-contained tags (famous don't use regex to parse html rant)
A:
Parse the HTML with Beautiful Soup.
To get all the text, without the tags, try:
''.join(soup.findAll(text=True))
A:
Personally, I use lxml because it's a swiss-army knife...
from lxml import html
print html.parse('http://someurl.at.domain').xpath('//body')[0].text_content()
This tells lxml to retrieve the page, locate the <body> tag then extract and print all the text.
I do a lot of page parsing and a regex is the wrong solution most of the time, unless it's a one-time-only need. If the author of the page changes their HTML you run a good risk of your regex breaking. A parser is a lot more likely to continue working.
The big problem with a parser is learning how to access the sections of the document you are after, but there are a lot of XPATH tools you can use inside your browser that simplify the task.
A:
You want to look at Extracting data from HTML documents - Dive into Python because HERE it does (almost)exactly what you want.
A:
The best modules for this task are lxml or html5lib; Beautifull Soap is imho not worth to use anymore. And for recursive models regular expressions are definitly the wrong method.
|
How to get the content of a Html page in Python
|
I have downloaded the web page into an html file. I am wondering what's the simplest way to get the content of that page. By content, I mean I need the strings that a browser would display.
To be clear:
Input:
<html><head><title>Page title</title></head>
<body><p id="firstpara" align="center">This is paragraph <b>one</b>.
<p id="secondpara" align="blah">This is paragraph <b>two</b>.
</html>
Output:
Page title This is paragraph one. This is paragraph two.
putting together:
from BeautifulSoup import BeautifulSoup
import re
def removeHtmlTags(page):
p = re.compile(r'''<(?:"[^"]*"['"]*|'[^']*'['"]*|[^'">])+>''')
return p.sub('', page)
def removeHtmlTags2(page):
soup = BeautifulSoup(page)
return ''.join(soup.findAll(text=True))
Related
Python HTML removal
Extracting text from HTML file using Python
What is a light python library that can eliminate HTML tags? (and only text)
Remove HTML tags in AppEngine Python Env (equivalent to Ruby’s Sanitize)
RegEx match open tags except XHTML self-contained tags (famous don't use regex to parse html rant)
|
[
"Parse the HTML with Beautiful Soup.\nTo get all the text, without the tags, try:\n''.join(soup.findAll(text=True))\n\n",
"Personally, I use lxml because it's a swiss-army knife...\n\nfrom lxml import html\n\nprint html.parse('http://someurl.at.domain').xpath('//body')[0].text_content()\n\nThis tells lxml to retrieve the page, locate the <body> tag then extract and print all the text.\nI do a lot of page parsing and a regex is the wrong solution most of the time, unless it's a one-time-only need. If the author of the page changes their HTML you run a good risk of your regex breaking. A parser is a lot more likely to continue working. \nThe big problem with a parser is learning how to access the sections of the document you are after, but there are a lot of XPATH tools you can use inside your browser that simplify the task.\n",
"You want to look at Extracting data from HTML documents - Dive into Python because HERE it does (almost)exactly what you want.\n",
"The best modules for this task are lxml or html5lib; Beautifull Soap is imho not worth to use anymore. And for recursive models regular expressions are definitly the wrong method.\n"
] |
[
12,
9,
2,
1
] |
[
"If I am getting your question correctly, this can simply be done by using urlopen function of urllib. Just have a look at this function to open an url and read the response which will be the html code of that page.\n",
"The quickest way to get a usable sample of what a browser would display is to remove any tags from the html and print the rest. This can, for example, be done using python's re.\n"
] |
[
-2,
-3
] |
[
"html",
"parsing",
"python"
] |
stackoverflow_0002416823_html_parsing_python.txt
|
Q:
Error installing MySQL-python on MAC Snow Leopard, OS 10.6
I am trying to install the MySQL-python on MAC OS 10.6 (Snow leopard, 64 bit). I followed the steps:
1. Installed MySQL for Mac OS X ver. 10.6 (x86, 64-bit), DMG Archive.
2. Downloaded MySQL-python-1.2.3c1.tar.gz and unzipped it
3. CD to MySQL-python-1.2.3c1 and built it as:
ARCHFLAGS="-arch x86_64" python setup.py build (see output bnelow)
4. Installed it as:
ARCHFLAGS="-arch x86_64" python setup.py install
5. But when I tried to import MySQLdb to python, I am getting error message
import MySQLdb
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "build/bdist.macosx-10.3-x86_64/egg/MySQLdb/__init__.py", line 19, in <module>
File "build/bdist.macosx-10.3-x86_64/egg/_mysql.py", line 7, in <module>
File "build/bdist.macosx-10.3-x86_64/egg/_mysql.py", line 6, in __bootstrap__
ImportError: dlopen(/Users/krokodil/.python-eggs/MySQL_python-1.2.3c1-py2.6-macosx-10.3-x86_64.egg-tmp/_mysql.so, 2): no suitable image found. Did find:
/Users/krokodil/.python-eggs/MySQL_python-1.2.3c1-py2.6-macosx-10.3-x86_64.egg-tmp/_mysql.so: mach-o, but wrong architecture
This "macosx-10.3-x86_64" is bothering me - it seems that somehow the build/install thought that I am still on Mac OS 10.3. Please also see Build and Install capture below.
It also using /Developer/SDKs/MacOSX10.4u.sdk compiler, not /Developer/SDKs/MacOSX10.6.sdk
I am using fresh install of Python 2.6.4.
I saw people having probles. Anyone found a good solution?
Thank you
Vlad
BUILD
krokodil:MySQL-python-1.2.3c1 krokodil$ ARCHFLAGS="-arch x86_64" python setup.py build
running build
running build_py
creating build
creating build/lib.macosx-10.3-x86_64-2.6
copying _mysql_exceptions.py -> build/lib.macosx-10.3-x86_64-2.6
creating build/lib.macosx-10.3-x86_64-2.6/MySQLdb
copying MySQLdb/__init__.py -> build/lib.macosx-10.3-x86_64-2.6/MySQLdb
copying MySQLdb/converters.py -> build/lib.macosx-10.3-x86_64-2.6/MySQLdb
copying MySQLdb/connections.py -> build/lib.macosx-10.3-x86_64-2.6/MySQLdb
copying MySQLdb/cursors.py -> build/lib.macosx-10.3-x86_64-2.6/MySQLdb
copying MySQLdb/release.py -> build/lib.macosx-10.3-x86_64-2.6/MySQLdb
copying MySQLdb/times.py -> build/lib.macosx-10.3-x86_64-2.6/MySQLdb
creating build/lib.macosx-10.3-x86_64-2.6/MySQLdb/constants
copying MySQLdb/constants/__init__.py -> build/lib.macosx-10.3-x86_64-2.6/MySQLdb/constants
copying MySQLdb/constants/CR.py -> build/lib.macosx-10.3-x86_64-2.6/MySQLdb/constants
copying MySQLdb/constants/FIELD_TYPE.py -> build/lib.macosx-10.3-x86_64-2.6/MySQLdb/constants
copying MySQLdb/constants/ER.py -> build/lib.macosx-10.3-x86_64-2.6/MySQLdb/constants
copying MySQLdb/constants/FLAG.py -> build/lib.macosx-10.3-x86_64-2.6/MySQLdb/constants
copying MySQLdb/constants/REFRESH.py -> build/lib.macosx-10.3-x86_64-2.6/MySQLdb/constants
copying MySQLdb/constants/CLIENT.py -> build/lib.macosx-10.3-x86_64-2.6/MySQLdb/constants
running build_ext
building '_mysql' extension
creating build/temp.macosx-10.3-x86_64-2.6
gcc-4.0 -isysroot /Developer/SDKs/MacOSX10.4u.sdk -fno-strict-aliasing -fno-common -dynamic -DNDEBUG -g -O3 -Dversion_info=(1,2,3,'gamma',1) -D__version__=1.2.3c1 -I/usr/local/mysql/include -I/Library/Frameworks/Python.framework/Versions/2.6/include/python2.6 -c _mysql.c -o build/temp.macosx-10.3-x86_64-2.6/_mysql.o -g -Os -arch x86_64 -fno-common -D_P1003_1B_VISIBLE -DSIGNAL_WITH_VIO_CLOSE -DSIGNALS_DONT_BREAK_READ -DIGNORE_SIGHUP_SIGQUIT -DDONT_DECLARE_CXA_PURE_VIRTUAL
In file included from _mysql.c:36:
/usr/local/mysql/include/my_config.h:1053:1: warning: "HAVE_WCSCOLL" redefined
In file included from /Library/Frameworks/Python.framework/Versions/2.6/include/python2.6/Python.h:8,
from pymemcompat.h:10,
from _mysql.c:29:
/Library/Frameworks/Python.framework/Versions/2.6/include/python2.6/pyconfig.h:805:1: warning: this is the location of the previous definition
gcc-4.0 -isysroot /Developer/SDKs/MacOSX10.4u.sdk -g -bundle -undefined dynamic_lookup -arch x86_64 build/temp.macosx-10.3-x86_64-2.6/_mysql.o -L/usr/local/mysql/lib -lmysqlclient_r -lz -lm -lmygcc -o build/lib.macosx-10.3-x86_64-2.6/_mysql.so
INSTALL
krokodil:MySQL-python-1.2.3c1 krokodil$ ARCHFLAGS="-arch x86_64" python setup.py install
running install
running bdist_egg
running egg_info
writing MySQL_python.egg-info/PKG-INFO
writing top-level names to MySQL_python.egg-info/top_level.txt
writing dependency_links to MySQL_python.egg-info/dependency_links.txt
reading manifest file 'MySQL_python.egg-info/SOURCES.txt'
reading manifest template 'MANIFEST.in'
writing manifest file 'MySQL_python.egg-info/SOURCES.txt'
installing library code to build/bdist.macosx-10.3-x86_64/egg
running install_lib
running build_py
copying MySQLdb/release.py -> build/lib.macosx-10.3-x86_64-2.6/MySQLdb
running build_ext
creating build/bdist.macosx-10.3-x86_64
creating build/bdist.macosx-10.3-x86_64/egg
copying build/lib.macosx-10.3-x86_64-2.6/_mysql.so -> build/bdist.macosx-10.3-x86_64/egg
copying build/lib.macosx-10.3-x86_64-2.6/_mysql_exceptions.py -> build/bdist.macosx-10.3-x86_64/egg
creating build/bdist.macosx-10.3-x86_64/egg/MySQLdb
copying build/lib.macosx-10.3-x86_64-2.6/MySQLdb/__init__.py -> build/bdist.macosx-10.3-x86_64/egg/MySQLdb
copying build/lib.macosx-10.3-x86_64-2.6/MySQLdb/connections.py -> build/bdist.macosx-10.3-x86_64/egg/MySQLdb
creating build/bdist.macosx-10.3-x86_64/egg/MySQLdb/constants
copying build/lib.macosx-10.3-x86_64-2.6/MySQLdb/constants/__init__.py -> build/bdist.macosx-10.3-x86_64/egg/MySQLdb/constants
copying build/lib.macosx-10.3-x86_64-2.6/MySQLdb/constants/CLIENT.py -> build/bdist.macosx-10.3-x86_64/egg/MySQLdb/constants
copying build/lib.macosx-10.3-x86_64-2.6/MySQLdb/constants/CR.py -> build/bdist.macosx-10.3-x86_64/egg/MySQLdb/constants
copying build/lib.macosx-10.3-x86_64-2.6/MySQLdb/constants/ER.py -> build/bdist.macosx-10.3-x86_64/egg/MySQLdb/constants
copying build/lib.macosx-10.3-x86_64-2.6/MySQLdb/constants/FIELD_TYPE.py -> build/bdist.macosx-10.3-x86_64/egg/MySQLdb/constants
copying build/lib.macosx-10.3-x86_64-2.6/MySQLdb/constants/FLAG.py -> build/bdist.macosx-10.3-x86_64/egg/MySQLdb/constants
copying build/lib.macosx-10.3-x86_64-2.6/MySQLdb/constants/REFRESH.py -> build/bdist.macosx-10.3-x86_64/egg/MySQLdb/constants
copying build/lib.macosx-10.3-x86_64-2.6/MySQLdb/converters.py -> build/bdist.macosx-10.3-x86_64/egg/MySQLdb
copying build/lib.macosx-10.3-x86_64-2.6/MySQLdb/cursors.py -> build/bdist.macosx-10.3-x86_64/egg/MySQLdb
copying build/lib.macosx-10.3-x86_64-2.6/MySQLdb/release.py -> build/bdist.macosx-10.3-x86_64/egg/MySQLdb
copying build/lib.macosx-10.3-x86_64-2.6/MySQLdb/times.py -> build/bdist.macosx-10.3-x86_64/egg/MySQLdb
byte-compiling build/bdist.macosx-10.3-x86_64/egg/_mysql_exceptions.py to _mysql_exceptions.pyc
byte-compiling build/bdist.macosx-10.3-x86_64/egg/MySQLdb/__init__.py to __init__.pyc
byte-compiling build/bdist.macosx-10.3-x86_64/egg/MySQLdb/connections.py to connections.pyc
byte-compiling build/bdist.macosx-10.3-x86_64/egg/MySQLdb/constants/__init__.py to __init__.pyc
byte-compiling build/bdist.macosx-10.3-x86_64/egg/MySQLdb/constants/CLIENT.py to CLIENT.pyc
byte-compiling build/bdist.macosx-10.3-x86_64/egg/MySQLdb/constants/CR.py to CR.pyc
byte-compiling build/bdist.macosx-10.3-x86_64/egg/MySQLdb/constants/ER.py to ER.pyc
byte-compiling build/bdist.macosx-10.3-x86_64/egg/MySQLdb/constants/FIELD_TYPE.py to FIELD_TYPE.pyc
byte-compiling build/bdist.macosx-10.3-x86_64/egg/MySQLdb/constants/FLAG.py to FLAG.pyc
byte-compiling build/bdist.macosx-10.3-x86_64/egg/MySQLdb/constants/REFRESH.py to REFRESH.pyc
byte-compiling build/bdist.macosx-10.3-x86_64/egg/MySQLdb/converters.py to converters.pyc
byte-compiling build/bdist.macosx-10.3-x86_64/egg/MySQLdb/cursors.py to cursors.pyc
byte-compiling build/bdist.macosx-10.3-x86_64/egg/MySQLdb/release.py to release.pyc
byte-compiling build/bdist.macosx-10.3-x86_64/egg/MySQLdb/times.py to times.pyc
creating stub loader for _mysql.so
byte-compiling build/bdist.macosx-10.3-x86_64/egg/_mysql.py to _mysql.pyc
creating build/bdist.macosx-10.3-x86_64/egg/EGG-INFO
copying MySQL_python.egg-info/PKG-INFO -> build/bdist.macosx-10.3-x86_64/egg/EGG-INFO
copying MySQL_python.egg-info/SOURCES.txt -> build/bdist.macosx-10.3-x86_64/egg/EGG-INFO
copying MySQL_python.egg-info/dependency_links.txt -> build/bdist.macosx-10.3-x86_64/egg/EGG-INFO
copying MySQL_python.egg-info/top_level.txt -> build/bdist.macosx-10.3-x86_64/egg/EGG-INFO
writing build/bdist.macosx-10.3-x86_64/egg/EGG-INFO/native_libs.txt
zip_safe flag not set; analyzing archive contents...
creating dist
creating 'dist/MySQL_python-1.2.3c1-py2.6-macosx-10.3-x86_64.egg' and adding 'build/bdist.macosx-10.3-x86_64/egg' to it
removing 'build/bdist.macosx-10.3-x86_64/egg' (and everything under it)
Processing MySQL_python-1.2.3c1-py2.6-macosx-10.3-x86_64.egg
Removing /Library/Frameworks/Python.framework/Versions/2.6/lib/python2.6/site-packages/MySQL_python-1.2.3c1-py2.6-macosx-10.3-x86_64.egg
Copying MySQL_python-1.2.3c1-py2.6-macosx-10.3-x86_64.egg to /Library/Frameworks/Python.framework/Versions/2.6/lib/python2.6/site-packages
Removing MySQL-python 1.2.3c1 from easy-install.pth file
Adding MySQL-python 1.2.3c1 to easy-install.pth file
Installed /Library/Frameworks/Python.framework/Versions/2.6/lib/python2.6/site-packages/MySQL_python-1.2.3c1-py2.6-macosx-10.3-x86_64.egg
Processing dependencies for MySQL-python==1.2.3c1
Finished processing dependencies for MySQL-python==1.2.3c1
A:
The python 2.6.4 you are using is 32-bit only (definitely true if you downloaded the OS X installer from python.org). You can't override the architecture for extension modules; they have to be compatible with the base python. The 10.3 shows up because the python you are using was built with a deployment target of 10.3 as it is designed to run on multiple versions of OS X. If you want to use a 64-bit version of MySQL, you'll need to use a 64-bit version of python, like the Apple-suppled python 2.6.1.
|
Error installing MySQL-python on MAC Snow Leopard, OS 10.6
|
I am trying to install the MySQL-python on MAC OS 10.6 (Snow leopard, 64 bit). I followed the steps:
1. Installed MySQL for Mac OS X ver. 10.6 (x86, 64-bit), DMG Archive.
2. Downloaded MySQL-python-1.2.3c1.tar.gz and unzipped it
3. CD to MySQL-python-1.2.3c1 and built it as:
ARCHFLAGS="-arch x86_64" python setup.py build (see output bnelow)
4. Installed it as:
ARCHFLAGS="-arch x86_64" python setup.py install
5. But when I tried to import MySQLdb to python, I am getting error message
import MySQLdb
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "build/bdist.macosx-10.3-x86_64/egg/MySQLdb/__init__.py", line 19, in <module>
File "build/bdist.macosx-10.3-x86_64/egg/_mysql.py", line 7, in <module>
File "build/bdist.macosx-10.3-x86_64/egg/_mysql.py", line 6, in __bootstrap__
ImportError: dlopen(/Users/krokodil/.python-eggs/MySQL_python-1.2.3c1-py2.6-macosx-10.3-x86_64.egg-tmp/_mysql.so, 2): no suitable image found. Did find:
/Users/krokodil/.python-eggs/MySQL_python-1.2.3c1-py2.6-macosx-10.3-x86_64.egg-tmp/_mysql.so: mach-o, but wrong architecture
This "macosx-10.3-x86_64" is bothering me - it seems that somehow the build/install thought that I am still on Mac OS 10.3. Please also see Build and Install capture below.
It also using /Developer/SDKs/MacOSX10.4u.sdk compiler, not /Developer/SDKs/MacOSX10.6.sdk
I am using fresh install of Python 2.6.4.
I saw people having probles. Anyone found a good solution?
Thank you
Vlad
BUILD
krokodil:MySQL-python-1.2.3c1 krokodil$ ARCHFLAGS="-arch x86_64" python setup.py build
running build
running build_py
creating build
creating build/lib.macosx-10.3-x86_64-2.6
copying _mysql_exceptions.py -> build/lib.macosx-10.3-x86_64-2.6
creating build/lib.macosx-10.3-x86_64-2.6/MySQLdb
copying MySQLdb/__init__.py -> build/lib.macosx-10.3-x86_64-2.6/MySQLdb
copying MySQLdb/converters.py -> build/lib.macosx-10.3-x86_64-2.6/MySQLdb
copying MySQLdb/connections.py -> build/lib.macosx-10.3-x86_64-2.6/MySQLdb
copying MySQLdb/cursors.py -> build/lib.macosx-10.3-x86_64-2.6/MySQLdb
copying MySQLdb/release.py -> build/lib.macosx-10.3-x86_64-2.6/MySQLdb
copying MySQLdb/times.py -> build/lib.macosx-10.3-x86_64-2.6/MySQLdb
creating build/lib.macosx-10.3-x86_64-2.6/MySQLdb/constants
copying MySQLdb/constants/__init__.py -> build/lib.macosx-10.3-x86_64-2.6/MySQLdb/constants
copying MySQLdb/constants/CR.py -> build/lib.macosx-10.3-x86_64-2.6/MySQLdb/constants
copying MySQLdb/constants/FIELD_TYPE.py -> build/lib.macosx-10.3-x86_64-2.6/MySQLdb/constants
copying MySQLdb/constants/ER.py -> build/lib.macosx-10.3-x86_64-2.6/MySQLdb/constants
copying MySQLdb/constants/FLAG.py -> build/lib.macosx-10.3-x86_64-2.6/MySQLdb/constants
copying MySQLdb/constants/REFRESH.py -> build/lib.macosx-10.3-x86_64-2.6/MySQLdb/constants
copying MySQLdb/constants/CLIENT.py -> build/lib.macosx-10.3-x86_64-2.6/MySQLdb/constants
running build_ext
building '_mysql' extension
creating build/temp.macosx-10.3-x86_64-2.6
gcc-4.0 -isysroot /Developer/SDKs/MacOSX10.4u.sdk -fno-strict-aliasing -fno-common -dynamic -DNDEBUG -g -O3 -Dversion_info=(1,2,3,'gamma',1) -D__version__=1.2.3c1 -I/usr/local/mysql/include -I/Library/Frameworks/Python.framework/Versions/2.6/include/python2.6 -c _mysql.c -o build/temp.macosx-10.3-x86_64-2.6/_mysql.o -g -Os -arch x86_64 -fno-common -D_P1003_1B_VISIBLE -DSIGNAL_WITH_VIO_CLOSE -DSIGNALS_DONT_BREAK_READ -DIGNORE_SIGHUP_SIGQUIT -DDONT_DECLARE_CXA_PURE_VIRTUAL
In file included from _mysql.c:36:
/usr/local/mysql/include/my_config.h:1053:1: warning: "HAVE_WCSCOLL" redefined
In file included from /Library/Frameworks/Python.framework/Versions/2.6/include/python2.6/Python.h:8,
from pymemcompat.h:10,
from _mysql.c:29:
/Library/Frameworks/Python.framework/Versions/2.6/include/python2.6/pyconfig.h:805:1: warning: this is the location of the previous definition
gcc-4.0 -isysroot /Developer/SDKs/MacOSX10.4u.sdk -g -bundle -undefined dynamic_lookup -arch x86_64 build/temp.macosx-10.3-x86_64-2.6/_mysql.o -L/usr/local/mysql/lib -lmysqlclient_r -lz -lm -lmygcc -o build/lib.macosx-10.3-x86_64-2.6/_mysql.so
INSTALL
krokodil:MySQL-python-1.2.3c1 krokodil$ ARCHFLAGS="-arch x86_64" python setup.py install
running install
running bdist_egg
running egg_info
writing MySQL_python.egg-info/PKG-INFO
writing top-level names to MySQL_python.egg-info/top_level.txt
writing dependency_links to MySQL_python.egg-info/dependency_links.txt
reading manifest file 'MySQL_python.egg-info/SOURCES.txt'
reading manifest template 'MANIFEST.in'
writing manifest file 'MySQL_python.egg-info/SOURCES.txt'
installing library code to build/bdist.macosx-10.3-x86_64/egg
running install_lib
running build_py
copying MySQLdb/release.py -> build/lib.macosx-10.3-x86_64-2.6/MySQLdb
running build_ext
creating build/bdist.macosx-10.3-x86_64
creating build/bdist.macosx-10.3-x86_64/egg
copying build/lib.macosx-10.3-x86_64-2.6/_mysql.so -> build/bdist.macosx-10.3-x86_64/egg
copying build/lib.macosx-10.3-x86_64-2.6/_mysql_exceptions.py -> build/bdist.macosx-10.3-x86_64/egg
creating build/bdist.macosx-10.3-x86_64/egg/MySQLdb
copying build/lib.macosx-10.3-x86_64-2.6/MySQLdb/__init__.py -> build/bdist.macosx-10.3-x86_64/egg/MySQLdb
copying build/lib.macosx-10.3-x86_64-2.6/MySQLdb/connections.py -> build/bdist.macosx-10.3-x86_64/egg/MySQLdb
creating build/bdist.macosx-10.3-x86_64/egg/MySQLdb/constants
copying build/lib.macosx-10.3-x86_64-2.6/MySQLdb/constants/__init__.py -> build/bdist.macosx-10.3-x86_64/egg/MySQLdb/constants
copying build/lib.macosx-10.3-x86_64-2.6/MySQLdb/constants/CLIENT.py -> build/bdist.macosx-10.3-x86_64/egg/MySQLdb/constants
copying build/lib.macosx-10.3-x86_64-2.6/MySQLdb/constants/CR.py -> build/bdist.macosx-10.3-x86_64/egg/MySQLdb/constants
copying build/lib.macosx-10.3-x86_64-2.6/MySQLdb/constants/ER.py -> build/bdist.macosx-10.3-x86_64/egg/MySQLdb/constants
copying build/lib.macosx-10.3-x86_64-2.6/MySQLdb/constants/FIELD_TYPE.py -> build/bdist.macosx-10.3-x86_64/egg/MySQLdb/constants
copying build/lib.macosx-10.3-x86_64-2.6/MySQLdb/constants/FLAG.py -> build/bdist.macosx-10.3-x86_64/egg/MySQLdb/constants
copying build/lib.macosx-10.3-x86_64-2.6/MySQLdb/constants/REFRESH.py -> build/bdist.macosx-10.3-x86_64/egg/MySQLdb/constants
copying build/lib.macosx-10.3-x86_64-2.6/MySQLdb/converters.py -> build/bdist.macosx-10.3-x86_64/egg/MySQLdb
copying build/lib.macosx-10.3-x86_64-2.6/MySQLdb/cursors.py -> build/bdist.macosx-10.3-x86_64/egg/MySQLdb
copying build/lib.macosx-10.3-x86_64-2.6/MySQLdb/release.py -> build/bdist.macosx-10.3-x86_64/egg/MySQLdb
copying build/lib.macosx-10.3-x86_64-2.6/MySQLdb/times.py -> build/bdist.macosx-10.3-x86_64/egg/MySQLdb
byte-compiling build/bdist.macosx-10.3-x86_64/egg/_mysql_exceptions.py to _mysql_exceptions.pyc
byte-compiling build/bdist.macosx-10.3-x86_64/egg/MySQLdb/__init__.py to __init__.pyc
byte-compiling build/bdist.macosx-10.3-x86_64/egg/MySQLdb/connections.py to connections.pyc
byte-compiling build/bdist.macosx-10.3-x86_64/egg/MySQLdb/constants/__init__.py to __init__.pyc
byte-compiling build/bdist.macosx-10.3-x86_64/egg/MySQLdb/constants/CLIENT.py to CLIENT.pyc
byte-compiling build/bdist.macosx-10.3-x86_64/egg/MySQLdb/constants/CR.py to CR.pyc
byte-compiling build/bdist.macosx-10.3-x86_64/egg/MySQLdb/constants/ER.py to ER.pyc
byte-compiling build/bdist.macosx-10.3-x86_64/egg/MySQLdb/constants/FIELD_TYPE.py to FIELD_TYPE.pyc
byte-compiling build/bdist.macosx-10.3-x86_64/egg/MySQLdb/constants/FLAG.py to FLAG.pyc
byte-compiling build/bdist.macosx-10.3-x86_64/egg/MySQLdb/constants/REFRESH.py to REFRESH.pyc
byte-compiling build/bdist.macosx-10.3-x86_64/egg/MySQLdb/converters.py to converters.pyc
byte-compiling build/bdist.macosx-10.3-x86_64/egg/MySQLdb/cursors.py to cursors.pyc
byte-compiling build/bdist.macosx-10.3-x86_64/egg/MySQLdb/release.py to release.pyc
byte-compiling build/bdist.macosx-10.3-x86_64/egg/MySQLdb/times.py to times.pyc
creating stub loader for _mysql.so
byte-compiling build/bdist.macosx-10.3-x86_64/egg/_mysql.py to _mysql.pyc
creating build/bdist.macosx-10.3-x86_64/egg/EGG-INFO
copying MySQL_python.egg-info/PKG-INFO -> build/bdist.macosx-10.3-x86_64/egg/EGG-INFO
copying MySQL_python.egg-info/SOURCES.txt -> build/bdist.macosx-10.3-x86_64/egg/EGG-INFO
copying MySQL_python.egg-info/dependency_links.txt -> build/bdist.macosx-10.3-x86_64/egg/EGG-INFO
copying MySQL_python.egg-info/top_level.txt -> build/bdist.macosx-10.3-x86_64/egg/EGG-INFO
writing build/bdist.macosx-10.3-x86_64/egg/EGG-INFO/native_libs.txt
zip_safe flag not set; analyzing archive contents...
creating dist
creating 'dist/MySQL_python-1.2.3c1-py2.6-macosx-10.3-x86_64.egg' and adding 'build/bdist.macosx-10.3-x86_64/egg' to it
removing 'build/bdist.macosx-10.3-x86_64/egg' (and everything under it)
Processing MySQL_python-1.2.3c1-py2.6-macosx-10.3-x86_64.egg
Removing /Library/Frameworks/Python.framework/Versions/2.6/lib/python2.6/site-packages/MySQL_python-1.2.3c1-py2.6-macosx-10.3-x86_64.egg
Copying MySQL_python-1.2.3c1-py2.6-macosx-10.3-x86_64.egg to /Library/Frameworks/Python.framework/Versions/2.6/lib/python2.6/site-packages
Removing MySQL-python 1.2.3c1 from easy-install.pth file
Adding MySQL-python 1.2.3c1 to easy-install.pth file
Installed /Library/Frameworks/Python.framework/Versions/2.6/lib/python2.6/site-packages/MySQL_python-1.2.3c1-py2.6-macosx-10.3-x86_64.egg
Processing dependencies for MySQL-python==1.2.3c1
Finished processing dependencies for MySQL-python==1.2.3c1
|
[
"The python 2.6.4 you are using is 32-bit only (definitely true if you downloaded the OS X installer from python.org). You can't override the architecture for extension modules; they have to be compatible with the base python. The 10.3 shows up because the python you are using was built with a deployment target of 10.3 as it is designed to run on multiple versions of OS X. If you want to use a 64-bit version of MySQL, you'll need to use a 64-bit version of python, like the Apple-suppled python 2.6.1. \n"
] |
[
1
] |
[] |
[] |
[
"macos",
"mysql",
"python"
] |
stackoverflow_0002414658_macos_mysql_python.txt
|
Q:
Open Windows shared folder through linux machine
I am using python 2.5 on Ubuntu, and there's a machine in the same network called machine1. The folder is shared.
How to to get a file in a specific folder of that machine?
I have tried, with no success:
urllib.urlopen('\\machine1\folder\file.txt')
A:
Linux has a utiliy called smbmount, which can be found in package smbutils I believe.
This is a command line utility which mounts a Windows share to a directory on the local machine, optionally with username/password.
smbmount is I believe a utility which runs as root, so whether it's suitable for you I don't know. Maybe it can be used as user.
You could either mount the share by default on the Linux machine, thereby accessing the files on it as local files, or you could do the smbmount / smbumount from within the python script with exec or something like that.
mkdir WindowsShare # Do this only once
smbmount \\server\share /home/me/WindowsShare -ousername=...,password=...
ls /home/me/WindowsShare
smbumount /home/me/WindowsShare
Username and password can be written in a file for some security. Check the man page.
If you need something totally python have a look at pysmb. Terms to google for are python, smb, CIFS.
A:
urllib does not understand the SMB protocol. You will need to use gio via pygobject in order to retrieve the file.
A:
If the folder is shared, I think it should be mounted in ~/.gvfs. Perhaps you can simply use open on the path as you see it in ~/.gvfs.
|
Open Windows shared folder through linux machine
|
I am using python 2.5 on Ubuntu, and there's a machine in the same network called machine1. The folder is shared.
How to to get a file in a specific folder of that machine?
I have tried, with no success:
urllib.urlopen('\\machine1\folder\file.txt')
|
[
"Linux has a utiliy called smbmount, which can be found in package smbutils I believe.\nThis is a command line utility which mounts a Windows share to a directory on the local machine, optionally with username/password.\nsmbmount is I believe a utility which runs as root, so whether it's suitable for you I don't know. Maybe it can be used as user.\nYou could either mount the share by default on the Linux machine, thereby accessing the files on it as local files, or you could do the smbmount / smbumount from within the python script with exec or something like that.\nmkdir WindowsShare # Do this only once\nsmbmount \\\\server\\share /home/me/WindowsShare -ousername=...,password=...\nls /home/me/WindowsShare\nsmbumount /home/me/WindowsShare\n\nUsername and password can be written in a file for some security. Check the man page.\nIf you need something totally python have a look at pysmb. Terms to google for are python, smb, CIFS.\n",
"urllib does not understand the SMB protocol. You will need to use gio via pygobject in order to retrieve the file.\n",
"If the folder is shared, I think it should be mounted in ~/.gvfs. Perhaps you can simply use open on the path as you see it in ~/.gvfs.\n"
] |
[
6,
2,
0
] |
[
"You should look for the default file browser.\nAnd then you can execute the process and pass in the folder you want as an argument (smb://machine1/folder/).\nFor example on windows you would do:\nexecl(\"explorer.exe\", \"D:\")\n\nTry to look for the path to your file browser (most of the time it's Nautilus).\nSo:\nexecl(\"/bin/nautilus\", \"smb://.../\")\n\nSome info on execl \n"
] |
[
-1
] |
[
"python",
"urllib"
] |
stackoverflow_0002419953_python_urllib.txt
|
Q:
How does OS handle a python dict that's larger than memory?
I have a python program that is going to eat a lot of memory, primarily in a dict. This dict will be responsible for assigning a unique integer value to a very large set of keys. As I am working with large matrices, I need a key-to-index correspondence that can also be recovered from (i.e., once matrix computations are complete, I need to map the values back to the original keys).
I believe this amount will eventually surpass available memory. I am wondering how this will be handled with regards to swap space. Perhaps there is a better data structure for this purpose.
A:
You need a database, if the data will exceed memory. The indexing of dictionaries isn't designed for good performance when a dictionary is bigger than memory.
A:
Swap space is a kernel feature and transparant to the user (python).
If you do have a huge dict and don't need all the data at once, you could look at redis which might do what you want. Or maybe not :)
A:
It will just end up in swap trashing, because a hash table has very much randomized memory access patterns.
If you know that the map exceeds the size of the physical memory, you could consider using a data structure on the disk in the first place. This especially if you don't need the data structure during the computation. When the hash table triggers swapping, it creates problems also outside the hash table itself.
A:
As far as I can remember, when a dict is expanded it just relies on C's malloc. The program will keep running as long as malloc keeps succeeding. Most OS's will keep malloc working as long as there is enough memory, and then as long as there are pages that can be swapped in. In either case Python will throw a MemoryError exception when malloc fails, as per the documentation. As far as the data structure goes, dict is going to be very efficient space-wise. The only way to really do better is to use an analytical function to map the values back and forth.
|
How does OS handle a python dict that's larger than memory?
|
I have a python program that is going to eat a lot of memory, primarily in a dict. This dict will be responsible for assigning a unique integer value to a very large set of keys. As I am working with large matrices, I need a key-to-index correspondence that can also be recovered from (i.e., once matrix computations are complete, I need to map the values back to the original keys).
I believe this amount will eventually surpass available memory. I am wondering how this will be handled with regards to swap space. Perhaps there is a better data structure for this purpose.
|
[
"You need a database, if the data will exceed memory. The indexing of dictionaries isn't designed for good performance when a dictionary is bigger than memory.\n",
"Swap space is a kernel feature and transparant to the user (python).\nIf you do have a huge dict and don't need all the data at once, you could look at redis which might do what you want. Or maybe not :)\n",
"It will just end up in swap trashing, because a hash table has very much randomized memory access patterns.\nIf you know that the map exceeds the size of the physical memory, you could consider using a data structure on the disk in the first place. This especially if you don't need the data structure during the computation. When the hash table triggers swapping, it creates problems also outside the hash table itself.\n",
"As far as I can remember, when a dict is expanded it just relies on C's malloc. The program will keep running as long as malloc keeps succeeding. Most OS's will keep malloc working as long as there is enough memory, and then as long as there are pages that can be swapped in. In either case Python will throw a MemoryError exception when malloc fails, as per the documentation. As far as the data structure goes, dict is going to be very efficient space-wise. The only way to really do better is to use an analytical function to map the values back and forth.\n"
] |
[
5,
2,
1,
1
] |
[] |
[] |
[
"data_structures",
"matrix",
"memory",
"python",
"swap"
] |
stackoverflow_0002420219_data_structures_matrix_memory_python_swap.txt
|
Q:
Python String with HTML /
I'm trying a simple program to send some html down a socket to a client. 2 things are goofing me up.
The code:
c.send( str.encode("<HTML><BODY>Test Page<///BODY><///HTML>") )
My python client receives:
b'<HTML><BODY>Test Page<///BODY><///HTML>'
According to Beginning Python which says it covers Python 3 (I'm using 3.1.1 on Windows), there is a String.Decode function. My environment cannot find it. I assume I'll run into the errors ('strict', 'ignore', 'replace' ) next.
Obviously, the extra /// is just guessing.
1) How do I decode this in Python?
2) I use my browser and obviously the HTML code is wrong, but I can see the server sent it. How do I make the HTML browser friendly?
Cordially,
Stephen
A:
You want '...'.encode() and b'...'.decode(). Saying "str.encode" is shorthand for saying that all str literals have this method.
|
Python String with HTML /
|
I'm trying a simple program to send some html down a socket to a client. 2 things are goofing me up.
The code:
c.send( str.encode("<HTML><BODY>Test Page<///BODY><///HTML>") )
My python client receives:
b'<HTML><BODY>Test Page<///BODY><///HTML>'
According to Beginning Python which says it covers Python 3 (I'm using 3.1.1 on Windows), there is a String.Decode function. My environment cannot find it. I assume I'll run into the errors ('strict', 'ignore', 'replace' ) next.
Obviously, the extra /// is just guessing.
1) How do I decode this in Python?
2) I use my browser and obviously the HTML code is wrong, but I can see the server sent it. How do I make the HTML browser friendly?
Cordially,
Stephen
|
[
"You want '...'.encode() and b'...'.decode(). Saying \"str.encode\" is shorthand for saying that all str literals have this method.\n"
] |
[
0
] |
[
"The extra '/' is wrong. You only need to worry about escaping for '\\'\n"
] |
[
-1
] |
[
"decode",
"html",
"python",
"string"
] |
stackoverflow_0002420246_decode_html_python_string.txt
|
Q:
google app engine: new version doesn't appear
I have made an update on Google App Engine with a small fix and I got:
Closing update: new version is ready to start serving.
However, when I open the website, there is still old version. I have changed version to 2 in app.yaml, before running update. What am I missing?
A:
You have to set the new version to be the active version in the Admin console. Click the 'Versions' link, and make your new version the Default.
|
google app engine: new version doesn't appear
|
I have made an update on Google App Engine with a small fix and I got:
Closing update: new version is ready to start serving.
However, when I open the website, there is still old version. I have changed version to 2 in app.yaml, before running update. What am I missing?
|
[
"You have to set the new version to be the active version in the Admin console. Click the 'Versions' link, and make your new version the Default.\n"
] |
[
4
] |
[] |
[] |
[
"django",
"google_app_engine",
"python",
"version"
] |
stackoverflow_0002420519_django_google_app_engine_python_version.txt
|
Q:
get an array variable in python
can I do this in a loop, by producing the file name from the name of the array to store ?
ab = array.array('B', map( operator.xor, a, b ) )
f1 = open('ab', 'wb')
ab.tofile(f1)
f1.close
ac = array.array('B', map( operator.xor, a, c ) )
f1 = open('ac', 'wb')
ac.tofile(f1)
f1.close
ad = array.array('B', map( operator.xor, a, d ) )
f1 = open('ad', 'wb')
ad.tofile(f1)
f1.close
ae = array.array('B', map( operator.xor, a, e ) )
f1 = open('ae', 'wb')
ae.tofile(f1)
f1.close
af = array.array('B', map( operator.xor, a, f ) )
f1 = open('af', 'wb')
af.tofile(f1)
f1.close
thank you for any help!
A:
Assuming you are storing all the intermediate arrays for a reason.
A={}
for v,x in zip((b,c,d,e,f),'bcdef'):
fname = 'a'+x
A[fname] = (array.array('B', map( operator.xor, a, v ) ))
f1 = open(fname, 'wb')
A[fname].tofile(f1)
f1.close
Or something like this should work too
A={}
for x in 'bcdef':
fname = 'a'+x
A[fname] = (array.array('B', map(a.__xor__, vars()[x] ) ))
f1 = open(fname, 'wb')
A[fname].tofile(f1)
f1.close
A:
One way is to have a,b,c,d,e,f in a dict. Then you'd just do something like:
for x in 'bcdef':
t = array.array('B', map( operator.xor, mydict['a'], mydict[x] ) )
f1 = open(''.join('a',x),'wb')
t.tofile(f1)
f1.close()
|
get an array variable in python
|
can I do this in a loop, by producing the file name from the name of the array to store ?
ab = array.array('B', map( operator.xor, a, b ) )
f1 = open('ab', 'wb')
ab.tofile(f1)
f1.close
ac = array.array('B', map( operator.xor, a, c ) )
f1 = open('ac', 'wb')
ac.tofile(f1)
f1.close
ad = array.array('B', map( operator.xor, a, d ) )
f1 = open('ad', 'wb')
ad.tofile(f1)
f1.close
ae = array.array('B', map( operator.xor, a, e ) )
f1 = open('ae', 'wb')
ae.tofile(f1)
f1.close
af = array.array('B', map( operator.xor, a, f ) )
f1 = open('af', 'wb')
af.tofile(f1)
f1.close
thank you for any help!
|
[
"Assuming you are storing all the intermediate arrays for a reason.\nA={}\nfor v,x in zip((b,c,d,e,f),'bcdef'):\n fname = 'a'+x\n A[fname] = (array.array('B', map( operator.xor, a, v ) ))\n f1 = open(fname, 'wb')\n A[fname].tofile(f1)\n f1.close\n\nOr something like this should work too\nA={}\nfor x in 'bcdef':\n fname = 'a'+x\n A[fname] = (array.array('B', map(a.__xor__, vars()[x] ) ))\n f1 = open(fname, 'wb')\n A[fname].tofile(f1)\n f1.close\n\n",
"One way is to have a,b,c,d,e,f in a dict. Then you'd just do something like:\nfor x in 'bcdef':\n t = array.array('B', map( operator.xor, mydict['a'], mydict[x] ) )\n f1 = open(''.join('a',x),'wb')\n t.tofile(f1)\n f1.close()\n\n"
] |
[
2,
1
] |
[] |
[] |
[
"arrays",
"introspection",
"python",
"variables"
] |
stackoverflow_0002420644_arrays_introspection_python_variables.txt
|
Q:
Why does my 'hello world' Python C module work correctly in everything but IDLE?
I compiled a simple hello world C module for Python and it works correctly in everything I've tried but IDLE. Here's what I type to test it:
>>> import hello
>>> hello.say_hello('Justin')
I have tried this using Python from the command prompt(I'm using Windows), in Eclipse's PyDev, and with PieDream and they all print out Hello Justin!. However, in IDLE it doesn't print anything - it just gives me the prompt.
The module and setup.py I'm using are from this page. I think that the problem is with the compiler. I'm using MinGW which I set as the compiler for distutils in a .cfg file. I build the module from the command prompt with:
python setup.py build
and get
running build
running build_ext
building 'hello' extension
creating build
creating build\temp.win32-2.6
creating build\temp.win32-2.6\Release
C:\MinGW\bin\gcc.exe -mno-cygwin -mdll -O -Wall -IC:\Python26\include -IC:\Python26\PC -c hellomodule.c -o build\temp.win32-2.6\Release\hellomodule.o
writing build\temp.win32-2.6\Release\hello.def
creating build\lib.win32-2.6
C:\MinGW\bin\gcc.exe -mno-cygwin -shared -s build\temp.win32-2.6\Release\hellomodule.o build\temp.win32-2.6\Release\hello.def -LC:\Python26\libs -LC:Python26\PCbuild -lpython26 -lmsvcr90 -o build\lib.win32-2.6\hello.pyd
I'm thinking that it might have something to do with the -mno-cygwin part in there, but I'm not sure.
Any ideas or suggestions as to why this module won't work in IDLE? Should I be using a different compiler?
A:
Sounds like the hello is writing directly to stdout. Python's stdout is not necessarily the the same place as C stdout
Normally you would return a string to Python so Python can print it to it's own stdout
A:
If you need to write to Python's sys.stdout from a C-coded extension, you can use something like:
void writeout(const char* nullterminated)
{
PyObject* sysmod = PyImport_ImportModuleNoBlock("sys");
PyObject* pystdout = PyObject_GetAttrString(sysmod, "stdout");
PyObject* result = PyObject_CallMethod(pystdout, "write", "s", nullterminated);
Py_XDECREF(result);
Py_XDECREF(pystdout);
Py_XDECREF(sysmod);
}
(plus, presumably, a little error checking -- just for sanity, in case somebody's done something crazy like del sys.stdout &c-).
Of course, if you need multiple writes, it may be more efficient to get stdout only once, keep it around as long as needed, and decref it just once when you're done "printing" stuff (but that won't behave quite right in cases in which your Python caller is reassigning sys.stdout while you hold a reference to its previous version: you'll keep printing to the previous version, just like a similarly-behaved Python-coded module would). This repeated lookup is equivalent to doing sys.stdout.write(somestring) in Python, which also looks things up each and every time -- a tad slower but "semantically safer" in case your Python caller is doing "pretty edgy" stuff with sys.stdout (as you've found out that IDLE does;-). ((Not all that edgy, really, so you may want to support it properly;-)).
|
Why does my 'hello world' Python C module work correctly in everything but IDLE?
|
I compiled a simple hello world C module for Python and it works correctly in everything I've tried but IDLE. Here's what I type to test it:
>>> import hello
>>> hello.say_hello('Justin')
I have tried this using Python from the command prompt(I'm using Windows), in Eclipse's PyDev, and with PieDream and they all print out Hello Justin!. However, in IDLE it doesn't print anything - it just gives me the prompt.
The module and setup.py I'm using are from this page. I think that the problem is with the compiler. I'm using MinGW which I set as the compiler for distutils in a .cfg file. I build the module from the command prompt with:
python setup.py build
and get
running build
running build_ext
building 'hello' extension
creating build
creating build\temp.win32-2.6
creating build\temp.win32-2.6\Release
C:\MinGW\bin\gcc.exe -mno-cygwin -mdll -O -Wall -IC:\Python26\include -IC:\Python26\PC -c hellomodule.c -o build\temp.win32-2.6\Release\hellomodule.o
writing build\temp.win32-2.6\Release\hello.def
creating build\lib.win32-2.6
C:\MinGW\bin\gcc.exe -mno-cygwin -shared -s build\temp.win32-2.6\Release\hellomodule.o build\temp.win32-2.6\Release\hello.def -LC:\Python26\libs -LC:Python26\PCbuild -lpython26 -lmsvcr90 -o build\lib.win32-2.6\hello.pyd
I'm thinking that it might have something to do with the -mno-cygwin part in there, but I'm not sure.
Any ideas or suggestions as to why this module won't work in IDLE? Should I be using a different compiler?
|
[
"Sounds like the hello is writing directly to stdout. Python's stdout is not necessarily the the same place as C stdout\nNormally you would return a string to Python so Python can print it to it's own stdout\n",
"If you need to write to Python's sys.stdout from a C-coded extension, you can use something like:\nvoid writeout(const char* nullterminated)\n{\n PyObject* sysmod = PyImport_ImportModuleNoBlock(\"sys\");\n PyObject* pystdout = PyObject_GetAttrString(sysmod, \"stdout\");\n PyObject* result = PyObject_CallMethod(pystdout, \"write\", \"s\", nullterminated);\n Py_XDECREF(result);\n Py_XDECREF(pystdout);\n Py_XDECREF(sysmod); \n }\n\n(plus, presumably, a little error checking -- just for sanity, in case somebody's done something crazy like del sys.stdout &c-).\nOf course, if you need multiple writes, it may be more efficient to get stdout only once, keep it around as long as needed, and decref it just once when you're done \"printing\" stuff (but that won't behave quite right in cases in which your Python caller is reassigning sys.stdout while you hold a reference to its previous version: you'll keep printing to the previous version, just like a similarly-behaved Python-coded module would). This repeated lookup is equivalent to doing sys.stdout.write(somestring) in Python, which also looks things up each and every time -- a tad slower but \"semantically safer\" in case your Python caller is doing \"pretty edgy\" stuff with sys.stdout (as you've found out that IDLE does;-). ((Not all that edgy, really, so you may want to support it properly;-)).\n"
] |
[
5,
5
] |
[] |
[] |
[
"c",
"mingw",
"module",
"python",
"windows"
] |
stackoverflow_0002420317_c_mingw_module_python_windows.txt
|
Q:
Django query with related models
For the below models:
class Customer(models.Model):
id = models.IntegerField(primary_key=True)
class OrderA(models.Model):
name = models.CharField(max_length=20)
foo = models.FloatField()
customer = models.ForeignKey(Customer)
type = models.IntegerField()
class OrderB(models.Model):
name = models.CharField(max_length=20)
customer = models.ForeignKey(Customer)
type = models.IntegerField()
I want to grab all the Customer objects with their related OrderA and OrderB objects in one go for a condition (where type in OrderA and OrderB equals 1)
A:
select_related() will pre-populate the appropriate attributes:
Customer.objects.filter(ordera_set__type=1, orderb_set__type=1).select_related()
A:
You're right in your comment to Ignacio that select_related works in the opposite direction.
I've written about a technique to do it in this direction on my blog (sorry about the plug).
|
Django query with related models
|
For the below models:
class Customer(models.Model):
id = models.IntegerField(primary_key=True)
class OrderA(models.Model):
name = models.CharField(max_length=20)
foo = models.FloatField()
customer = models.ForeignKey(Customer)
type = models.IntegerField()
class OrderB(models.Model):
name = models.CharField(max_length=20)
customer = models.ForeignKey(Customer)
type = models.IntegerField()
I want to grab all the Customer objects with their related OrderA and OrderB objects in one go for a condition (where type in OrderA and OrderB equals 1)
|
[
"select_related() will pre-populate the appropriate attributes:\nCustomer.objects.filter(ordera_set__type=1, orderb_set__type=1).select_related()\n\n",
"You're right in your comment to Ignacio that select_related works in the opposite direction.\nI've written about a technique to do it in this direction on my blog (sorry about the plug).\n"
] |
[
2,
-3
] |
[] |
[] |
[
"django",
"python"
] |
stackoverflow_0002421064_django_python.txt
|
Q:
How to filter a query by property of user profile in Django?
I have two models,Design and Profile. Profile is hooked up in settings.py as the profile to be used with the User model. So I can access it via user.get_profile().
And each Design instance has an author property that is a ForeignKey to User.
So, when I'm any view, I can get the screenname (a property of Profile) by:
user.get_profile().screenname
But what is the syntax to SEARCH BY FILTER for this property? What I currently have:
designs = Design.objects.filter(author__userprofile__screenname__icontains=w)
This doesn't work. Thoughts?
A:
If your profile class is named Profile, and you haven't customized the User <-> Profile relation using the related_name property of the ForeignKey, then shouldn't you be accessing via:
designs = Design.objects.filter(author__user__profile__screenname__icontains=w)
The User -> Profile spans a relation so you need the extra double underscores.
|
How to filter a query by property of user profile in Django?
|
I have two models,Design and Profile. Profile is hooked up in settings.py as the profile to be used with the User model. So I can access it via user.get_profile().
And each Design instance has an author property that is a ForeignKey to User.
So, when I'm any view, I can get the screenname (a property of Profile) by:
user.get_profile().screenname
But what is the syntax to SEARCH BY FILTER for this property? What I currently have:
designs = Design.objects.filter(author__userprofile__screenname__icontains=w)
This doesn't work. Thoughts?
|
[
"If your profile class is named Profile, and you haven't customized the User <-> Profile relation using the related_name property of the ForeignKey, then shouldn't you be accessing via:\ndesigns = Design.objects.filter(author__user__profile__screenname__icontains=w)\n\nThe User -> Profile spans a relation so you need the extra double underscores.\n"
] |
[
8
] |
[] |
[] |
[
"django",
"python"
] |
stackoverflow_0002421221_django_python.txt
|
Q:
Python Unicode strings and the Python interactive interpreter
I'm trying to understand how python 2.5 deals with unicode strings. Although by now I think I have a good grasp of how I'm supposed to handle them in code, I don't fully understand what's going on behind the scenes, particularly when you type strings at the interpreter's prompt.
So python pre 3.0 has two types for strings, namely: str (byte strings) and unicode, which are both derived from basestring. The default type for strings is str.
str objects have no notion of their actual encoding, they are just bytes. Either you've encoded a unicode string yourself and therefore know what encoding they are in, or you've read a stream of bytes whose encoding you also know beforehand (indeally). You can guess the encoding of a byte string whose encoding is unknown to you, but there just isn't a reliable way of figuring this out. Your best bet is to decode early, use unicode everywhere in your code and encode late.
That's fine. But strings typed into the interpreter are indeed encoded for you behind your back? Provided that my understanding of strings in Python is correct, what's the method/setting python uses to make this decision?
The source of my confusion is the differing results I get when I try the same thing on my system's python installation, and on my editor's embedded python console.
# Editor (Sublime Text)
>>> s = "La caña de España"
>>> s
'La ca\xc3\xb1a de Espa\xc3\xb1a'
>>> s.decode("utf-8")
u'La ca\xf1a de Espa\xf1a'
>>> sys.getdefaultencoding()
'ascii'
# Windows python interpreter
>>> s= "La caña de España"
>>> s
'La ca\xa4a de Espa\xa4a'
>>> s.decode("utf-8")
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "C:\Python25\lib\encodings\utf_8.py", line 16, in decode
return codecs.utf_8_decode(input, errors, True)
UnicodeDecodeError: 'utf8' codec can't decode byte 0xa4 in position 5: unexpected code byte
>>> sys.getdefaultencoding()
'ascii'
A:
Let me expand Ignacio's reply: In both cases there is an extra layer between Python and you: in one case it is Sublime Text and in the other it's cmd.exe. The difference in behaviour you see is not due to Python but by the different encodings used by Sublime Text (utf-8, as it seems) and cmd.exe (cp437).
So, when you type ñ, Sublime Text sends '\xc3\xb1' to Python, whereas cmd.exe sends \xa4. [I'm simplyfing here, omitting details that are not relevant to the question.].
Still, Python knows about that. From cmd.exe you'll probably get something like:
>>> import sys
>>> sys.stdin.encoding
'cp437'
whereas within Sublime Text you'll get something like
>>> import sys
>>> sys.stdin.encoding
'utf-8'
A:
The interpreter uses your command prompt's native encoding for text entry. In your case it's CP437:
>>> print '\xa4'.decode('cp437')
ñ
A:
You're getting confused because the editor and the interpreter are using different encodings themselves. The python interpreter uses your system default (in this case, cp437), while your editor uses utf-8.
Note, the difference disappears if you specify a unicode string, like so:
# Windows python interpreter
>>> s = "La caña de España"
>>> s
'La ca\xa4a de Espa\xa4a'
>>> s = u"La caña de España"
>>> s
u'La ca\xf1a de Espa\xf1a'
The moral of the story? Encodings are tricky. Be sure you know what encoding your source files are in, or play it safe by always using the escaped version of special characters.
|
Python Unicode strings and the Python interactive interpreter
|
I'm trying to understand how python 2.5 deals with unicode strings. Although by now I think I have a good grasp of how I'm supposed to handle them in code, I don't fully understand what's going on behind the scenes, particularly when you type strings at the interpreter's prompt.
So python pre 3.0 has two types for strings, namely: str (byte strings) and unicode, which are both derived from basestring. The default type for strings is str.
str objects have no notion of their actual encoding, they are just bytes. Either you've encoded a unicode string yourself and therefore know what encoding they are in, or you've read a stream of bytes whose encoding you also know beforehand (indeally). You can guess the encoding of a byte string whose encoding is unknown to you, but there just isn't a reliable way of figuring this out. Your best bet is to decode early, use unicode everywhere in your code and encode late.
That's fine. But strings typed into the interpreter are indeed encoded for you behind your back? Provided that my understanding of strings in Python is correct, what's the method/setting python uses to make this decision?
The source of my confusion is the differing results I get when I try the same thing on my system's python installation, and on my editor's embedded python console.
# Editor (Sublime Text)
>>> s = "La caña de España"
>>> s
'La ca\xc3\xb1a de Espa\xc3\xb1a'
>>> s.decode("utf-8")
u'La ca\xf1a de Espa\xf1a'
>>> sys.getdefaultencoding()
'ascii'
# Windows python interpreter
>>> s= "La caña de España"
>>> s
'La ca\xa4a de Espa\xa4a'
>>> s.decode("utf-8")
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "C:\Python25\lib\encodings\utf_8.py", line 16, in decode
return codecs.utf_8_decode(input, errors, True)
UnicodeDecodeError: 'utf8' codec can't decode byte 0xa4 in position 5: unexpected code byte
>>> sys.getdefaultencoding()
'ascii'
|
[
"Let me expand Ignacio's reply: In both cases there is an extra layer between Python and you: in one case it is Sublime Text and in the other it's cmd.exe. The difference in behaviour you see is not due to Python but by the different encodings used by Sublime Text (utf-8, as it seems) and cmd.exe (cp437).\nSo, when you type ñ, Sublime Text sends '\\xc3\\xb1' to Python, whereas cmd.exe sends \\xa4. [I'm simplyfing here, omitting details that are not relevant to the question.].\nStill, Python knows about that. From cmd.exe you'll probably get something like:\n>>> import sys\n>>> sys.stdin.encoding\n'cp437'\n\nwhereas within Sublime Text you'll get something like\n>>> import sys\n>>> sys.stdin.encoding\n'utf-8'\n\n",
"The interpreter uses your command prompt's native encoding for text entry. In your case it's CP437:\n>>> print '\\xa4'.decode('cp437')\nñ\n\n",
"You're getting confused because the editor and the interpreter are using different encodings themselves. The python interpreter uses your system default (in this case, cp437), while your editor uses utf-8.\nNote, the difference disappears if you specify a unicode string, like so:\n# Windows python interpreter\n>>> s = \"La caña de España\"\n>>> s\n'La ca\\xa4a de Espa\\xa4a'\n>>> s = u\"La caña de España\"\n>>> s\nu'La ca\\xf1a de Espa\\xf1a'\n\nThe moral of the story? Encodings are tricky. Be sure you know what encoding your source files are in, or play it safe by always using the escaped version of special characters.\n"
] |
[
7,
3,
1
] |
[] |
[] |
[
"python",
"string",
"sublimetext",
"unicode"
] |
stackoverflow_0002421145_python_string_sublimetext_unicode.txt
|
Q:
How do I modify a generator in Python?
Is there a common interface in Python that I could derive from to modify behavior of a generator?
For example, I want to modify an existing generator to insert some values in the stream and remove some other values.
How do I do that?
Thanks, Boda Cydo
A:
You can use the functions provided by itertools to take a generator and produce a new generator.
For example, you can use takewhile until a predicate is no longer fulfilled, and chain on a new series of values.
Take a look at the documentation for other examples, including things like ifilter, dropwhile and islice to name just a few more.
A:
You can just wrap the generator in your own generator.
from itertools import count
def odd_count():
for i in count():
if i % 2:
yield i
|
How do I modify a generator in Python?
|
Is there a common interface in Python that I could derive from to modify behavior of a generator?
For example, I want to modify an existing generator to insert some values in the stream and remove some other values.
How do I do that?
Thanks, Boda Cydo
|
[
"You can use the functions provided by itertools to take a generator and produce a new generator.\nFor example, you can use takewhile until a predicate is no longer fulfilled, and chain on a new series of values.\nTake a look at the documentation for other examples, including things like ifilter, dropwhile and islice to name just a few more.\n",
"You can just wrap the generator in your own generator.\nfrom itertools import count\n\ndef odd_count():\n for i in count():\n if i % 2:\n yield i\n\n"
] |
[
7,
7
] |
[] |
[] |
[
"generator",
"python"
] |
stackoverflow_0002421355_generator_python.txt
|
Q:
How to correctly call base class methods (and constructor) from inherited classes in Python?
Suppose I have a Base class and a Child class that inherits from Base. What is the right way to call the constructor of base class from a child class in Python? Do I use super?
Here is an example of what I have so far:
class Base(object):
def __init__(self, value):
self.value = value
...
class Child(Base):
def __init__(self, something_else):
super(Child, self).__init__(value=20)
self.something_else = something_else
...
Is this correct?
Thanks, Boda Cydo.
A:
That is correct. Note that you can also call the __init__ method directly on the Base class, like so:
class Child(Base):
def __init__(self, something_else):
Base.__init__(self, value = 20)
self.something_else = something_else
That's the way I generally do it. But it's discouraged, because it doesn't behave very well in the presence of multiple inheritance. Of course, multiple inheritance has all sorts of odd effects of its own, and so I avoid it like the plague.
In general, if the classes you're inheriting from use super, you need to as well.
A:
If you're using Python 3.1, super is new and improved. It figures out the class and instance arguments for you. So you should call super without arguments:
class Child(Base):
def __init__(self, value, something_else):
super().__init__(value)
self.something_else = something_else
...
A:
Yes, that's correct. If you wanted to be able to pass value into the Child class you could do it this way
class Child(Base):
def __init__(self, value, something_else):
super(Child, self).__init__(value)
self.something_else = something_else
...
|
How to correctly call base class methods (and constructor) from inherited classes in Python?
|
Suppose I have a Base class and a Child class that inherits from Base. What is the right way to call the constructor of base class from a child class in Python? Do I use super?
Here is an example of what I have so far:
class Base(object):
def __init__(self, value):
self.value = value
...
class Child(Base):
def __init__(self, something_else):
super(Child, self).__init__(value=20)
self.something_else = something_else
...
Is this correct?
Thanks, Boda Cydo.
|
[
"That is correct. Note that you can also call the __init__ method directly on the Base class, like so:\nclass Child(Base):\n def __init__(self, something_else):\n Base.__init__(self, value = 20)\n self.something_else = something_else\n\nThat's the way I generally do it. But it's discouraged, because it doesn't behave very well in the presence of multiple inheritance. Of course, multiple inheritance has all sorts of odd effects of its own, and so I avoid it like the plague.\nIn general, if the classes you're inheriting from use super, you need to as well.\n",
"If you're using Python 3.1, super is new and improved. It figures out the class and instance arguments for you. So you should call super without arguments:\nclass Child(Base):\n def __init__(self, value, something_else):\n super().__init__(value)\n self.something_else = something_else\n ...\n\n",
"Yes, that's correct. If you wanted to be able to pass value into the Child class you could do it this way\nclass Child(Base):\n def __init__(self, value, something_else):\n super(Child, self).__init__(value)\n self.something_else = something_else\n ...\n\n"
] |
[
72,
66,
13
] |
[] |
[] |
[
"python"
] |
stackoverflow_0002421307_python.txt
|
Q:
Verify RTSP service via URL
I am trying to verify that a video service is provided from an URL in python. I am asking does anyone know of any good libraries to use or a way to do this. I have not found much info for this on the web.
Thanks
A:
Digging around on StackOverflow I came across a previous question asking for an RTSP library in Python or C/C++ .
Linked there is an RTSP library provided by Twisted, and another one called Live555. Have you tried either of these?
I am just reposting the links for convenience.
A:
If you do not want to use a library, as suggested by synack, you can open a socket connection to the given URL and send an RTSP DESCRIEBE request. That is actually quite simple since RTSP is text-based HTTP-like. You would need to parse the response for a meaningful result, e.g look for the presence of media streams.
A:
If you try to validate the URL itself as a valid RTSP URL, I think that it's only the protocol token that changes from http:// to rtsp:// or rtspu://, and implicitly, the default port is no longer 80, but 554.
See RTSP RFC, section 3.2 ("RTSP URL") for more details regarding URL format.
However, if wish to know if "behind" a given RTSP URL there's a running RTSP server, you should actually open a connection to this server, usually using TCP sockets. You can make the "conversation" simply via code, but I suggest you use some kind of a product/library that provides RTSP stack for Python; I don't know if such product actually exists for Python, but there are a few things for C/C++.
A:
I don't believe Live555 provides a python library. However, they do provide source code that can be compiled to build openRTSP. This is a simple command-line utility that will perform the entire RTSP handshake to connect to the server and begin streaming to the client. It also can provide statistic measurements (such as jitter, number of packets lost, etc.) that can be used to measure the quality of the streaming connection.
|
Verify RTSP service via URL
|
I am trying to verify that a video service is provided from an URL in python. I am asking does anyone know of any good libraries to use or a way to do this. I have not found much info for this on the web.
Thanks
|
[
"Digging around on StackOverflow I came across a previous question asking for an RTSP library in Python or C/C++ .\nLinked there is an RTSP library provided by Twisted, and another one called Live555. Have you tried either of these?\nI am just reposting the links for convenience.\n",
"If you do not want to use a library, as suggested by synack, you can open a socket connection to the given URL and send an RTSP DESCRIEBE request. That is actually quite simple since RTSP is text-based HTTP-like. You would need to parse the response for a meaningful result, e.g look for the presence of media streams.\n",
"If you try to validate the URL itself as a valid RTSP URL, I think that it's only the protocol token that changes from http:// to rtsp:// or rtspu://, and implicitly, the default port is no longer 80, but 554.\nSee RTSP RFC, section 3.2 (\"RTSP URL\") for more details regarding URL format.\nHowever, if wish to know if \"behind\" a given RTSP URL there's a running RTSP server, you should actually open a connection to this server, usually using TCP sockets. You can make the \"conversation\" simply via code, but I suggest you use some kind of a product/library that provides RTSP stack for Python; I don't know if such product actually exists for Python, but there are a few things for C/C++.\n",
"I don't believe Live555 provides a python library. However, they do provide source code that can be compiled to build openRTSP. This is a simple command-line utility that will perform the entire RTSP handshake to connect to the server and begin streaming to the client. It also can provide statistic measurements (such as jitter, number of packets lost, etc.) that can be used to measure the quality of the streaming connection.\n"
] |
[
4,
3,
1,
0
] |
[] |
[] |
[
"python",
"rtsp",
"url",
"video_streaming"
] |
stackoverflow_0002207110_python_rtsp_url_video_streaming.txt
|
Q:
What is the Bash equivalent of Python's pass statement
Is there a Bash equivalent to the Python's pass statement?
A:
You can use : for this.
A:
true is a command that successfully does nothing.
(false would, in a way, be the opposite: it doesn't do anything, but claims that a failure occurred.)
|
What is the Bash equivalent of Python's pass statement
|
Is there a Bash equivalent to the Python's pass statement?
|
[
"You can use : for this.\n",
"true is a command that successfully does nothing.\n(false would, in a way, be the opposite: it doesn't do anything, but claims that a failure occurred.)\n"
] |
[
184,
47
] |
[] |
[] |
[
"bash",
"language_comparisons",
"python"
] |
stackoverflow_0002421586_bash_language_comparisons_python.txt
|
Q:
parsing words in string prefaced by 'password' with regex
a="aaaaaa password: GOD hello world password is G0D hello"
match = re.match("^(?:.*(?:password\sis\s|password:\s)([a-zA-Z]*)\s.*)*$",a)
print match.groups()
i want the output to be ('GOD','G0D') but all i get is ('G0D')
i am trying to solve this with Regex only. the amount of times "password" can appear in the text can vary.
help would be very much appreciated.
A:
I'd use re.findall, and simplify the regex a bit.
>>> re.findall(r"(?:password\sis\s+|password\:\s+)(\S+)", a)
['GOD', 'G0D']
Edit: Changed from \w to \S in order to also capture punctuation, and remove list expression.
A:
The ([a-zA-Z]*) regular subexpression does not accept digits, you might have meant ([a-zA-Z0-9]+) or another choice would be (\S+).
You have already used \s, are you aware of \S? Because you are using \s as the "delimiter" of your password token, you might as well be consistent and define the password as consisting of any characters which are not delimiters.
You could also simplify your regular expression overall as follows:
^(?:.*:password(\sis|:)\s(\S+)\s.*)*$
As pointed out by codaddict's analogy to PHP's preg_match_all, you also need to call re.findall. To do so, you will need to change the regular expression to one which is not overlapping, such as:
password(\sis|:)\s(\S+)
and then you will receive in the return value from re.findall() a list of matches, each consisting of a list of groups matched.
A:
I think you'll have to match the first occurrence and then continue matching possible more occurrences using the global matching feature of Pyhon (not sure how to do it, I know very little Python)
In PHP for example we can use a preg_match_all to solve this:
$a="aaaaaa password: GoD hello world password is G0D hello";
if(preg_match_all('/.*?(?:password\sis\s|password:\s)(\w+)/',$a,$matches)) {
var_dump($matches[1]); // prints God and GOD
}
|
parsing words in string prefaced by 'password' with regex
|
a="aaaaaa password: GOD hello world password is G0D hello"
match = re.match("^(?:.*(?:password\sis\s|password:\s)([a-zA-Z]*)\s.*)*$",a)
print match.groups()
i want the output to be ('GOD','G0D') but all i get is ('G0D')
i am trying to solve this with Regex only. the amount of times "password" can appear in the text can vary.
help would be very much appreciated.
|
[
"I'd use re.findall, and simplify the regex a bit.\n>>> re.findall(r\"(?:password\\sis\\s+|password\\:\\s+)(\\S+)\", a)\n['GOD', 'G0D']\n\nEdit: Changed from \\w to \\S in order to also capture punctuation, and remove list expression.\n",
"The ([a-zA-Z]*) regular subexpression does not accept digits, you might have meant ([a-zA-Z0-9]+) or another choice would be (\\S+).\nYou have already used \\s, are you aware of \\S? Because you are using \\s as the \"delimiter\" of your password token, you might as well be consistent and define the password as consisting of any characters which are not delimiters. \nYou could also simplify your regular expression overall as follows:\n^(?:.*:password(\\sis|:)\\s(\\S+)\\s.*)*$\nAs pointed out by codaddict's analogy to PHP's preg_match_all, you also need to call re.findall. To do so, you will need to change the regular expression to one which is not overlapping, such as:\npassword(\\sis|:)\\s(\\S+)\nand then you will receive in the return value from re.findall() a list of matches, each consisting of a list of groups matched.\n",
"I think you'll have to match the first occurrence and then continue matching possible more occurrences using the global matching feature of Pyhon (not sure how to do it, I know very little Python)\nIn PHP for example we can use a preg_match_all to solve this:\n$a=\"aaaaaa password: GoD hello world password is G0D hello\";\nif(preg_match_all('/.*?(?:password\\sis\\s|password:\\s)(\\w+)/',$a,$matches)) {\n var_dump($matches[1]); // prints God and GOD\n}\n\n"
] |
[
1,
0,
0
] |
[] |
[] |
[
"python",
"regex"
] |
stackoverflow_0002421529_python_regex.txt
|
Q:
RegExp in Python
This is an example that searches PDF files in the current directory.
import os, os.path
import re
def print_pdf (arg, dir, files):
for file in files:
path = os.path.join(dir, file)
path = os.path.normcase(path)
if re.search(r".*\.pdf", path):
print path
os.path.walk('.', print_pdf, 0)
Could anyone explain what r".*\.pdf" means here?
Why ".*\"?
Thanks!
A:
it means any character zero or more times, followed by the literal dot and letters pdf (due to the greedy nature of the asterisk, it's basically guaranteed that the '.pdf' are going to be at the end of the subject string).
There is glob module to do this the right way:
>>> glob.glob(os.path.join(dirname, '*.pdf'))
A:
Why ".*\"?
Wrong question, you missed a crucial character of the expression. ;-)
In fact, .* will match any character (. in regex), as many times as possible (* in regex; relates to the previous string, so . in this case).
\., on the other hand, will match exactly one dot (.). \ escapes the following character (.) so it does no longer have its special meaning (e.g. in this case “match any character”) but rather it will be treated as-is.
A:
The . means match any character but "\n". The * means "repeat the previous character 0 or more times". The \. matches an actual ".".
BTW, this is all in the docs.
A:
This searches for a string containing zero or more chars followed by ".pdf" The .* is a common idiom in regexps and it means match any char 0 or more times. The . is because in regexps, the . has a special meaning, and the \ escapes that.
A:
The period (.)
will match any character except newlines
The following asterisk (*)
means unlimited number of repetitions
of the preceding period
The backslash ()
escapes the period in .pdf So it looks for a real
period, so ONLY the .pdf and not "any
character".pdf again'
So in the end it looks for
Any piece of text that ends in .pdf
A:
use os.walk() instead. And there's no need to use regex.
for r,d,f in os.walk(path):
for files in f:
if files[-4:].lower() == ".pdf":
print "found pdf: ",os.path.join(r,files)
|
RegExp in Python
|
This is an example that searches PDF files in the current directory.
import os, os.path
import re
def print_pdf (arg, dir, files):
for file in files:
path = os.path.join(dir, file)
path = os.path.normcase(path)
if re.search(r".*\.pdf", path):
print path
os.path.walk('.', print_pdf, 0)
Could anyone explain what r".*\.pdf" means here?
Why ".*\"?
Thanks!
|
[
"it means any character zero or more times, followed by the literal dot and letters pdf (due to the greedy nature of the asterisk, it's basically guaranteed that the '.pdf' are going to be at the end of the subject string).\nThere is glob module to do this the right way:\n>>> glob.glob(os.path.join(dirname, '*.pdf'))\n\n",
"\nWhy \".*\\\"?\n\nWrong question, you missed a crucial character of the expression. ;-)\nIn fact, .* will match any character (. in regex), as many times as possible (* in regex; relates to the previous string, so . in this case).\n\\., on the other hand, will match exactly one dot (.). \\ escapes the following character (.) so it does no longer have its special meaning (e.g. in this case “match any character”) but rather it will be treated as-is.\n",
"The . means match any character but \"\\n\". The * means \"repeat the previous character 0 or more times\". The \\. matches an actual \".\".\nBTW, this is all in the docs.\n",
"This searches for a string containing zero or more chars followed by \".pdf\" The .* is a common idiom in regexps and it means match any char 0 or more times. The . is because in regexps, the . has a special meaning, and the \\ escapes that.\n",
"The period (.)\nwill match any character except newlines\nThe following asterisk (*)\n means unlimited number of repetitions\n of the preceding period\nThe backslash ()\nescapes the period in .pdf So it looks for a real\n period, so ONLY the .pdf and not \"any\n character\".pdf again'\nSo in the end it looks for\nAny piece of text that ends in .pdf\n",
"use os.walk() instead. And there's no need to use regex.\nfor r,d,f in os.walk(path):\n for files in f:\n if files[-4:].lower() == \".pdf\":\n print \"found pdf: \",os.path.join(r,files)\n\n"
] |
[
8,
3,
2,
1,
0,
0
] |
[] |
[] |
[
"python",
"regex"
] |
stackoverflow_0002419147_python_regex.txt
|
Q:
Cannot fetch a web site with python urllib.urlopen() or any web browser other than Shiretoko
Here is the URL of the site I want to fetch
https://salami.parc.com/spartag/GetRepository?friend=jmankoff&keywords=antibiotic&option=jmankoff%27s+tags
When I fetch the web site with the following code and display the contents with the following code:
sock = urllib.urlopen("https://salami.parc.com/spartag/GetRepository?friend=jmankoff&keywords=antibiotic&option=jmankoff's+tags")
html = sock.read()
sock.close()
soup = BeautifulSoup(html)
print soup.prettify()
I get the following output:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN">
<html>
<head>
<title>
Error message
</title>
</head>
<body>
<h2>
Invalid input data
</h2>
</body>
</html>
I get the same result with urllib2 as well. Now interestingly, this URL works on only Shiretoko web browser v3.5.7. (when I say it works I mean that it brings me the right page). When I feed this URL into Firefox 3.0.15 or Konqueror v4.2.2. I get exactly the same error page (with "Invalid input data"). I don't have any idea what creates this difference and how I can fetch this page using Python. Any ideas?
Thanks
A:
If you see the urllib2 doc, it says
urllib2.build_opener([handler, ...])¶
.....
If the Python installation has SSL support (i.e., if the ssl module can be imported), HTTPSHandler will also be added.
.....
you can try using urllib2 together with ssl module. alternatively, you can use httplib
A:
That's exactly what you get when you click on the link with a webbrowser. Maybe you are supposed to be logged in or have a cookie set or something
I get the same message for firefox 3.5.8 (shiretoko) on linux
|
Cannot fetch a web site with python urllib.urlopen() or any web browser other than Shiretoko
|
Here is the URL of the site I want to fetch
https://salami.parc.com/spartag/GetRepository?friend=jmankoff&keywords=antibiotic&option=jmankoff%27s+tags
When I fetch the web site with the following code and display the contents with the following code:
sock = urllib.urlopen("https://salami.parc.com/spartag/GetRepository?friend=jmankoff&keywords=antibiotic&option=jmankoff's+tags")
html = sock.read()
sock.close()
soup = BeautifulSoup(html)
print soup.prettify()
I get the following output:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN">
<html>
<head>
<title>
Error message
</title>
</head>
<body>
<h2>
Invalid input data
</h2>
</body>
</html>
I get the same result with urllib2 as well. Now interestingly, this URL works on only Shiretoko web browser v3.5.7. (when I say it works I mean that it brings me the right page). When I feed this URL into Firefox 3.0.15 or Konqueror v4.2.2. I get exactly the same error page (with "Invalid input data"). I don't have any idea what creates this difference and how I can fetch this page using Python. Any ideas?
Thanks
|
[
"If you see the urllib2 doc, it says\nurllib2.build_opener([handler, ...])¶\n\n .....\n If the Python installation has SSL support (i.e., if the ssl module can be imported), HTTPSHandler will also be added. \n\n .....\n\nyou can try using urllib2 together with ssl module. alternatively, you can use httplib\n",
"That's exactly what you get when you click on the link with a webbrowser. Maybe you are supposed to be logged in or have a cookie set or something\nI get the same message for firefox 3.5.8 (shiretoko) on linux\n"
] |
[
2,
0
] |
[] |
[] |
[
"beautifulsoup",
"python",
"urllib"
] |
stackoverflow_0002421857_beautifulsoup_python_urllib.txt
|
Q:
PyGTK StatusIcon with transparency
I'm trying to create a PyGTK StatusIcon with transparent background. I need to draw the contents of the StatusIcon at runtime.
StatusIcon wants a Pixbuf object (which can have transparency). No problem with that:
pixbuf = gtk.gdk.Pixbuf(gtk.gdk.COLORSPACE_RGB, True, 8, width, height)
pixbuf.fill(0xffffffff)
The problem is, I can't draw to Pixbuf objects. My current approach is to draw to a Pixmap and then convert it to a Pixbuf, but unfortunately Pixmaps can't have transparency.
How do I get a Pixbuf with transparent background that I can draw at runtime?
Greets,
Philip
A:
You can add transparency to Pixbuf objects with the add_alpha() method. The following line will set zero opacity for the color #ffffff:
pixbuf = pixbuf.add_alpha(True, 0xFF, 0xFF, 0xFF)
Too easy... :-|
|
PyGTK StatusIcon with transparency
|
I'm trying to create a PyGTK StatusIcon with transparent background. I need to draw the contents of the StatusIcon at runtime.
StatusIcon wants a Pixbuf object (which can have transparency). No problem with that:
pixbuf = gtk.gdk.Pixbuf(gtk.gdk.COLORSPACE_RGB, True, 8, width, height)
pixbuf.fill(0xffffffff)
The problem is, I can't draw to Pixbuf objects. My current approach is to draw to a Pixmap and then convert it to a Pixbuf, but unfortunately Pixmaps can't have transparency.
How do I get a Pixbuf with transparent background that I can draw at runtime?
Greets,
Philip
|
[
"You can add transparency to Pixbuf objects with the add_alpha() method. The following line will set zero opacity for the color #ffffff:\npixbuf = pixbuf.add_alpha(True, 0xFF, 0xFF, 0xFF)\n\nToo easy... :-|\n"
] |
[
4
] |
[] |
[] |
[
"alpha_transparency",
"pygtk",
"python"
] |
stackoverflow_0002412346_alpha_transparency_pygtk_python.txt
|
Q:
How to Check if request.GET var is None?
I'm getting into django and this is getting me a headache. I'm trying to get a simple GET variable. URL is site.com/search/?q=search-term
My view is:
def search(request):
if request.method == 'GET' and 'q' in request.GET:
q = request.GET.get('q', None)
if q is not None:
results = Task.objects.filter(
Q(title__contains=q)
|
Q(description__contains=q),
)
...return...
else:
...
else:
...
Search queries like mysite.com/search/? (without q) get through the first if correctly.
The problem is in queries like mysite.com/search/?q=. They don't get caught by if q is not None:
So, the short answer would be How can I check q == None? (I've already tried '', None, etc, to no avail.)
A:
First, check if the request.GET dict contains a parameter named q. You're doing this properly already:
if request.method == 'GET' and 'q' in request.GET:
Next, check if the value of q is either None or the empty string. To do that, you can write this:
q = request.GET['q']
if q is not None and q != '':
# Do processing here
Notice that it is not necessary to write request.GET.get('q', None). We've already checked to make sure there is a 'q' key inside the request.GET dict, so we can grab the value directly. The only time you should use the get method is if you're not sure a dict has a certain key and want to avoid raising a KeyError exception.
However, there is an even better solution based on the following facts:
The value None evaluates to False
The empty string '' also evaluates to False
Any non-empty string evaluates to True.
So now you can write:
q = request.GET['q']
if q:
# Do processing here
See these other resources for more details:
Python: Truth Value Testing
Python: dict.get
A:
Thanks for the clarification by @Ned.
Found a complete explanation here.
Basically:
'==' can be thought of as "value equality", that is, if two things look
the same, == should return a true value. (For those with a Java
background, Python's == is actually doing something akin to an equals()
method.)
'is' can be thought of as 'object
identity', that is, if the two things
actually are the same object.
|
How to Check if request.GET var is None?
|
I'm getting into django and this is getting me a headache. I'm trying to get a simple GET variable. URL is site.com/search/?q=search-term
My view is:
def search(request):
if request.method == 'GET' and 'q' in request.GET:
q = request.GET.get('q', None)
if q is not None:
results = Task.objects.filter(
Q(title__contains=q)
|
Q(description__contains=q),
)
...return...
else:
...
else:
...
Search queries like mysite.com/search/? (without q) get through the first if correctly.
The problem is in queries like mysite.com/search/?q=. They don't get caught by if q is not None:
So, the short answer would be How can I check q == None? (I've already tried '', None, etc, to no avail.)
|
[
"First, check if the request.GET dict contains a parameter named q. You're doing this properly already:\nif request.method == 'GET' and 'q' in request.GET:\n\nNext, check if the value of q is either None or the empty string. To do that, you can write this:\nq = request.GET['q']\nif q is not None and q != '':\n # Do processing here\n\nNotice that it is not necessary to write request.GET.get('q', None). We've already checked to make sure there is a 'q' key inside the request.GET dict, so we can grab the value directly. The only time you should use the get method is if you're not sure a dict has a certain key and want to avoid raising a KeyError exception.\nHowever, there is an even better solution based on the following facts:\n\nThe value None evaluates to False\nThe empty string '' also evaluates to False\nAny non-empty string evaluates to True.\n\nSo now you can write:\nq = request.GET['q']\nif q:\n # Do processing here\n\nSee these other resources for more details:\n\nPython: Truth Value Testing\nPython: dict.get\n\n",
"Thanks for the clarification by @Ned.\nFound a complete explanation here.\nBasically:\n\n'==' can be thought of as \"value equality\", that is, if two things look\n the same, == should return a true value. (For those with a Java\n background, Python's == is actually doing something akin to an equals()\n method.)\n'is' can be thought of as 'object\n identity', that is, if the two things\n actually are the same object.\n\n"
] |
[
55,
2
] |
[] |
[] |
[
"django",
"python"
] |
stackoverflow_0002422055_django_python.txt
|
Q:
Apache2: mod_wsgi or mod_python, which one is better?
I am planning to write web service in python. But, I found wsgi also does the similar thing. Which one can be preferred?
Thank you
Bala
Update
I am still confused. Please help.
Better in my sense means:
1. Bug will be fixed periodically.
2. Chosen by most developers.
3. Additional features like authentication tokens like AWS, can be supported out of the box.
4. No strong dependency on version.( I see that wsgi requires python 2.6)
5. All python libraries will work out of the box.
6. Scalable in the future.
7. Future upgrade don't cause any issues.
With my limited experience, I want these features. There might be some I might be missing.
Thanks
Bala
Update
I am sorry for all the confusion caused. I just want to expose a restful web services in python language. Is there a good framework?
A:
mod_wsgi is more actively maintained and (I hear -- haven't benchmarked them myself!) better performing than mod_python. So unless you need exclusive features of mod_python, just to use a web app framework (or non-framework, like werkzeug;-), you're probably better off with mod_wsgi! (Just about every Python web framework, and many non-frameworks of which werkzeug is my favorite, support WSGI as their standard interface to the web server, these days).
A:
Don't confuse what WSGI and mod_wsgi are. WSGI is an interface specification for hosting Python web applications on a server. The mod_wsgi module is an implementation of the WSGI specification using Apache as the underlying web server. Thus, Python and WSGI are not choices exactly, WSGI is just one way of being able to communicate between a Python web service/application and the web server. The mod_wsgi package is one implementation of that interface. So, WSGI is a means to an end, not a solution in itself.
Personally, I'd very much suggest you just use a minimal Python framework/non framework and as Alex suggests, Werkzeug is a good choice.
A:
If you just want to run web apps then use mod_wsgi. If you need to write a handler for the rest of httpd's request/response phases then use mod_python.
A:
mod_wsgi is specifically tuned to run Python web apps that use WSGI in Apache. mod_python is for any kind of Python web app, including WSGI apps. mod_wsgi also has a lower memory footprint than mod_python.
A:
mod_wsgi is much more actively maintained than mod_python at this point. It also has a good bit of momentum, as it was somewhat recently adopted as the preferred deployment method on apache2 by Django. The author is also actively engaged with the Python community in regards to the future evolution of WSGI.
A:
Bug will be fixed periodically.
Unless you're paying money, you cannot have any idea about this.
Chosen by most developers.
mod_wsgi
Additional features like authentication tokens like AWS, can be supported out of the box.
True for every framework.
No strong dependency on version.( I see that wsgi requires python 2.6)
What? Everything depends on compatible versions. Everything. Every single piece of software.
All python libraries will work out of the box.
"All?" What about the poorly-written ones?
Scalable in the future.
Sure. We always hope for this. There's no guarantee.
Future upgrade don't cause any issues.
That's funny.
"I want these features."
We all do. Realistically, you can get #2. The rest don't make sense or cannot every be assured.
|
Apache2: mod_wsgi or mod_python, which one is better?
|
I am planning to write web service in python. But, I found wsgi also does the similar thing. Which one can be preferred?
Thank you
Bala
Update
I am still confused. Please help.
Better in my sense means:
1. Bug will be fixed periodically.
2. Chosen by most developers.
3. Additional features like authentication tokens like AWS, can be supported out of the box.
4. No strong dependency on version.( I see that wsgi requires python 2.6)
5. All python libraries will work out of the box.
6. Scalable in the future.
7. Future upgrade don't cause any issues.
With my limited experience, I want these features. There might be some I might be missing.
Thanks
Bala
Update
I am sorry for all the confusion caused. I just want to expose a restful web services in python language. Is there a good framework?
|
[
"mod_wsgi is more actively maintained and (I hear -- haven't benchmarked them myself!) better performing than mod_python. So unless you need exclusive features of mod_python, just to use a web app framework (or non-framework, like werkzeug;-), you're probably better off with mod_wsgi! (Just about every Python web framework, and many non-frameworks of which werkzeug is my favorite, support WSGI as their standard interface to the web server, these days).\n",
"Don't confuse what WSGI and mod_wsgi are. WSGI is an interface specification for hosting Python web applications on a server. The mod_wsgi module is an implementation of the WSGI specification using Apache as the underlying web server. Thus, Python and WSGI are not choices exactly, WSGI is just one way of being able to communicate between a Python web service/application and the web server. The mod_wsgi package is one implementation of that interface. So, WSGI is a means to an end, not a solution in itself.\nPersonally, I'd very much suggest you just use a minimal Python framework/non framework and as Alex suggests, Werkzeug is a good choice.\n",
"If you just want to run web apps then use mod_wsgi. If you need to write a handler for the rest of httpd's request/response phases then use mod_python.\n",
"mod_wsgi is specifically tuned to run Python web apps that use WSGI in Apache. mod_python is for any kind of Python web app, including WSGI apps. mod_wsgi also has a lower memory footprint than mod_python.\n",
"mod_wsgi is much more actively maintained than mod_python at this point. It also has a good bit of momentum, as it was somewhat recently adopted as the preferred deployment method on apache2 by Django. The author is also actively engaged with the Python community in regards to the future evolution of WSGI.\n",
"\nBug will be fixed periodically.\nUnless you're paying money, you cannot have any idea about this.\n\nChosen by most developers.\nmod_wsgi\n\nAdditional features like authentication tokens like AWS, can be supported out of the box.\nTrue for every framework.\n\nNo strong dependency on version.( I see that wsgi requires python 2.6)\nWhat? Everything depends on compatible versions. Everything. Every single piece of software.\n\nAll python libraries will work out of the box.\n\"All?\" What about the poorly-written ones?\n\nScalable in the future.\nSure. We always hope for this. There's no guarantee.\n\nFuture upgrade don't cause any issues.\nThat's funny.\n\n\n\"I want these features.\"\nWe all do. Realistically, you can get #2. The rest don't make sense or cannot every be assured.\n"
] |
[
14,
5,
4,
3,
1,
0
] |
[] |
[] |
[
"apache2",
"python",
"rest",
"web_services"
] |
stackoverflow_0002421007_apache2_python_rest_web_services.txt
|
Q:
Quickly implement a sortable table of objects in Django
Hey all. I have a question on how to implement the following with Django. I'd like to display a tabular view of my objects with each column corresponding to a particular model field. I'd like to be able to have the user sort the columns or search through all of them. Basically just like the admin, but client facing and read-only. It's simple, but I was wondering if there was a way I could implement this without having to write all that logic from scratch.
A:
Alex Gaynor's django-filter may be what you want.
A:
Depending on how much you wanted to work with it, Yahoo YUI's DataTable control is pretty easy to get working with a JSON data source. See http://developer.yahoo.com/yui/datatable/
|
Quickly implement a sortable table of objects in Django
|
Hey all. I have a question on how to implement the following with Django. I'd like to display a tabular view of my objects with each column corresponding to a particular model field. I'd like to be able to have the user sort the columns or search through all of them. Basically just like the admin, but client facing and read-only. It's simple, but I was wondering if there was a way I could implement this without having to write all that logic from scratch.
|
[
"Alex Gaynor's django-filter may be what you want.\n",
"Depending on how much you wanted to work with it, Yahoo YUI's DataTable control is pretty easy to get working with a JSON data source. See http://developer.yahoo.com/yui/datatable/\n"
] |
[
1,
0
] |
[] |
[] |
[
"django",
"python"
] |
stackoverflow_0002421006_django_python.txt
|
Q:
How do I create a list with 256 elements?
I've started teaching myself Python, and as an exercise I've set myself the task of generating lookup tables I need for another project.
I need to generate a list of 256 elements in which each element is the value of math.sin(2*i*pi/256). The problem is, I don't know how to generate a list initialized to "dummy" values that I can then use a for loop to step through and assign the values of the sin function.
Using list() seems to create an "empty" list, but with no elements so I get a "list assignment index out of range" error in the loop. Is there a way to this other than explicitly creating a list declaration containing 256 elements all with "0" as a value?
A:
Two answers have already shown you how to build your list at a single stroke, using the "list comprehension" (AKA "listcomp") construct.
To answer your specific question, though,
mylist = [None] * 256
is the simplest way to make a list with 256 items, all None, in case you want to fill it in later.
If you start with an empty list, call its .append(...) method to add each item at the end. A loop doing nothing but append on an initially-empty list is what normally gets replaced with a more concise listcomp.
Of course, for the task you actually state,
mylist = [math.sin(2 * math.pi/256)] * 256
would be by far the best approach -- no sense computing a sin 256 times when the argument's always the same (daringly assuming that what you say is what you mean;-).
A:
my_list = [math.sin(2 * math.pi/256) for i in xrange(256)]
A:
I need to generate a list of 256
elements in which each element is the
value of math.sin(2*math.pi/256)
To answer your question literally:
my_list=[math.sin(2*math.pi/256)]*256
A:
You can also try:
l = []
for i in range(256):
l.append(math.sin(2*math.pi/256))
This is an iterative for loop that keeps adding the same value to the end of the list 256 times
A:
Thanks for the help, everyone. I did make a mistake in the specification I posted for the question, in that the value of each element in the list needs to be the sin of the angle incremented by 2*pi/256 each time. The code that works for me in that case is:
li = [math.sin((2*math.pi/256)*i) for i in xrange(0,256)]
|
How do I create a list with 256 elements?
|
I've started teaching myself Python, and as an exercise I've set myself the task of generating lookup tables I need for another project.
I need to generate a list of 256 elements in which each element is the value of math.sin(2*i*pi/256). The problem is, I don't know how to generate a list initialized to "dummy" values that I can then use a for loop to step through and assign the values of the sin function.
Using list() seems to create an "empty" list, but with no elements so I get a "list assignment index out of range" error in the loop. Is there a way to this other than explicitly creating a list declaration containing 256 elements all with "0" as a value?
|
[
"Two answers have already shown you how to build your list at a single stroke, using the \"list comprehension\" (AKA \"listcomp\") construct.\nTo answer your specific question, though,\nmylist = [None] * 256\n\nis the simplest way to make a list with 256 items, all None, in case you want to fill it in later.\nIf you start with an empty list, call its .append(...) method to add each item at the end. A loop doing nothing but append on an initially-empty list is what normally gets replaced with a more concise listcomp.\nOf course, for the task you actually state,\nmylist = [math.sin(2 * math.pi/256)] * 256\n\nwould be by far the best approach -- no sense computing a sin 256 times when the argument's always the same (daringly assuming that what you say is what you mean;-).\n",
"my_list = [math.sin(2 * math.pi/256) for i in xrange(256)]\n\n",
"\nI need to generate a list of 256\n elements in which each element is the\n value of math.sin(2*math.pi/256)\n\nTo answer your question literally:\nmy_list=[math.sin(2*math.pi/256)]*256\n\n",
"You can also try:\nl = []\nfor i in range(256):\n l.append(math.sin(2*math.pi/256))\n\nThis is an iterative for loop that keeps adding the same value to the end of the list 256 times\n",
"Thanks for the help, everyone. I did make a mistake in the specification I posted for the question, in that the value of each element in the list needs to be the sin of the angle incremented by 2*pi/256 each time. The code that works for me in that case is:\nli = [math.sin((2*math.pi/256)*i) for i in xrange(0,256)]\n\n"
] |
[
10,
5,
1,
1,
0
] |
[] |
[] |
[
"python"
] |
stackoverflow_0002422461_python.txt
|
Q:
Are PyArg_ParseTuple() "s" format specifiers useful in Python 3.x C API?
I'm trying to write a Python C extension that processes byte strings, and I have something basically working for Python 2.x and Python 3.x.
For the Python 2.x code, near the start of my function, I currently have a line:
if (!PyArg_ParseTuple(args, "s#:in_bytes", &src_ptr, &src_len))
...
I notice that the s# format specifier accepts both Unicode strings and byte strings. I really just want it to accept byte strings and reject Unicode. For Python 2.x, this might be "good enough"--the standard hashlib seems to do the same, accepting Unicode as well as byte strings. However, Python 3.x is meant to clean up the Unicode/byte string mess and not let the two be interchangeable.
So, I'm surprised to find that in Python 3.x, the s format specifiers for PyArg_ParseTuple() still seem to accept Unicode and provide a "default encoded string version" of the Unicode. This seems to go against the principles of Python 3.x, making the s format specifiers unusable in practice. Is my analysis correct, or am I missing something?
Looking at the implementation for hashlib for Python 3.x (e.g. see md5module.c, function MD5_update() and its use of GET_BUFFER_VIEW_OR_ERROUT() macro) I see that it avoids the s format specifiers, and just takes a generic object (O specifier) and then does various explicit type checks using the GET_BUFFER_VIEW_OR_ERROUT() macro. Is this what we have to do?
A:
I agree with you -- it's one of several spots where the C API migration of Python 3 was clearly not designed as carefully and thouroughly as the Python coder-visible parts. I do also agree that probably the best workaround for now is focusing on "buffer views", per that macro -- until and unless something better gets designed into a future Python C API (don't hold your breath waiting for that to happen, though;-).
|
Are PyArg_ParseTuple() "s" format specifiers useful in Python 3.x C API?
|
I'm trying to write a Python C extension that processes byte strings, and I have something basically working for Python 2.x and Python 3.x.
For the Python 2.x code, near the start of my function, I currently have a line:
if (!PyArg_ParseTuple(args, "s#:in_bytes", &src_ptr, &src_len))
...
I notice that the s# format specifier accepts both Unicode strings and byte strings. I really just want it to accept byte strings and reject Unicode. For Python 2.x, this might be "good enough"--the standard hashlib seems to do the same, accepting Unicode as well as byte strings. However, Python 3.x is meant to clean up the Unicode/byte string mess and not let the two be interchangeable.
So, I'm surprised to find that in Python 3.x, the s format specifiers for PyArg_ParseTuple() still seem to accept Unicode and provide a "default encoded string version" of the Unicode. This seems to go against the principles of Python 3.x, making the s format specifiers unusable in practice. Is my analysis correct, or am I missing something?
Looking at the implementation for hashlib for Python 3.x (e.g. see md5module.c, function MD5_update() and its use of GET_BUFFER_VIEW_OR_ERROUT() macro) I see that it avoids the s format specifiers, and just takes a generic object (O specifier) and then does various explicit type checks using the GET_BUFFER_VIEW_OR_ERROUT() macro. Is this what we have to do?
|
[
"I agree with you -- it's one of several spots where the C API migration of Python 3 was clearly not designed as carefully and thouroughly as the Python coder-visible parts. I do also agree that probably the best workaround for now is focusing on \"buffer views\", per that macro -- until and unless something better gets designed into a future Python C API (don't hold your breath waiting for that to happen, though;-).\n"
] |
[
3
] |
[] |
[] |
[
"python",
"python_3.x"
] |
stackoverflow_0002422572_python_python_3.x.txt
|
Q:
Filter across three tables using Django
I have 3 django models, where the first has a foreign key to the second, and the second has a foreign key to the third. Like this:
class Book(models.Model):
year_published = models.IntField()
author = models.ForeignKey(Author)
class Author(models.Model):
author_id = models.AutoField(primary_key=True)
name = models.CharField(max_length=50)
agent = models.ForeignKey(LitAgent)
class LitAgent(models.Model):
agent_id = models.AutoField(primary_key=True)
name = models.CharField(max_length=50)
I want to ask for all the literary agents whose authors had books published in 2006, for example. How can I do this in Django? I have looked at the documentation about filters and QuerySets, and don't see an obvious way. Thanks.
A:
LitAgent.objects.filter(author__book__year_published=2006)
|
Filter across three tables using Django
|
I have 3 django models, where the first has a foreign key to the second, and the second has a foreign key to the third. Like this:
class Book(models.Model):
year_published = models.IntField()
author = models.ForeignKey(Author)
class Author(models.Model):
author_id = models.AutoField(primary_key=True)
name = models.CharField(max_length=50)
agent = models.ForeignKey(LitAgent)
class LitAgent(models.Model):
agent_id = models.AutoField(primary_key=True)
name = models.CharField(max_length=50)
I want to ask for all the literary agents whose authors had books published in 2006, for example. How can I do this in Django? I have looked at the documentation about filters and QuerySets, and don't see an obvious way. Thanks.
|
[
"LitAgent.objects.filter(author__book__year_published=2006)\n\n"
] |
[
11
] |
[] |
[] |
[
"django",
"python"
] |
stackoverflow_0002422668_django_python.txt
|
Q:
Unable to set iPython to use 2.6.1 Python
I have installed the newest iPython in Mac. However, it uses the Python verion 2.5.1.
I installed the Python 2.6.1 by MacPython package at here.
How can I make my iPython to use Python 2.6.1?
I am not sure where the MacPython package exactly installed the newest Python.
The newest Python should somehow put the PATH so that iPyhon can use it.
[edit] after the first answer
I run the following command
$ln -s python python2.6
I cannot open python2.6 by
python
A:
A good way to get it to work is here. I needed to restart my terminal before ipython pointed to python2.6. Note the latest ipython distribution is 0.10, not 0.9.
A:
you should have a python, python2.5 and python2.6, is that correct? If you wan't to use python2.6 system wide the symple solution would be to sym link (ln -s ..) python to python2.6 instead of python2.5
|
Unable to set iPython to use 2.6.1 Python
|
I have installed the newest iPython in Mac. However, it uses the Python verion 2.5.1.
I installed the Python 2.6.1 by MacPython package at here.
How can I make my iPython to use Python 2.6.1?
I am not sure where the MacPython package exactly installed the newest Python.
The newest Python should somehow put the PATH so that iPyhon can use it.
[edit] after the first answer
I run the following command
$ln -s python python2.6
I cannot open python2.6 by
python
|
[
"A good way to get it to work is here. I needed to restart my terminal before ipython pointed to python2.6. Note the latest ipython distribution is 0.10, not 0.9.\n",
"you should have a python, python2.5 and python2.6, is that correct? If you wan't to use python2.6 system wide the symple solution would be to sym link (ln -s ..) python to python2.6 instead of python2.5\n"
] |
[
4,
1
] |
[] |
[] |
[
"ipython",
"python"
] |
stackoverflow_0000641000_ipython_python.txt
|
Q:
Python: avoiding if condition?
Which is better?
if not var:
var = get_var()
(or)
var = var or get_var()
Also, How do I know the better of the two?
edit:One more option from steve,
var = var if var else get_var()
A:
The better is the one you like better. I would use first version with if but this is very personal.
A:
When two style variations are so close stylistically, I use timeit as the tie-breaker: faster must mean closer to Python's mainstream, i.e., better. Hey, it's better than endless debate, y?-) So:
$ python -mtimeit -s'var=0; getvar=lambda:0' 'var = var or getvar()'
1000000 loops, best of 3: 0.359 usec per loop
$ python -mtimeit -s'var=0; getvar=lambda:0' 'if not var: var = getvar()'
1000000 loops, best of 3: 0.361 usec per loop
$ python -mtimeit -s'var=1; getvar=lambda:1' 'var = var or getvar()'
10000000 loops, best of 3: 0.123 usec per loop
$ python -mtimeit -s'var=1; getvar=lambda:1' 'if not var: var = getvar()'
10000000 loops, best of 3: 0.0899 usec per loop
the if has it -- equivalent when var is false, faster when it's true.
A:
Actually, if you are trying to determine if var has been previously set using a call to get_var, then I would contend that both forms are wrong. Python treats a number of perfectly ordinary values as evaluating to a boolean 'false': 0, None, [], (,), set(), and {}. So let's say var is going to be an integer, and get_var() happens to return 0. Now, regardless of which form you use, get_var() will get called again and again, even though we already know that var is 0!
There are several methods for detecting whether a variable has been defined or not:
look in the dict returned by globals() or locals()
wrap the statement var = var in a try/except block, trapping on NameError
use a sentinel value like None, and initialize var to this value; then you can test for if var is None: var = get_var() (using 'is', not '=='). If you are unlucky, and None is a potential value to be returned from get_var(), then you'll need to define your own special not-yet-defined value, using something like NOT_DEFINED = object(), initialize var with it, and then you can test for if var is NOT_DEFINED.
A:
To me, the first idiom, the one using the explicit if, is preferable because more explicit.
However I've seen the or construct being referenced as the preferred / more pythonic one.
So, on the one hand, Explicit is better than implicit (Zen citation), on the other hand, the short expression can be viewed as pythonic (although shorter isn't equivalent to pythonic in all cases!)
A closely related SO question is most idiomatic way to convert None to empty string, and both the if and the or idioms were listed there.
A:
the first version is more intuitive to me. But then again, its all about your own taste.
A:
Second one is more pythonic, and I normally use that.
A:
Neither is wrong.
The former is clearer to understand for someone reading the code.
Ask yourself if, when you are thinking about the problem you are trying to solve, the concepts that come to mind are closer to "if this, then that" or "a logical OR of two almost, but not quite, Boolean variables."
A:
Both will eventually compile to the same code, given that or is a short-circuit operator (it doesn't evaluate the right hand argument if left hand is true).
I'd prefer the first one as it expresses your intent more clearly. The second one is probably more compact.
A:
The interpreter will likely execute them both the way. There are tradeoffs regarding code readability. Which statement is easier to recognize what it does? Certainly, the first is much clearer. For me, reading this post, I had to think more about the second one. I would use the first due to increased readability, even if the second statement is slightly 'sexier'.
Hope this helps.
-tjw
|
Python: avoiding if condition?
|
Which is better?
if not var:
var = get_var()
(or)
var = var or get_var()
Also, How do I know the better of the two?
edit:One more option from steve,
var = var if var else get_var()
|
[
"The better is the one you like better. I would use first version with if but this is very personal.\n",
"When two style variations are so close stylistically, I use timeit as the tie-breaker: faster must mean closer to Python's mainstream, i.e., better. Hey, it's better than endless debate, y?-) So:\n$ python -mtimeit -s'var=0; getvar=lambda:0' 'var = var or getvar()'\n1000000 loops, best of 3: 0.359 usec per loop\n$ python -mtimeit -s'var=0; getvar=lambda:0' 'if not var: var = getvar()'\n1000000 loops, best of 3: 0.361 usec per loop\n$ python -mtimeit -s'var=1; getvar=lambda:1' 'var = var or getvar()'\n10000000 loops, best of 3: 0.123 usec per loop\n$ python -mtimeit -s'var=1; getvar=lambda:1' 'if not var: var = getvar()'\n10000000 loops, best of 3: 0.0899 usec per loop\n\nthe if has it -- equivalent when var is false, faster when it's true.\n",
"Actually, if you are trying to determine if var has been previously set using a call to get_var, then I would contend that both forms are wrong. Python treats a number of perfectly ordinary values as evaluating to a boolean 'false': 0, None, [], (,), set(), and {}. So let's say var is going to be an integer, and get_var() happens to return 0. Now, regardless of which form you use, get_var() will get called again and again, even though we already know that var is 0!\nThere are several methods for detecting whether a variable has been defined or not:\n\nlook in the dict returned by globals() or locals()\nwrap the statement var = var in a try/except block, trapping on NameError\nuse a sentinel value like None, and initialize var to this value; then you can test for if var is None: var = get_var() (using 'is', not '=='). If you are unlucky, and None is a potential value to be returned from get_var(), then you'll need to define your own special not-yet-defined value, using something like NOT_DEFINED = object(), initialize var with it, and then you can test for if var is NOT_DEFINED.\n\n",
"To me, the first idiom, the one using the explicit if, is preferable because more explicit.\nHowever I've seen the or construct being referenced as the preferred / more pythonic one.\nSo, on the one hand, Explicit is better than implicit (Zen citation), on the other hand, the short expression can be viewed as pythonic (although shorter isn't equivalent to pythonic in all cases!)\nA closely related SO question is most idiomatic way to convert None to empty string, and both the if and the or idioms were listed there. \n",
"the first version is more intuitive to me. But then again, its all about your own taste.\n",
"Second one is more pythonic, and I normally use that.\n",
"Neither is wrong.\nThe former is clearer to understand for someone reading the code.\nAsk yourself if, when you are thinking about the problem you are trying to solve, the concepts that come to mind are closer to \"if this, then that\" or \"a logical OR of two almost, but not quite, Boolean variables.\"\n",
"Both will eventually compile to the same code, given that or is a short-circuit operator (it doesn't evaluate the right hand argument if left hand is true).\nI'd prefer the first one as it expresses your intent more clearly. The second one is probably more compact.\n",
"The interpreter will likely execute them both the way. There are tradeoffs regarding code readability. Which statement is easier to recognize what it does? Certainly, the first is much clearer. For me, reading this post, I had to think more about the second one. I would use the first due to increased readability, even if the second statement is slightly 'sexier'.\nHope this helps.\n-tjw\n"
] |
[
7,
7,
4,
3,
2,
1,
1,
1,
1
] |
[] |
[] |
[
"conditional_statements",
"python",
"variable_assignment"
] |
stackoverflow_0002422905_conditional_statements_python_variable_assignment.txt
|
Q:
Best practices for logging in django project
It is always good to utilize existing patterns for solving the given problem rather then reinventing the wheel. This time it is about doing logging stuffs in django based project.
Can you please share your ideas with me and other about how do you prefer to implement logging in django based project in the following context?
What factors would you consider before starting design of logging system?
What would you like to log in a project? (messages, errors, request etc)?
How would you like to log?
What should be directory structure?
In what format would you like to log?
Which django apps do you use?
Have you make any such reusable apps? if yes, can you share with other?
Or any other idea which you find useful to share with other.
... Any little help would be really good for all django developers ...
cheers
A:
In Django, like in any other Python application, I'd use the standard library's logging module and call logging.debug, logging.info etc as appropriate to each message.
|
Best practices for logging in django project
|
It is always good to utilize existing patterns for solving the given problem rather then reinventing the wheel. This time it is about doing logging stuffs in django based project.
Can you please share your ideas with me and other about how do you prefer to implement logging in django based project in the following context?
What factors would you consider before starting design of logging system?
What would you like to log in a project? (messages, errors, request etc)?
How would you like to log?
What should be directory structure?
In what format would you like to log?
Which django apps do you use?
Have you make any such reusable apps? if yes, can you share with other?
Or any other idea which you find useful to share with other.
... Any little help would be really good for all django developers ...
cheers
|
[
"In Django, like in any other Python application, I'd use the standard library's logging module and call logging.debug, logging.info etc as appropriate to each message.\n"
] |
[
7
] |
[] |
[] |
[
"django",
"logging",
"python"
] |
stackoverflow_0002423005_django_logging_python.txt
|
Q:
Similar to ``tabnanny``, how can I check that all the python code is using 4 spaces as an indent?
Similar to tabnanny, is there a utility for python to check if a python file is using 4 spaces for indentation?
A:
Pylint can check this among many other things. Here's a warning it gave me with a test file:
W: 3: Bad indentation. Found 3 spaces, expected 4
It's also possible to make it expect another indent type using this command line option:
--indent-string=<string>
String used as indentation unit. This is usually " "
(4 spaces) or "\t" (1 tab). [current: ' ']
A:
You can try the reindent.py script, found in tools/scripts of your python install.
Change Python (.py) files to use 4-space indents and no hard tab characters. Also trim excess spaces and tabs from ends of lines, and remove empty lines at the end of files. Also ensure the last line ends with a newline.
A:
Pylint (http://www.logilab.org/project/pylint) checks this (and much more).
Other Python code checkers (pep8, pyflakes, pychecker...) may do so too.
|
Similar to ``tabnanny``, how can I check that all the python code is using 4 spaces as an indent?
|
Similar to tabnanny, is there a utility for python to check if a python file is using 4 spaces for indentation?
|
[
"Pylint can check this among many other things. Here's a warning it gave me with a test file:\nW: 3: Bad indentation. Found 3 spaces, expected 4\n\nIt's also possible to make it expect another indent type using this command line option:\n--indent-string=<string>\n String used as indentation unit. This is usually \" \" \n (4 spaces) or \"\\t\" (1 tab). [current: ' ']\n\n",
"You can try the reindent.py script, found in tools/scripts of your python install. \n\nChange Python (.py) files to use 4-space indents and no hard tab characters. Also trim excess spaces and tabs from ends of lines, and remove empty lines at the end of files. Also ensure the last line ends with a newline.\n\n",
"Pylint (http://www.logilab.org/project/pylint) checks this (and much more). \nOther Python code checkers (pep8, pyflakes, pychecker...) may do so too. \n"
] |
[
4,
4,
1
] |
[] |
[] |
[
"python",
"tabs"
] |
stackoverflow_0002421755_python_tabs.txt
|
Q:
In Python, is this a good practice?
try:
spam.foo
except AttributeError:
do_somthing()
(Is it wise to check an attribute like that without using it?)
A:
Update:
If you are really only interested in whether the attribute foo exists (and not doing something with the attribute) than of course hasattr() might be better way to check for the attribute.
From a developer/user point of view I have to confess that, for me, the use of hasattr() better reflects your intention. And besides that it would result in less code:
if not hasattr(spam,'foo'):
do_something()
The documentation of hasattr() describes that it is implemented by:
(This is implemented by) calling getattr(object, name) and seeing whether it raises an exception or not.
So basically hasattr() does exactly the same as you are doing. In this case I would definitely go with the build in solution, i.e. hasattr(). You won't gain any speed advantage.
Python encourages the EAFP paradigm:
It is Easier to Ask for Forgiveness than Permission
So yes this is exactly the way one should do this if you more or less know that spam will have a foo attribute most of the time (the code will be (little?) faster).
Otherwise, if spam does not have a foo attribute (most of the time), then this approach would be better:
if hasattr(spam, 'foo'):
bar = spam.foo
else:
do_somthing()
The section on Wikipedia I linked to describes this. Quote (where the EAFP version refers to the way you wrote your code sample):
These two code samples have the same effect, although there will be performance differences. When spam has the attribute eggs, the EAFP sample will run faster. When spam does not have the attribute eggs (the "exceptional" case), the EAFP sample will run slower. (...) If exceptional cases are rare, then the EAFP version will have superior average performance than the alternative.
Which is somehow obvious as (with EAFP) you don't have to introspect the object every time before you want to access the attribute.
A:
Better use
if hasattr(spam,"foo"):
#dosomthing with spam.foo
else:
do_somthing()
Python docs:
hasattr(object, name)
The arguments are an object and a string. The result is True if the
string is the name of one of the
object’s attributes, False if not.
(This is implemented by calling
getattr(object, name) and seeing
whether it raises an exception or
not.)
|
In Python, is this a good practice?
|
try:
spam.foo
except AttributeError:
do_somthing()
(Is it wise to check an attribute like that without using it?)
|
[
"Update:\nIf you are really only interested in whether the attribute foo exists (and not doing something with the attribute) than of course hasattr() might be better way to check for the attribute.\nFrom a developer/user point of view I have to confess that, for me, the use of hasattr() better reflects your intention. And besides that it would result in less code:\nif not hasattr(spam,'foo'):\n do_something()\n\nThe documentation of hasattr() describes that it is implemented by: \n\n(This is implemented by) calling getattr(object, name) and seeing whether it raises an exception or not.\n\nSo basically hasattr() does exactly the same as you are doing. In this case I would definitely go with the build in solution, i.e. hasattr(). You won't gain any speed advantage.\n\nPython encourages the EAFP paradigm:\n\nIt is Easier to Ask for Forgiveness than Permission\n\nSo yes this is exactly the way one should do this if you more or less know that spam will have a foo attribute most of the time (the code will be (little?) faster).\nOtherwise, if spam does not have a foo attribute (most of the time), then this approach would be better:\nif hasattr(spam, 'foo'):\n bar = spam.foo\nelse:\n do_somthing()\n\nThe section on Wikipedia I linked to describes this. Quote (where the EAFP version refers to the way you wrote your code sample):\n\nThese two code samples have the same effect, although there will be performance differences. When spam has the attribute eggs, the EAFP sample will run faster. When spam does not have the attribute eggs (the \"exceptional\" case), the EAFP sample will run slower. (...) If exceptional cases are rare, then the EAFP version will have superior average performance than the alternative.\n\nWhich is somehow obvious as (with EAFP) you don't have to introspect the object every time before you want to access the attribute.\n",
"Better use \nif hasattr(spam,\"foo\"):\n #dosomthing with spam.foo\nelse:\n do_somthing()\n\nPython docs:\n\nhasattr(object, name)\n The arguments are an object and a string. The result is True if the\n string is the name of one of the\n object’s attributes, False if not.\n (This is implemented by calling\n getattr(object, name) and seeing\n whether it raises an exception or\n not.)\n\n"
] |
[
14,
2
] |
[] |
[] |
[
"python"
] |
stackoverflow_0002423145_python.txt
|
Q:
The data format for post in urllib2.Request
What should data look like before data encoding in:
urllib2.Request(someurl,data) I tried [('name1','value1'),('name2','value2'),...]but not work.:(
EDIT:
I made a log in the program and recorded the value of urllib.urlencode(data):
content=%E5%8F%91%E5%B8%83%E4%BA%86%E4%B8%80%E4%B8%AA%E6%96%B0%E4%B8%BB%E9%A2%98%EF%BC%9A%3Ca+href%3D%27http%3A%2F%2Fbbs.jianshe99.com%2Fforum-5-195%2Ftopic-448618.html%27+target%3D%27_blank%27%3E+fsdfdsf%3C%2Fa%3E
then post it to a php script which is
<?php
print_r($_POST);
?>
but always get a response as:
array()
A:
data may be a string specifying additional data to send to the server, or None if no such data is needed. Currently HTTP requests are the only ones that use data; the HTTP request will be a POST instead of a GET when the data parameter is provided. data should be a buffer in the standard application/x-www-form-urlencoded format. The urllib.urlencode() function takes a mapping or sequence of 2-tuples and returns a string in this format.
See Also
urllib2.Request
|
The data format for post in urllib2.Request
|
What should data look like before data encoding in:
urllib2.Request(someurl,data) I tried [('name1','value1'),('name2','value2'),...]but not work.:(
EDIT:
I made a log in the program and recorded the value of urllib.urlencode(data):
content=%E5%8F%91%E5%B8%83%E4%BA%86%E4%B8%80%E4%B8%AA%E6%96%B0%E4%B8%BB%E9%A2%98%EF%BC%9A%3Ca+href%3D%27http%3A%2F%2Fbbs.jianshe99.com%2Fforum-5-195%2Ftopic-448618.html%27+target%3D%27_blank%27%3E+fsdfdsf%3C%2Fa%3E
then post it to a php script which is
<?php
print_r($_POST);
?>
but always get a response as:
array()
|
[
"data may be a string specifying additional data to send to the server, or None if no such data is needed. Currently HTTP requests are the only ones that use data; the HTTP request will be a POST instead of a GET when the data parameter is provided. data should be a buffer in the standard application/x-www-form-urlencoded format. The urllib.urlencode() function takes a mapping or sequence of 2-tuples and returns a string in this format.\nSee Also\n\nurllib2.Request\n\n"
] |
[
2
] |
[] |
[] |
[
"python"
] |
stackoverflow_0002423146_python.txt
|
Q:
Uneditable file and Unreadable(for further processing) file( WHY? ) after processing it through C++ Program
:) This might look to be a very long question to you I understand, but trust me on this its not long. I am not able to identify why after processing this text is not being able to be read and edited. I tried using the ord() function in python to check if the text contains any Unicode characters( non ascii characters) apart from the ascii ones.. I found quite a number of them.
I have a strong feeling that this could be due to the original text itself( The INPUT ).
Input-File: Just copy paste it into a file "acle5v1.txt"
The objective of this code below is to check for upper case characters and to convert it to lower case and also to remove all punctuations so that these words are taken for further processing for word alignment
#include<iostrea>
#include<fstream>
#include<ctype.h>
#include<cstring>
using namespace std;
ifstream fin2("acle5v1.txt");
ofstream fin3("acle5v1_op.txt");
ofstream fin4("chkcharadded.txt");
ofstream fin5("chkcharntadded.txt");
ofstream fin6("chkprintchar.txt");
ofstream fin7("chknonasci.txt");
ofstream fin8("nonprinchar.txt");
int main()
{
char ch,ch1;
fin2.seekg(0);
fin3.seekp(0);
int flag = 0;
while(!fin2.eof())
{
ch1=ch;
fin2.get(ch);
if (isprint(ch))// if the character is printable
flag = 1;
if(flag)
{
fin6<<"Printable character:\t"<<ch<<"\t"<<(int)ch<<endl;
flag = 0;
}
else
{
fin8<<"Non printable character caught:\t"<<ch<<"\t"<<int(ch)<<endl;
}
if( isalnum(ch) || ch == '@' || ch == ' ' )// checks for alpha numeric characters
{
fin4<<"char added: "<<ch<<"\tits ascii value: "<<int(ch)<<endl;
if(isupper(ch))
{
//tolower(ch);
fin3<<(char)tolower(ch);
}
else
{
fin3<<ch;
}
}
else if( ( ch=='\t' || ch=='.' || ch==',' || ch=='#' || ch=='?' || ch=='!' || ch=='"' || ch != ';' || ch != ':') && ch1 != ' ' )
{
fin3<<' ';
}
else if( (ch=='\t' || ch=='.' || ch==',' || ch=='#' || ch=='?' || ch=='!' || ch=='"' || ch != ';' || ch != ':') && ch1 == ' ' )
{
//fin3<<" ';
}
else if( !(int(ch)>=0 && int(ch)<=127) )
{
fin5<<"Char of ascii within range not added: "<<ch<<"\tits ascii value: "<<int(ch)<<endl;
}
else
{
fin7<<"Non ascii character caught(could be a -ve value also)\t"<<ch<<int(ch)<<endl;
}
}
return 0;
}
I have a similar code as the above written in python which gives me an otput which is again not readable and not editable
The code in python looks like this:
#!/usr/bin/python
# -*- coding: UTF-8 -*-
import sys
input_file=sys.argv[1]
output_file=sys.argv[2]
list1=[]
f=open(input_file)
for line in f:
line=line.strip()
#line=line.rstrip('.')
line=line.replace('.','')
line=line.replace(',','')
line=line.replace('#','')
line=line.replace('?','')
line=line.replace('!','')
line=line.replace('"','')
line=line.replace('।','')
line=line.replace('|','')
line = line.lower()
list1.append(line)
f.close()
f1=open(output_file,'w')
f1.write(' '.join(list1))
f1.close()
the file takes ip and op at runtime.. as:
python punc_remover.py acle5v1.txt acle5v1_op.txt
The output of this file is in "acle5v1_op.txt"
now after processing this particular output file is needed for further processing. This particular file "aclee5v1_op.txt" is the UNREADABLE Aand UNEDITABLE File that I am not being able to use for further processing. I need this for Word alignment in NLP. I tried readin this output with the following program
#include<iostream>
#include<fstream>
using namespace std;
ifstream fin1("acle5v1_op.txt");
ofstream fout1("chckread_acle5v1_op.txt");
ofstream fout2("chcknotread_acle5v1_op.txt");
int main()
{
char ch;
int flag = 0;
long int r = 0; long int nr = 0;
while(!(fin1))
{
fin1.get(ch);
if(ch)
{
flag = 1;
}
if(flag)
{
fout1<<ch;
flag = 0;
r++;
}
else
{
fout2<<"Char not been able to be read from source file\n";
nr++;
}
}
cout<<"Number of characters able to be read: "<<r;
cout<<endl<<"Number of characters not been able to be read: "<<nr;
return 0;
}
which prints the character if its readable and if not it doesn't print them but I observed the output of both the file is blank thus I could draw a conclusion that this file "acle5v1_op.txt" is UNREADABLE AND UNEDITABLE. Could you please help me on how to deal with this problem..
To tell you a bit about the statistics wrt the original input file "acle5v1.txt" file it has around 3441 lines in it and around 3 million characters in it.
Keeping in mind the number of characters in the file you editor might/might not be able to manage to open the file.. I was able to open the file in gedit of Fedora 10 which I am currently using .. This is just to notify you that opening with a particular editor was not actually an issue at least in my case...
Can I use scripting languages like Python and Perl to deal with this problem if Yes how? could please be specific on that regard as I am a novice to Perl and Python. Or could you please tell me how do I solve this problem using C++ itself.. Thank you...:) I am really looking forward to some help or guidance on how to go about this problem....
A:
(now i can reply, after taking some time editing the post. when posting, please use the preview and read the help !)
There is no problem Python cannot tackle... and this problam can definitely be solved using python.
After modifying a bit your python script (indentation is messed up !), i was able to process the content i could copy from your link, the output was fine (but still containing some punctuation like ':' and '()').
you say that after the first processing step, the output is unreadable and uneditable, but what is the content of the output file after processing ? did you try opening it in your editor and see what was in the file ? if this first step is not working, then correct your code at the first step and focus your question on this first step. try using a debugger to see where your code fails.
personally, i suspect an encoding problem: is your input file a pure ascii file ? or could it be that it is encoded in unicode ?
please note that a 3MB file is not much. if this is posing some problems to you, change your editor ! (try jEdit, epsilon, emacs, vi...)
|
Uneditable file and Unreadable(for further processing) file( WHY? ) after processing it through C++ Program
|
:) This might look to be a very long question to you I understand, but trust me on this its not long. I am not able to identify why after processing this text is not being able to be read and edited. I tried using the ord() function in python to check if the text contains any Unicode characters( non ascii characters) apart from the ascii ones.. I found quite a number of them.
I have a strong feeling that this could be due to the original text itself( The INPUT ).
Input-File: Just copy paste it into a file "acle5v1.txt"
The objective of this code below is to check for upper case characters and to convert it to lower case and also to remove all punctuations so that these words are taken for further processing for word alignment
#include<iostrea>
#include<fstream>
#include<ctype.h>
#include<cstring>
using namespace std;
ifstream fin2("acle5v1.txt");
ofstream fin3("acle5v1_op.txt");
ofstream fin4("chkcharadded.txt");
ofstream fin5("chkcharntadded.txt");
ofstream fin6("chkprintchar.txt");
ofstream fin7("chknonasci.txt");
ofstream fin8("nonprinchar.txt");
int main()
{
char ch,ch1;
fin2.seekg(0);
fin3.seekp(0);
int flag = 0;
while(!fin2.eof())
{
ch1=ch;
fin2.get(ch);
if (isprint(ch))// if the character is printable
flag = 1;
if(flag)
{
fin6<<"Printable character:\t"<<ch<<"\t"<<(int)ch<<endl;
flag = 0;
}
else
{
fin8<<"Non printable character caught:\t"<<ch<<"\t"<<int(ch)<<endl;
}
if( isalnum(ch) || ch == '@' || ch == ' ' )// checks for alpha numeric characters
{
fin4<<"char added: "<<ch<<"\tits ascii value: "<<int(ch)<<endl;
if(isupper(ch))
{
//tolower(ch);
fin3<<(char)tolower(ch);
}
else
{
fin3<<ch;
}
}
else if( ( ch=='\t' || ch=='.' || ch==',' || ch=='#' || ch=='?' || ch=='!' || ch=='"' || ch != ';' || ch != ':') && ch1 != ' ' )
{
fin3<<' ';
}
else if( (ch=='\t' || ch=='.' || ch==',' || ch=='#' || ch=='?' || ch=='!' || ch=='"' || ch != ';' || ch != ':') && ch1 == ' ' )
{
//fin3<<" ';
}
else if( !(int(ch)>=0 && int(ch)<=127) )
{
fin5<<"Char of ascii within range not added: "<<ch<<"\tits ascii value: "<<int(ch)<<endl;
}
else
{
fin7<<"Non ascii character caught(could be a -ve value also)\t"<<ch<<int(ch)<<endl;
}
}
return 0;
}
I have a similar code as the above written in python which gives me an otput which is again not readable and not editable
The code in python looks like this:
#!/usr/bin/python
# -*- coding: UTF-8 -*-
import sys
input_file=sys.argv[1]
output_file=sys.argv[2]
list1=[]
f=open(input_file)
for line in f:
line=line.strip()
#line=line.rstrip('.')
line=line.replace('.','')
line=line.replace(',','')
line=line.replace('#','')
line=line.replace('?','')
line=line.replace('!','')
line=line.replace('"','')
line=line.replace('।','')
line=line.replace('|','')
line = line.lower()
list1.append(line)
f.close()
f1=open(output_file,'w')
f1.write(' '.join(list1))
f1.close()
the file takes ip and op at runtime.. as:
python punc_remover.py acle5v1.txt acle5v1_op.txt
The output of this file is in "acle5v1_op.txt"
now after processing this particular output file is needed for further processing. This particular file "aclee5v1_op.txt" is the UNREADABLE Aand UNEDITABLE File that I am not being able to use for further processing. I need this for Word alignment in NLP. I tried readin this output with the following program
#include<iostream>
#include<fstream>
using namespace std;
ifstream fin1("acle5v1_op.txt");
ofstream fout1("chckread_acle5v1_op.txt");
ofstream fout2("chcknotread_acle5v1_op.txt");
int main()
{
char ch;
int flag = 0;
long int r = 0; long int nr = 0;
while(!(fin1))
{
fin1.get(ch);
if(ch)
{
flag = 1;
}
if(flag)
{
fout1<<ch;
flag = 0;
r++;
}
else
{
fout2<<"Char not been able to be read from source file\n";
nr++;
}
}
cout<<"Number of characters able to be read: "<<r;
cout<<endl<<"Number of characters not been able to be read: "<<nr;
return 0;
}
which prints the character if its readable and if not it doesn't print them but I observed the output of both the file is blank thus I could draw a conclusion that this file "acle5v1_op.txt" is UNREADABLE AND UNEDITABLE. Could you please help me on how to deal with this problem..
To tell you a bit about the statistics wrt the original input file "acle5v1.txt" file it has around 3441 lines in it and around 3 million characters in it.
Keeping in mind the number of characters in the file you editor might/might not be able to manage to open the file.. I was able to open the file in gedit of Fedora 10 which I am currently using .. This is just to notify you that opening with a particular editor was not actually an issue at least in my case...
Can I use scripting languages like Python and Perl to deal with this problem if Yes how? could please be specific on that regard as I am a novice to Perl and Python. Or could you please tell me how do I solve this problem using C++ itself.. Thank you...:) I am really looking forward to some help or guidance on how to go about this problem....
|
[
"(now i can reply, after taking some time editing the post. when posting, please use the preview and read the help !)\nThere is no problem Python cannot tackle... and this problam can definitely be solved using python.\nAfter modifying a bit your python script (indentation is messed up !), i was able to process the content i could copy from your link, the output was fine (but still containing some punctuation like ':' and '()'). \nyou say that after the first processing step, the output is unreadable and uneditable, but what is the content of the output file after processing ? did you try opening it in your editor and see what was in the file ? if this first step is not working, then correct your code at the first step and focus your question on this first step. try using a debugger to see where your code fails. \npersonally, i suspect an encoding problem: is your input file a pure ascii file ? or could it be that it is encoded in unicode ?\nplease note that a 3MB file is not much. if this is posing some problems to you, change your editor ! (try jEdit, epsilon, emacs, vi...)\n"
] |
[
2
] |
[] |
[] |
[
"c++",
"file",
"perl",
"python"
] |
stackoverflow_0002423380_c++_file_perl_python.txt
|
Q:
Python: installing multiprocessing
I need to import the multiprocessing module in Python 2.5.
I've followed the instructions here exactly: http://code.google.com/p/python-multiprocessing/wiki/Install
make and make test run without errors. I've also edited $PYTHONPATH to include the directory where the package is installed.
But 'import multiprocessing' still says: "ImportError: no module named multiprocessing".
What am I doing wrong? Is there some step missing from these instructions? I haven't installed a Python module before.
A:
Navigate to the directory containing the package then type:
python setup.py install
This info was contained in the INSTALL.txt file.
http://code.google.com/p/python-multiprocessing/source/browse/trunk/INSTALL.txt
|
Python: installing multiprocessing
|
I need to import the multiprocessing module in Python 2.5.
I've followed the instructions here exactly: http://code.google.com/p/python-multiprocessing/wiki/Install
make and make test run without errors. I've also edited $PYTHONPATH to include the directory where the package is installed.
But 'import multiprocessing' still says: "ImportError: no module named multiprocessing".
What am I doing wrong? Is there some step missing from these instructions? I haven't installed a Python module before.
|
[
"Navigate to the directory containing the package then type:\npython setup.py install\n\nThis info was contained in the INSTALL.txt file.\nhttp://code.google.com/p/python-multiprocessing/source/browse/trunk/INSTALL.txt\n"
] |
[
4
] |
[
"perhaps you can try:\nimport sys\nsys.path.append('/path/to/processingdotpylibs/')\nimport processing\n\n"
] |
[
-1
] |
[
"module",
"python"
] |
stackoverflow_0002424078_module_python.txt
|
Q:
manipulating list items python
line = "english: while french: pendant que spanish: mientras german: whrend "
words = line.split('\t')
for each in words:
each = each.rstrip()
print words
the string in 'line' is tab delimited but also features a single white space character after each translated word, so while split returns the list I'm after, each word annoyingly has a whitespace character at the end of the string.
in the loop I'm trying to go through the list and remove any trailing whitespaces in the strings but it doest seem to work, suggestions?
A:
Just line.split() could give you stripped words list.
Updating each inside the loop does not make any changes to the words list
Should be done like this
for i in range(len(words)):
words[i]=words[i].rstrip()
Or
words=map(str.rstrip,words)
See the map docs for details on map.
Or one liner with list comprehension
words=[x.rstrip() for x in line.split("\t")]
Or with regex .findall
words=re.findall("[^\t]+",line)
A:
words = line.split('\t')
words = [ i.rstrip() for i in words ]
A:
You can use a regular expression:
import re
words = re.split(r' *\t| +$', line)[:-1]
With this you define the possible sequence as the delimiter. It also allows more than one space because of the * operator (or no space at all).
EDIT: Fixed after Roger Pate pointed an error.
|
manipulating list items python
|
line = "english: while french: pendant que spanish: mientras german: whrend "
words = line.split('\t')
for each in words:
each = each.rstrip()
print words
the string in 'line' is tab delimited but also features a single white space character after each translated word, so while split returns the list I'm after, each word annoyingly has a whitespace character at the end of the string.
in the loop I'm trying to go through the list and remove any trailing whitespaces in the strings but it doest seem to work, suggestions?
|
[
"Just line.split() could give you stripped words list.\nUpdating each inside the loop does not make any changes to the words list\nShould be done like this\nfor i in range(len(words)):\n words[i]=words[i].rstrip()\n\nOr\nwords=map(str.rstrip,words)\n\nSee the map docs for details on map.\nOr one liner with list comprehension\nwords=[x.rstrip() for x in line.split(\"\\t\")]\n\nOr with regex .findall\nwords=re.findall(\"[^\\t]+\",line)\n\n",
"words = line.split('\\t')\nwords = [ i.rstrip() for i in words ]\n\n",
"You can use a regular expression:\nimport re\nwords = re.split(r' *\\t| +$', line)[:-1]\n\nWith this you define the possible sequence as the delimiter. It also allows more than one space because of the * operator (or no space at all).\nEDIT: Fixed after Roger Pate pointed an error.\n"
] |
[
1,
1,
0
] |
[] |
[] |
[
"python",
"string"
] |
stackoverflow_0002424226_python_string.txt
|
Q:
Append previous lines of a file based on a condition
I have a text file with a few 1000 lines of text in it. A sample is given below:
person1
person2
person3
person4
have paid
---------
person5
person6
person7
person9
person10
person11
have paid
---------
Each line starts with either "p" or "h" or "-". When "have paid" is encountered while reading the file, I want to append the previous two lines into a list so that I can differentiate people who have paid and people who have not paid. Any help?
Cheers,
Chav
A:
data=open("file").read().split("\n\n")
for rec in data:
if "have paid" in rec:
print rec.split("have paid")[0]
A:
Just iterate the file putting every line into a List or a hashtable. Then iterate the collection and for each match grab the two previous entries using the index of match -1 and -2.
A:
This parses correctly your example file:
with open('yourfile') as f:
result = {'have paid': [], '': []}
current = []
for line in f:
line = line.strip().strip('-')
if line in result:
result[line].extend(current)
current = []
else:
current.append(line)
print 'These have paid:', ','.join(result['have paid'])
print 'These have not paid:', ','.join(result[''])
Result:
These have paid: person3,person4,person10,person11
These have not paid: person1,person2,person5,person6,person7,person9
|
Append previous lines of a file based on a condition
|
I have a text file with a few 1000 lines of text in it. A sample is given below:
person1
person2
person3
person4
have paid
---------
person5
person6
person7
person9
person10
person11
have paid
---------
Each line starts with either "p" or "h" or "-". When "have paid" is encountered while reading the file, I want to append the previous two lines into a list so that I can differentiate people who have paid and people who have not paid. Any help?
Cheers,
Chav
|
[
"data=open(\"file\").read().split(\"\\n\\n\")\nfor rec in data:\n if \"have paid\" in rec:\n print rec.split(\"have paid\")[0]\n\n",
"Just iterate the file putting every line into a List or a hashtable. Then iterate the collection and for each match grab the two previous entries using the index of match -1 and -2.\n",
"This parses correctly your example file:\nwith open('yourfile') as f:\n result = {'have paid': [], '': []}\n current = []\n for line in f:\n line = line.strip().strip('-')\n if line in result:\n result[line].extend(current)\n current = []\n else:\n current.append(line)\n\nprint 'These have paid:', ','.join(result['have paid'])\nprint 'These have not paid:', ','.join(result[''])\n\nResult:\nThese have paid: person3,person4,person10,person11\nThese have not paid: person1,person2,person5,person6,person7,person9\n\n"
] |
[
1,
0,
0
] |
[] |
[] |
[
"append",
"list",
"python"
] |
stackoverflow_0002424411_append_list_python.txt
|
Q:
creating a frame to put pictures in it and saving back to database
I'm working on a mobile site and what I have to do is 1.create a picture frame 2.add to it pictures posted by users individually, then save each picture back to the database. Does anyone know how to go about this
A:
Start with this: http://docs.djangoproject.com/en/dev/ref/models/fields/#imagefield
If you need to have multiple images for user, you probably need similar model:
class ImageUpload(Model):
user = ForeignKey(User)
image = ImageField(..)
|
creating a frame to put pictures in it and saving back to database
|
I'm working on a mobile site and what I have to do is 1.create a picture frame 2.add to it pictures posted by users individually, then save each picture back to the database. Does anyone know how to go about this
|
[
"Start with this: http://docs.djangoproject.com/en/dev/ref/models/fields/#imagefield\nIf you need to have multiple images for user, you probably need similar model:\nclass ImageUpload(Model):\n user = ForeignKey(User)\n image = ImageField(..)\n\n"
] |
[
1
] |
[] |
[] |
[
"django",
"python",
"python_imaging_library"
] |
stackoverflow_0002423162_django_python_python_imaging_library.txt
|
Q:
How to get a list with elements that are contained in two other lists?
We have two lists:
a=['1','2','3','4']
b=['2','3','4','5']
How to get a list with elements that are contained in both lists:
a_and_b=['2','3','4']
and a list with elements that are contained only in one list, but not the other:
only_a=['1']
only_b=['5']
Yes, I can use cycles, but it's lame =)
A:
if order is not important
>>> a=['1','2','3','4']
>>> b=['2','3','4','5']
>>> set(a) & set(b)
set(['3', '2', '4'])
only a
>>> set(a).difference(b) # or set(a) - set(b)
set(['1'])
only b
>>> set(b).difference(a) # or set(b) - set(a)
set(['5'])
A:
Simply with the use of sets:
>>> a=['1','2','3','4']; b=['2','3','4','5']
>>> a = set(a)
>>> b = set(b)
>>> a & b
set(['3', '2', '4'])
>>> a - b
set(['1'])
>>> b - a
set(['5'])
>>>
|
How to get a list with elements that are contained in two other lists?
|
We have two lists:
a=['1','2','3','4']
b=['2','3','4','5']
How to get a list with elements that are contained in both lists:
a_and_b=['2','3','4']
and a list with elements that are contained only in one list, but not the other:
only_a=['1']
only_b=['5']
Yes, I can use cycles, but it's lame =)
|
[
"if order is not important\n>>> a=['1','2','3','4']\n>>> b=['2','3','4','5']\n>>> set(a) & set(b)\nset(['3', '2', '4'])\n\nonly a\n>>> set(a).difference(b) # or set(a) - set(b)\nset(['1'])\n\nonly b\n>>> set(b).difference(a) # or set(b) - set(a)\nset(['5'])\n\n",
"Simply with the use of sets:\n>>> a=['1','2','3','4']; b=['2','3','4','5']\n>>> a = set(a)\n>>> b = set(b)\n>>> a & b\nset(['3', '2', '4'])\n>>> a - b\nset(['1'])\n>>> b - a\nset(['5'])\n>>>\n\n"
] |
[
8,
5
] |
[] |
[] |
[
"python"
] |
stackoverflow_0002424700_python.txt
|
Q:
How to save django FileField to user folder?
I've got a model like this
def upload_location(instance, filename):
return 'validate/%s/builds/%s' % (get_current_user(), filename)
class MidletPair(models.Model):
jad_file = models.FileField(upload_to = upload_location)
jar_file = models.FileField(upload_to = upload_location)
upload_to=tempfile.gettempdir()
How can I get the current user in upload_location()... ?
Side note: Looking up django stuff is confusing as theres a lot of pre-1.0 stuff around on the net.
A:
The current user is stored in the request object, and you can't get that in a model method unless you pass it in from elsewhere - which you can't do in the upload_to function.
So you'll need to approach this in a different manner - I would suggest doing it at the form level. You can pass the request object into the form's __init__ method and store it in an instance attribute, where you can get to it in a custom upload handler. For documentation on upload handlers, look here.
A:
If you added a user field to the model, and have that attribute set before you performed an upload, then you could get the user in to your upload_location function via the instance attribute.
A:
First, don't search the net for Django help. Search here only: http://docs.djangoproject.com/en/dev/
Second, the current user is part of Authentication.
http://docs.djangoproject.com/en/dev/topics/auth/#topics-auth
The user is recorded in the request. request.user
|
How to save django FileField to user folder?
|
I've got a model like this
def upload_location(instance, filename):
return 'validate/%s/builds/%s' % (get_current_user(), filename)
class MidletPair(models.Model):
jad_file = models.FileField(upload_to = upload_location)
jar_file = models.FileField(upload_to = upload_location)
upload_to=tempfile.gettempdir()
How can I get the current user in upload_location()... ?
Side note: Looking up django stuff is confusing as theres a lot of pre-1.0 stuff around on the net.
|
[
"The current user is stored in the request object, and you can't get that in a model method unless you pass it in from elsewhere - which you can't do in the upload_to function.\nSo you'll need to approach this in a different manner - I would suggest doing it at the form level. You can pass the request object into the form's __init__ method and store it in an instance attribute, where you can get to it in a custom upload handler. For documentation on upload handlers, look here.\n",
"If you added a user field to the model, and have that attribute set before you performed an upload, then you could get the user in to your upload_location function via the instance attribute.\n",
"First, don't search the net for Django help. Search here only: http://docs.djangoproject.com/en/dev/\nSecond, the current user is part of Authentication.\nhttp://docs.djangoproject.com/en/dev/topics/auth/#topics-auth\nThe user is recorded in the request. request.user\n"
] |
[
8,
5,
4
] |
[] |
[] |
[
"django",
"django_models",
"python",
"upload"
] |
stackoverflow_0000858213_django_django_models_python_upload.txt
|
Q:
Testing for Inactivity in Python on Mac
Is there a way to test, using Python, how long the system has been idle on Mac? Or, failing that, even if the system is currently idle?
Answer
Using the information from the accepted solution, here is an ugly but functional and fairly efficient function for the job:
from subprocess import *
def idleTime():
'''Return idle time in seconds'''
# Get the output from
# ioreg -c IOHIDSystem
s = Popen(["ioreg", "-c", "IOHIDSystem"], stdout=PIPE).communicate()[0]
lines = s.split('\n')
raw_line = ''
for line in lines:
if line.find('HIDIdleTime') > 0:
raw_line = line
break
nano_seconds = long(raw_line.split('=')[-1])
seconds = nano_seconds/10**9
return seconds
A:
Untested (for now), but according to this thread you could parse the output of
ioreg -c IOHIDSystem
|
Testing for Inactivity in Python on Mac
|
Is there a way to test, using Python, how long the system has been idle on Mac? Or, failing that, even if the system is currently idle?
Answer
Using the information from the accepted solution, here is an ugly but functional and fairly efficient function for the job:
from subprocess import *
def idleTime():
'''Return idle time in seconds'''
# Get the output from
# ioreg -c IOHIDSystem
s = Popen(["ioreg", "-c", "IOHIDSystem"], stdout=PIPE).communicate()[0]
lines = s.split('\n')
raw_line = ''
for line in lines:
if line.find('HIDIdleTime') > 0:
raw_line = line
break
nano_seconds = long(raw_line.split('=')[-1])
seconds = nano_seconds/10**9
return seconds
|
[
"Untested (for now), but according to this thread you could parse the output of \n\nioreg -c IOHIDSystem\n\n"
] |
[
2
] |
[] |
[] |
[
"macos",
"python"
] |
stackoverflow_0002425087_macos_python.txt
|
Q:
Does the MySQLdb module support prepared statements?
Does MySQLdb support server-side prepared statements? I can't figure this out from its manual.
A:
Check the MySQLdb Package Comments:
"Parameterization" is done in MySQLdb by escaping strings and then blindly interpolating them into the query, instead of using the MYSQL_STMT API. As a result unicode strings have to go through two intermediate representations (encoded string, escaped encoded string) before they're received by the database.
So the answer is: No, it doesn't.
A:
It has some kind of parameterization, yes.
Even then, I advise you switch to oursql. It brings a lot of advantages over MySQLdb:
oursql has real parameterization.
oursql allows text or binary data to be streamed into the database and streamed out of the database, instead of requiring everything to be buffered in the client.
oursql can both insert rows lazily and fetch rows lazily.
oursql has unicode support on by default.
oursql supports python 2.4 through 2.7 without any deprecation warnings on 2.6+ (see PEP 218) and without completely failing on 2.7 (see PEP 328).
oursql is licensed under the BSD license.
|
Does the MySQLdb module support prepared statements?
|
Does MySQLdb support server-side prepared statements? I can't figure this out from its manual.
|
[
"Check the MySQLdb Package Comments:\n\n\"Parameterization\" is done in MySQLdb by escaping strings and then blindly interpolating them into the query, instead of using the MYSQL_STMT API. As a result unicode strings have to go through two intermediate representations (encoded string, escaped encoded string) before they're received by the database.\n\nSo the answer is: No, it doesn't.\n",
"It has some kind of parameterization, yes.\nEven then, I advise you switch to oursql. It brings a lot of advantages over MySQLdb:\n\noursql has real parameterization.\noursql allows text or binary data to be streamed into the database and streamed out of the database, instead of requiring everything to be buffered in the client.\noursql can both insert rows lazily and fetch rows lazily.\noursql has unicode support on by default.\noursql supports python 2.4 through 2.7 without any deprecation warnings on 2.6+ (see PEP 218) and without completely failing on 2.7 (see PEP 328).\noursql is licensed under the BSD license.\n\n"
] |
[
18,
12
] |
[] |
[] |
[
"mysql",
"prepared_statement",
"python"
] |
stackoverflow_0002424531_mysql_prepared_statement_python.txt
|
Q:
Python: PSP & HTML tables
I have a python psp page code is shown below. Currently it only prints out the characters in single rows of 60, with the character count in the left column.
<table>
<%
s = ''.join(aa[i] for i in table if i in aa)
for i in range(0, len(s), 60):
req.write('<tr><td><TT>%04d</td><td><TT>%s</TT></td></tr>' % (i+1, s[i:i+60]));
#end
%>
</table>
The problem i am having trouble is with out putting each character in an individual cell rather than a cell of 60 characters. I've tried doing this with the code below, but it prints out a line of 60 characters 60 times.
<table>
<%
s = ''.join(aa[i] for i in table if i in aa)
for i in range(0, len(s), 60):
req.write('<tr><td>%04d</td>' % (i+1));
for k in s:
req.write('<td>%s</td></tr>' % s[i:i+60]);
#end
%>
</table>
A:
for k in s[i:i+60]:
req.write('<td>%s</td>' % k)
req.write('</tr>')
|
Python: PSP & HTML tables
|
I have a python psp page code is shown below. Currently it only prints out the characters in single rows of 60, with the character count in the left column.
<table>
<%
s = ''.join(aa[i] for i in table if i in aa)
for i in range(0, len(s), 60):
req.write('<tr><td><TT>%04d</td><td><TT>%s</TT></td></tr>' % (i+1, s[i:i+60]));
#end
%>
</table>
The problem i am having trouble is with out putting each character in an individual cell rather than a cell of 60 characters. I've tried doing this with the code below, but it prints out a line of 60 characters 60 times.
<table>
<%
s = ''.join(aa[i] for i in table if i in aa)
for i in range(0, len(s), 60):
req.write('<tr><td>%04d</td>' % (i+1));
for k in s:
req.write('<td>%s</td></tr>' % s[i:i+60]);
#end
%>
</table>
|
[
"for k in s[i:i+60]:\n req.write('<td>%s</td>' % k)\nreq.write('</tr>')\n\n"
] |
[
0
] |
[] |
[] |
[
"html",
"html_table",
"python",
"python_server_pages"
] |
stackoverflow_0002425787_html_html_table_python_python_server_pages.txt
|
Q:
django forms MultipleChoiceField reverts to original value on save
I have wrote a custom MultipleChoiceField. I have everything working ok but when I submit the form the selected values go back to the original choices even though the form validates ok.
my code looks something like this:
class ProgrammeField(forms.MultipleChoiceField):
widget = widgets.SelectMultiple
class ProgrammeForm(forms.Form):
programmes = ProgrammeField(required=False)
def __init__(self, user, *args, **kwargs):
self.fields['programmes'].choices = Mymodel.objects.all()
self.fields['programmes'].initial = Mymodel.objects.filter(created=user)
view.py
if request.method == 'POST':
form = ProgrammeForm(user=request.user, data=request.POST)
if form.is_valid():
form.save()
form = ProgrammeForm(request.user)
return render_to_response(form.html', {'form': form })
I haven't included all the other fields etc. but this is basically the code I am having trouble with. Anyone have any ideas how to get it to display the new values after the form has been submitted or why it is going back to the original values
Thanks
A:
You're always passing back an unbound instance of the form, try this:
view.py
if request.method == 'POST':
form = ProgrammeForm(user=request.user, data=request.POST)
if form.is_valid():
form.save()
else: ##this is the changge
form = ProgrammeForm(request.user)
return render_to_response('form.html', {'form': form })
|
django forms MultipleChoiceField reverts to original value on save
|
I have wrote a custom MultipleChoiceField. I have everything working ok but when I submit the form the selected values go back to the original choices even though the form validates ok.
my code looks something like this:
class ProgrammeField(forms.MultipleChoiceField):
widget = widgets.SelectMultiple
class ProgrammeForm(forms.Form):
programmes = ProgrammeField(required=False)
def __init__(self, user, *args, **kwargs):
self.fields['programmes'].choices = Mymodel.objects.all()
self.fields['programmes'].initial = Mymodel.objects.filter(created=user)
view.py
if request.method == 'POST':
form = ProgrammeForm(user=request.user, data=request.POST)
if form.is_valid():
form.save()
form = ProgrammeForm(request.user)
return render_to_response(form.html', {'form': form })
I haven't included all the other fields etc. but this is basically the code I am having trouble with. Anyone have any ideas how to get it to display the new values after the form has been submitted or why it is going back to the original values
Thanks
|
[
"You're always passing back an unbound instance of the form, try this:\nview.py\nif request.method == 'POST':\n form = ProgrammeForm(user=request.user, data=request.POST)\n if form.is_valid():\n form.save()\nelse: ##this is the changge\n form = ProgrammeForm(request.user)\nreturn render_to_response('form.html', {'form': form }) \n\n"
] |
[
3
] |
[] |
[] |
[
"django",
"django_forms",
"python"
] |
stackoverflow_0002425668_django_django_forms_python.txt
|
Q:
Django deployment. Error loading MySQLdb module. Trouble reading/writing from /tmp directory
I'm deploying my Django app to another host/server using mod_wsgi and MySQLdb. Right now, I'm getting a 500 error with the following log:
ImproperlyConfigured: Error loading MySQLdb module: /tmp/MySQL_python-1.2.3c1-py2.4-linux-i686.egg-tmp/_mysql.so: failed to map segment from shared object: Operation not permitted
Did some research and it looks like the /tmp directory is non-exacutable. Found this: http://bit.ly/ckoIep
Can anyone shed some light on this, and possibly recommend a solution?
A:
Point the WSGIPythonEggs directive to a writable, executable path.
|
Django deployment. Error loading MySQLdb module. Trouble reading/writing from /tmp directory
|
I'm deploying my Django app to another host/server using mod_wsgi and MySQLdb. Right now, I'm getting a 500 error with the following log:
ImproperlyConfigured: Error loading MySQLdb module: /tmp/MySQL_python-1.2.3c1-py2.4-linux-i686.egg-tmp/_mysql.so: failed to map segment from shared object: Operation not permitted
Did some research and it looks like the /tmp directory is non-exacutable. Found this: http://bit.ly/ckoIep
Can anyone shed some light on this, and possibly recommend a solution?
|
[
"Point the WSGIPythonEggs directive to a writable, executable path.\n"
] |
[
1
] |
[] |
[] |
[
"apache",
"django",
"mysql",
"python"
] |
stackoverflow_0002425715_apache_django_mysql_python.txt
|
Q:
Requesting a JavaScript property in Python (GAE)
I'm currently making an iphone web app based on Google App Engine (python). I need to check if the user is browsing not through safari but by the home screen. I can check this with an read-only 'window.navigator.standalone' Boolean JavaScript property as read on: https://developer.apple.com/library/archive/documentation/AppleApplications/Reference/SafariHTMLRef/Articles/MetaTags.html
How can I read this Boolean in Python? I guess by self.request.headers.get() or something but it won't work.
A:
According to this page on HTTP headers and MobileSafari, you can tell if the user has launched your site from their home screen by testing to see whether the string Safari is found in the HTTP_USER_AGENT header. If it's missing, they are browsing from the home screen.
This seems awfully fragile (and doesn't appear to be documented outside of a couple of non-Apple blog posts), so it might not be the best thing to rely on.
|
Requesting a JavaScript property in Python (GAE)
|
I'm currently making an iphone web app based on Google App Engine (python). I need to check if the user is browsing not through safari but by the home screen. I can check this with an read-only 'window.navigator.standalone' Boolean JavaScript property as read on: https://developer.apple.com/library/archive/documentation/AppleApplications/Reference/SafariHTMLRef/Articles/MetaTags.html
How can I read this Boolean in Python? I guess by self.request.headers.get() or something but it won't work.
|
[
"According to this page on HTTP headers and MobileSafari, you can tell if the user has launched your site from their home screen by testing to see whether the string Safari is found in the HTTP_USER_AGENT header. If it's missing, they are browsing from the home screen.\nThis seems awfully fragile (and doesn't appear to be documented outside of a couple of non-Apple blog posts), so it might not be the best thing to rely on.\n"
] |
[
2
] |
[] |
[] |
[
"google_app_engine",
"iphone",
"javascript",
"python"
] |
stackoverflow_0002426232_google_app_engine_iphone_javascript_python.txt
|
Q:
Python: list assignment out of range
This module is part of a simple todo app I made with Python...
def deleteitem():
showlist()
get_item = int(raw_input( "\n Enter number of item to delete: \n"))
f = open('todo.txt')
lines = f.readlines()
f.close()
lines[get_item] = ""
f = open('todo.txt','w')
f.writelines(lines)
f.close()
showlist()
The number of lines in f obviously changes as items are added to the list... Problem here is that for example if a user enters '10' when there are only 9 lines in the file ( or anything else not in range) , it exits as expected with :
IndexError: list assignment index out of range
What can I add to the module so as to have it prompt user to enter an item within the range? I am assuming maybe a Try block ... Or is there a way to catch an exception.. I am guessing there is an easy way to do this...
A:
Either catch IndexError when indexing or check the len() of the list beforehand.
A:
First read the file, and then ask user in a loop, until the answer is acceptable:
while True:
get_item = int(raw_input( "\n Enter number of item to delete: \n"))
if get_item >=0 and get_item < len(lines):
break
That will, of course, break when the file is empty and doesn't give any hint about the acceptable values to the user. But let's keep some exercise for you.
A:
Judicious changes to your current code:
def deleteitem():
showlist()
with open("todo.txt") as f:
lines = f.readlines()
if len(lines) == 0: # completely empty file
return # handle appropriately
prompt = "Enter number to delete (1-%d), or 0 to abort: " % len(lines)
while True:
input = raw_input(prompt)
try:
input = int(input, 10)
except ValueError:
print "Invalid input."
else:
if 0 <= input <= len(lines):
break
print "Input out of range."
if input == 0:
return
input -= 1 # adjust from [1,len] to [0,len)
#del lines[input] # if you want to remove that line completely
lines[input] = "\n" # or just make that line blank (what you had)
with open("todo.txt", "w") as f:
f.writelines(lines)
showlist()
A:
def deleteitem():
showlist()
get_item = int(raw_input( "\n Enter number of item to delete: \n"))
f = open('todo.txt')
lines = f.readlines()
f.close()
try:
lines[get_item] = ""
except Exception,err:
print err
f = open('todo.txt','w')
f.writelines(lines)
f.close()
showlist()
A:
Try something like this:
def deleteitem():
showlist()
f = open('todo.txt')
lines = f.readlines()
f.close()
if len(lines) == 0:
print "File is empty!"
return False
print "File has %d items\n" % len(lines)
item = 0
while item < len(lines):
item = raw_input( "\n Enter number of item to delete(0-%d): \n" % len(lines))
item = int(item) # because of the width of the code
f = open('todo.txt','w')
f.write(lines[0:item-1])
f.write(lines[item::])
f.close()
showlist()
A:
For what it's worth.... I'll put the code to my todo.py program here... It's just something I run from a Terminal in OS X to keep control of stuff I need to do at work...I am sure it's horribly un-pythonic,inefficient and everything else...but maybe it'll be of use to some one who stumbles across this thread :
from __future__ import with_statement
import sys
import os
import fileinput
os.system('clear')
print ("############## TO DO LIST ############")
print ("############## ############")
def showlist():
os.system('clear')
print ("############ Current To Do List ######")
print ("########################################")
get_list = open('todo.txt')
entire_list = get_list.readlines()
for i in range (len(entire_list)):
print i, entire_list[i]
get_list.close()
print ("########################################")
print ("########################################")
def appendlist():
print ("#######################################")
print ("#######################################")
addtolist = str( raw_input("Enter new item: \n"))
thelist = open('todo.txt', 'a')
thelist.write(str(addtolist))
thelist.write(str('\n'))
thelist.close()
showlist()
def deleteitem():
showlist()
with open("todo.txt") as f:
lines = f.readlines()
if len(lines) == 0:
return
prompt = "Enter number to delete or '0' to abort: "
while True:
input = raw_input(prompt)
try:
input = int(input, 10)
except ValueError:
print "Invalid input."
else:
if 0 <= input <= len(lines):
break
print "Input out of range."
if input == 0:
return
lines[input] = ""
with open("todo.txt", "w") as f:
f.writelines(lines)
showlist()
while True:
askme = raw_input("\nDo you want to:\n(S)ee list\n(A)ppend list\n(D)elte from list\n(Q)Quit?\n")
print str('\n')
if askme == "S":
showlist()
elif askme == "A":
appendlist()
elif askme == "D":
deleteitem()
elif askme == "Q":
sys.exit()
else:
print ("Try again?")
print ("#######################################")
print ("#######################################")
|
Python: list assignment out of range
|
This module is part of a simple todo app I made with Python...
def deleteitem():
showlist()
get_item = int(raw_input( "\n Enter number of item to delete: \n"))
f = open('todo.txt')
lines = f.readlines()
f.close()
lines[get_item] = ""
f = open('todo.txt','w')
f.writelines(lines)
f.close()
showlist()
The number of lines in f obviously changes as items are added to the list... Problem here is that for example if a user enters '10' when there are only 9 lines in the file ( or anything else not in range) , it exits as expected with :
IndexError: list assignment index out of range
What can I add to the module so as to have it prompt user to enter an item within the range? I am assuming maybe a Try block ... Or is there a way to catch an exception.. I am guessing there is an easy way to do this...
|
[
"Either catch IndexError when indexing or check the len() of the list beforehand.\n",
"First read the file, and then ask user in a loop, until the answer is acceptable:\nwhile True:\n get_item = int(raw_input( \"\\n Enter number of item to delete: \\n\"))\n if get_item >=0 and get_item < len(lines):\n break\n\nThat will, of course, break when the file is empty and doesn't give any hint about the acceptable values to the user. But let's keep some exercise for you.\n",
"Judicious changes to your current code:\ndef deleteitem():\n showlist()\n\n with open(\"todo.txt\") as f:\n lines = f.readlines()\n if len(lines) == 0: # completely empty file\n return # handle appropriately\n prompt = \"Enter number to delete (1-%d), or 0 to abort: \" % len(lines)\n while True:\n input = raw_input(prompt)\n try:\n input = int(input, 10)\n except ValueError:\n print \"Invalid input.\"\n else:\n if 0 <= input <= len(lines):\n break\n print \"Input out of range.\"\n if input == 0:\n return\n input -= 1 # adjust from [1,len] to [0,len)\n\n #del lines[input] # if you want to remove that line completely\n lines[input] = \"\\n\" # or just make that line blank (what you had)\n\n with open(\"todo.txt\", \"w\") as f:\n f.writelines(lines)\n\n showlist()\n\n",
"def deleteitem():\n showlist()\n get_item = int(raw_input( \"\\n Enter number of item to delete: \\n\"))\n f = open('todo.txt')\n lines = f.readlines()\n f.close()\n try:\n lines[get_item] = \"\"\n except Exception,err: \n print err\n f = open('todo.txt','w')\n f.writelines(lines)\n f.close()\n showlist()\n\n",
"Try something like this:\ndef deleteitem():\n\nshowlist()\nf = open('todo.txt')\nlines = f.readlines()\nf.close()\nif len(lines) == 0:\n print \"File is empty!\"\n return False\nprint \"File has %d items\\n\" % len(lines)\nitem = 0\nwhile item < len(lines):\n item = raw_input( \"\\n Enter number of item to delete(0-%d): \\n\" % len(lines))\n item = int(item) # because of the width of the code\nf = open('todo.txt','w')\nf.write(lines[0:item-1])\nf.write(lines[item::])\nf.close()\nshowlist()\n\n",
"For what it's worth.... I'll put the code to my todo.py program here... It's just something I run from a Terminal in OS X to keep control of stuff I need to do at work...I am sure it's horribly un-pythonic,inefficient and everything else...but maybe it'll be of use to some one who stumbles across this thread : \nfrom __future__ import with_statement\nimport sys\nimport os\nimport fileinput\n\nos.system('clear')\n\nprint (\"############## TO DO LIST ############\")\nprint (\"############## ############\")\n\ndef showlist():\n os.system('clear')\n print (\"############ Current To Do List ######\")\n print (\"########################################\")\n\n get_list = open('todo.txt')\n entire_list = get_list.readlines()\n for i in range (len(entire_list)):\n print i, entire_list[i]\n get_list.close()\n print (\"########################################\")\n print (\"########################################\")\n\ndef appendlist():\n print (\"#######################################\")\n print (\"#######################################\")\n\n\n addtolist = str( raw_input(\"Enter new item: \\n\"))\n thelist = open('todo.txt', 'a')\n thelist.write(str(addtolist))\n thelist.write(str('\\n'))\n thelist.close() \n showlist()\n\n\ndef deleteitem():\n showlist()\n\n with open(\"todo.txt\") as f:\n lines = f.readlines()\n if len(lines) == 0: \n return \n prompt = \"Enter number to delete or '0' to abort: \" \n while True:\n input = raw_input(prompt)\n try:\n input = int(input, 10)\n except ValueError:\n print \"Invalid input.\"\n else:\n if 0 <= input <= len(lines):\n break\n print \"Input out of range.\"\n if input == 0:\n return\n\n lines[input] = \"\" \n\n with open(\"todo.txt\", \"w\") as f:\n f.writelines(lines)\n\n showlist()\n\nwhile True:\n\n askme = raw_input(\"\\nDo you want to:\\n(S)ee list\\n(A)ppend list\\n(D)elte from list\\n(Q)Quit?\\n\")\n print str('\\n')\n\n if askme == \"S\":\n showlist()\n elif askme == \"A\":\n appendlist()\n elif askme == \"D\":\n deleteitem()\n\n elif askme == \"Q\":\n sys.exit()\n else: \n print (\"Try again?\")\n\nprint (\"#######################################\")\nprint (\"#######################################\")\n\n"
] |
[
3,
3,
1,
0,
0,
0
] |
[] |
[] |
[
"error_handling",
"list",
"python"
] |
stackoverflow_0002425543_error_handling_list_python.txt
|
Q:
Python server pages, tables and lists
I am using MySQL and python server pages to show the data in a database. In the db I have selected this data: a list x =[1, 61, 121, 181, 241, 301] and a list of lists z = (['a','b'],['c','d'],['e','f'],['g','h'],['i','j'],['k','l']) and I would like to put these in a table to look like:
001 a b
061 c d
121 e f
181 g h
241 i j
301 k l
Am I right in thinking that I would have to use two 'for loops' to do this? Here is what I am using:
rows = cur.fetchall()
z=[]
for row in rows:
z.append(dict[row[1]])
x=[]
for i in range(1, len(rows),60):
x.append(i)
for i in range(0,len(z), 60):
req.write("<tr><td>%s</td><td>%s</td></tr>" %(str(x[i:i+60]), str(z[i:i+60])))
And this is what I'm outputting:
[1, 61, 121, 181, 241, 301] a b
c d
e f
g h
i j
k l
Any help would be massively appreciated!
A:
for index, (a, b) in zip(x, z):
print(index, a, b) # format as appropriate
Also, your creation of z list might be improved upon:
z = [dic[row[1]] for row in rows] # calling variable dict shadows built-in
x can either be created as range(1, len(rows), 60)
A:
You're doing the "step by 60" twice on x -- you're building x to have exactly the list you see, already stepped by 60 at a time, and then getting its first 60 items (it doesn't have that many, so you're getting all items in fact) with the str(x[i:i+60]) in the second loop.
Change the second loop to, e.g.:
for i in range(0,len(z), 60):
req.write("<tr><td>%s</td><td>%s</td></tr>" %(x[i//60], z[i:i+60]))
I've also eliminated the redundant str calls since the %s formatting already does that internally.
A:
#Following code will work in Python 3.x
x =[1, 61, 121, 181, 241, 301]
z = (['a','b'],['c','d'],['e','f'],['g','h'],['i','j'],['k','l'])
for i in zip(x, z):
print("{0:03} {1} {2}".format(i[0], i[1][0], i[1][1]))
A:
Try to use iterators instead of arrays + indekses. Foe example use xrange instead of range etc. It might be beneficial (I don't know MySQL capabilities) to use 2 cursors instead of caching everything in table.
There is zip function which takes two iteratable - like two arrays.
Example code:
for (xe, ze) in zip (x, z):
req.write("<tr><td>%s</td><td>%s</td></tr>" % (xe, ' '.join(ze))
|
Python server pages, tables and lists
|
I am using MySQL and python server pages to show the data in a database. In the db I have selected this data: a list x =[1, 61, 121, 181, 241, 301] and a list of lists z = (['a','b'],['c','d'],['e','f'],['g','h'],['i','j'],['k','l']) and I would like to put these in a table to look like:
001 a b
061 c d
121 e f
181 g h
241 i j
301 k l
Am I right in thinking that I would have to use two 'for loops' to do this? Here is what I am using:
rows = cur.fetchall()
z=[]
for row in rows:
z.append(dict[row[1]])
x=[]
for i in range(1, len(rows),60):
x.append(i)
for i in range(0,len(z), 60):
req.write("<tr><td>%s</td><td>%s</td></tr>" %(str(x[i:i+60]), str(z[i:i+60])))
And this is what I'm outputting:
[1, 61, 121, 181, 241, 301] a b
c d
e f
g h
i j
k l
Any help would be massively appreciated!
|
[
"for index, (a, b) in zip(x, z):\n print(index, a, b) # format as appropriate\n\nAlso, your creation of z list might be improved upon:\nz = [dic[row[1]] for row in rows] # calling variable dict shadows built-in\n\nx can either be created as range(1, len(rows), 60)\n",
"You're doing the \"step by 60\" twice on x -- you're building x to have exactly the list you see, already stepped by 60 at a time, and then getting its first 60 items (it doesn't have that many, so you're getting all items in fact) with the str(x[i:i+60]) in the second loop.\nChange the second loop to, e.g.:\nfor i in range(0,len(z), 60):\n req.write(\"<tr><td>%s</td><td>%s</td></tr>\" %(x[i//60], z[i:i+60]))\n\nI've also eliminated the redundant str calls since the %s formatting already does that internally.\n",
"#Following code will work in Python 3.x\n\nx =[1, 61, 121, 181, 241, 301]\nz = (['a','b'],['c','d'],['e','f'],['g','h'],['i','j'],['k','l'])\n\nfor i in zip(x, z):\n print(\"{0:03} {1} {2}\".format(i[0], i[1][0], i[1][1]))\n\n",
"\nTry to use iterators instead of arrays + indekses. Foe example use xrange instead of range etc. It might be beneficial (I don't know MySQL capabilities) to use 2 cursors instead of caching everything in table.\nThere is zip function which takes two iteratable - like two arrays.\n\nExample code:\nfor (xe, ze) in zip (x, z):\n req.write(\"<tr><td>%s</td><td>%s</td></tr>\" % (xe, ' '.join(ze))\n\n"
] |
[
1,
1,
0,
0
] |
[] |
[] |
[
"python",
"python_server_pages"
] |
stackoverflow_0002426401_python_python_server_pages.txt
|
Q:
Python: For loop problem
I have a simple for loop problem, when i run the code below it prints out series of 'blue green' sequences then a series of 'green' sequences. I want the output to be; if row[4] is equal to 1 to print blue else print green.
for row in rows:
for i in `row[4]`:
if i ==`1`:
print 'blue '
else:
print 'green '
Any help would be grateful
thanks
Yas
A:
Try something like this:
for i in xrange(len(rows)):
if rows[i] == '1':
print "blue"
else:
print "green"
Or, since you don't actually seem to care about the index, you can of course do it more cleanly:
for r in rows:
if r == "1":
print "blue"
else:
print "green"
A:
the enumerate() function will iterate and give you the index as well as the value:
for i, v in enumerate(rows):
if i == 4:
print "blue"
else:
print "green"
if you want to print blue on every fourth line else green do this:
for i, v in enumerate(rows):
if i % 4 == 0:
print "blue"
else:
print "green"
A:
if rows[4] == 1:
print 'blue'
else:
print 'green'
|
Python: For loop problem
|
I have a simple for loop problem, when i run the code below it prints out series of 'blue green' sequences then a series of 'green' sequences. I want the output to be; if row[4] is equal to 1 to print blue else print green.
for row in rows:
for i in `row[4]`:
if i ==`1`:
print 'blue '
else:
print 'green '
Any help would be grateful
thanks
Yas
|
[
"Try something like this:\nfor i in xrange(len(rows)):\n if rows[i] == '1':\n print \"blue\"\n else:\n print \"green\"\n\nOr, since you don't actually seem to care about the index, you can of course do it more cleanly:\nfor r in rows:\n if r == \"1\":\n print \"blue\"\n else:\n print \"green\"\n\n",
"the enumerate() function will iterate and give you the index as well as the value:\nfor i, v in enumerate(rows):\n if i == 4:\n print \"blue\"\n else:\n print \"green\"\n\nif you want to print blue on every fourth line else green do this:\nfor i, v in enumerate(rows):\n if i % 4 == 0:\n print \"blue\"\n else:\n print \"green\"\n\n",
"if rows[4] == 1:\n print 'blue'\nelse:\n print 'green'\n\n"
] |
[
3,
2,
1
] |
[] |
[] |
[
"for_loop",
"loops",
"python"
] |
stackoverflow_0002426719_for_loop_loops_python.txt
|
Q:
Create a user-group in linux using python
I want to create a user group using python on CentOS system. When I say 'using python' I mean I don't want to do something like os.system and give the unix command to create a new group. I would like to know if there is any python module that deals with this.
Searching on the net did not reveal much about what I want, except for python user groups.. so I had to ask this.
I learned about the grp module by searching here on SO, but couldn't find anything about creating a group.
EDIT: I dont know if I have to start a new question for this, but I would also like to know how to add (existing) users to the newly created group.
Any help appreciated.
Thank you.
A:
I don't know of a python module to do it, but the /etc/group and /etc/gshadow format is pretty standard, so if you wanted you could just open the files, parse their current contents and then add the new group if necessary.
Before you go doing this, consider:
What happens if you try to add a group that already exists on the system
What happens when multiple instances of your program try to add a group at the same time
What happens to your code when an incompatible change is made to the group format a couple releases down the line
NIS, LDAP, Kerberos, ...
If you're not willing to deal with these kinds of problems, just use the subprocess module and run groupadd. It will be way less likely to break your customers machines.
Another thing you could do that would be less fragile than writing your own would be to wrap the code in groupadd.c (in the shadow package) in Python and do it that way. I don't see this buying you much versus just exec'ing it, though, and it would add more complexity and fragility to your build.
A:
I think you should use the commandline programs from your program, a lot of care has gone into making sure that they don't break the groups file if something goes wrong.
However the file format is quite straight forward to write something yourself if you choose to go that way
A:
There are no library calls for creating a group. This is because there's really no such thing as creating a group. A GID is simply a number assigned to a process or a file. All these numbers exist already - there is nothing you need to do to start using a GID. With the appropriate privileges, you can call chown(2) to set the GID of a file to any number, or setgid(2) to set the GID of the current process (there's a little more to it than that, with effective IDs, supplementary IDs, etc).
Giving a name to a GID is done by an entry in /etc/group on basic Unix/Linux/POSIX systems, but that's really just a convention adhered to by the Unix/Linux/POSIX userland tools. Other network-based directories also exist, as mentioned by Jack Lloyd.
The man page group(5) describes the format of the /etc/group file, but it is not recommended that you write to it directly. Your distribution will have policies on how unnamed GIDs are allocated, such as reserving certain spaces for different purposes (fixed system groups, dynamic system groups, user groups, etc). The range of these number spaces differs on different distributions. These policies are usually encoded in the command-line tools that a sysadmin uses to assign unnamed GIDs.
This means the best way to add a group locally is to use the command-line tools.
|
Create a user-group in linux using python
|
I want to create a user group using python on CentOS system. When I say 'using python' I mean I don't want to do something like os.system and give the unix command to create a new group. I would like to know if there is any python module that deals with this.
Searching on the net did not reveal much about what I want, except for python user groups.. so I had to ask this.
I learned about the grp module by searching here on SO, but couldn't find anything about creating a group.
EDIT: I dont know if I have to start a new question for this, but I would also like to know how to add (existing) users to the newly created group.
Any help appreciated.
Thank you.
|
[
"I don't know of a python module to do it, but the /etc/group and /etc/gshadow format is pretty standard, so if you wanted you could just open the files, parse their current contents and then add the new group if necessary.\nBefore you go doing this, consider:\n\nWhat happens if you try to add a group that already exists on the system\nWhat happens when multiple instances of your program try to add a group at the same time\nWhat happens to your code when an incompatible change is made to the group format a couple releases down the line\nNIS, LDAP, Kerberos, ...\n\nIf you're not willing to deal with these kinds of problems, just use the subprocess module and run groupadd. It will be way less likely to break your customers machines.\nAnother thing you could do that would be less fragile than writing your own would be to wrap the code in groupadd.c (in the shadow package) in Python and do it that way. I don't see this buying you much versus just exec'ing it, though, and it would add more complexity and fragility to your build.\n",
"I think you should use the commandline programs from your program, a lot of care has gone into making sure that they don't break the groups file if something goes wrong. \nHowever the file format is quite straight forward to write something yourself if you choose to go that way\n",
"There are no library calls for creating a group. This is because there's really no such thing as creating a group. A GID is simply a number assigned to a process or a file. All these numbers exist already - there is nothing you need to do to start using a GID. With the appropriate privileges, you can call chown(2) to set the GID of a file to any number, or setgid(2) to set the GID of the current process (there's a little more to it than that, with effective IDs, supplementary IDs, etc).\nGiving a name to a GID is done by an entry in /etc/group on basic Unix/Linux/POSIX systems, but that's really just a convention adhered to by the Unix/Linux/POSIX userland tools. Other network-based directories also exist, as mentioned by Jack Lloyd.\nThe man page group(5) describes the format of the /etc/group file, but it is not recommended that you write to it directly. Your distribution will have policies on how unnamed GIDs are allocated, such as reserving certain spaces for different purposes (fixed system groups, dynamic system groups, user groups, etc). The range of these number spaces differs on different distributions. These policies are usually encoded in the command-line tools that a sysadmin uses to assign unnamed GIDs.\nThis means the best way to add a group locally is to use the command-line tools.\n"
] |
[
11,
5,
1
] |
[
"If you are looking at Python, then try this program. Its fairly simple to use, and the code can easily be customized http://aleph-null.tv/downloads/mpb-adduser-1.tgz\n"
] |
[
-2
] |
[
"linux",
"python",
"usergroups"
] |
stackoverflow_0001570401_linux_python_usergroups.txt
|
Q:
Compare DB row values efficiently
I want to loop through a database of documents and calculate a pairwise comparison score.
A simplistic, naive method would nest a loop within another loop. This would result in the program comparing documents twice and also comparing each document to itself.
Is there a name for the algorithm for doing this task efficiently?
Is there a name for this approach?
Thanks.
A:
Assume all items have a number ItemNumber
Simple solution -- always have the 2nd element's ItemNumber greater than the first item.
eg
for (firstitem = 1 to maxitemnumber)
for (seconditem = firstitemnumber+1 to maxitemnumber)
compare(firstitem, seconditem)
visual note: if you think of the compare as a matrix (item number of one on one axis item of the other on the other axis) this looks at one of the triangles.
........
x.......
xx......
xxx.....
xxxx....
xxxxx...
xxxxxx..
xxxxxxx.
A:
I don't think its complicated enough to qualify for a name.
You can avoid duplicate pairs just by forcing a comparison on any value which might be different between different rows - the primary key is an obvious choice, e.g.
Unique pairings:
SELECT a.item as a_item, b.item as b_item
FROM table AS a, table AS b
WHERE a.id<b.id
Potentially there are a lot of ways in which the the comparison operation can be used to generate data summmaries and therefore identify potentially similar items - for single words the soundex is an obvious choice - however you don't say what your comparison metric is.
C.
A:
You can keep track of which documents you have already compared, e.g. (with numbers ;))
compared = set()
for i in [1,2,3]:
for j in [1,2,3]:
pair = frozenset((i,j))
if i != k and pair not in compared:
compare.add(pair)
compare(i,j)
Another idea would be to create the combination of documents first and iterate over them. But in order to generate this, you have to iterate over both lists and the you iterate over the result list again so I don't think that it has any advantage.
Update:
If you have the documents already in a list, then Hogan's answer is indeed better. But I think it needs a better example:
docs = [1,2,3]
l = len(docs)
for i in range(l):
for j in range(i+1,l):
compare(l[i],l[j])
A:
Something like this?
src = [1,2,3]
for i, x in enumerate(src):
for y in src[i:]:
compare(x, y)
Or you might wish to generate a list of pairs instead:
pairs = [(x, y) for i, x in enumerate(src) for y in src[i:]]
|
Compare DB row values efficiently
|
I want to loop through a database of documents and calculate a pairwise comparison score.
A simplistic, naive method would nest a loop within another loop. This would result in the program comparing documents twice and also comparing each document to itself.
Is there a name for the algorithm for doing this task efficiently?
Is there a name for this approach?
Thanks.
|
[
"Assume all items have a number ItemNumber\nSimple solution -- always have the 2nd element's ItemNumber greater than the first item.\neg\nfor (firstitem = 1 to maxitemnumber)\n for (seconditem = firstitemnumber+1 to maxitemnumber)\n compare(firstitem, seconditem)\n\nvisual note: if you think of the compare as a matrix (item number of one on one axis item of the other on the other axis) this looks at one of the triangles.\n........\nx.......\nxx......\nxxx.....\nxxxx....\nxxxxx...\nxxxxxx..\nxxxxxxx.\n\n",
"I don't think its complicated enough to qualify for a name.\nYou can avoid duplicate pairs just by forcing a comparison on any value which might be different between different rows - the primary key is an obvious choice, e.g.\nUnique pairings:\nSELECT a.item as a_item, b.item as b_item\nFROM table AS a, table AS b\nWHERE a.id<b.id\n\nPotentially there are a lot of ways in which the the comparison operation can be used to generate data summmaries and therefore identify potentially similar items - for single words the soundex is an obvious choice - however you don't say what your comparison metric is.\nC.\n",
"You can keep track of which documents you have already compared, e.g. (with numbers ;))\ncompared = set()\n\nfor i in [1,2,3]:\n for j in [1,2,3]:\n pair = frozenset((i,j))\n if i != k and pair not in compared:\n compare.add(pair)\n compare(i,j)\n\nAnother idea would be to create the combination of documents first and iterate over them. But in order to generate this, you have to iterate over both lists and the you iterate over the result list again so I don't think that it has any advantage.\nUpdate:\nIf you have the documents already in a list, then Hogan's answer is indeed better. But I think it needs a better example:\ndocs = [1,2,3]\nl = len(docs)\nfor i in range(l):\n for j in range(i+1,l):\n compare(l[i],l[j])\n\n",
"Something like this?\nsrc = [1,2,3]\nfor i, x in enumerate(src):\n for y in src[i:]:\n compare(x, y)\n\nOr you might wish to generate a list of pairs instead:\npairs = [(x, y) for i, x in enumerate(src) for y in src[i:]]\n\n"
] |
[
3,
2,
0,
0
] |
[] |
[] |
[
"database",
"logic",
"mysql",
"python"
] |
stackoverflow_0002426246_database_logic_mysql_python.txt
|
Q:
PostgreSQL pgdb driver raises "can't rollback" exception
for some reason I'm experiencing the Operational Error with "can't rollback" message when I attempt to roll back my transaction in the following context:
try:
cursors[instance].execute("lock revision, app, timeout IN SHARE MODE")
cursors[instance].execute("insert into app (type, active, active_revision, contents, z) values ('session', true, %s, %s, 0) returning id", (cRevision, sessionId))
sAppId = cursors[instance].fetchone()[0]
cursors[instance].execute("insert into revision (app_id, type) values (%s, 'active')", (sAppId,))
cursors[instance].execute("insert into timeout (app_id, last_seen) values (%s, now())", (sAppId,))
connections[instance].commit()
except pgdb.DatabaseError, e:
connections[instance].rollback()
return "{status: 'error', errno:4, errmsg: \"%s\"}"%(str(e).replace('\"', '\\"').replace('\n', '\\n').replace('\r', '\\r'))
The driver in use is PGDB.
What is fundamentally wrong here?
A:
You are looking in the wrong place. What does the PostgreSQL log say about what you are doing?
A:
What happens if you exclude the lock statement?
This is what's happening inside pgdb.py:
def rollback(self):
"""Roll back to the start of any pending transaction."""
if self._cnx:
if self._tnx:
self._tnx = False
try:
self._cnx.source().execute("ROLLBACK")
except Exception:
raise OperationalError("can't rollback")
else:
raise OperationalError("connection has been closed")
So I suggest you replace your connections[instance].rollback() call with:
connections[instance]._tnx = False
connections[instance]._cnx.source().execute("ROLLBACK")
to see if that gives you a more informative error message (the except clause inside pgdb is greedy).
Also: check the Postgresql log, it will have probably logged the reason!
A:
Where do you start the transaction? I do see a COMMIT but don't see a BEGIN or START TRANSACTION.
|
PostgreSQL pgdb driver raises "can't rollback" exception
|
for some reason I'm experiencing the Operational Error with "can't rollback" message when I attempt to roll back my transaction in the following context:
try:
cursors[instance].execute("lock revision, app, timeout IN SHARE MODE")
cursors[instance].execute("insert into app (type, active, active_revision, contents, z) values ('session', true, %s, %s, 0) returning id", (cRevision, sessionId))
sAppId = cursors[instance].fetchone()[0]
cursors[instance].execute("insert into revision (app_id, type) values (%s, 'active')", (sAppId,))
cursors[instance].execute("insert into timeout (app_id, last_seen) values (%s, now())", (sAppId,))
connections[instance].commit()
except pgdb.DatabaseError, e:
connections[instance].rollback()
return "{status: 'error', errno:4, errmsg: \"%s\"}"%(str(e).replace('\"', '\\"').replace('\n', '\\n').replace('\r', '\\r'))
The driver in use is PGDB.
What is fundamentally wrong here?
|
[
"You are looking in the wrong place. What does the PostgreSQL log say about what you are doing?\n",
"What happens if you exclude the lock statement?\nThis is what's happening inside pgdb.py:\ndef rollback(self):\n \"\"\"Roll back to the start of any pending transaction.\"\"\"\n if self._cnx:\n if self._tnx:\n self._tnx = False\n try:\n self._cnx.source().execute(\"ROLLBACK\")\n except Exception:\n raise OperationalError(\"can't rollback\")\n else:\n raise OperationalError(\"connection has been closed\")\n\nSo I suggest you replace your connections[instance].rollback() call with:\nconnections[instance]._tnx = False\nconnections[instance]._cnx.source().execute(\"ROLLBACK\")\n\nto see if that gives you a more informative error message (the except clause inside pgdb is greedy).\nAlso: check the Postgresql log, it will have probably logged the reason!\n",
"Where do you start the transaction? I do see a COMMIT but don't see a BEGIN or START TRANSACTION.\n"
] |
[
1,
0,
0
] |
[] |
[] |
[
"exception",
"postgresql",
"python",
"transactions"
] |
stackoverflow_0002419500_exception_postgresql_python_transactions.txt
|
Q:
Introspection of win32com module / pythoncom module
what is the best way to see what all functions that can be performed using pythoncom module?
Specifically, i was working with the win32com module to operate upon excel files. I was not able to find introspection for it as we do for the rest of the modules.
Can anyone please suggest how can i retrieve this information?
A:
run the make.py file in \lib\site-packages\win32com\client.
When you run it, a dialog comes up showing installed COM objects... choose the one for the Excel Ojbect library and you'll get something like this:
c:\Python26\Lib\site-packages\win32com\client>makepy.py
Generating to C:\Python26\lib\site-packages\win32com\gen_py\00020813-0000-0000-C
000-000000000046x9x1x0.py
Building definitions from type library...
Generating...
Importing module
Now when you call win32com.client.Dispatch on Excel, the object you get back will have attributes that support introspection (from the file that gets created when you run the step above). This is basically creating an early-bound version of the COM object.
This topic is covered in detail in Mark Hammond's "Python Programming on Win32". It's an old book, but still very useful! http://www.amazon.com/Python-Programming-WIN32-Windows-Programmers/dp/1565926218
A:
The win32com module doesn't provide the functions to manipulate an Excel spreadsheet directly. Rather, it provides you a function to acquire an Excel spreadsheet object. From this object, you can then manipulate a spreadsheet in an object-oriented fashion:
import win32com.client
excel = win32com.client.Dispatch("Excel.Application")
The methods and properties available to excel can be found in the Application Object documentation, part of the Excel Object Model Reference at MSDN.
For example, the documentation indicates that an Application object has a Workbooks property:
workbooks = excel.Workbooks
The Workbooks collection has an Open method:
workbook = workbooks.Open("C:\\something.xls")
You can now manipulate this workbook using the Workbook documentation!
As you can see, working with win32com follows the MSDN documentation rather closely. :)
|
Introspection of win32com module / pythoncom module
|
what is the best way to see what all functions that can be performed using pythoncom module?
Specifically, i was working with the win32com module to operate upon excel files. I was not able to find introspection for it as we do for the rest of the modules.
Can anyone please suggest how can i retrieve this information?
|
[
"run the make.py file in \\lib\\site-packages\\win32com\\client.\nWhen you run it, a dialog comes up showing installed COM objects... choose the one for the Excel Ojbect library and you'll get something like this:\nc:\\Python26\\Lib\\site-packages\\win32com\\client>makepy.py\nGenerating to C:\\Python26\\lib\\site-packages\\win32com\\gen_py\\00020813-0000-0000-C\n000-000000000046x9x1x0.py\nBuilding definitions from type library...\nGenerating...\nImporting module\n\nNow when you call win32com.client.Dispatch on Excel, the object you get back will have attributes that support introspection (from the file that gets created when you run the step above). This is basically creating an early-bound version of the COM object. \nThis topic is covered in detail in Mark Hammond's \"Python Programming on Win32\". It's an old book, but still very useful! http://www.amazon.com/Python-Programming-WIN32-Windows-Programmers/dp/1565926218\n",
"The win32com module doesn't provide the functions to manipulate an Excel spreadsheet directly. Rather, it provides you a function to acquire an Excel spreadsheet object. From this object, you can then manipulate a spreadsheet in an object-oriented fashion:\nimport win32com.client\n\nexcel = win32com.client.Dispatch(\"Excel.Application\")\n\nThe methods and properties available to excel can be found in the Application Object documentation, part of the Excel Object Model Reference at MSDN.\nFor example, the documentation indicates that an Application object has a Workbooks property:\nworkbooks = excel.Workbooks\n\nThe Workbooks collection has an Open method:\nworkbook = workbooks.Open(\"C:\\\\something.xls\")\n\nYou can now manipulate this workbook using the Workbook documentation!\nAs you can see, working with win32com follows the MSDN documentation rather closely. :)\n"
] |
[
5,
2
] |
[] |
[] |
[
"python"
] |
stackoverflow_0002379809_python.txt
|
Q:
Python and a "time value of money" problem
(I asked this question earlier today, but I did a poor job of explaining myself. Let me try again)
I have a client who is an industrial maintenance company. They sell service agreements that are prepaid 20 hour blocks of a technician's time. Some of their larger customers might burn through that agreement in two weeks while customers with fewer problems might go eight months on that same contract. I would like to use Python to help model projected sales revenue and determine how many billable hours per month that they'll be on the hook for.
If each customer only ever bought a single service contract (never renewed) it would be easy to figure sales as monthly_revenue = contract_value * qty_contracts_sold. Billable hours would also be easy: billable_hrs = hrs_per_contract * qty_contracts_sold. However, how do I account for renewals? Assuming that 90% (or some other arbitrary amount) of customers renew, then their monthly revenue ought to grow geometrically. Another important variable is how long the average customer burns through a contract. How do I determine what the revenue and billable hours will be 3, 6, or 12 months from now, based on various renewal and burn rates?
I assume that I'd use some type of recursive function but math was never one of my strong points. Any suggestions please?
Edit: I'm thinking that the best way to approach this is to think of it as a "time value of money" problem. I've retitled the question as such. The problem is probably a lot more common if you think of "monthly sales" as something similar to annuity payments.
A:
If you want to consider the problem in terms of present value of future revenue (that's what "time value of money" implies to me), then you have the following parameters: discount rate D (on a monthly basis for convenience), time T a customer will take to exhaust their prepaid hours, likelihood L that they will renew when their prepaid hours are up, dollar amounts for first sale F and renewal R. This has several assumptions of course (maybe the customers who consume support faster are more likely to renew, for example -- this model doesn't account for that) but it may still be a useful first approximation.
So making a sale today is worth: F immediately for sure; plus, in T months, R more with probability L; plus, in 2T months, R more with probability LL; and so on. So the worth of that sale is F + RL / (DT) + RLL / (D2T) + ... = F + (R*L / DT ) * (1 + L/DT + L2/(DT)**2 + ...).
The series converges to 1 / (1 - L/(D**T)), so the overall formula in closed form (shifting to Python;-):
def salesworth(D, T, L, F, R):
return F + (R * L) / (D**T * (1 - L / (D**T)))
Expected billable hours can be had with the same formula, just using for F and R the number of hours in a first sale and renewal, and (if the discount rate concept does not apply to billable hours) a D of 1 (so T doesn't actually matter, as 1**T == 1 for any T;-).
A:
Thanks for the assistance even though my requirements were a bit vague. After consulting someone who is extremely versed in financial mathematics, I determined that a simple formula was not an appropriate solution.
What I ended up doing is "exploding" the months into the component days using xrange() and iterating over each day. When evaluating each day, I determined whether a new contract was signed on that day, and if so, which dates in future the contract would need to be renewed. I pushed those renewal dates into a list and then summed the values.
|
Python and a "time value of money" problem
|
(I asked this question earlier today, but I did a poor job of explaining myself. Let me try again)
I have a client who is an industrial maintenance company. They sell service agreements that are prepaid 20 hour blocks of a technician's time. Some of their larger customers might burn through that agreement in two weeks while customers with fewer problems might go eight months on that same contract. I would like to use Python to help model projected sales revenue and determine how many billable hours per month that they'll be on the hook for.
If each customer only ever bought a single service contract (never renewed) it would be easy to figure sales as monthly_revenue = contract_value * qty_contracts_sold. Billable hours would also be easy: billable_hrs = hrs_per_contract * qty_contracts_sold. However, how do I account for renewals? Assuming that 90% (or some other arbitrary amount) of customers renew, then their monthly revenue ought to grow geometrically. Another important variable is how long the average customer burns through a contract. How do I determine what the revenue and billable hours will be 3, 6, or 12 months from now, based on various renewal and burn rates?
I assume that I'd use some type of recursive function but math was never one of my strong points. Any suggestions please?
Edit: I'm thinking that the best way to approach this is to think of it as a "time value of money" problem. I've retitled the question as such. The problem is probably a lot more common if you think of "monthly sales" as something similar to annuity payments.
|
[
"If you want to consider the problem in terms of present value of future revenue (that's what \"time value of money\" implies to me), then you have the following parameters: discount rate D (on a monthly basis for convenience), time T a customer will take to exhaust their prepaid hours, likelihood L that they will renew when their prepaid hours are up, dollar amounts for first sale F and renewal R. This has several assumptions of course (maybe the customers who consume support faster are more likely to renew, for example -- this model doesn't account for that) but it may still be a useful first approximation.\nSo making a sale today is worth: F immediately for sure; plus, in T months, R more with probability L; plus, in 2T months, R more with probability LL; and so on. So the worth of that sale is F + RL / (DT) + RLL / (D2T) + ... = F + (R*L / DT ) * (1 + L/DT + L2/(DT)**2 + ...).\nThe series converges to 1 / (1 - L/(D**T)), so the overall formula in closed form (shifting to Python;-):\ndef salesworth(D, T, L, F, R):\n return F + (R * L) / (D**T * (1 - L / (D**T))) \n\nExpected billable hours can be had with the same formula, just using for F and R the number of hours in a first sale and renewal, and (if the discount rate concept does not apply to billable hours) a D of 1 (so T doesn't actually matter, as 1**T == 1 for any T;-).\n",
"Thanks for the assistance even though my requirements were a bit vague. After consulting someone who is extremely versed in financial mathematics, I determined that a simple formula was not an appropriate solution.\nWhat I ended up doing is \"exploding\" the months into the component days using xrange() and iterating over each day. When evaluating each day, I determined whether a new contract was signed on that day, and if so, which dates in future the contract would need to be renewed. I pushed those renewal dates into a list and then summed the values.\n"
] |
[
1,
0
] |
[] |
[] |
[
"finance",
"math",
"python"
] |
stackoverflow_0002376355_finance_math_python.txt
|
Q:
How does this decorator make a call to the 'register' method?
I'm trying to understand what is going on in the decorator @not_authenticated.
The next step in the TraceRoute is to the method 'register' which is also located in django_authopenid/views.py which I just don't understand because I don't see anywhere that register is even mentioned in signin()
How is the method 'register' called?
def not_authenticated(func):
""" decorator that redirect user to next page if he is already logged."""
def decorated(request, *args, **kwargs):
if request.user.is_authenticated():
next = request.GET.get("next", "/")
return HttpResponseRedirect(next)
return func(request, *args, **kwargs)
return decorated
@not_authenticated
def signin(request,newquestion=False,newanswer=False):
"""
signin page. It manage the legacy authentification (user/password)
and authentification with openid.
url: /signin/
template : authopenid/signin.htm
"""
request.encoding = 'UTF-8'
on_failure = signin_failure
next = clean_next(request.GET.get('next'))
form_signin = OpenidSigninForm(initial={'next':next})
form_auth = OpenidAuthForm(initial={'next':next})
if request.POST:
if 'bsignin' in request.POST.keys() or 'openid_username' in request.POST.keys():
form_signin = OpenidSigninForm(request.POST)
if form_signin.is_valid():
next = clean_next(form_signin.cleaned_data.get('next'))
sreg_req = sreg.SRegRequest(optional=['nickname', 'email'])
redirect_to = "%s%s?%s" % (
get_url_host(request),
reverse('user_complete_signin'),
urllib.urlencode({'next':next})
)
return ask_openid(request,
form_signin.cleaned_data['openid_url'],
redirect_to,
on_failure=signin_failure,
sreg_request=sreg_req)
elif 'blogin' in request.POST.keys():
# perform normal django authentification
form_auth = OpenidAuthForm(request.POST)
if form_auth.is_valid():
user_ = form_auth.get_user()
login(request, user_)
next = clean_next(form_auth.cleaned_data.get('next'))
return HttpResponseRedirect(next)
question = None
if newquestion == True:
from forum.models import AnonymousQuestion as AQ
session_key = request.session.session_key
qlist = AQ.objects.filter(session_key=session_key).order_by('-added_at')
if len(qlist) > 0:
question = qlist[0]
answer = None
if newanswer == True:
from forum.models import AnonymousAnswer as AA
session_key = request.session.session_key
alist = AA.objects.filter(session_key=session_key).order_by('-added_at')
if len(alist) > 0:
answer = alist[0]
return render('authopenid/signin.html', {
'question':question,
'answer':answer,
'form1': form_auth,
'form2': form_signin,
'msg': request.GET.get('msg',''),
'sendpw_url': reverse('user_sendpw'),
}, context_instance=RequestContext(request))
Looking at the request, it seems that account/register/ does reference the register method with 'PATH_INFO': u'/account/register/'
Here is the request:
<WSGIRequest GET:<QueryDict: {}>, POST:<QueryDict: {u'username': [u'BryanWheelock'], u'email': [u'bryan.wheck@gmail.com'], u'bnewaccount': [u'Signup']}>, COOKIES:{'__utma': '127460431.1218630960.1266769637.1266769637.1266864494.2', '__utmb': '127460431.3.10.1266864494', '__utmc': '127460431', '__utmz': '127460431.1266769637.1.1.utmcsr=(direct)|utmccn=(direct)|utmcmd=(none)', 'sessionid': 'fb15ee538320170a22d3a3a324aad968'}, META:{'CONTENT_LENGTH': '74', 'CONTENT_TYPE': 'application/x-www-form-urlencoded', 'DOCUMENT_ROOT': '/usr/local/apache2/htdocs', 'GATEWAY_INTERFACE': 'CGI/1.1', 'HTTP_ACCEPT': 'application/xml,application/xhtml+xml,text/html;q=0.9,text/plain;q=0.8,image/png,*/*;q=0.5', 'HTTP_ACCEPT_CHARSET': 'ISO-8859-1,utf-8;q=0.7,*;q=0.3', 'HTTP_ACCEPT_ENCODING': 'gzip,deflate,sdch', 'HTTP_ACCEPT_LANGUAGE': 'en-US,en;q=0.8', 'HTTP_CACHE_CONTROL': 'max-age=0', 'HTTP_CONNECTION': 'close', 'HTTP_COOKIE': '__utmz=127460431.1266769637.1.1.utmcsr=(direct)|utmccn=(direct)|utmcmd=(none); __utma=127460431.1218630960.1266769637.1266769637.1266864494.2; __utmc=127460431; __utmb=127460431.3.10.1266864494; sessionid=fb15ee538320170a22d3a3a324aad968', 'HTTP_HOST': 'workproject.com', 'HTTP_ORIGIN': 'http://workproject.com', 'HTTP_REFERER': 'http://workproject.com/account/signin/complete/?next=%2F&janrain_nonce=2010-02-22T18%3A49%3A53ZG2KXci&openid.ns=http%3A%2F%2Fspecs.openid.net%2Fauth%2F2.0&openid.mode=id_res&openid.op_endpoint=https%3A%2F%2Fwww.google.com%2Faccounts%2Fo8%2Fud&openid.response_nonce=2010-02-22T18%3A49%3A53Znxxxxxxxxxw&openid.return_to=http%3A%2F%2Fworkproject.com%2Faccount%2Fsignin%2Fcomplete%2F%3Fnext%3D%252F%26janrain_nonce%3D2010-02-22T18%253A49%253A53ZG2KXci&openid.assoc_handle=AOQobUepU4xs-kGg5LiyLzfN3RYv0I0Jocgjf_1odT4RR9zfMFpQVpMg&openid.signed=op_endpoint%2Cclaimed_id%2Cidentity%2Creturn_to%2Cresponse_nonce%2Cassoc_handle&openid.sig=Jf76i2RNhqpLTJMjeQ0nnQz6fgA%3D&openid.identity=https%3A%2F%2Fwww.google.com%2Faccounts%2Fo8%2Fid%3Fid%3DAItxxxxxxxxxs9CxHQ3PrHw_N5_3j1HM&openid.claimed_id=https%3A%2F%2Fwww.google.com%2Faccounts%2Fo8%2Fid%3Fid%3DAItOaxxxxxxxxxxx4s9CxHQ3PrHw_N5_3j1HM', 'HTTP_USER_AGENT': 'Mozilla/5.0 (Macintosh; U; Intel Mac OS X 10_5_8; en-US) AppleWebKit/532.9 (KHTML, like Gecko) Chrome/5.0.307.7 Safari/532.9', 'HTTP_X_FORWARDED_FOR': '96.8.31.235', 'PATH': '/usr/bin:/bin', 'PATH_INFO': u'/account/register/', 'PATH_TRANSLATED': '/home/spirituality/webapps/work/spirit_app.wsgi/account/register/', 'QUERY_STRING': '', 'REMOTE_ADDR': '127.0.0.1', 'REMOTE_PORT': '59956', 'REQUEST_METHOD': 'POST', 'REQUEST_URI': '/account/register/', 'SCRIPT_FILENAME': '/home/spirituality/webapps/spirituality/spirit_app.wsgi', 'SCRIPT_NAME': u'', 'SERVER_ADDR': '127.0.0.1', 'SERVER_ADMIN': '[no address given]', 'SERVER_NAME': 'workproject.com', 'SERVER_PORT': '80', 'SERVER_PROTOCOL': 'HTTP/1.0', 'SERVER_SIGNATURE': '', 'SERVER_SOFTWARE': 'Apache/2.2.12 (Unix) mod_wsgi/2.5 Python/2.5.4', 'mod_wsgi.application_group': 'www.workProject.com|', 'mod_wsgi.callable_object': 'application', 'mod_wsgi.listener_host': '', 'mod_wsgi.listener_port': '25931', 'mod_wsgi.process_group': '', 'mod_wsgi.reload_mechanism': '0', 'mod_wsgi.script_reloading': '1', 'mod_wsgi.version': (2, 5), 'wsgi.errors': <mod_wsgi.Log object at 0xb7ce0038>, 'wsgi.file_wrapper': <built-in method file_wrapper of mod_wsgi.Adapter object at 0xb7e94b18>, 'wsgi.input': <mod_wsgi.Input object at 0x999cc78>, 'wsgi.multiprocess': True, 'wsgi.multithread': False, 'wsgi.run_once': False, 'wsgi.url_scheme': 'http', 'wsgi.version': (1, 0)}>
A:
Without attempting to understand all of that why don't you insert:
import pdb; pdb.set_trace()
wherever this "register" method is?
Than hit "bt"
A:
Are you sure the call gets into signin()?
Because if the user is already authenticated (request.user.is_authenticated()) , the openid code is called directly, and signin() redirects anyway..
You have this inside httpreferrer:
'HTTP_REFERER': 'http://workproject.com/account/signin/complete/?next=%2F&janrain_nonce=2010-02-22T18%3A49%3A53ZG2KXci&openid.ns=http%3A%2F%2Fspecs.openid.net%2Fauth%2F2.0&openid.mode=id_res&openid.op_endpoint=https%3A%2F%2Fwww.google.com%2Faccounts%2Fo8%2Fud&openid.response_nonce=2010-02-22T18%3A49%3A53Znxxxxxxxxxw&openid.return_to=http%3A%2F%2Fworkproject.com%2Faccount%2Fsignin%2Fcomplete%2F%3Fnext%3D%252F%26janrain_nonce%3D2010-02-22T18%253A49%253A53ZG2KXci&openid.assoc_handle=AOQobUepU4xs-kGg5LiyLzfN3RYv0I0Jocgjf_1odT4RR9zfMFpQVpMg&openid.signed=op_endpoint%2Cclaimed_id%2Cidentity%2Creturn_to%2Cresponse_nonce%2Cassoc_handle&openid.sig=Jf76i2RNhqpLTJMjeQ0nnQz6fgA%3D&openid.identity=https%3A%2F%2Fwww.google.com%2Faccounts%2Fo8%2Fid%3Fid%3DAItxxxxxxxxxs9CxHQ3PrHw_N5_3j1HM&openid.claimed_id=https%3A%2F%2Fwww.google.com%2Faccounts%2Fo8%2Fid%3Fid%3DAItOaxxxxxxxxxxx4s9CxHQ3PrHw_N5_3j1HM',
A:
After looking through django_authopenid/views.py , the part that appears to be calling register is this part of signin:
return ask_openid(request,
form_signin.cleaned_data['openid_url'],
redirect_to,
on_failure=signin_failure,
sreg_request=sreg_req)
I don't particularly know all of the ways that can trigger this Registration Request, but that is the piece that is calling register. Follow your trace and read the code for ask_openid for clues to how you got there.
|
How does this decorator make a call to the 'register' method?
|
I'm trying to understand what is going on in the decorator @not_authenticated.
The next step in the TraceRoute is to the method 'register' which is also located in django_authopenid/views.py which I just don't understand because I don't see anywhere that register is even mentioned in signin()
How is the method 'register' called?
def not_authenticated(func):
""" decorator that redirect user to next page if he is already logged."""
def decorated(request, *args, **kwargs):
if request.user.is_authenticated():
next = request.GET.get("next", "/")
return HttpResponseRedirect(next)
return func(request, *args, **kwargs)
return decorated
@not_authenticated
def signin(request,newquestion=False,newanswer=False):
"""
signin page. It manage the legacy authentification (user/password)
and authentification with openid.
url: /signin/
template : authopenid/signin.htm
"""
request.encoding = 'UTF-8'
on_failure = signin_failure
next = clean_next(request.GET.get('next'))
form_signin = OpenidSigninForm(initial={'next':next})
form_auth = OpenidAuthForm(initial={'next':next})
if request.POST:
if 'bsignin' in request.POST.keys() or 'openid_username' in request.POST.keys():
form_signin = OpenidSigninForm(request.POST)
if form_signin.is_valid():
next = clean_next(form_signin.cleaned_data.get('next'))
sreg_req = sreg.SRegRequest(optional=['nickname', 'email'])
redirect_to = "%s%s?%s" % (
get_url_host(request),
reverse('user_complete_signin'),
urllib.urlencode({'next':next})
)
return ask_openid(request,
form_signin.cleaned_data['openid_url'],
redirect_to,
on_failure=signin_failure,
sreg_request=sreg_req)
elif 'blogin' in request.POST.keys():
# perform normal django authentification
form_auth = OpenidAuthForm(request.POST)
if form_auth.is_valid():
user_ = form_auth.get_user()
login(request, user_)
next = clean_next(form_auth.cleaned_data.get('next'))
return HttpResponseRedirect(next)
question = None
if newquestion == True:
from forum.models import AnonymousQuestion as AQ
session_key = request.session.session_key
qlist = AQ.objects.filter(session_key=session_key).order_by('-added_at')
if len(qlist) > 0:
question = qlist[0]
answer = None
if newanswer == True:
from forum.models import AnonymousAnswer as AA
session_key = request.session.session_key
alist = AA.objects.filter(session_key=session_key).order_by('-added_at')
if len(alist) > 0:
answer = alist[0]
return render('authopenid/signin.html', {
'question':question,
'answer':answer,
'form1': form_auth,
'form2': form_signin,
'msg': request.GET.get('msg',''),
'sendpw_url': reverse('user_sendpw'),
}, context_instance=RequestContext(request))
Looking at the request, it seems that account/register/ does reference the register method with 'PATH_INFO': u'/account/register/'
Here is the request:
<WSGIRequest GET:<QueryDict: {}>, POST:<QueryDict: {u'username': [u'BryanWheelock'], u'email': [u'bryan.wheck@gmail.com'], u'bnewaccount': [u'Signup']}>, COOKIES:{'__utma': '127460431.1218630960.1266769637.1266769637.1266864494.2', '__utmb': '127460431.3.10.1266864494', '__utmc': '127460431', '__utmz': '127460431.1266769637.1.1.utmcsr=(direct)|utmccn=(direct)|utmcmd=(none)', 'sessionid': 'fb15ee538320170a22d3a3a324aad968'}, META:{'CONTENT_LENGTH': '74', 'CONTENT_TYPE': 'application/x-www-form-urlencoded', 'DOCUMENT_ROOT': '/usr/local/apache2/htdocs', 'GATEWAY_INTERFACE': 'CGI/1.1', 'HTTP_ACCEPT': 'application/xml,application/xhtml+xml,text/html;q=0.9,text/plain;q=0.8,image/png,*/*;q=0.5', 'HTTP_ACCEPT_CHARSET': 'ISO-8859-1,utf-8;q=0.7,*;q=0.3', 'HTTP_ACCEPT_ENCODING': 'gzip,deflate,sdch', 'HTTP_ACCEPT_LANGUAGE': 'en-US,en;q=0.8', 'HTTP_CACHE_CONTROL': 'max-age=0', 'HTTP_CONNECTION': 'close', 'HTTP_COOKIE': '__utmz=127460431.1266769637.1.1.utmcsr=(direct)|utmccn=(direct)|utmcmd=(none); __utma=127460431.1218630960.1266769637.1266769637.1266864494.2; __utmc=127460431; __utmb=127460431.3.10.1266864494; sessionid=fb15ee538320170a22d3a3a324aad968', 'HTTP_HOST': 'workproject.com', 'HTTP_ORIGIN': 'http://workproject.com', 'HTTP_REFERER': 'http://workproject.com/account/signin/complete/?next=%2F&janrain_nonce=2010-02-22T18%3A49%3A53ZG2KXci&openid.ns=http%3A%2F%2Fspecs.openid.net%2Fauth%2F2.0&openid.mode=id_res&openid.op_endpoint=https%3A%2F%2Fwww.google.com%2Faccounts%2Fo8%2Fud&openid.response_nonce=2010-02-22T18%3A49%3A53Znxxxxxxxxxw&openid.return_to=http%3A%2F%2Fworkproject.com%2Faccount%2Fsignin%2Fcomplete%2F%3Fnext%3D%252F%26janrain_nonce%3D2010-02-22T18%253A49%253A53ZG2KXci&openid.assoc_handle=AOQobUepU4xs-kGg5LiyLzfN3RYv0I0Jocgjf_1odT4RR9zfMFpQVpMg&openid.signed=op_endpoint%2Cclaimed_id%2Cidentity%2Creturn_to%2Cresponse_nonce%2Cassoc_handle&openid.sig=Jf76i2RNhqpLTJMjeQ0nnQz6fgA%3D&openid.identity=https%3A%2F%2Fwww.google.com%2Faccounts%2Fo8%2Fid%3Fid%3DAItxxxxxxxxxs9CxHQ3PrHw_N5_3j1HM&openid.claimed_id=https%3A%2F%2Fwww.google.com%2Faccounts%2Fo8%2Fid%3Fid%3DAItOaxxxxxxxxxxx4s9CxHQ3PrHw_N5_3j1HM', 'HTTP_USER_AGENT': 'Mozilla/5.0 (Macintosh; U; Intel Mac OS X 10_5_8; en-US) AppleWebKit/532.9 (KHTML, like Gecko) Chrome/5.0.307.7 Safari/532.9', 'HTTP_X_FORWARDED_FOR': '96.8.31.235', 'PATH': '/usr/bin:/bin', 'PATH_INFO': u'/account/register/', 'PATH_TRANSLATED': '/home/spirituality/webapps/work/spirit_app.wsgi/account/register/', 'QUERY_STRING': '', 'REMOTE_ADDR': '127.0.0.1', 'REMOTE_PORT': '59956', 'REQUEST_METHOD': 'POST', 'REQUEST_URI': '/account/register/', 'SCRIPT_FILENAME': '/home/spirituality/webapps/spirituality/spirit_app.wsgi', 'SCRIPT_NAME': u'', 'SERVER_ADDR': '127.0.0.1', 'SERVER_ADMIN': '[no address given]', 'SERVER_NAME': 'workproject.com', 'SERVER_PORT': '80', 'SERVER_PROTOCOL': 'HTTP/1.0', 'SERVER_SIGNATURE': '', 'SERVER_SOFTWARE': 'Apache/2.2.12 (Unix) mod_wsgi/2.5 Python/2.5.4', 'mod_wsgi.application_group': 'www.workProject.com|', 'mod_wsgi.callable_object': 'application', 'mod_wsgi.listener_host': '', 'mod_wsgi.listener_port': '25931', 'mod_wsgi.process_group': '', 'mod_wsgi.reload_mechanism': '0', 'mod_wsgi.script_reloading': '1', 'mod_wsgi.version': (2, 5), 'wsgi.errors': <mod_wsgi.Log object at 0xb7ce0038>, 'wsgi.file_wrapper': <built-in method file_wrapper of mod_wsgi.Adapter object at 0xb7e94b18>, 'wsgi.input': <mod_wsgi.Input object at 0x999cc78>, 'wsgi.multiprocess': True, 'wsgi.multithread': False, 'wsgi.run_once': False, 'wsgi.url_scheme': 'http', 'wsgi.version': (1, 0)}>
|
[
"Without attempting to understand all of that why don't you insert:\nimport pdb; pdb.set_trace()\n\nwherever this \"register\" method is?\nThan hit \"bt\"\n",
"Are you sure the call gets into signin()?\nBecause if the user is already authenticated (request.user.is_authenticated()) , the openid code is called directly, and signin() redirects anyway..\nYou have this inside httpreferrer:\n\n'HTTP_REFERER': 'http://workproject.com/account/signin/complete/?next=%2F&janrain_nonce=2010-02-22T18%3A49%3A53ZG2KXci&openid.ns=http%3A%2F%2Fspecs.openid.net%2Fauth%2F2.0&openid.mode=id_res&openid.op_endpoint=https%3A%2F%2Fwww.google.com%2Faccounts%2Fo8%2Fud&openid.response_nonce=2010-02-22T18%3A49%3A53Znxxxxxxxxxw&openid.return_to=http%3A%2F%2Fworkproject.com%2Faccount%2Fsignin%2Fcomplete%2F%3Fnext%3D%252F%26janrain_nonce%3D2010-02-22T18%253A49%253A53ZG2KXci&openid.assoc_handle=AOQobUepU4xs-kGg5LiyLzfN3RYv0I0Jocgjf_1odT4RR9zfMFpQVpMg&openid.signed=op_endpoint%2Cclaimed_id%2Cidentity%2Creturn_to%2Cresponse_nonce%2Cassoc_handle&openid.sig=Jf76i2RNhqpLTJMjeQ0nnQz6fgA%3D&openid.identity=https%3A%2F%2Fwww.google.com%2Faccounts%2Fo8%2Fid%3Fid%3DAItxxxxxxxxxs9CxHQ3PrHw_N5_3j1HM&openid.claimed_id=https%3A%2F%2Fwww.google.com%2Faccounts%2Fo8%2Fid%3Fid%3DAItOaxxxxxxxxxxx4s9CxHQ3PrHw_N5_3j1HM',\n\n",
"After looking through django_authopenid/views.py , the part that appears to be calling register is this part of signin:\nreturn ask_openid(request, \n form_signin.cleaned_data['openid_url'], \n redirect_to, \n on_failure=signin_failure, \n sreg_request=sreg_req)\n\nI don't particularly know all of the ways that can trigger this Registration Request, but that is the piece that is calling register. Follow your trace and read the code for ask_openid for clues to how you got there.\n"
] |
[
0,
0,
0
] |
[] |
[] |
[
"decorator",
"django",
"python"
] |
stackoverflow_0002313666_decorator_django_python.txt
|
Q:
Python appengine Query does not work when using a variable
I am trying to use a fetcher method to retrieve items from my datastore. If I use the following
def getItem(item_id):
q = Item.all()
q.filter("itemid = ", item_id)
It fails because nothing is returned. If I hard code in an item like
def getItem(item_id):
q = Item.all()
q.filter("itemid = ", 9000)
it fetches just fine, and sings merrily along. I have tried every which way to get this to work. I have used
result = db.GqlQuery("SELECT * FROM Item WHERE item_id = :1 LIMIT 1",
title).fetch(1)
to the same effect. If I hard code in a number, works fine. I have tried setting the select statement as a local string, assembling it that way, casting the int as a string, and nothing. When I output the SELECT statement to the screen, looks fine. I can cut ans paste the output into the string, and whammo, it works. Any help would be appreciated.
A:
Does it make any difference if you do this:
def getItem(item_id):
q = Item.all()
q.filter("itemid = ", int(item_id))
The most likely cause of the problem that I can see is that the item_id parameter may be a string even though it is holding a numerical value. Coerce it to an int, and see if that makes any difference.
|
Python appengine Query does not work when using a variable
|
I am trying to use a fetcher method to retrieve items from my datastore. If I use the following
def getItem(item_id):
q = Item.all()
q.filter("itemid = ", item_id)
It fails because nothing is returned. If I hard code in an item like
def getItem(item_id):
q = Item.all()
q.filter("itemid = ", 9000)
it fetches just fine, and sings merrily along. I have tried every which way to get this to work. I have used
result = db.GqlQuery("SELECT * FROM Item WHERE item_id = :1 LIMIT 1",
title).fetch(1)
to the same effect. If I hard code in a number, works fine. I have tried setting the select statement as a local string, assembling it that way, casting the int as a string, and nothing. When I output the SELECT statement to the screen, looks fine. I can cut ans paste the output into the string, and whammo, it works. Any help would be appreciated.
|
[
"Does it make any difference if you do this:\ndef getItem(item_id):\n q = Item.all()\n q.filter(\"itemid = \", int(item_id))\n\nThe most likely cause of the problem that I can see is that the item_id parameter may be a string even though it is holding a numerical value. Coerce it to an int, and see if that makes any difference.\n"
] |
[
2
] |
[] |
[] |
[
"google_app_engine",
"google_cloud_datastore",
"python"
] |
stackoverflow_0002428047_google_app_engine_google_cloud_datastore_python.txt
|
Q:
Silence output from SimpleXMLRPCServer
I am running an xml-rpc server using SimpleXMLRPCServer from the stdlib.
My code looks something like this:
import SimpleXMLRPCServer
import socket
class RemoteStarter:
def start(self):
return 'foo'
rs = RemoteStarter()
host = socket.gethostbyaddr(socket.gethostname())[0]
port = 9000
server = SimpleXMLRPCServer.SimpleXMLRPCServer((host, port))
server.register_instance(rs)
server.serve_forever()
every time the 'start' method gets called remotely, the server prints an access line like this:
<server_name> - - [10/Mar/2010 13:06:20] "POST /RPC2 HTTP/1.0" 200 -
I can't figure out a way to silence the output so it doesn't print these access lines to stdout.
anyone?
A:
the answer is:
pass logRequests=False to SimpleXMLRPCServer when you create it:
server = SimpleXMLRPCServer.SimpleXMLRPCServer((host, port), logRequests=False)
|
Silence output from SimpleXMLRPCServer
|
I am running an xml-rpc server using SimpleXMLRPCServer from the stdlib.
My code looks something like this:
import SimpleXMLRPCServer
import socket
class RemoteStarter:
def start(self):
return 'foo'
rs = RemoteStarter()
host = socket.gethostbyaddr(socket.gethostname())[0]
port = 9000
server = SimpleXMLRPCServer.SimpleXMLRPCServer((host, port))
server.register_instance(rs)
server.serve_forever()
every time the 'start' method gets called remotely, the server prints an access line like this:
<server_name> - - [10/Mar/2010 13:06:20] "POST /RPC2 HTTP/1.0" 200 -
I can't figure out a way to silence the output so it doesn't print these access lines to stdout.
anyone?
|
[
"the answer is:\npass logRequests=False to SimpleXMLRPCServer when you create it:\nserver = SimpleXMLRPCServer.SimpleXMLRPCServer((host, port), logRequests=False)\n\n"
] |
[
9
] |
[] |
[] |
[
"python",
"xml_rpc"
] |
stackoverflow_0002419405_python_xml_rpc.txt
|
Q:
How to create instances of a class from a static method?
Here is my problem. I have created a pretty heavy readonly class making many database calls with a static "factory" method. The goal of this method is to avoid killing the database by looking in a pool of already-created objects if an identical instance of the same object (same type, same init parameters) already exists.
If something was found, the method will just return it. No problem. But if not, how may I create an instance of the object, in a way that works with inheritance?
>>> class A(Object):
>>> @classmethod
>>> def get_cached_obj(self, some_identifier):
>>> # Should do something like `return A(idenfier)`, but in a way that works
>>> class B(A):
>>> pass
>>> A.get_cached_obj('foo') # Should do the same as A('foo')
>>> A().get_cached_obj('foo') # Should do the same as A('foo')
>>> B.get_cached_obj('bar') # Should do the same as B('bar')
>>> B().get_cached_obj('bar') # Should do the same as B('bar')
Thanks.
A:
import weakref
class A(object):
_get_obj_cache = weakref.WeakValueDictionary()
@classmethod
def get_obj(cls, identifier):
cache = cls._get_obj_cache
obj = cache.get((cls, identifier))
if obj is None:
obj = cache[(cls, identifier)] = cls(identifier)
return obj
class B(A):
pass
Because a WeakValueDictionary is used, the objects will remain cached as long as you have any other reference to them, and you can call SomeClass.get_obj(identifier) as many times as you like to get that same object. If I've understood you correctly, it's the cls(identifier) which will hit the database and what you want to call less frequently, since you know the objects are immutable.
If you want to keep objects in the cache even if they are no longer referenced elsewhere, then change the WeakValueDictionary into a normal dict.
This requires that identifier is suitable for a dict key, and if it's a string as you have in your example code, then it is.
A:
One usual approach is this.
class SomeClass( object ):
# Something that is precious and needs to be pooled.
class SomeClassPool( object ):
def __init__( self ):
self.pool= [ SomeClass() ]
def getInstance( self ):
if len(self.pool) == 0:
self.pool.append( SomeClass() )
# maybe allocate several, depends on the costs
return self.pool.pop()
def release( self, anInstance ):
self.pool.append( anInstance )
We separate the pool from the objects being pooled. They have nothing to do with each other.
You can subclass the objects being pooled all you want.
You can -- independently -- change the pooling strategies without breaking or retesting the objects being pooled.
A:
Expanding on S.Lott's comment:
"I want to return the correct instance
each time, without removing it from
the pool". You mean you want a
dictionary of objects? -S.Lott
the_cache = {}
def get_obj(cls, identifier):
key = (cls, identifier)
if key not in the_cache:
the_cache[key] = cls(identifier)
return the_cache[key]
or
def get_obj(cls, identifier):
key = (cls, identifier)
try:
return the_cache[key]
except KeyError:
the_cache[key] = cls(identifier)
return the_cache[key]
|
How to create instances of a class from a static method?
|
Here is my problem. I have created a pretty heavy readonly class making many database calls with a static "factory" method. The goal of this method is to avoid killing the database by looking in a pool of already-created objects if an identical instance of the same object (same type, same init parameters) already exists.
If something was found, the method will just return it. No problem. But if not, how may I create an instance of the object, in a way that works with inheritance?
>>> class A(Object):
>>> @classmethod
>>> def get_cached_obj(self, some_identifier):
>>> # Should do something like `return A(idenfier)`, but in a way that works
>>> class B(A):
>>> pass
>>> A.get_cached_obj('foo') # Should do the same as A('foo')
>>> A().get_cached_obj('foo') # Should do the same as A('foo')
>>> B.get_cached_obj('bar') # Should do the same as B('bar')
>>> B().get_cached_obj('bar') # Should do the same as B('bar')
Thanks.
|
[
"import weakref\n\nclass A(object):\n _get_obj_cache = weakref.WeakValueDictionary()\n @classmethod\n def get_obj(cls, identifier):\n cache = cls._get_obj_cache\n obj = cache.get((cls, identifier))\n if obj is None:\n obj = cache[(cls, identifier)] = cls(identifier)\n return obj\n\nclass B(A):\n pass\n\nBecause a WeakValueDictionary is used, the objects will remain cached as long as you have any other reference to them, and you can call SomeClass.get_obj(identifier) as many times as you like to get that same object. If I've understood you correctly, it's the cls(identifier) which will hit the database and what you want to call less frequently, since you know the objects are immutable.\nIf you want to keep objects in the cache even if they are no longer referenced elsewhere, then change the WeakValueDictionary into a normal dict.\nThis requires that identifier is suitable for a dict key, and if it's a string as you have in your example code, then it is.\n",
"One usual approach is this.\nclass SomeClass( object ):\n # Something that is precious and needs to be pooled.\n\nclass SomeClassPool( object ):\n def __init__( self ):\n self.pool= [ SomeClass() ]\n def getInstance( self ):\n if len(self.pool) == 0:\n self.pool.append( SomeClass() )\n # maybe allocate several, depends on the costs\n return self.pool.pop()\n def release( self, anInstance ):\n self.pool.append( anInstance )\n\nWe separate the pool from the objects being pooled. They have nothing to do with each other.\nYou can subclass the objects being pooled all you want.\nYou can -- independently -- change the pooling strategies without breaking or retesting the objects being pooled.\n",
"Expanding on S.Lott's comment:\n\n\"I want to return the correct instance\n each time, without removing it from\n the pool\". You mean you want a\n dictionary of objects? -S.Lott\n\nthe_cache = {}\n\ndef get_obj(cls, identifier):\n key = (cls, identifier)\n if key not in the_cache:\n the_cache[key] = cls(identifier)\n return the_cache[key]\n\nor\ndef get_obj(cls, identifier):\n key = (cls, identifier)\n try:\n return the_cache[key]\n except KeyError:\n the_cache[key] = cls(identifier)\n return the_cache[key]\n\n"
] |
[
5,
1,
0
] |
[] |
[] |
[
"python"
] |
stackoverflow_0002426690_python.txt
|
Q:
datetime command line argument in python 2.4
I want to pass a datetime value into my python script on the command line. My first idea was to use optparse and pass the value in as a string, then use datetime.strptime to convert it to a datetime. This works fine on my machine (python 2.6), but I also need to run this script on machines that are running python 2.4, which doesn't have datetime.strptime.
How can I pass the datetime value to the script in python 2.4?
Here's the code I'm using in 2.6:
parser = optparse.OptionParser()
parser.add_option("-m", "--max_timestamp", dest="max_timestamp",
help="only aggregate items older than MAX_TIMESTAMP",
metavar="MAX_TIMESTAMP(YYYY-MM-DD HH24:MM)")
options,args = parser.parse_args()
if options.max_timestamp:
# Try parsing the date argument
try:
max_timestamp = datetime.datetime.strptime(options.max_timestamp, "%Y-%m-%d %H:%M")
except:
print "Error parsing date input:",sys.exc_info()
sys.exit(1)
A:
Go by way of the time module, which did already have strptime in 2.4:
>>> import time
>>> t = time.strptime("2010-02-02 7:31", "%Y-%m-%d %H:%M")
>>> t
(2010, 2, 2, 7, 31, 0, 1, 33, -1)
>>> import datetime
>>> datetime.datetime(*t[:6])
datetime.datetime(2010, 2, 2, 7, 31)
|
datetime command line argument in python 2.4
|
I want to pass a datetime value into my python script on the command line. My first idea was to use optparse and pass the value in as a string, then use datetime.strptime to convert it to a datetime. This works fine on my machine (python 2.6), but I also need to run this script on machines that are running python 2.4, which doesn't have datetime.strptime.
How can I pass the datetime value to the script in python 2.4?
Here's the code I'm using in 2.6:
parser = optparse.OptionParser()
parser.add_option("-m", "--max_timestamp", dest="max_timestamp",
help="only aggregate items older than MAX_TIMESTAMP",
metavar="MAX_TIMESTAMP(YYYY-MM-DD HH24:MM)")
options,args = parser.parse_args()
if options.max_timestamp:
# Try parsing the date argument
try:
max_timestamp = datetime.datetime.strptime(options.max_timestamp, "%Y-%m-%d %H:%M")
except:
print "Error parsing date input:",sys.exc_info()
sys.exit(1)
|
[
"Go by way of the time module, which did already have strptime in 2.4:\n>>> import time\n>>> t = time.strptime(\"2010-02-02 7:31\", \"%Y-%m-%d %H:%M\")\n>>> t\n(2010, 2, 2, 7, 31, 0, 1, 33, -1)\n>>> import datetime\n>>> datetime.datetime(*t[:6])\ndatetime.datetime(2010, 2, 2, 7, 31)\n\n"
] |
[
16
] |
[] |
[] |
[
"datetime",
"python"
] |
stackoverflow_0002428746_datetime_python.txt
|
Q:
os.path.getmtime() doesn't return fraction of a second
I compiled python 2.6.4 for centos 5.3 and find this issue that os.path.getmtime() or os.stat().m_time doesn't have the fraction part. As per docs, if os.stat_float_times() returns True, then it should return float value. In my case, I do see it as float, but no fraction part (it is 0).
In [3]: os.path.getmtime('/tmp')
Out[3]: 1268339116.0
In [4]: os.stat('/tmp')
Out[4]: posix.stat_result(st_mode=17407, st_ino=508897L, st_dev=29952L, st_nlink=7, st_uid=0, st_gid=0, st_size=4096L, st_atime=1268101696, st_mtime=1268339116, st_ctime=1268339116)
In [5]: os.stat_float_times()
True
In [6]: os.stat('/tmp').st_mtime
Out[6]: 1268339116.0
It is also strange that the stat() output seems like an int. On windows, I do see a fraction part with the same python version. I am running centos on top of colinux, could that be playing a role, or is it some python build issue? I couldn't find any hits for generic colinux issue. May be it is how colinux configures the filesystem? What would I need to check in that case?
A:
This is a filesystem limitation, rather than a Python one. Centos is still on ext3, which provides integer mtimes. You can see this if you display the mtimes with ls. Try
ls -ld --full-time /tmp
On my ext3 Centos box, I get
drwxrwxrwt 11 root root 69632 2010-03-11 13:16:30.000000000 -0800 /tmp
On my ext4 Ubuntu box, I get
drwxrwxrwt 16 root root 20480 2010-03-11 21:20:02.088188962 +0000 /tmp
This is described in the ext4 Wikipedia article:
Improved timestamps
As computers become faster in general and as Linux becomes used more for mission critical applications, the granularity of second-based timestamps becomes insufficient. To solve this, ext4 provides timestamps measured in nanoseconds. In addition, 2 bits of the expanded timestamp field are added to the most significant bits of the seconds field of the timestamps to defer the year 2038 problem for an additional 204 years.
|
os.path.getmtime() doesn't return fraction of a second
|
I compiled python 2.6.4 for centos 5.3 and find this issue that os.path.getmtime() or os.stat().m_time doesn't have the fraction part. As per docs, if os.stat_float_times() returns True, then it should return float value. In my case, I do see it as float, but no fraction part (it is 0).
In [3]: os.path.getmtime('/tmp')
Out[3]: 1268339116.0
In [4]: os.stat('/tmp')
Out[4]: posix.stat_result(st_mode=17407, st_ino=508897L, st_dev=29952L, st_nlink=7, st_uid=0, st_gid=0, st_size=4096L, st_atime=1268101696, st_mtime=1268339116, st_ctime=1268339116)
In [5]: os.stat_float_times()
True
In [6]: os.stat('/tmp').st_mtime
Out[6]: 1268339116.0
It is also strange that the stat() output seems like an int. On windows, I do see a fraction part with the same python version. I am running centos on top of colinux, could that be playing a role, or is it some python build issue? I couldn't find any hits for generic colinux issue. May be it is how colinux configures the filesystem? What would I need to check in that case?
|
[
"This is a filesystem limitation, rather than a Python one. Centos is still on ext3, which provides integer mtimes. You can see this if you display the mtimes with ls. Try\nls -ld --full-time /tmp\n\nOn my ext3 Centos box, I get\ndrwxrwxrwt 11 root root 69632 2010-03-11 13:16:30.000000000 -0800 /tmp\n\nOn my ext4 Ubuntu box, I get\ndrwxrwxrwt 16 root root 20480 2010-03-11 21:20:02.088188962 +0000 /tmp\n\nThis is described in the ext4 Wikipedia article:\n\nImproved timestamps\nAs computers become faster in general and as Linux becomes used more for mission critical applications, the granularity of second-based timestamps becomes insufficient. To solve this, ext4 provides timestamps measured in nanoseconds. In addition, 2 bits of the expanded timestamp field are added to the most significant bits of the seconds field of the timestamps to defer the year 2038 problem for an additional 204 years.\n\n"
] |
[
6
] |
[] |
[] |
[
"centos",
"linux",
"python"
] |
stackoverflow_0002428556_centos_linux_python.txt
|
Q:
Most efficent way to create all possible combinations of four lists in Python?
I have four different lists. headers, descriptions, short_descriptions and misc. I want to combine these into all the possible ways to print out:
header\n
description\n
short_description\n
misc
like if i had (i'm skipping short_description and misc in this example for obvious reasons)
headers = ['Hello there', 'Hi there!']
description = ['I like pie', 'Ho ho ho']
...
I want it to print out like:
Hello there
I like pie
...
Hello there
Ho ho ho
...
Hi there!
I like pie
...
Hi there!
Ho ho ho
...
What would you say is the best/cleanest/most efficent way to do this? Is for-nesting the only way to go?
A:
Is this what you're looking for?
http://docs.python.org/library/itertools.html#itertools.product
A:
import itertools
headers = ['Hello there', 'Hi there!']
description = ['I like pie', 'Ho ho ho']
for p in itertools.product(headers,description):
print('\n'.join(p)+'\n')
A:
A generator expression to do that:
for h, d in ((h,d) for h in headers for d in description):
print h
print d
A:
Have a look to the itertools module, it contains functions to get combinations and permutations from any iterables.
A:
>>> h = 'h1 h2 h3'.split()
>>> h
['h1', 'h2', 'h3']
>>> d = 'd1 d2'.split()
>>> s = 's1 s2 s3'.split()
>>> lists = [h, d, s]
>>> from itertools import product
>>> for hds in product(*lists):
print(', '.join(hds))
h1, d1, s1
h1, d1, s2
h1, d1, s3
h1, d2, s1
h1, d2, s2
h1, d2, s3
h2, d1, s1
h2, d1, s2
h2, d1, s3
h2, d2, s1
h2, d2, s2
h2, d2, s3
h3, d1, s1
h3, d1, s2
h3, d1, s3
h3, d2, s1
h3, d2, s2
h3, d2, s3
>>>
|
Most efficent way to create all possible combinations of four lists in Python?
|
I have four different lists. headers, descriptions, short_descriptions and misc. I want to combine these into all the possible ways to print out:
header\n
description\n
short_description\n
misc
like if i had (i'm skipping short_description and misc in this example for obvious reasons)
headers = ['Hello there', 'Hi there!']
description = ['I like pie', 'Ho ho ho']
...
I want it to print out like:
Hello there
I like pie
...
Hello there
Ho ho ho
...
Hi there!
I like pie
...
Hi there!
Ho ho ho
...
What would you say is the best/cleanest/most efficent way to do this? Is for-nesting the only way to go?
|
[
"Is this what you're looking for?\nhttp://docs.python.org/library/itertools.html#itertools.product\n",
"import itertools\n\nheaders = ['Hello there', 'Hi there!']\ndescription = ['I like pie', 'Ho ho ho']\n\nfor p in itertools.product(headers,description):\n print('\\n'.join(p)+'\\n')\n\n",
"A generator expression to do that:\nfor h, d in ((h,d) for h in headers for d in description):\n print h\n print d\n\n",
"Have a look to the itertools module, it contains functions to get combinations and permutations from any iterables.\n",
">>> h = 'h1 h2 h3'.split()\n>>> h\n['h1', 'h2', 'h3']\n>>> d = 'd1 d2'.split()\n>>> s = 's1 s2 s3'.split()\n>>> lists = [h, d, s]\n>>> from itertools import product\n>>> for hds in product(*lists):\n print(', '.join(hds))\n\nh1, d1, s1\nh1, d1, s2\nh1, d1, s3\nh1, d2, s1\nh1, d2, s2\nh1, d2, s3\nh2, d1, s1\nh2, d1, s2\nh2, d1, s3\nh2, d2, s1\nh2, d2, s2\nh2, d2, s3\nh3, d1, s1\nh3, d1, s2\nh3, d1, s3\nh3, d2, s1\nh3, d2, s2\nh3, d2, s3\n>>> \n\n"
] |
[
10,
4,
3,
0,
0
] |
[] |
[] |
[
"algorithm",
"python"
] |
stackoverflow_0002390316_algorithm_python.txt
|
Q:
Mimic Haskell with Python
Haskell provides the feature something like f = f1 . f2
How can I mimic that with Python?
For example, if I have to do the 'map' operation two times, is there any way to do something like map . map in Python?
x = ['1','2','3']
x = map(int,x)
x = map(lambda i:i+1, x)
A:
I think you are looking for function composition in Python.
You can do this:
f = lambda x: f1(f2(x))
A:
There have been several proposals for a compose operation, but none have been formalized. In the meantime it is possible to use a list comprehension or a generator expression to apply complex transformations to a sequence.
A:
def compose(f,g):
return lambda x: f(g(x))
def inc(x): return x+1
map(compose(inc, int), ['1', '2', '3'])
# [2, 3, 4]
A:
>>> import functional, functools, operator
>>> f1 = int
>>> f2 = functools.partial(operator.add, 1)
>>> f = functional.compose(f1, f2)
>>> x = map(f, ['1', '2', '3'])
A:
There's a good recipe for this here.
|
Mimic Haskell with Python
|
Haskell provides the feature something like f = f1 . f2
How can I mimic that with Python?
For example, if I have to do the 'map' operation two times, is there any way to do something like map . map in Python?
x = ['1','2','3']
x = map(int,x)
x = map(lambda i:i+1, x)
|
[
"I think you are looking for function composition in Python.\nYou can do this:\nf = lambda x: f1(f2(x))\n\n",
"There have been several proposals for a compose operation, but none have been formalized. In the meantime it is possible to use a list comprehension or a generator expression to apply complex transformations to a sequence.\n",
"def compose(f,g):\n return lambda x: f(g(x))\n\ndef inc(x): return x+1\n\nmap(compose(inc, int), ['1', '2', '3'])\n# [2, 3, 4]\n\n",
"\n>>> import functional, functools, operator\n>>> f1 = int\n>>> f2 = functools.partial(operator.add, 1)\n>>> f = functional.compose(f1, f2)\n>>> x = map(f, ['1', '2', '3'])\n\n",
"There's a good recipe for this here.\n"
] |
[
2,
1,
1,
1,
0
] |
[] |
[] |
[
"python"
] |
stackoverflow_0002429039_python.txt
|
Q:
How to determine if the given object is of given type in Python?
I always thought operator is determined if the given variable is of the given type. But I just determined it was not true:
>>> class A():
pass
...
>>> a = A()
>>> a is A
False
How do I test if a is of type class A?
Please advise.
Thanks, Boda Cydo.
A:
You want isinstance(a, A).
Keep in mind, it might be better to avoid the isinstance check by adding methods to A that make it do what you want without explicitly determining that it is an A.
is determines if two objects are the same object.
A:
isinstance(a,A)
|
How to determine if the given object is of given type in Python?
|
I always thought operator is determined if the given variable is of the given type. But I just determined it was not true:
>>> class A():
pass
...
>>> a = A()
>>> a is A
False
How do I test if a is of type class A?
Please advise.
Thanks, Boda Cydo.
|
[
"You want isinstance(a, A).\nKeep in mind, it might be better to avoid the isinstance check by adding methods to A that make it do what you want without explicitly determining that it is an A.\nis determines if two objects are the same object.\n",
"isinstance(a,A)\n"
] |
[
7,
2
] |
[] |
[] |
[
"python",
"types"
] |
stackoverflow_0002429164_python_types.txt
|
Q:
Merging all sub-arrays with mutual elements into one sub-array
I need to find all sub-arrays which share any mutual element and merge them into one sub-array.
(Implementing in Python but any algorithmic idea would be helpful)
Multidimensional array structure:
categories = {'car':['automobile','auto'],
'bike':['vehicle','motorcycle','motorbike','automobile'],
'software':['computer','macbook','apple','microsoft','mozilla'],
'firefox':['internet','mozilla','browser']
'bicycle':['vehicle']}
I'd like to have 'car', 'bike' and 'bicycle' merged into one list (keep first list's key new list's key could be any of the relevant keys) and 'software' and 'firefox' merged into one list as well.
Performance is crucial.
Best solution I could come with so far is to maintain a flatten one-dimension array of element => list_key (e.g 'automobile' => 'car') and then run the following recursive function for each list in the multidimensional array (pseudocode):
function merge_similar(list_key):
For each element in categories[list_key]:
If flatten_array.has_key(element):
list_to_merge = flatten_array[element]
merge_similar(list_to_merge) /* merge other lists which share an element with our newly found similar list */
categories[list_key] = merge(categories [list_key], categories[list_to_merge])
delete categories[list_to_merge]
Any idea how to improve it's performance?
Thanks!
A:
Note that there is no "first key" -- dicts don't keep order, so if you need some order preserved you'll need to start from some different, alternative data structure.
Apart from order-related issues, I'd start with something like:
def merged(dictoflists):
result = dict()
reversed = dict()
for k, l in dictoflists.iteritems():
intersecting = set(reversed.get(w) for w in l) - set([None])
if intersecting:
pickone = intersecting.pop()
into = result[pickone]
else:
pickone = k
into = result[k] = set()
for ok in intersecting:
into.update(result.pop(ok))
into.update(l)
for w in into:
reversed[w] = pickone
return dict((k, sorted(l)) for k, l in result.iteritems())
If order is important to you, the uses of set will be problematic and you'll need more complicated (and slower) data structures -- however, if that's the case, you should first specify in complete detail exactly what ordering constraints you need to respect in the various possible cases that can occur.
A:
I can't imagine that a recursive solution would be speedy.
Is using list.extend() too slow?
You could do something like this:
categories['car'].extend(categories['bike']);
categories['car'].extend(categories['bicycle']);
Or to be more general, if you pass in a list of keys you want to merge:
first_key=None;
for key in keys_whose_lists_I_want_to_merge:
if first_key is None:
first_key=key;
else:
categories[first_key].extend(categories[key]);
If you're merging a ton of lists, you can optimize that loop to not perform the None check after the first time. See the tip entitled 'Re-map Functions at runtime' on the Python Performance Tips page.
A:
>>> categories = {'car':['automobile','auto'],
'bike':['vehicle','motorcycle','motorbike','automobile'],
'software':['computer','macbook','apple','microsoft','mozilla'],
'firefox':['internet','mozilla','browser'],
'bicycle':['vehicle']}
>>> # Use sets for values
>>> for k,v in categories.items(): categories[k] = set(v)
>>> # Acumulate
>>> for k1, v1 in categories.items():
if v1:
for k2,v2 in categories.items():
if v2 and k1 != k2 and v1 & v2:
v1 |= v2
categories[k2] = None
categories[k1] = v1
>>> # Print
>>> for k1, v1 in categories.items():
if v1: print('%s: %r' %(k1,v1))
bicycle: {'motorbike', 'vehicle', 'auto', 'automobile', 'motorcycle'}
firefox: {'apple', 'mozilla', 'macbook', 'computer', 'internet', 'microsoft', 'browser'}
>>>
|
Merging all sub-arrays with mutual elements into one sub-array
|
I need to find all sub-arrays which share any mutual element and merge them into one sub-array.
(Implementing in Python but any algorithmic idea would be helpful)
Multidimensional array structure:
categories = {'car':['automobile','auto'],
'bike':['vehicle','motorcycle','motorbike','automobile'],
'software':['computer','macbook','apple','microsoft','mozilla'],
'firefox':['internet','mozilla','browser']
'bicycle':['vehicle']}
I'd like to have 'car', 'bike' and 'bicycle' merged into one list (keep first list's key new list's key could be any of the relevant keys) and 'software' and 'firefox' merged into one list as well.
Performance is crucial.
Best solution I could come with so far is to maintain a flatten one-dimension array of element => list_key (e.g 'automobile' => 'car') and then run the following recursive function for each list in the multidimensional array (pseudocode):
function merge_similar(list_key):
For each element in categories[list_key]:
If flatten_array.has_key(element):
list_to_merge = flatten_array[element]
merge_similar(list_to_merge) /* merge other lists which share an element with our newly found similar list */
categories[list_key] = merge(categories [list_key], categories[list_to_merge])
delete categories[list_to_merge]
Any idea how to improve it's performance?
Thanks!
|
[
"Note that there is no \"first key\" -- dicts don't keep order, so if you need some order preserved you'll need to start from some different, alternative data structure.\nApart from order-related issues, I'd start with something like:\ndef merged(dictoflists):\n result = dict()\n reversed = dict()\n for k, l in dictoflists.iteritems():\n intersecting = set(reversed.get(w) for w in l) - set([None])\n if intersecting:\n pickone = intersecting.pop()\n into = result[pickone]\n else:\n pickone = k\n into = result[k] = set()\n for ok in intersecting:\n into.update(result.pop(ok))\n into.update(l)\n for w in into:\n reversed[w] = pickone\n return dict((k, sorted(l)) for k, l in result.iteritems())\n\nIf order is important to you, the uses of set will be problematic and you'll need more complicated (and slower) data structures -- however, if that's the case, you should first specify in complete detail exactly what ordering constraints you need to respect in the various possible cases that can occur.\n",
"I can't imagine that a recursive solution would be speedy.\nIs using list.extend() too slow?\nYou could do something like this: \ncategories['car'].extend(categories['bike']);\ncategories['car'].extend(categories['bicycle']);\n\nOr to be more general, if you pass in a list of keys you want to merge:\nfirst_key=None;\nfor key in keys_whose_lists_I_want_to_merge:\n if first_key is None:\n first_key=key;\n else:\n categories[first_key].extend(categories[key]);\n\nIf you're merging a ton of lists, you can optimize that loop to not perform the None check after the first time. See the tip entitled 'Re-map Functions at runtime' on the Python Performance Tips page.\n",
">>> categories = {'car':['automobile','auto'],\n 'bike':['vehicle','motorcycle','motorbike','automobile'],\n 'software':['computer','macbook','apple','microsoft','mozilla'],\n 'firefox':['internet','mozilla','browser'],\n 'bicycle':['vehicle']}\n>>> # Use sets for values\n>>> for k,v in categories.items(): categories[k] = set(v)\n\n>>> # Acumulate\n>>> for k1, v1 in categories.items():\n if v1:\n for k2,v2 in categories.items():\n if v2 and k1 != k2 and v1 & v2:\n v1 |= v2\n categories[k2] = None\n categories[k1] = v1\n\n\n>>> # Print\n>>> for k1, v1 in categories.items():\n if v1: print('%s: %r' %(k1,v1))\n\n\nbicycle: {'motorbike', 'vehicle', 'auto', 'automobile', 'motorcycle'}\nfirefox: {'apple', 'mozilla', 'macbook', 'computer', 'internet', 'microsoft', 'browser'}\n>>> \n\n"
] |
[
2,
0,
0
] |
[] |
[] |
[
"algorithm",
"arrays",
"performance",
"python"
] |
stackoverflow_0002098948_algorithm_arrays_performance_python.txt
|
Q:
Difference between Python dynamic field lookup
What's the difference (if any) between
model.__dict__['title_en']
and
model.__getattribute__('title_en')
and what's best practice ?
A:
Best practice? Use getattr.
getattr(model, 'title_en')
You only want __getattr__ or __getattribute__ when you want to override the default attribute fetching mechanism.
A:
As others have said, the getattr built-in is the right way to get an attribute (in general you don't access Python special methods directly: you access them through built-ins and operators!).
getattr does a lot more than a lookup in the object's __dict__: it supports properties and other descriptors, attributes inherited from the class and its bases (such as methods), attributes that may be dynamically generated via a __getattr__ method (in the object's class, or, again, one of its bases). Just like direct access model.title_en does, when you know the name at the time you're writing the code (in which case of course you wouldn't use getattr;-). This makes it by far the preferred way of accessing an attribute whose name you "learn" only dynamically!
A:
The first won't work because __dict__ is supposed to be a dictionary, not a function. And the correct way is getattr(model, 'title_en').
|
Difference between Python dynamic field lookup
|
What's the difference (if any) between
model.__dict__['title_en']
and
model.__getattribute__('title_en')
and what's best practice ?
|
[
"Best practice? Use getattr.\ngetattr(model, 'title_en')\n\nYou only want __getattr__ or __getattribute__ when you want to override the default attribute fetching mechanism.\n",
"As others have said, the getattr built-in is the right way to get an attribute (in general you don't access Python special methods directly: you access them through built-ins and operators!).\ngetattr does a lot more than a lookup in the object's __dict__: it supports properties and other descriptors, attributes inherited from the class and its bases (such as methods), attributes that may be dynamically generated via a __getattr__ method (in the object's class, or, again, one of its bases). Just like direct access model.title_en does, when you know the name at the time you're writing the code (in which case of course you wouldn't use getattr;-). This makes it by far the preferred way of accessing an attribute whose name you \"learn\" only dynamically!\n",
"The first won't work because __dict__ is supposed to be a dictionary, not a function. And the correct way is getattr(model, 'title_en').\n"
] |
[
5,
5,
1
] |
[] |
[] |
[
"python"
] |
stackoverflow_0002429232_python.txt
|
Q:
Why is Decimal('0') > 9999.0 True in Python?
This is somehow related to my question Why is ''>0 True in Python?
In Python 2.6.4:
>> Decimal('0') > 9999.0
True
From the answer to my original question I understand that when comparing objects of different types in Python 2.x the types are ordered by their name. But in this case:
>> type(Decimal('0')).__name__ > type(9999.0).__name__
False
Why is Decimal('0') > 9999.0 == True then?
UPDATE: I usually work on Ubuntu (Linux 2.6.31-20-generic #57-Ubuntu SMP Mon Feb 8 09:05:19 UTC 2010 i686 GNU/Linux, Python 2.6.4 (r264:75706, Dec 7 2009, 18:45:15) [GCC 4.4.1] on linux2). On Windows (WinXP Professional SP3, Python 2.6.4 (r264:75706, Nov 3 2009, 13:23:17) [MSC v.1500 32 bit (Intel)] on win32) my original statement works differently:
>> Decimal('0') > 9999.0
False
I even more puzzled now. %-(
A:
Because the decimal module does not compare against any type except long, int, and Decimal. In all other cases, decimal silently returns the "not something it knows about object" as greater. You can see this behavior in the _convert_other() function of decimal.py
Silly, silly Decimal class.
Oh, see http://bugs.python.org/issue2531 as well.
So, here is what happens:
The interpreter calls the Decimal.__gt__ comparison function.
Decimal.__gt__ calls Decimal._convert_other to convert the incoming float to a Decimal.
Decimal._convert_other doesn't understand floats. The implementation down in Decimal._convert_other
explicitly checks for long, int, and Decimal types of the operand. Yes, this is
a bug, in that unexpected library implementations cause bugs further down the line. It
would be cleaner to do the right thing or even just through a TypeException. Instead
it throughs the same NotImplemented that would happen comparing a Decimal to, say,
a hash of Employee records.
A few other comparison operations are tried. Comparison gives up.
The default comparison, down in CPython's Objects/object.c/default_3way_compare get called.
In Python 3, this rightly barfs. In Python 2, it compares the id() functions.
On Windows, a case insensitive comparison is used (sort of). On modern systems, a
case sensitive comparison is used.
So you get different results.
Are we there yet?
A:
def __gt__(self, other, context=None):
other = _convert_other(other)
if other is NotImplemented:
return other
ans = self._compare_check_nans(other, context)
if ans:
return False
return self._cmp(other) > 0
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
|
Why is Decimal('0') > 9999.0 True in Python?
|
This is somehow related to my question Why is ''>0 True in Python?
In Python 2.6.4:
>> Decimal('0') > 9999.0
True
From the answer to my original question I understand that when comparing objects of different types in Python 2.x the types are ordered by their name. But in this case:
>> type(Decimal('0')).__name__ > type(9999.0).__name__
False
Why is Decimal('0') > 9999.0 == True then?
UPDATE: I usually work on Ubuntu (Linux 2.6.31-20-generic #57-Ubuntu SMP Mon Feb 8 09:05:19 UTC 2010 i686 GNU/Linux, Python 2.6.4 (r264:75706, Dec 7 2009, 18:45:15) [GCC 4.4.1] on linux2). On Windows (WinXP Professional SP3, Python 2.6.4 (r264:75706, Nov 3 2009, 13:23:17) [MSC v.1500 32 bit (Intel)] on win32) my original statement works differently:
>> Decimal('0') > 9999.0
False
I even more puzzled now. %-(
|
[
"Because the decimal module does not compare against any type except long, int, and Decimal. In all other cases, decimal silently returns the \"not something it knows about object\" as greater. You can see this behavior in the _convert_other() function of decimal.py\nSilly, silly Decimal class. \nOh, see http://bugs.python.org/issue2531 as well.\nSo, here is what happens:\n\nThe interpreter calls the Decimal.__gt__ comparison function. \nDecimal.__gt__ calls Decimal._convert_other to convert the incoming float to a Decimal.\nDecimal._convert_other doesn't understand floats. The implementation down in Decimal._convert_other \nexplicitly checks for long, int, and Decimal types of the operand. Yes, this is \na bug, in that unexpected library implementations cause bugs further down the line. It\nwould be cleaner to do the right thing or even just through a TypeException. Instead\nit throughs the same NotImplemented that would happen comparing a Decimal to, say,\na hash of Employee records.\nA few other comparison operations are tried. Comparison gives up.\nThe default comparison, down in CPython's Objects/object.c/default_3way_compare get called. \nIn Python 3, this rightly barfs. In Python 2, it compares the id() functions.\nOn Windows, a case insensitive comparison is used (sort of). On modern systems, a \ncase sensitive comparison is used.\nSo you get different results.\n\nAre we there yet?\n",
"def __gt__(self, other, context=None):\n other = _convert_other(other)\n if other is NotImplemented:\n return other\n ans = self._compare_check_nans(other, context)\n if ans:\n return False\n return self._cmp(other) > 0\n\n\ndef _convert_other(other, raiseit=False):\n \"\"\"Convert other to Decimal.\n\n Verifies that it's ok to use in an implicit construction.\n \"\"\"\n if isinstance(other, Decimal):\n return other\n if isinstance(other, (int, long)):\n return Decimal(other)\n if raiseit:\n raise TypeError(\"Unable to convert %s to Decimal\" % other)\n return NotImplemented\n\n"
] |
[
12,
1
] |
[] |
[] |
[
"comparison",
"logic",
"operators",
"python",
"types"
] |
stackoverflow_0002429475_comparison_logic_operators_python_types.txt
|
Q:
python: variable not getting defined after several conditionals
For some reason this program is saying that 'switch' is not defined. What is going on?
#PYTHON 3.1.1
class mysrt:
def __init__(self):
self.DATA = open('ORDER.txt', 'r')
self.collect = 0
cache1 = str(self.DATA.readlines())
cache2 = []
for i in range(len(cache1)):
if cache1[i] == '*':
if self.collect == 0: self.collect = 1
elif self.collect == 1: self.collect = 0
elif self.collect == 1:
cache2.append(cache1[i])
self.ORDER = cache2
self.ARRAY = []
self.GLOBALi = 0
self.GLOBALmax = range(len(self.ORDER))
self.GLOBALc = []
self.GLOBALl = []
def sorter(self, array):
CACHE_LIST_1 = []
CACHE_LIST_2 = []
i = 0
for ORDERi in range(len(self.ORDER)):
for ARRAYi in range(len(array)):
CACHE = array[ARRAYi]
if CACHE[self.GLOBALi] == self.ORDER[ORDERi]:
CACHE_LIST_1.append(CACHE)
else:
CACHE_LIST_2.append(CACHE)
for i in range(len(CACHE_LIST_1)):
if CACHE_LIST_1[0] == CACHE_LIST_1[i] or range(len(CACHE_LIST_1)) == 1:
switch = 1
print ('1')
else:
switch = 0
print ('0')
break
if switch == 1:
self.GLOBALl += CACHE_LIST_1 + self.GLOBALc
self.GLOBALi = 0
self.GLOBALc = []
else:
self.GLOBALi += 1
self.GLOBALc += CACHE_LIST_2
mysrt.sorter(CACHE)
return (self.GLOBALl)
#GLOBALi =0
# if range(len(self.GLOBALc)) =! range(len(self.ARRAY))
array = ['ape', 'cow','dog','bat']
ORDER_FILE = []
mysort = mysrt()
print (mysort.sorter(array))
A:
If CACHE_LIST_1 is an empty sequence then switch will never get bound.
|
python: variable not getting defined after several conditionals
|
For some reason this program is saying that 'switch' is not defined. What is going on?
#PYTHON 3.1.1
class mysrt:
def __init__(self):
self.DATA = open('ORDER.txt', 'r')
self.collect = 0
cache1 = str(self.DATA.readlines())
cache2 = []
for i in range(len(cache1)):
if cache1[i] == '*':
if self.collect == 0: self.collect = 1
elif self.collect == 1: self.collect = 0
elif self.collect == 1:
cache2.append(cache1[i])
self.ORDER = cache2
self.ARRAY = []
self.GLOBALi = 0
self.GLOBALmax = range(len(self.ORDER))
self.GLOBALc = []
self.GLOBALl = []
def sorter(self, array):
CACHE_LIST_1 = []
CACHE_LIST_2 = []
i = 0
for ORDERi in range(len(self.ORDER)):
for ARRAYi in range(len(array)):
CACHE = array[ARRAYi]
if CACHE[self.GLOBALi] == self.ORDER[ORDERi]:
CACHE_LIST_1.append(CACHE)
else:
CACHE_LIST_2.append(CACHE)
for i in range(len(CACHE_LIST_1)):
if CACHE_LIST_1[0] == CACHE_LIST_1[i] or range(len(CACHE_LIST_1)) == 1:
switch = 1
print ('1')
else:
switch = 0
print ('0')
break
if switch == 1:
self.GLOBALl += CACHE_LIST_1 + self.GLOBALc
self.GLOBALi = 0
self.GLOBALc = []
else:
self.GLOBALi += 1
self.GLOBALc += CACHE_LIST_2
mysrt.sorter(CACHE)
return (self.GLOBALl)
#GLOBALi =0
# if range(len(self.GLOBALc)) =! range(len(self.ARRAY))
array = ['ape', 'cow','dog','bat']
ORDER_FILE = []
mysort = mysrt()
print (mysort.sorter(array))
|
[
"If CACHE_LIST_1 is an empty sequence then switch will never get bound.\n"
] |
[
5
] |
[] |
[] |
[
"class",
"python",
"python_3.x"
] |
stackoverflow_0002429637_class_python_python_3.x.txt
|
Q:
What is the purpose of a zip function (as in Python or C# 4.0)?
Someone asked How to do Python’s zip in C#?...
...which leads me to ask, what good is zip? In what scenarios do I need this? Is it really so foundational that I need this in the base class library?
A:
A use case:
>>> fields = ["id", "name", "location"]
>>> values = ["13", "bill", "redmond"]
>>> dict(zip(fields, values))
{'location': 'redmond', 'id': '13', 'name': 'bill'}
Try doing this without zip...
A:
Someone actually asked a question here fairly recently that I answered with the Zip extension method, so it's obviously important for some people. ;)
Actually, it is a fairly important operation for mathematical algorithms - matrices, curve fitting, interpolation, pattern recognition, that sort of thing. Also very important in engineering applications like digital signal processing where much of what you do is combine multiple signals or apply linear transforms to them - both are based on the sample index, hence, zip it. Zipping two sequences is far, far faster than sorting and joining them based on some key, especially when you know in advance that the sequences have the same number of elements and are in the same order.
I can't get into tight specifics here on account of my current employment, but speaking generally, this is also valuable for telemetry data - industrial, scientific, that sort of thing. Often you'll have time sequences of data coming from hundreds or thousands of points - parallel sources - and you need to aggregate, but horizontally, over devices, not over time. At the end, you want another time sequence, but with the sum or average or some other aggregate of all the individual points.
It may sound like a simple sort/group/join in SQL Server (for example) but it's actually really hard to do efficiently this way. For one thing, the timestamps may not match exactly, but you don't care about differences of a few milliseconds, so you end up having to generate a surrogate key/row number and group on that - and of course, the surrogate row number is nothing more than the time index which you already had. Zipping is simple, fast, and infinitely parallelizable.
I don't know if I'd call it foundational, but it it is important. I don't use the Reverse method very often either, but by the same token I'm glad I don't have to keep writing it myself on those rare occasions when I do find a need for it.
One of the reasons it might not seem that useful to you now is that .NET/C# 3.5 does not have tuples. C# 4 does have tuples, and when you're working with tuples, zipping really is a fundamental operation because ordering is strictly enforced.
A:
zip is useful if you'd like to iterate over multiple iterables simultaneously, which is a reasonably common scenario in Python.
One real-world scenario where zip has come in handy for me is if you have an M by N array, and you want to look at columns instead of rows. For example:
>>> five_by_two = ((0, 1), (1, 2), (2, 3), (3, 4), (4, 5))
>>> two_by_five = tuple(zip(*five_by_two))
>>> two_by_five
((0, 1, 2, 3, 4), (1, 2, 3, 4, 5))
A:
It allows you to process sequences in parallel instead of sequentially or nested. There's... so many uses for it that they currently escape me.
A:
Here's a common use case for zip:
x = [1,2,3,4,5]
y = [6,7,8,9,0]
for a,b in zip(x,y):
print a, b
Which would output:
1 6
2 7
3 8
4 9
5 0
A:
It's handy in different places. My favorite, from http://norvig.com/python-iaq.html, is transposing a matrix:
>>> x = [ [1,2,3,4,5],[6,7,8,9,10],[11,12,13,14,15]]
>>> zip(*x)
[(1, 6, 11), (2, 7, 12), (3, 8, 13), (4, 9, 14), (5, 10, 15)]
A:
Here's a case where I used zip() to useful effect, in a Python class for comparing version numbers:
class Version(object):
# ... snip ...
def get_tuple(self):
return (self.major, self.minor, self.revision)
def compare(self, other):
def comp(a, b):
if a == '*' or b == '*':
return 0
elif a == b:
return 0
elif a < b:
return -1
else:
return 1
return tuple(comp(a, b) for a, b in zip(self.get_tuple(), Version(other).get_tuple()))
def is_compatible(self, other):
tup = self.compare(other)
return (tup[0] == 0 and tup[1] == 0)
def __eq__(self, other):
return all(x == 0 for x in self.compare(other))
def __ne__(self, other):
return any(x != 0 for x in self.compare(other))
def __lt__(self, other):
for x in self.compare(other):
if x < 0:
return True
elif x > 0:
return False
return False
def __gt__(self, other):
for x in self.compare(other):
if x > 0:
return True
elif x < 0:
return False
return False
I think zip(), coupled with all() and any(), makes the comparison operator implementations particularly clear and elegant. Sure, it could have been done without zip(), but then the same could be said about practically any language feature.
|
What is the purpose of a zip function (as in Python or C# 4.0)?
|
Someone asked How to do Python’s zip in C#?...
...which leads me to ask, what good is zip? In what scenarios do I need this? Is it really so foundational that I need this in the base class library?
|
[
"A use case:\n>>> fields = [\"id\", \"name\", \"location\"]\n>>> values = [\"13\", \"bill\", \"redmond\"]\n>>> dict(zip(fields, values))\n{'location': 'redmond', 'id': '13', 'name': 'bill'}\n\nTry doing this without zip...\n",
"Someone actually asked a question here fairly recently that I answered with the Zip extension method, so it's obviously important for some people. ;)\nActually, it is a fairly important operation for mathematical algorithms - matrices, curve fitting, interpolation, pattern recognition, that sort of thing. Also very important in engineering applications like digital signal processing where much of what you do is combine multiple signals or apply linear transforms to them - both are based on the sample index, hence, zip it. Zipping two sequences is far, far faster than sorting and joining them based on some key, especially when you know in advance that the sequences have the same number of elements and are in the same order.\nI can't get into tight specifics here on account of my current employment, but speaking generally, this is also valuable for telemetry data - industrial, scientific, that sort of thing. Often you'll have time sequences of data coming from hundreds or thousands of points - parallel sources - and you need to aggregate, but horizontally, over devices, not over time. At the end, you want another time sequence, but with the sum or average or some other aggregate of all the individual points.\nIt may sound like a simple sort/group/join in SQL Server (for example) but it's actually really hard to do efficiently this way. For one thing, the timestamps may not match exactly, but you don't care about differences of a few milliseconds, so you end up having to generate a surrogate key/row number and group on that - and of course, the surrogate row number is nothing more than the time index which you already had. Zipping is simple, fast, and infinitely parallelizable.\nI don't know if I'd call it foundational, but it it is important. I don't use the Reverse method very often either, but by the same token I'm glad I don't have to keep writing it myself on those rare occasions when I do find a need for it.\nOne of the reasons it might not seem that useful to you now is that .NET/C# 3.5 does not have tuples. C# 4 does have tuples, and when you're working with tuples, zipping really is a fundamental operation because ordering is strictly enforced.\n",
"zip is useful if you'd like to iterate over multiple iterables simultaneously, which is a reasonably common scenario in Python.\nOne real-world scenario where zip has come in handy for me is if you have an M by N array, and you want to look at columns instead of rows. For example:\n>>> five_by_two = ((0, 1), (1, 2), (2, 3), (3, 4), (4, 5))\n>>> two_by_five = tuple(zip(*five_by_two))\n>>> two_by_five\n((0, 1, 2, 3, 4), (1, 2, 3, 4, 5))\n\n",
"It allows you to process sequences in parallel instead of sequentially or nested. There's... so many uses for it that they currently escape me.\n",
"Here's a common use case for zip:\nx = [1,2,3,4,5]\ny = [6,7,8,9,0]\n\nfor a,b in zip(x,y):\n print a, b\n\nWhich would output:\n1 6\n2 7\n3 8\n4 9\n5 0\n\n",
"It's handy in different places. My favorite, from http://norvig.com/python-iaq.html, is transposing a matrix:\n>>> x = [ [1,2,3,4,5],[6,7,8,9,10],[11,12,13,14,15]]\n>>> zip(*x)\n[(1, 6, 11), (2, 7, 12), (3, 8, 13), (4, 9, 14), (5, 10, 15)]\n\n",
"Here's a case where I used zip() to useful effect, in a Python class for comparing version numbers:\nclass Version(object):\n\n # ... snip ...\n\n def get_tuple(self):\n return (self.major, self.minor, self.revision)\n\n def compare(self, other):\n def comp(a, b):\n if a == '*' or b == '*':\n return 0\n elif a == b:\n return 0\n elif a < b:\n return -1\n else:\n return 1\n return tuple(comp(a, b) for a, b in zip(self.get_tuple(), Version(other).get_tuple()))\n\n def is_compatible(self, other):\n tup = self.compare(other)\n return (tup[0] == 0 and tup[1] == 0)\n\n def __eq__(self, other):\n return all(x == 0 for x in self.compare(other))\n\n def __ne__(self, other):\n return any(x != 0 for x in self.compare(other))\n\n def __lt__(self, other):\n for x in self.compare(other):\n if x < 0:\n return True\n elif x > 0:\n return False\n return False\n\n def __gt__(self, other):\n for x in self.compare(other):\n if x > 0:\n return True\n elif x < 0:\n return False\n return False\n\nI think zip(), coupled with all() and any(), makes the comparison operator implementations particularly clear and elegant. Sure, it could have been done without zip(), but then the same could be said about practically any language feature.\n"
] |
[
13,
13,
12,
8,
8,
3,
2
] |
[] |
[] |
[
"c#",
"python",
"zip"
] |
stackoverflow_0002429692_c#_python_zip.txt
|
Q:
How to detect an 'image area' percentage inside an image?
Mhh, kinda hard to explain with my poor english ;)
So, lets say I have an image, doesnt matter what kind of (gif, jpg, png) with 200x200 pixel size (total area 40000 pixels)
This image have a background, that can be trasparent, or every color (but i know the background-color in advance).
Lets say that in the middle of this image, there is a picture (for keep the example simple lets suppose is a square drawn), of 100x100 pixels (total area 10000 pixels).
I need to know the area percentage that the small square fill inside the image.
So, in i know the full image size and the background-color, there is a way in php/python to scan the image and retrieve that (in short, counting the pixel that are different from the given background)?
In the above example, the result should be 25%
EDIT: this are two image as example (gimped oin the way ;):
I need to know the percentage of the green pepper in the whole image (that is 400x400)
A:
from PIL import Image
image = Image.open("pepper.png")
bg = image.getpixel((0,0))
width, height = image.size
bg_count = next(n for n,c in image.getcolors(width*height) if c==bg)
img_count = width*height - bg_count
img_percent = img_count*100.0/width/height
gives 7.361875 for both images
A:
I am assuming the surrounding area has only one colour and the object in the image can have any shape (so you need to find out its coordinates first, right?)
If you can use ImageMagick, it's easy.
Store size of image (40000 Pixels)
Send image to ImageMagick and trim the surrounding area using -trim (description here)
Compare size of resulting image (10000 Pixels) with that of original image
If you can't use ImageMagick, you will have to use GD to crop the surrounding area away. A rough description is in the answer to this question. I'm pretty sure this has been implemented in PHP already, though.
A:
Using Python and PIL (Python Imaging Library) you could try the following (untested - credit goes to the original thread here):
from PIL import ImageChops
def trim(im, border):
bg = Image.new(im.mode, im.size, border)
diff = ImageChops.difference(im, bg)
bbox = diff.getbbox()
if bbox:
return im.crop(bbox)
else:
# found no content
raise ValueError("cannot trim; image was empty")
And then do your calculations based on width * height (before and after the trim).
A:
It depends a bit on your accuracy requirements and on the presence of the background color in the image. Consider this annoying test case:
Make a 400 pt large "G".
Make the text white. Hit "Shadow" or "Outline" so it surrounded by black.
Put it on a white background.
Pick your effort:
You can get a bounding box, which heavily overestimates the size of the 'G' because
of the large blank space inside.
You can count the white pixels, which heavily underestimates the size of the 'G' because of the many white pixels inside the outline.
You can pick a color not in the image, like blue, and run a recursive painter's algorithm from the top left corner. Then you can accurately count the blue pixels.
There are faster methods, which are more complicated.
You can usually use PIL (Python Imaging Library) http://www.pythonware.com/products/pil/ to access raw image data from the file formats.
|
How to detect an 'image area' percentage inside an image?
|
Mhh, kinda hard to explain with my poor english ;)
So, lets say I have an image, doesnt matter what kind of (gif, jpg, png) with 200x200 pixel size (total area 40000 pixels)
This image have a background, that can be trasparent, or every color (but i know the background-color in advance).
Lets say that in the middle of this image, there is a picture (for keep the example simple lets suppose is a square drawn), of 100x100 pixels (total area 10000 pixels).
I need to know the area percentage that the small square fill inside the image.
So, in i know the full image size and the background-color, there is a way in php/python to scan the image and retrieve that (in short, counting the pixel that are different from the given background)?
In the above example, the result should be 25%
EDIT: this are two image as example (gimped oin the way ;):
I need to know the percentage of the green pepper in the whole image (that is 400x400)
|
[
"from PIL import Image\nimage = Image.open(\"pepper.png\")\nbg = image.getpixel((0,0))\nwidth, height = image.size\nbg_count = next(n for n,c in image.getcolors(width*height) if c==bg)\nimg_count = width*height - bg_count\nimg_percent = img_count*100.0/width/height\n\ngives 7.361875 for both images\n",
"I am assuming the surrounding area has only one colour and the object in the image can have any shape (so you need to find out its coordinates first, right?)\nIf you can use ImageMagick, it's easy. \n\nStore size of image (40000 Pixels)\nSend image to ImageMagick and trim the surrounding area using -trim (description here)\nCompare size of resulting image (10000 Pixels) with that of original image \n\nIf you can't use ImageMagick, you will have to use GD to crop the surrounding area away. A rough description is in the answer to this question. I'm pretty sure this has been implemented in PHP already, though.\n",
"Using Python and PIL (Python Imaging Library) you could try the following (untested - credit goes to the original thread here):\n from PIL import ImageChops\n\n def trim(im, border):\n bg = Image.new(im.mode, im.size, border)\n diff = ImageChops.difference(im, bg)\n bbox = diff.getbbox()\n if bbox:\n return im.crop(bbox)\n else:\n # found no content\n raise ValueError(\"cannot trim; image was empty\")\n\nAnd then do your calculations based on width * height (before and after the trim).\n",
"It depends a bit on your accuracy requirements and on the presence of the background color in the image. Consider this annoying test case:\n\nMake a 400 pt large \"G\". \nMake the text white. Hit \"Shadow\" or \"Outline\" so it surrounded by black.\nPut it on a white background.\n\nPick your effort:\n\nYou can get a bounding box, which heavily overestimates the size of the 'G' because\nof the large blank space inside.\nYou can count the white pixels, which heavily underestimates the size of the 'G' because of the many white pixels inside the outline.\nYou can pick a color not in the image, like blue, and run a recursive painter's algorithm from the top left corner. Then you can accurately count the blue pixels.\nThere are faster methods, which are more complicated.\n\nYou can usually use PIL (Python Imaging Library) http://www.pythonware.com/products/pil/ to access raw image data from the file formats.\n"
] |
[
4,
0,
0,
0
] |
[] |
[] |
[
"image_manipulation",
"image_processing",
"php",
"python",
"web_applications"
] |
stackoverflow_0002428916_image_manipulation_image_processing_php_python_web_applications.txt
|
Q:
Need help understanding "TypeError: default __new__ takes no parameters" error in python
For some reason I am having trouble getting my head around __init__ and __new__. I have a bunch of code that runs fine from the terminal, but when I load it as a plugin for Google Quick Search Box, I get the error TypeError: default __new__ takes no parameters.
I have been reading about the error, and it's kind of making my brain spin. As it stands I have 3 classes, with no sub-classes, each class has it's own defs. I never use def __init__ or def __new__, but I have gotten the distinct feeling that these are the functions (or the lack thereof) that would be giving me the error.
I have no idea how to summarize the code down to a snippet that would be helpful here, since I'm a bit over my head, but the entire script can be found at github. Not expecting anyone to bugfix my code for me, I am just at my wit's end on this. A simple (plain english, not the quote from the python docs which I have read 20 times and still don't really understand) explination of why this error would pop up, or why I should be, or not be, using the __init__ and/or __new__ functions would be seriously appreciated.
A:
Simplest way to reproduce your problem:
>>> class Bah(object): pass
...
>>> x = Bah(23)
Traceback (most recent call last):
File "<stdin>", line 1, in ?
TypeError: default __new__ takes no parameters
So it looks like there's a class in your code (not when run from the terminal, but then you do very different imports then) that has no __init__ defined, and you're somewhere calling the class with some parameters. In the error traceback you should get the location where the call happens (if not, e.g. due to GUI subtleties, you can use a try/except around everything and make sure you dump the traceback to a /tmp file in the except clause, use module traceback from the standard library).
A:
There are a handful of basic class construction concepts that you seem to be missing.
The __init__ method is used when the class is first initialized, and is how you set up its internals. You also want to take advantage of Python's new-style classes (the default in Python 3).
I would suggest starting with Dive Into Python and branching out from there.
|
Need help understanding "TypeError: default __new__ takes no parameters" error in python
|
For some reason I am having trouble getting my head around __init__ and __new__. I have a bunch of code that runs fine from the terminal, but when I load it as a plugin for Google Quick Search Box, I get the error TypeError: default __new__ takes no parameters.
I have been reading about the error, and it's kind of making my brain spin. As it stands I have 3 classes, with no sub-classes, each class has it's own defs. I never use def __init__ or def __new__, but I have gotten the distinct feeling that these are the functions (or the lack thereof) that would be giving me the error.
I have no idea how to summarize the code down to a snippet that would be helpful here, since I'm a bit over my head, but the entire script can be found at github. Not expecting anyone to bugfix my code for me, I am just at my wit's end on this. A simple (plain english, not the quote from the python docs which I have read 20 times and still don't really understand) explination of why this error would pop up, or why I should be, or not be, using the __init__ and/or __new__ functions would be seriously appreciated.
|
[
"Simplest way to reproduce your problem:\n>>> class Bah(object): pass\n... \n>>> x = Bah(23)\nTraceback (most recent call last):\n File \"<stdin>\", line 1, in ?\nTypeError: default __new__ takes no parameters\n\nSo it looks like there's a class in your code (not when run from the terminal, but then you do very different imports then) that has no __init__ defined, and you're somewhere calling the class with some parameters. In the error traceback you should get the location where the call happens (if not, e.g. due to GUI subtleties, you can use a try/except around everything and make sure you dump the traceback to a /tmp file in the except clause, use module traceback from the standard library).\n",
"There are a handful of basic class construction concepts that you seem to be missing. \nThe __init__ method is used when the class is first initialized, and is how you set up its internals. You also want to take advantage of Python's new-style classes (the default in Python 3).\nI would suggest starting with Dive Into Python and branching out from there. \n"
] |
[
7,
2
] |
[] |
[] |
[
"init",
"python",
"typeerror"
] |
stackoverflow_0002429899_init_python_typeerror.txt
|
Q:
Python help() function and the string.title function
Why doesn't
import string;help(string.title)
seem to work but
help(string.strip)
works just fine?
I get the error
Traceback (most recent call last):
File "", line 1, in
AttributeError: 'module' object has no
attribute 'title'
A:
title is a method on objects of type str, not a function in the string module. That means you can do "foo".title() or str.title("foo") but not string.title("foo").
A:
help(str.title) seems to work just fine.
|
Python help() function and the string.title function
|
Why doesn't
import string;help(string.title)
seem to work but
help(string.strip)
works just fine?
I get the error
Traceback (most recent call last):
File "", line 1, in
AttributeError: 'module' object has no
attribute 'title'
|
[
"title is a method on objects of type str, not a function in the string module. That means you can do \"foo\".title() or str.title(\"foo\") but not string.title(\"foo\").\n",
"help(str.title) seems to work just fine.\n"
] |
[
2,
1
] |
[] |
[] |
[
"python"
] |
stackoverflow_0002430166_python.txt
|
Q:
Problem with makefile
I created a python project in IDE Anjuta, added some python files and the problem follows.
I need that would make the program after a few .py files lying in src copied to dir /usr/bin. Anjuta generates enormous configure- and makefiles. 'll Show you need to register and where that would make described above.
Thank you.
A:
I'm also having trouble understanding your question, but it sounds like you want to run make and have the py files copied to a certain directory. This would look like:
$(shell cp *.py /usr/bin)
Hope this helps.
-tjw
|
Problem with makefile
|
I created a python project in IDE Anjuta, added some python files and the problem follows.
I need that would make the program after a few .py files lying in src copied to dir /usr/bin. Anjuta generates enormous configure- and makefiles. 'll Show you need to register and where that would make described above.
Thank you.
|
[
"I'm also having trouble understanding your question, but it sounds like you want to run make and have the py files copied to a certain directory. This would look like:\n$(shell cp *.py /usr/bin)\n\nHope this helps.\n-tjw\n"
] |
[
0
] |
[] |
[] |
[
"anjuta",
"installation",
"makefile",
"python"
] |
stackoverflow_0002325646_anjuta_installation_makefile_python.txt
|
Q:
Add Keyboard Binding To Existing Emacs Mode
I'm attempting my first modification of Emacs. I recorded a little keyboard macro and had Emacs spit it out as elisp, resulting in:
(setq add-docstring
"\C-rdef\C-n\C-a\C-m\C-p\C-i\C-u6\"\C-u3\C-b")
(global-set-key "\C-c\C-d" 'add-docstring)
Searching the Emacs reference, though, revealed that C-c C-d is already bound in diff mode. I don't plan on using diff mode, but the future is unknowable and I'd like to not lay a trap for myself. So I'd like this keybinding to only operate in python mode, where it tries to help me add docstrings.
In my /usr/share/emacs/23.whatever/list/progmodes, I found python.elc and python.el.gz. I unzipped python.el.gz and got a readable version of the elisp file. Now, though, the documentation becomes opaque to me.
How can I add my key binding to the python mode, instead of globally?
Is it possible, for bonus points, to apply the changes to python mode without restarting emacs or closing open files? It's the self-modifying editor, I figure there's a good chance that it's possible.
A:
It turns out, C-c C-d is already bound in python-mode (to 'python-pdbtrack-toggle-stack-tracking), so you may want to revisit your choice of key binding.
Note: if you just want to cut/paste a solution, jump to the end of the answer. Read on for an explanation of how to get there - in case you want to do it again.
The macro is a good start, but what you have won't quite work. To get something you can bind to a key, try M-x insert-kbd-macro for that macro, and you'll get:
(fset 'add-docstring
(lambda (&optional arg) "Keyboard macro." (interactive "p") (kmacro-exec-ring-item (quote ("def ...unprintable characters...6\"3" 0 "%d")) arg)))
(hm.... non-printable characters, I can't cut/paste into SO, but you can do it yourself to get the right thing). With a little munging, what you get is equivalent to this:
(fset 'add-docstring
(lambda (&optional arg)
"Keyboard macro."
(interactive "p")
(kmacro-exec-ring-item `(,(kbd "C-r def C-n C-a C-m C-p C-i C-u 6 \" C-u 3 C-b") 0 "%d")
arg)))
That's the first step. With the above, you can do M-x add-docstring and get the behavior you want.
The next step is what you asked - how to bind to keys locally. The documentation for keybindings begins here, and of interest to you is the Local Keymaps section, which leads to the following:
(add-hook 'python-mode-hook
(lambda () (define-key python-mode-map (kbd "C-c C-d") 'add-docstring)))
This sets up an anonymous function to be called when python-mode is turned on, and that function does one thing - it sets up the key binding you want in the keymap specifically for python-mode.
If you read the Keymaps section closely, you'll see that Emacs follows the convention that only users should bind commads to C-c a, where a is any lower or upper-case letter (e.g. C-c d C-c T C-c p are all available), and packages constrain mode-specific bindings to C-c %, where % is any punctuation character or control key (e.g. C-c C-c C-c [ C-c C-z).
So, if you change your binding to C-c d, then you're pretty much guaranteed not to conflict with any packages out there. The python.el shipped with Emacs does follow these conventions, as do most (all?) packages shipped with Emacs.
You'll notice that I use kbd to read in the key sequences. It is portable and I find it a lot easier to read.
There are further things you could do to clean this up:
put the customizations in a named function
rewrite the macro in elisp
use eval-after-load instead of the hook (see this question)
Here's what I'd do for #1, which gives you a handy place to put other customizations:
(add-hook 'python-mode-hook 'my-python-customizations)
(defun my-python-customizations ()
"set up my personal customizations for python mode"
;; put other customizations in here
(define-key python-mode-map (kbd "C-c C-d") 'add-docstring))
(defun add-docstring (&optional arg)
"Keyboard macro."
(interactive "p")
(kmacro-exec-ring-item `(,(kbd "C-r def C-n C-a C-m C-p C-i C-u 6 \" C-u 3 C-b") 0 "%d")
arg))
Using a named function is a little cleaner in that you can later do (remove-hook 'python-mode-hook 'my-python-customizations) if you so desire. Also, if you look at the value for the hook (C-h v python-mode-hook RET), it's obvious what gets called (the anonymous function is longer and more difficult to read).
For the bonus points, after you pasted the code into your .emacs do M-x eval-region, which will tell Emacs to evaluate the code in the region. To see the changes in your existing python buffers, you'd just have to open a new python file/buffer, which would trigger the keybinding change - which is common to all python buffers.
Happy hacking.
A:
Firstly, do not mess with python.el. What you want to do is to create your own custom binding for python mode. This is usually done in your .emacs file in your home directory.
In that file add something like the following (I have not tested this -- so there may be some error in syntax and I do not use python myself)
(add-hook 'python-mode-hook
'(lambda () (define-key python-mode-map "\C-c\C-d" 'add-doc-string)))
This is using the hook mechanism. It is a function that is called each time you invoke python mode. This function only binds C-c C-d to your add-doc-string function.
This answer is very brief. Read about the .emacs file, customizations and hooks in the emacs documentation.
|
Add Keyboard Binding To Existing Emacs Mode
|
I'm attempting my first modification of Emacs. I recorded a little keyboard macro and had Emacs spit it out as elisp, resulting in:
(setq add-docstring
"\C-rdef\C-n\C-a\C-m\C-p\C-i\C-u6\"\C-u3\C-b")
(global-set-key "\C-c\C-d" 'add-docstring)
Searching the Emacs reference, though, revealed that C-c C-d is already bound in diff mode. I don't plan on using diff mode, but the future is unknowable and I'd like to not lay a trap for myself. So I'd like this keybinding to only operate in python mode, where it tries to help me add docstrings.
In my /usr/share/emacs/23.whatever/list/progmodes, I found python.elc and python.el.gz. I unzipped python.el.gz and got a readable version of the elisp file. Now, though, the documentation becomes opaque to me.
How can I add my key binding to the python mode, instead of globally?
Is it possible, for bonus points, to apply the changes to python mode without restarting emacs or closing open files? It's the self-modifying editor, I figure there's a good chance that it's possible.
|
[
"It turns out, C-c C-d is already bound in python-mode (to 'python-pdbtrack-toggle-stack-tracking), so you may want to revisit your choice of key binding.\nNote: if you just want to cut/paste a solution, jump to the end of the answer. Read on for an explanation of how to get there - in case you want to do it again.\nThe macro is a good start, but what you have won't quite work. To get something you can bind to a key, try M-x insert-kbd-macro for that macro, and you'll get:\n(fset 'add-docstring\n (lambda (&optional arg) \"Keyboard macro.\" (interactive \"p\") (kmacro-exec-ring-item (quote (\"def ...unprintable characters...6\\\"3\" 0 \"%d\")) arg)))\n\n(hm.... non-printable characters, I can't cut/paste into SO, but you can do it yourself to get the right thing). With a little munging, what you get is equivalent to this:\n(fset 'add-docstring\n (lambda (&optional arg)\n \"Keyboard macro.\"\n (interactive \"p\")\n (kmacro-exec-ring-item `(,(kbd \"C-r def C-n C-a C-m C-p C-i C-u 6 \\\" C-u 3 C-b\") 0 \"%d\")\n arg)))\n\nThat's the first step. With the above, you can do M-x add-docstring and get the behavior you want.\nThe next step is what you asked - how to bind to keys locally. The documentation for keybindings begins here, and of interest to you is the Local Keymaps section, which leads to the following:\n(add-hook 'python-mode-hook\n (lambda () (define-key python-mode-map (kbd \"C-c C-d\") 'add-docstring)))\n\nThis sets up an anonymous function to be called when python-mode is turned on, and that function does one thing - it sets up the key binding you want in the keymap specifically for python-mode.\nIf you read the Keymaps section closely, you'll see that Emacs follows the convention that only users should bind commads to C-c a, where a is any lower or upper-case letter (e.g. C-c d C-c T C-c p are all available), and packages constrain mode-specific bindings to C-c %, where % is any punctuation character or control key (e.g. C-c C-c C-c [ C-c C-z).\nSo, if you change your binding to C-c d, then you're pretty much guaranteed not to conflict with any packages out there. The python.el shipped with Emacs does follow these conventions, as do most (all?) packages shipped with Emacs.\nYou'll notice that I use kbd to read in the key sequences. It is portable and I find it a lot easier to read.\nThere are further things you could do to clean this up:\n\nput the customizations in a named function\nrewrite the macro in elisp\nuse eval-after-load instead of the hook (see this question)\n\nHere's what I'd do for #1, which gives you a handy place to put other customizations:\n(add-hook 'python-mode-hook 'my-python-customizations)\n(defun my-python-customizations ()\n \"set up my personal customizations for python mode\"\n ;; put other customizations in here\n (define-key python-mode-map (kbd \"C-c C-d\") 'add-docstring))\n(defun add-docstring (&optional arg)\n \"Keyboard macro.\"\n (interactive \"p\")\n (kmacro-exec-ring-item `(,(kbd \"C-r def C-n C-a C-m C-p C-i C-u 6 \\\" C-u 3 C-b\") 0 \"%d\")\n arg))\n\nUsing a named function is a little cleaner in that you can later do (remove-hook 'python-mode-hook 'my-python-customizations) if you so desire. Also, if you look at the value for the hook (C-h v python-mode-hook RET), it's obvious what gets called (the anonymous function is longer and more difficult to read).\nFor the bonus points, after you pasted the code into your .emacs do M-x eval-region, which will tell Emacs to evaluate the code in the region. To see the changes in your existing python buffers, you'd just have to open a new python file/buffer, which would trigger the keybinding change - which is common to all python buffers.\nHappy hacking.\n",
"Firstly, do not mess with python.el. What you want to do is to create your own custom binding for python mode. This is usually done in your .emacs file in your home directory.\nIn that file add something like the following (I have not tested this -- so there may be some error in syntax and I do not use python myself)\n(add-hook 'python-mode-hook\n '(lambda () (define-key python-mode-map \"\\C-c\\C-d\" 'add-doc-string)))\n\nThis is using the hook mechanism. It is a function that is called each time you invoke python mode. This function only binds C-c C-d to your add-doc-string function.\nThis answer is very brief. Read about the .emacs file, customizations and hooks in the emacs documentation.\n"
] |
[
16,
4
] |
[] |
[] |
[
"elisp",
"emacs",
"keyboard_shortcuts",
"python"
] |
stackoverflow_0002429603_elisp_emacs_keyboard_shortcuts_python.txt
|
Q:
Mocking imported modules in Python
I'm trying to implement unit tests for function that uses imported external objects.
For example helpers.py is:
import os
import pylons
def some_func(arg):
...
var1 = os.path.exist(...)
var2 = os.path.getmtime(...)
var3 = pylons.request.environ['HTTP_HOST']
...
So when I'm creating unit test for it I do some mocking (minimock in my case)
and replacing references to pylons.request and os.path:
import helpers
def test_some_func():
helpers.pylons.request = minimock.Mock("pylons.request")
helpers.pylons.request.environ = { 'HTTP_HOST': "localhost" }
helpers.os.path = minimock.Mock(....)
...
some_func(...)
# assert
...
This does not look good for me.
Is there any other better way or strategy to substitute imported function/objects in Python?
A:
Use voidspace's mocking library and it's patching/wrapping ability.
http://www.voidspace.org.uk/python/mock/patch.html
A:
Well, in minimock there is an easier paradigm for this than what you are using above:
>>> from minimock import mock
>>> import os.path
>>> mock('os.path.isfile', returns=True)
See http://pypi.python.org/pypi/MiniMock#creating-mocks
Once you do that, any module that does os.path.isfile("blah") is going to get True back. You don't need to go and explicitly reassign the module-under-test's namespace.
|
Mocking imported modules in Python
|
I'm trying to implement unit tests for function that uses imported external objects.
For example helpers.py is:
import os
import pylons
def some_func(arg):
...
var1 = os.path.exist(...)
var2 = os.path.getmtime(...)
var3 = pylons.request.environ['HTTP_HOST']
...
So when I'm creating unit test for it I do some mocking (minimock in my case)
and replacing references to pylons.request and os.path:
import helpers
def test_some_func():
helpers.pylons.request = minimock.Mock("pylons.request")
helpers.pylons.request.environ = { 'HTTP_HOST': "localhost" }
helpers.os.path = minimock.Mock(....)
...
some_func(...)
# assert
...
This does not look good for me.
Is there any other better way or strategy to substitute imported function/objects in Python?
|
[
"Use voidspace's mocking library and it's patching/wrapping ability.\nhttp://www.voidspace.org.uk/python/mock/patch.html\n",
"Well, in minimock there is an easier paradigm for this than what you are using above:\n>>> from minimock import mock\n>>> import os.path\n>>> mock('os.path.isfile', returns=True)\n\nSee http://pypi.python.org/pypi/MiniMock#creating-mocks\nOnce you do that, any module that does os.path.isfile(\"blah\") is going to get True back. You don't need to go and explicitly reassign the module-under-test's namespace.\n"
] |
[
2,
1
] |
[] |
[] |
[
"mocking",
"python",
"unit_testing"
] |
stackoverflow_0002348712_mocking_python_unit_testing.txt
|
Q:
How to ping an ip and get only the ms in the Tk with Python?
I want to make a little tk app that continuous ping an ip and only show the MS, like, "10ms"
how could I do?
A:
If you want to use Windows ping, you'll have to parse the output from the command line.
This is very specific, but should work:
import os
while(1):
ping = os.popen('ping www.google.com -n 1')
result = ping.readlines()
msLine = result[-1].strip()
print msLine.splot(' = ')[-1]
A:
To continuously ping an IP
os.system("ping -t 192.168.1.1")
|
How to ping an ip and get only the ms in the Tk with Python?
|
I want to make a little tk app that continuous ping an ip and only show the MS, like, "10ms"
how could I do?
|
[
"If you want to use Windows ping, you'll have to parse the output from the command line.\nThis is very specific, but should work:\nimport os\nwhile(1):\n ping = os.popen('ping www.google.com -n 1')\n result = ping.readlines()\n msLine = result[-1].strip()\n print msLine.splot(' = ')[-1]\n\n",
"To continuously ping an IP\nos.system(\"ping -t 192.168.1.1\")\n\n"
] |
[
3,
0
] |
[] |
[] |
[
"ping",
"python",
"windows"
] |
stackoverflow_0002430519_ping_python_windows.txt
|
Q:
Old desktop programmer wants to create S+S project
I have an idea for a product that I want to be web-based. But because I live in a part of the world where the internet is not always available, there needs to be a client desktop component that is available for when the internet is down. Also, I have been a SQL programmer, a desktop application programmer using dBase, VB and Pascal, and I have created simple websites using HTML and website creation tools, such as Frontpage.
So from my research, I think I have the following options; PHP, Ruby on Rails, Python or .NET for the programming side. MySQL for the DB. And Apache, or possibly IIS, for the webserver.
I will probably start with a local ISP provider for the cloud servce. But then maybe move to something more "robust" and universal in the future, ie. Amazon, or Azure, or something along that line.
My question then is this. What would you recommend for something like this? I'm sure that I have not listed all of the possibilities, but the ones I have researched and thought of.
Thanks everyone,
Craig
A:
If you want a 'desktop component' that is available for you to do development on whenever your internet is out, you could really choose any of those technologies. You can always have a local server (like apache) running on your machine, as well as a local sql database, though if your database contains a large amount of data you may need to scale it down.
Ruby on Rails may be the easiest for you to get started with, though, since it comes packaged with WEBrick (a ruby library that provides HTTP services), and SQLite, a lightweight SQL database management system. Ruby on Rails is configured by default to use these.
A:
The languages you list are all serverside components. The big question is whether you can sensibly build a thick client - effectively you could develop a multi-tier application where the webserver sits on the client and uses a webservice as a datafeed if/when its available but the solution is not very portable.
You could build a purely ajax driven website in javascript then deploy it to the client as signed javascripts on the local filesystem (they need to be signed to get around the restriction that javscripts can only connect back to the server where they served from normally).
Another approach would be to use Google Gears - but that would be a single browser solution.
C.
A:
If you wan't to run a version of the server on desktops, your best options would be Python, Rails, or Java servlets, all of which can be easily packaged into small self contained servers with no dependencies.
My recommendation for the desktop would be HTML 5 local storage. The standard hasn't been finalized, but there is experimental support in Google Chrome. If you can force your users to use a specific browser version, you should be OK, until it is finalized.
I would recommend looking at Django and Rails before any other framework. They have different design philosophies, so one of them might be better suited for your application. Another framework to consider is Grails, which is essentially a clone of Rails in the groovy language.
|
Old desktop programmer wants to create S+S project
|
I have an idea for a product that I want to be web-based. But because I live in a part of the world where the internet is not always available, there needs to be a client desktop component that is available for when the internet is down. Also, I have been a SQL programmer, a desktop application programmer using dBase, VB and Pascal, and I have created simple websites using HTML and website creation tools, such as Frontpage.
So from my research, I think I have the following options; PHP, Ruby on Rails, Python or .NET for the programming side. MySQL for the DB. And Apache, or possibly IIS, for the webserver.
I will probably start with a local ISP provider for the cloud servce. But then maybe move to something more "robust" and universal in the future, ie. Amazon, or Azure, or something along that line.
My question then is this. What would you recommend for something like this? I'm sure that I have not listed all of the possibilities, but the ones I have researched and thought of.
Thanks everyone,
Craig
|
[
"If you want a 'desktop component' that is available for you to do development on whenever your internet is out, you could really choose any of those technologies. You can always have a local server (like apache) running on your machine, as well as a local sql database, though if your database contains a large amount of data you may need to scale it down.\nRuby on Rails may be the easiest for you to get started with, though, since it comes packaged with WEBrick (a ruby library that provides HTTP services), and SQLite, a lightweight SQL database management system. Ruby on Rails is configured by default to use these.\n",
"The languages you list are all serverside components. The big question is whether you can sensibly build a thick client - effectively you could develop a multi-tier application where the webserver sits on the client and uses a webservice as a datafeed if/when its available but the solution is not very portable.\nYou could build a purely ajax driven website in javascript then deploy it to the client as signed javascripts on the local filesystem (they need to be signed to get around the restriction that javscripts can only connect back to the server where they served from normally).\nAnother approach would be to use Google Gears - but that would be a single browser solution.\nC.\n",
"If you wan't to run a version of the server on desktops, your best options would be Python, Rails, or Java servlets, all of which can be easily packaged into small self contained servers with no dependencies.\nMy recommendation for the desktop would be HTML 5 local storage. The standard hasn't been finalized, but there is experimental support in Google Chrome. If you can force your users to use a specific browser version, you should be OK, until it is finalized.\nI would recommend looking at Django and Rails before any other framework. They have different design philosophies, so one of them might be better suited for your application. Another framework to consider is Grails, which is essentially a clone of Rails in the groovy language.\n"
] |
[
0,
0,
0
] |
[] |
[] |
[
"php",
"programming_languages",
"python",
"ruby_on_rails",
"saas"
] |
stackoverflow_0002428077_php_programming_languages_python_ruby_on_rails_saas.txt
|
Q:
Which XML library for what purposes?
A search for "python" and "xml" returns a variety of libraries for combining the two.
This list probably faulty:
xml.dom
xml.etree
xml.sax
xml.parsers.expat
PyXML
beautifulsoup?
HTMLParser
htmllib
sgmllib
Be nice if someone can offer a quick summary of when to use which, and why.
A:
The DOM/SAX divide is a basic one. It applies not just to python since DOM and SAX are cross-language.
DOM: read the whole document into memory and manipulate it.
Good for:
complex relationships across tags in the markup
small intricate XML documents
Cautions:
Easy to use excessive memory
SAX: parse the document while you read it. Good for:
Long documents or open ended streams
places where memory is a constraint
Cautions:
You'll need to code a stateful parser, which can be tricky
beautifulsoup:
Great for HTML or not-quite-well-formed markup. Easy to use and fast. Good for screen scraping, etc. It can work with markup where the XML based ones would just through an error saying the markup is incorrect.
Most of the rest I haven't used, but I don't think there's hard and fast rules about when to use which. Just your standard considerations: who is going to maintain the code, which APIs do you find most easy to use, how well do they work, etc.
In general, for basic needs, it's nice to use the standard library modules since they are "standard" and thus available and well known. However, if you need to dig deep into something, almost always there are newer nonstandard modules with superior functionality outside of the standard library.
A:
I find xml.etree essentially sufficient for everything, except for BeautifulSoup if I ever need to parse broken XML (not a common problem, differently from broken HTML, which BeautifulSoup also helps with and is everywhere): it has reasonable support for reading entire XML docs in memory, navigating them, creating them, incrementally-parsing large docs. lxml supports the same interface, and is generally faster -- useful to push performance when you can afford to install third party Python extensions (e.g. on App Engine you can't -- but xml.etree is still there, so you can run exactly the same code). lxml also has more features, and offers BeautifulSoup too.
The other libs you mention mimic APIs designed for very different languages, and in general I see no reason to contort Python into those gyrations. If you have very specific needs such as support for xslt, various kinds of validations, etc, it may be worth looking around for other libraries yet, but I haven't had such needs in a long time so I'm not current wrt the offerings for them.
A:
I don't do much with XML, but when I've needed to, lxml has been a joy to work with and is apparently quite fast. The element tree API is very nice in an object oriented setting.
A:
For many problems you can get by with the xml. It has the major advantage of being part of the standard library. This means that it is pre-installed on almost every system and that the interface will be static. It is not the best, or the fastest, but it is there.
For everything else there is lxml. Specically, lxml is best for parsing broken HTML, xHTML, or suspect feeds. It uses libxml2 and libxslt to handle XPath, XSLT, and EXSLT. The tutorial is clear and the interface is simplistically straight-forward. The rest of the libraries mentioned exist because lxml was not available in its current form.
This is my opinion.
|
Which XML library for what purposes?
|
A search for "python" and "xml" returns a variety of libraries for combining the two.
This list probably faulty:
xml.dom
xml.etree
xml.sax
xml.parsers.expat
PyXML
beautifulsoup?
HTMLParser
htmllib
sgmllib
Be nice if someone can offer a quick summary of when to use which, and why.
|
[
"The DOM/SAX divide is a basic one. It applies not just to python since DOM and SAX are cross-language.\nDOM: read the whole document into memory and manipulate it.\nGood for:\n\ncomplex relationships across tags in the markup\nsmall intricate XML documents\nCautions:\n\n\nEasy to use excessive memory\n\n\nSAX: parse the document while you read it. Good for:\n\nLong documents or open ended streams\nplaces where memory is a constraint\nCautions:\n\n\nYou'll need to code a stateful parser, which can be tricky\n\n\nbeautifulsoup:\nGreat for HTML or not-quite-well-formed markup. Easy to use and fast. Good for screen scraping, etc. It can work with markup where the XML based ones would just through an error saying the markup is incorrect.\nMost of the rest I haven't used, but I don't think there's hard and fast rules about when to use which. Just your standard considerations: who is going to maintain the code, which APIs do you find most easy to use, how well do they work, etc.\nIn general, for basic needs, it's nice to use the standard library modules since they are \"standard\" and thus available and well known. However, if you need to dig deep into something, almost always there are newer nonstandard modules with superior functionality outside of the standard library.\n",
"I find xml.etree essentially sufficient for everything, except for BeautifulSoup if I ever need to parse broken XML (not a common problem, differently from broken HTML, which BeautifulSoup also helps with and is everywhere): it has reasonable support for reading entire XML docs in memory, navigating them, creating them, incrementally-parsing large docs. lxml supports the same interface, and is generally faster -- useful to push performance when you can afford to install third party Python extensions (e.g. on App Engine you can't -- but xml.etree is still there, so you can run exactly the same code). lxml also has more features, and offers BeautifulSoup too.\nThe other libs you mention mimic APIs designed for very different languages, and in general I see no reason to contort Python into those gyrations. If you have very specific needs such as support for xslt, various kinds of validations, etc, it may be worth looking around for other libraries yet, but I haven't had such needs in a long time so I'm not current wrt the offerings for them.\n",
"I don't do much with XML, but when I've needed to, lxml has been a joy to work with and is apparently quite fast. The element tree API is very nice in an object oriented setting.\n",
"For many problems you can get by with the xml. It has the major advantage of being part of the standard library. This means that it is pre-installed on almost every system and that the interface will be static. It is not the best, or the fastest, but it is there.\nFor everything else there is lxml. Specically, lxml is best for parsing broken HTML, xHTML, or suspect feeds. It uses libxml2 and libxslt to handle XPath, XSLT, and EXSLT. The tutorial is clear and the interface is simplistically straight-forward. The rest of the libraries mentioned exist because lxml was not available in its current form.\nThis is my opinion. \n"
] |
[
6,
4,
1,
1
] |
[] |
[] |
[
"python",
"xml"
] |
stackoverflow_0002430423_python_xml.txt
|
Q:
Passing keyword arguments to a class method decorator
I have a class that has an output() method which returns a matplotlib Figure instance. I have a decorator I wrote that takes that fig instance and turns it into a Django response object.
My decorator looks like this:
class plot_svg(object):
def __init__(self, view):
self.view = view
def __call__(self, *args, **kwargs):
print args, kwargs
fig = self.view(*args, **kwargs)
canvas=FigureCanvas(fig)
response=HttpResponse(content_type='image/svg+xml')
canvas.print_svg(response)
return response
and this is how it was being used:
def as_avg(self):
return plot_svg(self.output)()
The only reason I has it that way instead of using the "@" syntax is because when I do it with the "@":
@plot_svg
def as_svg(self):
return self.output()
I get this error:
as_svg() takes exactly 1 argument (0 given)
I'm trying to 'fix' this by putting it in the "@" syntax but I can't figure out how to get it working. I'm thinking it has something to do with self not getting passed where it's supposed to...
A:
Right: when you decorate with a class, instead of with a function, you have to make it a descriptor (give it a __get__ method, at least) to get the "automatic self". Simplest is to decorate with a function instead:
def plot_svg(view):
def wrapper(*args, **kwargs):
print args, kwargs
fig = view(*args, **kwargs)
canvas = FigureCanvas(fig)
response = HttpResponse(content_type='image/svg+xml')
canvas.print_svg(response)
return response
return wrapper
Background: the reason functions "become methods" (when defined in a class and accessed on an instance thereof by attribute-get notation), in other words, the reason such functions can get their automatic self is that they're descriptors -- the function type has a __get__.
A class doesn't have a __get__ method -- unless you explicitly add one. So why not just decorate with a function instead, as in the above example? This way you get the nice __get__ of functions automatically -- and as you see the nested function "lexical closure" property doesn't pose any problem at all (indeed, it simplifies things -- the nested function calls view, not self.view which might be rather confusing if self could mean either an instance of your decorator class OR an instance of the class whose method you're decorating...!-).
A:
OK, there seem to be a couple of issues.
First, some syntax. You are getting the "takes exactly one argument" error because
your decorator, @plot_svg, is expecting one parameter (a view). There are other syntax errors as well.
Second, and more importantly, you want to write a function instead of a decorator. A decorator destroys your access to one concept and only gives you access to the combined
concept. You just want a new function like this:
def as_svg(an_object):
return django_response(an_object.output())
Alternately, I misunderstand your question from having a little too little code example.
|
Passing keyword arguments to a class method decorator
|
I have a class that has an output() method which returns a matplotlib Figure instance. I have a decorator I wrote that takes that fig instance and turns it into a Django response object.
My decorator looks like this:
class plot_svg(object):
def __init__(self, view):
self.view = view
def __call__(self, *args, **kwargs):
print args, kwargs
fig = self.view(*args, **kwargs)
canvas=FigureCanvas(fig)
response=HttpResponse(content_type='image/svg+xml')
canvas.print_svg(response)
return response
and this is how it was being used:
def as_avg(self):
return plot_svg(self.output)()
The only reason I has it that way instead of using the "@" syntax is because when I do it with the "@":
@plot_svg
def as_svg(self):
return self.output()
I get this error:
as_svg() takes exactly 1 argument (0 given)
I'm trying to 'fix' this by putting it in the "@" syntax but I can't figure out how to get it working. I'm thinking it has something to do with self not getting passed where it's supposed to...
|
[
"Right: when you decorate with a class, instead of with a function, you have to make it a descriptor (give it a __get__ method, at least) to get the \"automatic self\". Simplest is to decorate with a function instead:\ndef plot_svg(view):\n\n def wrapper(*args, **kwargs):\n print args, kwargs\n fig = view(*args, **kwargs)\n canvas = FigureCanvas(fig)\n response = HttpResponse(content_type='image/svg+xml')\n canvas.print_svg(response)\n return response\n\n return wrapper\n\nBackground: the reason functions \"become methods\" (when defined in a class and accessed on an instance thereof by attribute-get notation), in other words, the reason such functions can get their automatic self is that they're descriptors -- the function type has a __get__.\nA class doesn't have a __get__ method -- unless you explicitly add one. So why not just decorate with a function instead, as in the above example? This way you get the nice __get__ of functions automatically -- and as you see the nested function \"lexical closure\" property doesn't pose any problem at all (indeed, it simplifies things -- the nested function calls view, not self.view which might be rather confusing if self could mean either an instance of your decorator class OR an instance of the class whose method you're decorating...!-).\n",
"OK, there seem to be a couple of issues.\nFirst, some syntax. You are getting the \"takes exactly one argument\" error because\nyour decorator, @plot_svg, is expecting one parameter (a view). There are other syntax errors as well.\nSecond, and more importantly, you want to write a function instead of a decorator. A decorator destroys your access to one concept and only gives you access to the combined\nconcept. You just want a new function like this:\ndef as_svg(an_object):\n return django_response(an_object.output())\n\nAlternately, I misunderstand your question from having a little too little code example.\n"
] |
[
5,
1
] |
[] |
[] |
[
"decorator",
"python"
] |
stackoverflow_0002430759_decorator_python.txt
|
Q:
A list vs. tuple situation in Python
Is there a situation where the use of a list leads to an error, and you must use a tuple instead?
I know something about the properties of both tuples and lists, but not enough to find out the answer to this question. If the question would be the other way around, it would be that lists can be adjusted but tuples don't.
A:
You can use tuples as dictionary keys, because they are immutable, but you can't use lists. Eg:
d = {(1, 2): 'a', (3, 8, 1): 'b'} # Valid.
d = {[1, 2]: 'a', [3, 8, 1]: 'b'} # Error.
A:
Because of their immutable nature, tuples (unlike lists) are hashable. This is what allows tuples to be keys in dictionaries and also members of sets. Strictly speaking it is their hashability, not their immutability that counts.
So in addition to the dictionary key answer already given, a couple of other things that will work for tuples but not lists are:
>>> hash((1, 2))
3713081631934410656
>>> set([(1, 2), (2, 3, 4), (1, 2)])
set([(1, 2), (2, 3, 4)])
A:
In string formatting tuples are mandatory:
"You have %s new %s" % ('5', 'mails') # must be a tuple, not a list!
Using a list in that example produces the error "not enough arguments for format string", because a list is considered as one argument. Weird but true.
|
A list vs. tuple situation in Python
|
Is there a situation where the use of a list leads to an error, and you must use a tuple instead?
I know something about the properties of both tuples and lists, but not enough to find out the answer to this question. If the question would be the other way around, it would be that lists can be adjusted but tuples don't.
|
[
"You can use tuples as dictionary keys, because they are immutable, but you can't use lists. Eg:\nd = {(1, 2): 'a', (3, 8, 1): 'b'} # Valid.\nd = {[1, 2]: 'a', [3, 8, 1]: 'b'} # Error.\n\n",
"Because of their immutable nature, tuples (unlike lists) are hashable. This is what allows tuples to be keys in dictionaries and also members of sets. Strictly speaking it is their hashability, not their immutability that counts.\nSo in addition to the dictionary key answer already given, a couple of other things that will work for tuples but not lists are:\n>>> hash((1, 2))\n3713081631934410656\n\n>>> set([(1, 2), (2, 3, 4), (1, 2)])\nset([(1, 2), (2, 3, 4)])\n\n",
"In string formatting tuples are mandatory:\n\"You have %s new %s\" % ('5', 'mails') # must be a tuple, not a list!\n\nUsing a list in that example produces the error \"not enough arguments for format string\", because a list is considered as one argument. Weird but true.\n"
] |
[
15,
10,
4
] |
[] |
[] |
[
"list",
"python",
"tuples"
] |
stackoverflow_0002280881_list_python_tuples.txt
|
Q:
Technique to limit number of instances of our application under Terminal Server
I'm looking for simple ways to monitor and limit the number of instances of our application under Terminal Server (2003 and 2008).
The purpose of this restriction is to make sure we don't overload our servers. This is an internal administrative requirement - I am not looking for a licensing solution.
The application in question is written in Python 2.6 (32-bit) but I'm happy to receive development tool agnostic answers. Although we are not using Citrix, I am happy to receive Citrix related ideas with the hope that I can use a similar technique with Terminal Server.
A:
The various instances of your application need some way to communicate with one another. When an instance starts up, it asks the question, 'how many are already running?'. If there are more than the allowed n, it chooses not to start up.
One implementation approach might be to make n files to lock for the n instances of your application you allow to run at the same time. Then, the application tries to get a lock on one of those files; if it can't, it exits immediately. Release the lock when you're done, but presumably the OS would release the lock for you if you crash.
Another approach would be to register some per-process unique piece of information (a PID?) in a central location (some database) when you start.
Yet a third might be to use a host-only network server where either a dedicated server program or one of the instances coordinates communications with the other instances. If the host exits, one of the other instances can self-promote to being the server.
A:
Based on feedback on the Python Win32 API mailing list I'm also considering one of the following techniques:
Using Windows Semaphores
Using a pool of Mutexes (offer better recoverability than semaphores)
Using a range of ports
|
Technique to limit number of instances of our application under Terminal Server
|
I'm looking for simple ways to monitor and limit the number of instances of our application under Terminal Server (2003 and 2008).
The purpose of this restriction is to make sure we don't overload our servers. This is an internal administrative requirement - I am not looking for a licensing solution.
The application in question is written in Python 2.6 (32-bit) but I'm happy to receive development tool agnostic answers. Although we are not using Citrix, I am happy to receive Citrix related ideas with the hope that I can use a similar technique with Terminal Server.
|
[
"The various instances of your application need some way to communicate with one another. When an instance starts up, it asks the question, 'how many are already running?'. If there are more than the allowed n, it chooses not to start up.\nOne implementation approach might be to make n files to lock for the n instances of your application you allow to run at the same time. Then, the application tries to get a lock on one of those files; if it can't, it exits immediately. Release the lock when you're done, but presumably the OS would release the lock for you if you crash.\nAnother approach would be to register some per-process unique piece of information (a PID?) in a central location (some database) when you start. \nYet a third might be to use a host-only network server where either a dedicated server program or one of the instances coordinates communications with the other instances. If the host exits, one of the other instances can self-promote to being the server.\n",
"Based on feedback on the Python Win32 API mailing list I'm also considering one of the following techniques:\n\nUsing Windows Semaphores\nUsing a pool of Mutexes (offer better recoverability than semaphores)\nUsing a range of ports \n\n"
] |
[
1,
1
] |
[] |
[] |
[
"citrix",
"python",
"terminal_services"
] |
stackoverflow_0002409200_citrix_python_terminal_services.txt
|
Q:
Eclipse Pydev: Supress no-self errors in python wrappers generated with swig
when generating python wrappers with swig the python wrapper classes in the generated python file do not have an explicit self parameter, for example see below:
class PySwigIterator(_object):
def value(*args): return _spatiotemporalnmf.PySwigIterator_value(*args)
def incr(*args): return _spatiotemporalnmf.PySwigIterator_incr(*args)
def decr(*args): return _spatiotemporalnmf.PySwigIterator_decr(*args)
def distance(*args): return _spatiotemporalnmf.PySwigIterator_distance(*args)
I am developing with the eclipse pluging Pydev. Pydev always shows an error when it detects a method without explicit self parameter. I am aware of two methods to get rid of the errors: First, disable error checking for the whole project in the Pydev preferences. Second, add a #@NoSelf to every line with an error. I don't want to use the first one, because I still want to get error warnings for my non-swig-generated files. Obviously the second one is also not very good, because I would have to do it by hand and every time I generate the file again, all #@NoSelfs will be gone.
My Question now is, is there a better way to achieve this?
Thanks
A:
As from the documentation, any file with the comment
#@PydevCodeAnalysisIgnore
inside will not be analyzed.
Therefore, you just need to add it to all SWIG-generated files, and you should be OK. It is just one place to change, and you could even write a very small processor that will add it automatically.
|
Eclipse Pydev: Supress no-self errors in python wrappers generated with swig
|
when generating python wrappers with swig the python wrapper classes in the generated python file do not have an explicit self parameter, for example see below:
class PySwigIterator(_object):
def value(*args): return _spatiotemporalnmf.PySwigIterator_value(*args)
def incr(*args): return _spatiotemporalnmf.PySwigIterator_incr(*args)
def decr(*args): return _spatiotemporalnmf.PySwigIterator_decr(*args)
def distance(*args): return _spatiotemporalnmf.PySwigIterator_distance(*args)
I am developing with the eclipse pluging Pydev. Pydev always shows an error when it detects a method without explicit self parameter. I am aware of two methods to get rid of the errors: First, disable error checking for the whole project in the Pydev preferences. Second, add a #@NoSelf to every line with an error. I don't want to use the first one, because I still want to get error warnings for my non-swig-generated files. Obviously the second one is also not very good, because I would have to do it by hand and every time I generate the file again, all #@NoSelfs will be gone.
My Question now is, is there a better way to achieve this?
Thanks
|
[
"As from the documentation, any file with the comment \n#@PydevCodeAnalysisIgnore\n\ninside will not be analyzed.\nTherefore, you just need to add it to all SWIG-generated files, and you should be OK. It is just one place to change, and you could even write a very small processor that will add it automatically.\n"
] |
[
1
] |
[] |
[] |
[
"pydev",
"python",
"swig"
] |
stackoverflow_0002431435_pydev_python_swig.txt
|
Q:
doctest locally defined functions
is there any way to doctest locally defined functions? As an example I would want
def foo():
""" >>> foo()
testfoo"""
def foo2():
""" >>> 1/0 """
print 'testfoo'
foo2()
to NOT pass the test. But still I would not want to make foo2 global for the entire module...
A:
Thanks. I already feared there would be no way around code outside the docstring. Still I thought there might be a trick to import the locals of a function and thus get access to nested functions. Anyhow, a solution using Alex' approach would read
def foo(debug=False):
"""
>>> foo()
testfoo
>>> foo(debug=True)
"""
def foo2():
"""
>>> 1/0"""
print 'testfoo'
if debug :
import doctest
for f in [foo2]: doctest.run_docstring_examples(f,locals())
foo2()
Now the only question is how to automate this approach, so one has something like
for f in locals().values(): doctest.run_docstring_examples(f,locals())
but without the imported and built in functions and variables.
A:
You just have a whitespace problem -- if you fix it, for example as follows:
def foo():
"""
>>> foo()
testfoo"""
def foo2():
""" >>> 1/0 """
print 'testfoo'
foo2()
if __name__ == '__main__':
import doctest
doctest.testmod()
the test passes just fine.
|
doctest locally defined functions
|
is there any way to doctest locally defined functions? As an example I would want
def foo():
""" >>> foo()
testfoo"""
def foo2():
""" >>> 1/0 """
print 'testfoo'
foo2()
to NOT pass the test. But still I would not want to make foo2 global for the entire module...
|
[
"Thanks. I already feared there would be no way around code outside the docstring. Still I thought there might be a trick to import the locals of a function and thus get access to nested functions. Anyhow, a solution using Alex' approach would read\ndef foo(debug=False):\n \"\"\"\n >>> foo()\n testfoo\n >>> foo(debug=True)\n \"\"\"\n\n def foo2():\n \"\"\"\n >>> 1/0\"\"\"\n print 'testfoo'\n\n\n if debug :\n import doctest\n for f in [foo2]: doctest.run_docstring_examples(f,locals())\n\n foo2()\n\nNow the only question is how to automate this approach, so one has something like \nfor f in locals().values(): doctest.run_docstring_examples(f,locals())\n\nbut without the imported and built in functions and variables.\n",
"You just have a whitespace problem -- if you fix it, for example as follows:\ndef foo():\n \"\"\"\n >>> foo()\n testfoo\"\"\"\n\n def foo2():\n \"\"\" >>> 1/0 \"\"\" \n print 'testfoo'\n\n foo2()\n\nif __name__ == '__main__':\n import doctest\n doctest.testmod()\n\nthe test passes just fine.\n"
] |
[
4,
1
] |
[] |
[] |
[
"doctest",
"python"
] |
stackoverflow_0002403237_doctest_python.txt
|
Q:
using python 'with' statement with iterators?
I'm using Python 2.5. I'm trying to use this 'with' statement.
from __future__ import with_statement
a = []
with open('exampletxt.txt','r') as f:
while True:
a.append(f.next().strip().split())
print a
The contents of 'exampletxt.txt' are simple:
a
b
In this case, I get the error:
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "/tmp/python-7036sVf.py", line 5, in <module>
a.append(f.next().strip().split())
StopIteration
And if I replace f.next() with f.read(), it seems to be caught in an infinite loop.
I wonder if I have to write a decorator class that accepts the iterator object as an argument, and define an __exit__ method for it?
I know it's more pythonic to use a for-loop for iterators, but I wanted to implement a while loop within a generator that's called by a for-loop... something like
def g(f):
while True:
x = f.next()
if test1(x):
a = x
elif test2(x):
b = f.next()
yield [a,x,b]
a = []
with open(filename) as f:
for x in g(f):
a.append(x)
A:
Raising StopIteration is what an iterator does when it gets to the end. Normally the for statement catches it silently and continues to the else clause, but if it's being iterated manually as in your case then the code has to be prepared to handle the exception itself.
A:
Your while loop doesn't end, but the file does so it raises a StopIteration exception when there is nothing else to iterate to.
A:
You don't have any terminating condition in any of your while loops, so you keep returning until you get StopIteration exception which you don't handle.
A:
You can always rewrite while-with-explicit-next loops. When you have an explicit next, you're just looking ahead one token.
Generally, loops of this form can be rewritten.
def g(f):
while True:
x = f.next()
if test1(x):
a = x
elif test2(x):
b = f.next()
yield [a,x,b]
You can always replace a look-ahead next by buffering a value.
def g(f):
prev, a = None, None
for x in f:
if test2(prev)
yield [ a, prev, x ]
elif test1(x):
a = x
prev= x
|
using python 'with' statement with iterators?
|
I'm using Python 2.5. I'm trying to use this 'with' statement.
from __future__ import with_statement
a = []
with open('exampletxt.txt','r') as f:
while True:
a.append(f.next().strip().split())
print a
The contents of 'exampletxt.txt' are simple:
a
b
In this case, I get the error:
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "/tmp/python-7036sVf.py", line 5, in <module>
a.append(f.next().strip().split())
StopIteration
And if I replace f.next() with f.read(), it seems to be caught in an infinite loop.
I wonder if I have to write a decorator class that accepts the iterator object as an argument, and define an __exit__ method for it?
I know it's more pythonic to use a for-loop for iterators, but I wanted to implement a while loop within a generator that's called by a for-loop... something like
def g(f):
while True:
x = f.next()
if test1(x):
a = x
elif test2(x):
b = f.next()
yield [a,x,b]
a = []
with open(filename) as f:
for x in g(f):
a.append(x)
|
[
"Raising StopIteration is what an iterator does when it gets to the end. Normally the for statement catches it silently and continues to the else clause, but if it's being iterated manually as in your case then the code has to be prepared to handle the exception itself.\n",
"Your while loop doesn't end, but the file does so it raises a StopIteration exception when there is nothing else to iterate to.\n",
"You don't have any terminating condition in any of your while loops, so you keep returning until you get StopIteration exception which you don't handle.\n",
"You can always rewrite while-with-explicit-next loops. When you have an explicit next, you're just looking ahead one token.\nGenerally, loops of this form can be rewritten.\ndef g(f):\n while True:\n x = f.next()\n if test1(x):\n a = x\n elif test2(x):\n b = f.next()\n yield [a,x,b]\n\nYou can always replace a look-ahead next by buffering a value.\ndef g(f):\n prev, a = None, None\n for x in f:\n if test2(prev)\n yield [ a, prev, x ]\n elif test1(x):\n a = x\n prev= x\n\n"
] |
[
3,
1,
1,
0
] |
[] |
[] |
[
"python"
] |
stackoverflow_0002430501_python.txt
|
Q:
Python: Lits containg tuples and long int
I have a list containing a tuples and long integers the list looks like this:
table = [(1L,), (1L,), (1L,), (2L,), (2L,), (2L,), (3L,), (3L,)]
How do i convert the table to look like a formal list?
so the output would be:
table = ['1','1','1','2','2','2','3','3']
For information purposes the data was obtained from a mysql database.
A:
>>> table = [(1L,), (1L,), (1L,), (2L,), (2L,), (2L,), (3L,), (3L,)]
>>> [int(e[0]) for e in table]
[1, 1, 1, 2, 2, 2, 3, 3]
>>> [str(e[0]) for e in table]
['1', '1', '1', '2', '2', '2', '3', '3']
A:
With itertools
import itertools
>>> x=[(1L,), (1L,), (1L,), (2L,), (2L,), (2L,), (3L,), (3L,)]
>>>
>>> list(itertools.chain(*x))
[1L, 1L, 1L, 2L, 2L, 2L, 3L, 3L]
>>>
>>> map(str,itertools.chain(*x))
['1', '1', '1', '2', '2', '2', '3', '3']
A:
You shouldn't worry about the differences between ints and longs. If you ever try to print a long, the L will disappear.
nums = [1L, 1L, 1L, 2L, 2L, 2L, 3L, 3L]
>>> for num in nums:
... print num,
1 1 1 2 2 2 3 3
Also, why do you want your result list to have strings? You should keep them as numbers right up until the moment you want to print them. Then you can convert them to strings using string formatting (which is more flexible, too. Especially if you start dealing with floating point or decimal numbers.
>>> print "Your number is: %d" % 1L
Your number is 1
>>> print "If we're talking money, you might want $%.2f" % 2L
If we're talking money, you might want $2.00
Everything will work the way you expect. The L only shows up in the repr of the long, so you know you're working with longs instead of ints.
To get them out of their tuples, you can either do:
>>> nums = [(1L,), (1L,), (2L,), (3L,)]
>>> nums = [x[0] for x in nums]
Which copies your list to a new list, or you can do:
>>> for i, num in enumerate(nums):
... nums[i] = num
>>> for i in xrange(nums):
... nums[i] = int(nums[i])
Which will modify your original list rather than creating a new one. In both cases, nums will hold a list of longs.
|
Python: Lits containg tuples and long int
|
I have a list containing a tuples and long integers the list looks like this:
table = [(1L,), (1L,), (1L,), (2L,), (2L,), (2L,), (3L,), (3L,)]
How do i convert the table to look like a formal list?
so the output would be:
table = ['1','1','1','2','2','2','3','3']
For information purposes the data was obtained from a mysql database.
|
[
">>> table = [(1L,), (1L,), (1L,), (2L,), (2L,), (2L,), (3L,), (3L,)]\n>>> [int(e[0]) for e in table]\n[1, 1, 1, 2, 2, 2, 3, 3]\n\n>>> [str(e[0]) for e in table]\n['1', '1', '1', '2', '2', '2', '3', '3']\n\n",
"With itertools\nimport itertools\n\n>>> x=[(1L,), (1L,), (1L,), (2L,), (2L,), (2L,), (3L,), (3L,)]\n>>>\n>>> list(itertools.chain(*x))\n[1L, 1L, 1L, 2L, 2L, 2L, 3L, 3L]\n>>>\n>>> map(str,itertools.chain(*x))\n['1', '1', '1', '2', '2', '2', '3', '3']\n\n",
"You shouldn't worry about the differences between ints and longs. If you ever try to print a long, the L will disappear. \nnums = [1L, 1L, 1L, 2L, 2L, 2L, 3L, 3L]\n>>> for num in nums:\n... print num,\n1 1 1 2 2 2 3 3\n\nAlso, why do you want your result list to have strings? You should keep them as numbers right up until the moment you want to print them. Then you can convert them to strings using string formatting (which is more flexible, too. Especially if you start dealing with floating point or decimal numbers.\n>>> print \"Your number is: %d\" % 1L\nYour number is 1\n>>> print \"If we're talking money, you might want $%.2f\" % 2L\nIf we're talking money, you might want $2.00\n\nEverything will work the way you expect. The L only shows up in the repr of the long, so you know you're working with longs instead of ints.\nTo get them out of their tuples, you can either do:\n>>> nums = [(1L,), (1L,), (2L,), (3L,)]\n>>> nums = [x[0] for x in nums]\n\nWhich copies your list to a new list, or you can do:\n>>> for i, num in enumerate(nums):\n... nums[i] = num\n\n>>> for i in xrange(nums):\n... nums[i] = int(nums[i])\n\nWhich will modify your original list rather than creating a new one. In both cases, nums will hold a list of longs.\n"
] |
[
8,
2,
1
] |
[] |
[] |
[
"list",
"python",
"tuples"
] |
stackoverflow_0002432402_list_python_tuples.txt
|
Q:
Unbuffered subprocess output (last line missing)
I must be overlooking something terribly obvious. I need to execute a C program, display its output in real time and finally parse its last line, which should be straightforward as the last line printed is always the same.
process = subprocess.Popen(args, shell = True,
stdout = subprocess.PIPE, stderr = subprocess.PIPE)
# None indicates that the process hasn't terminated yet.
while process.poll() is None:
# Always save the last non-emtpy line that was output by the child
# process, as it will write an empty line when closing its stdout.
out = process.stdout.readline()
if out:
last_non_empty_line = out
if verbose:
sys.stdout.write(out)
sys.stdout.flush()
# Parse 'out' here...
Once in a while, however, the last line is not printed. The default value for Popens's bufsize is 0, so it is supposed to be unbuffered. I have also tried, to no avail, adding fflush(stdout) to the C code just before exiting, but it seems that there is absolutely no need to flush a stream before exiting a program.
Ideas anyone?
A:
The problem is that you are reading lines till the process exits, (process.poll()) while you do use buffering because of the shell flag.
You would have to keep reading process.stdout till you reach the end of the file or the empty line.
A:
readline() has to buffer the text, waiting for a new-line.
You'll always have a race condition - no amount of un-buffered streams will handle the fact that you're handling a line, then checking for exit, then reading a line, so if the subprocess exits while you're handling a line, you won't read anything else. In addition the shell is probably introducing its own buffering.
So you could either:
Use communicate() and give up the verbose output while the subprocess is running.
Make sure you continue reading after the process has exited, until you get EOF.
I would also suggest altering your code so that you don't have to use shell=True.
|
Unbuffered subprocess output (last line missing)
|
I must be overlooking something terribly obvious. I need to execute a C program, display its output in real time and finally parse its last line, which should be straightforward as the last line printed is always the same.
process = subprocess.Popen(args, shell = True,
stdout = subprocess.PIPE, stderr = subprocess.PIPE)
# None indicates that the process hasn't terminated yet.
while process.poll() is None:
# Always save the last non-emtpy line that was output by the child
# process, as it will write an empty line when closing its stdout.
out = process.stdout.readline()
if out:
last_non_empty_line = out
if verbose:
sys.stdout.write(out)
sys.stdout.flush()
# Parse 'out' here...
Once in a while, however, the last line is not printed. The default value for Popens's bufsize is 0, so it is supposed to be unbuffered. I have also tried, to no avail, adding fflush(stdout) to the C code just before exiting, but it seems that there is absolutely no need to flush a stream before exiting a program.
Ideas anyone?
|
[
"The problem is that you are reading lines till the process exits, (process.poll()) while you do use buffering because of the shell flag.\nYou would have to keep reading process.stdout till you reach the end of the file or the empty line.\n",
"readline() has to buffer the text, waiting for a new-line.\nYou'll always have a race condition - no amount of un-buffered streams will handle the fact that you're handling a line, then checking for exit, then reading a line, so if the subprocess exits while you're handling a line, you won't read anything else. In addition the shell is probably introducing its own buffering.\nSo you could either:\n\nUse communicate() and give up the verbose output while the subprocess is running.\nMake sure you continue reading after the process has exited, until you get EOF.\n\nI would also suggest altering your code so that you don't have to use shell=True.\n"
] |
[
3,
2
] |
[] |
[] |
[
"popen",
"python",
"subprocess"
] |
stackoverflow_0002432556_popen_python_subprocess.txt
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.