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:
Print set() item fill with python generator
I have a generator:
foundUnique = set()
def unique_items(myList, index, clearFlag):
for item in myList:
if clearFlag is True:
foundUnique.clear()
clearFlag = False
if item[index] not in foundUnique:
yield item
foundUnique.add(item[index])
And I am using this `unique_items to get a unique list:
senderDupSend = unique_items(ip, 4, True)
Now I want my set to be reachable (I can print its element or do some changes on specific element .....) but when I write:
for item in foundUnique:
print item
It prints nothing!
But if I write:
for item in senderDupSend:
print item
for item in foundUnique:
print item
It prints all foundUnique items.
Please tell what did I do wrong? How can I solve this problem?
A:
The problem is that unique_items is a generator so that
senderDupSend = unique_items(ip, 4, True)
is a generator that needs to be iterated over. When you run
for item in foundUnique:
print item
the generator has not actually run yet so foundUnique is still empty.
When you later go on to do
for item in senderDupSend: # This is what actually fills the list.
print item
for item in foundUnique:
print item
It should print out the set twice: once while it is being constructed and once after it is constructed.
It seems like what you are trying to do is construct a set that has the same index taken from every element of some sequence. You can do it like this very easily:
found_unique = set(item[index] for item in sequence)
In the concrete case that you show, it would be:
found_unique = set(item[4] for item in ip)
If you later wanted to extend the set to contain other items, you could do
found_unique.union(item[4] for item in other_ip_list)
| Print set() item fill with python generator | I have a generator:
foundUnique = set()
def unique_items(myList, index, clearFlag):
for item in myList:
if clearFlag is True:
foundUnique.clear()
clearFlag = False
if item[index] not in foundUnique:
yield item
foundUnique.add(item[index])
And I am using this `unique_items to get a unique list:
senderDupSend = unique_items(ip, 4, True)
Now I want my set to be reachable (I can print its element or do some changes on specific element .....) but when I write:
for item in foundUnique:
print item
It prints nothing!
But if I write:
for item in senderDupSend:
print item
for item in foundUnique:
print item
It prints all foundUnique items.
Please tell what did I do wrong? How can I solve this problem?
| [
"The problem is that unique_items is a generator so that \nsenderDupSend = unique_items(ip, 4, True)\n\nis a generator that needs to be iterated over. When you run\nfor item in foundUnique:\n print item\n\nthe generator has not actually run yet so foundUnique is still empty.\nWhen you later go on to do\nfor item... | [
4
] | [] | [] | [
"generator",
"python"
] | stackoverflow_0004104208_generator_python.txt |
Q:
AS3 RemoteObject with XMLRPC Python Server : "NetConnection.Call.BadVersion" problem
I want to use XMLRPC mechanism between my Flex app and my XMLRPC Python Server.
My server :
class ServerMockUp(SimpleXMLRPCRequestHandler):
# Services path declaration
rpc_paths = ()
myServer = SimpleXMLRPCServer(("localhost", 80),
requestHandler=ServerMockUp,
logRequests=True)
def isUserAuthenticated(key, time):
print "[loginService > isUserAuthenticated]"
print ":key='%s' :time=%d" %(key, time)
return True
if __name__ == '__main__':
# Services registration
myServer.register_function(isUserAuthenticated)
myServer.register_introspection_functions()
# Start server ...
myServer.serve_forever()
My services-config.xml file:
...
<channel-definition id="my-amf" class="mx.messaging.channels.AMFChannel">
<endpoint url="http://{server.name}:{server.port}/{context.root}/messagebroker/amf" class="flex.messaging.endpoints.AMFEndpoint"/>
</channel-definition>
...
And this is connection error appears:
faultCode:Client.Error.MessageSend faultString:'Send failed' faultDetail:'Channel.Connect.Failed error NetConnection.Call.BadVersion: : url: 'http://localhost/MyApp/messagebroker/amf''
When I debug my XMLRPC server, the exception is catch is (in SimpleXMLRPCServer class):
params, method = xmlrpclib.loads(data)
with error :
str: <?xml version='1.0'?>
<methodResponse>
<fault>
<value><struct>
<member>
<name>faultCode</name>
<value><int>1</int></value>
</member>
<member>
<name>faultString</name>
<value><string><class 'xml.parsers.expat.ExpatError'>:not well-formed (invalid token): line 1, column 0</string></value>
</member>
</struct></value>
</fault>
</methodResponse>
Thanks a lot for your help !
Regards
Anthony
A:
Maybe it has something to do with objectEncoding.
Try to set it to AMF0 with :
nc.defaultObjectEncoding = ObjectEncoding.AMF0;
Just before connecting.
| AS3 RemoteObject with XMLRPC Python Server : "NetConnection.Call.BadVersion" problem | I want to use XMLRPC mechanism between my Flex app and my XMLRPC Python Server.
My server :
class ServerMockUp(SimpleXMLRPCRequestHandler):
# Services path declaration
rpc_paths = ()
myServer = SimpleXMLRPCServer(("localhost", 80),
requestHandler=ServerMockUp,
logRequests=True)
def isUserAuthenticated(key, time):
print "[loginService > isUserAuthenticated]"
print ":key='%s' :time=%d" %(key, time)
return True
if __name__ == '__main__':
# Services registration
myServer.register_function(isUserAuthenticated)
myServer.register_introspection_functions()
# Start server ...
myServer.serve_forever()
My services-config.xml file:
...
<channel-definition id="my-amf" class="mx.messaging.channels.AMFChannel">
<endpoint url="http://{server.name}:{server.port}/{context.root}/messagebroker/amf" class="flex.messaging.endpoints.AMFEndpoint"/>
</channel-definition>
...
And this is connection error appears:
faultCode:Client.Error.MessageSend faultString:'Send failed' faultDetail:'Channel.Connect.Failed error NetConnection.Call.BadVersion: : url: 'http://localhost/MyApp/messagebroker/amf''
When I debug my XMLRPC server, the exception is catch is (in SimpleXMLRPCServer class):
params, method = xmlrpclib.loads(data)
with error :
str: <?xml version='1.0'?>
<methodResponse>
<fault>
<value><struct>
<member>
<name>faultCode</name>
<value><int>1</int></value>
</member>
<member>
<name>faultString</name>
<value><string><class 'xml.parsers.expat.ExpatError'>:not well-formed (invalid token): line 1, column 0</string></value>
</member>
</struct></value>
</fault>
</methodResponse>
Thanks a lot for your help !
Regards
Anthony
| [
"Maybe it has something to do with objectEncoding.\nTry to set it to AMF0 with :\nnc.defaultObjectEncoding = ObjectEncoding.AMF0;\n\nJust before connecting.\n"
] | [
0
] | [] | [] | [
"actionscript_3",
"python",
"remoteobject",
"simplexmlrpcserver"
] | stackoverflow_0004101419_actionscript_3_python_remoteobject_simplexmlrpcserver.txt |
Q:
TRAC 0.12 buildout error - no attribute 'env_open'
I am trying to use Tarek Ziadé's Trac buildout recipe from PyPi (and his book 'Expert Python Programming', which I don't have access to.)
It worked fine the first time round, however upon creating a new (Python 2.6 virtualenv) environment I got the following error on buildout.
File "/usr/local/Plone/buildout-cache/eggs/pbp.recipe.trac-0.2.3-py2.6.egg/pbp/recipe/trac/__init__.py", line 59, in install
milestone_list = [m.name for m in Milestone.select(trac.env_open())]
AttributeError: TracAdmin instance has no attribute 'env_open'
Sure enough, if i insert a pdb.set_trace() before line 59 and introspect trac then I can see there is no env_open attribute (although there is env_set, env_check etc).
The one time it did work was in a very messy development environment that already had one (non buildout) Trac instance set up and had been built with sudo permissions (the newer environment has normal permissions).
I'm at a loss as to why this is happening, although, based on the above, it feels like the recipe is trying to open a trac instance that doesnt exist yet or it can't access?
A:
pbp.recipe.trac 0.4.0 was just released and add full support of Trac 0.12: http://pypi.python.org/pypi/pbp.recipe.trac/0.4.0 .
A:
The error appears to be caused by a change made between Trac 0.11 and 0.12.
Setting the following in the buildout file, will result in a successful build.
[buildout]
versions = versions
parts = trac
index = http://pypi.python.org/simple
[versions]
Trac = 0.11
[trac]
etc....
However, I will leave the question open, as I would like the buildout to eventually work with 0.12 too.
A:
FYI, I've recently updated the pbp.recipe.trac recipe to have full support of Trac 0.11. See: http://pypi.python.org/pypi/pbp.recipe.trac/0.3.0 .
Trac 0.12 support is coming soon. Tests, feature requests and contributions are welcomed ! :)
| TRAC 0.12 buildout error - no attribute 'env_open' | I am trying to use Tarek Ziadé's Trac buildout recipe from PyPi (and his book 'Expert Python Programming', which I don't have access to.)
It worked fine the first time round, however upon creating a new (Python 2.6 virtualenv) environment I got the following error on buildout.
File "/usr/local/Plone/buildout-cache/eggs/pbp.recipe.trac-0.2.3-py2.6.egg/pbp/recipe/trac/__init__.py", line 59, in install
milestone_list = [m.name for m in Milestone.select(trac.env_open())]
AttributeError: TracAdmin instance has no attribute 'env_open'
Sure enough, if i insert a pdb.set_trace() before line 59 and introspect trac then I can see there is no env_open attribute (although there is env_set, env_check etc).
The one time it did work was in a very messy development environment that already had one (non buildout) Trac instance set up and had been built with sudo permissions (the newer environment has normal permissions).
I'm at a loss as to why this is happening, although, based on the above, it feels like the recipe is trying to open a trac instance that doesnt exist yet or it can't access?
| [
"pbp.recipe.trac 0.4.0 was just released and add full support of Trac 0.12: http://pypi.python.org/pypi/pbp.recipe.trac/0.4.0 .\n",
"The error appears to be caused by a change made between Trac 0.11 and 0.12.\nSetting the following in the buildout file, will result in a successful build.\n[buildout]\nversions = v... | [
1,
0,
0
] | [] | [] | [
"buildout",
"python",
"trac"
] | stackoverflow_0003460757_buildout_python_trac.txt |
Q:
Problem with Django site on a shared hosting
I have a problem when i try to install a Django website, on a Mocha hosting, and their technical support is so much uninformed... (I strongly don't recomment Mocha hosting for a django hosting)
They have mod_wsgi support, and mod_python installed, but when i am uploading the site as in their tutorial
http://www.mochasupport.com/kayako/index.php?_m=knowledgebase&_a=viewarticle&kbarticleid=448&nav=0,46
but at the end i am getting an error like:
Traceback (most recent call last):
File "/usr/lib64/python2.5/site-packages/mod_python/importer.py", line 1537, in HandlerDispatch
default=default_handler, arg=req, silent=hlist.silent)
File "/usr/lib64/python2.5/site-packages/mod_python/importer.py", line 1202, in _process_target
module = import_module(module_name, path=path)
File "/usr/lib64/python2.5/site-packages/mod_python/importer.py", line 304, in import_module
return import(module_name, {}, {}, ['*'])
ImportError: No module named django.core.handlers.modpython
I know this issue has been treated here as well: Error while deploying Django on Apache
But i don't have access to the terminal, how can i solve it? Is there a way to correctly set the python path without terminal access?
Thanks!
A:
Do you double check that you upload a django in
/home/youraccount/webapps/django
Most likely the hosting provieder has harcode (width you account)
that path in the apache configuration for the mod_python approach.
Or
Why don't you use mod_wsgi and in the wsgi script add your django, like this.
import os
import sys
sys.path.append('/home/youraccount/webapps/django') # Path to your custom django.
from django.core.handlers.wsgi import WSGIHandler
os.environ['DJANGO_SETTINGS_MODULE'] = 'myapp.settings'
application = WSGIHandler()
A:
Looking at that article, it seems that they don't provide Django for your use. You'll need to upload it as well.
| Problem with Django site on a shared hosting | I have a problem when i try to install a Django website, on a Mocha hosting, and their technical support is so much uninformed... (I strongly don't recomment Mocha hosting for a django hosting)
They have mod_wsgi support, and mod_python installed, but when i am uploading the site as in their tutorial
http://www.mochasupport.com/kayako/index.php?_m=knowledgebase&_a=viewarticle&kbarticleid=448&nav=0,46
but at the end i am getting an error like:
Traceback (most recent call last):
File "/usr/lib64/python2.5/site-packages/mod_python/importer.py", line 1537, in HandlerDispatch
default=default_handler, arg=req, silent=hlist.silent)
File "/usr/lib64/python2.5/site-packages/mod_python/importer.py", line 1202, in _process_target
module = import_module(module_name, path=path)
File "/usr/lib64/python2.5/site-packages/mod_python/importer.py", line 304, in import_module
return import(module_name, {}, {}, ['*'])
ImportError: No module named django.core.handlers.modpython
I know this issue has been treated here as well: Error while deploying Django on Apache
But i don't have access to the terminal, how can i solve it? Is there a way to correctly set the python path without terminal access?
Thanks!
| [
"Do you double check that you upload a django in \n\n/home/youraccount/webapps/django\n\nMost likely the hosting provieder has harcode (width you account) \nthat path in the apache configuration for the mod_python approach.\nOr\nWhy don't you use mod_wsgi and in the wsgi script add your django, like this.\nimport ... | [
2,
1
] | [] | [] | [
"django",
"hosting",
"python",
"shared"
] | stackoverflow_0004103814_django_hosting_python_shared.txt |
Q:
Python ternary operator
Possible Duplicate:
Ternary conditional operator in Python
var foo = (test) ? "True" : "False";
What would this look like in Python?
Using Python 2.7 if that makes a difference.
A:
PEP 308 adds a ternary operator:
foo = "True" if test else "False"
It's been implemented since Python 2.5
| Python ternary operator |
Possible Duplicate:
Ternary conditional operator in Python
var foo = (test) ? "True" : "False";
What would this look like in Python?
Using Python 2.7 if that makes a difference.
| [
"PEP 308 adds a ternary operator:\nfoo = \"True\" if test else \"False\"\n\nIt's been implemented since Python 2.5\n"
] | [
94
] | [
"This one looks a bit more like original ternary:\nfoo=a and b or c\n\n"
] | [
-1
] | [
"python"
] | stackoverflow_0004103667_python.txt |
Q:
Python 2 to 3 bytes/string error
I'm trying to convert a Python library made for Python 2 to Python 3, here is the code.
I have an error at line 152. In the Py2 version, the function is:
def write(self, data):
self._write_buffer += data
The error is:
TypeError: Can't convert 'bytes'
object to str implicitly
I found that I've to decode the variable, so I changed the function to:
def write(self, data):
self._write_buffer += data.decode('utf8')
It works but I have another error in the asyncore library which said that
(the Type) must be bytes or buffer, not
str
So, what can I do ?
A:
You need to be clear about where you want bytes and where you want strings. If you simply add decode and encode where the errors appear, you will be playing whack-a-mole. In your case, you are writing a socket implementation. Sockets deal with bytes, not strings. So I would think your _write_buffer should be a bytes object, not a string as you now have it.
Line 91 should change to:
self._write_buffer = b''
Then you can work from there to ensure that you use bytes throughout.
| Python 2 to 3 bytes/string error | I'm trying to convert a Python library made for Python 2 to Python 3, here is the code.
I have an error at line 152. In the Py2 version, the function is:
def write(self, data):
self._write_buffer += data
The error is:
TypeError: Can't convert 'bytes'
object to str implicitly
I found that I've to decode the variable, so I changed the function to:
def write(self, data):
self._write_buffer += data.decode('utf8')
It works but I have another error in the asyncore library which said that
(the Type) must be bytes or buffer, not
str
So, what can I do ?
| [
"You need to be clear about where you want bytes and where you want strings. If you simply add decode and encode where the errors appear, you will be playing whack-a-mole. In your case, you are writing a socket implementation. Sockets deal with bytes, not strings. So I would think your _write_buffer should be a... | [
5
] | [] | [] | [
"byte",
"python",
"string"
] | stackoverflow_0004104485_byte_python_string.txt |
Q:
Python mechanize module proxy setting question
It seems like these codes would work:
MechBrowser = mechanize.Browser()
MechBrowser.set_proxies({"http": "111.11.11.11"})
response = MechBrowser.open("http://google.com")
But as you see "111.11.11.11" is just a random ip I came up with to test if the proxy setting works, and it's not a valid proxy. The weird thing is MechBrowser still open google.com without giving any error, so does this mean if the proxy you set not working mechanize will use default setting to browse? If I want it to throw exception when the proxy is broken, how should I do?
Thanks a lot
A:
Syntax is ok, and its working on my machine as it should do.
------> print(mechanize.__version__)
(0, 2, 1, None, None)
>python -V
Python 2.6.5
When proxy is unavailable, for example, it will raise URLError. I can recommend you to check the version of mechanize+python you`re using at the moment and run this code in python interpreter interactively.
| Python mechanize module proxy setting question | It seems like these codes would work:
MechBrowser = mechanize.Browser()
MechBrowser.set_proxies({"http": "111.11.11.11"})
response = MechBrowser.open("http://google.com")
But as you see "111.11.11.11" is just a random ip I came up with to test if the proxy setting works, and it's not a valid proxy. The weird thing is MechBrowser still open google.com without giving any error, so does this mean if the proxy you set not working mechanize will use default setting to browse? If I want it to throw exception when the proxy is broken, how should I do?
Thanks a lot
| [
"Syntax is ok, and its working on my machine as it should do.\n------> print(mechanize.__version__)\n(0, 2, 1, None, None)\n\n>python -V\nPython 2.6.5\n\nWhen proxy is unavailable, for example, it will raise URLError. I can recommend you to check the version of mechanize+python you`re using at the moment and run th... | [
0
] | [] | [] | [
"mechanize",
"python"
] | stackoverflow_0004102919_mechanize_python.txt |
Q:
Python Reflection and callable objects
I have a two part question.
>>> class One(object):
... pass
...
>>> class Two(object):
... pass
...
>>> def digest(constr):
... c = apply(constr)
... print c.__class__.__name__
... print constr.__class__.__name__
...
>>> digest(Two)
Two
type
How would one create object 'Two'? Neither constr() or c() work; and it seems that apply turns it into a type.
What happens when you pass a class rather and an instance into a method?
A:
Classes are high level objects, so you can simply pass them like this:
def createMyClass ( myClass ):
obj = myClass()
return obj
class A ( object ):
pass
>>> x = createMyClass( A )
>>> type( x )
<class '__main__.A'>
A:
Just another one example:
def InstanceFactory(classname):
cls = globals()[classname]
return cls()
class A(object):
def start(self):
print "a.start"
class B(object):
def start(self):
print "b.start"
InstanceFactory("A").start()
InstanceFactory("B").start()
If the class belongs to another module:
def InstanceFactory(modulename, classname):
if '.' in modulename:
raise ValueError, "can't handle dotted modules yet"
mod = __import__(modulename)
cls = getattr(mod, classname]
return cls()
A:
How would one create object 'Two'?
Neither constr() or c() work; and it
seems that apply turns it into a
type.
The above comment was made in regards to this code:
>>> def digest(constr):
... c = apply(constr)
... print c.__class__.__name__
... print constr.__class__.__name__
apply (deprecated: see @pyfunc's answer) certainly does not turn the class Two into a type: It already is one.
>>> class Two(object): pass
...
>>> type(Two)
<type 'type'>
Classes are first class objects: they're instances of type. This makes sense if you look at the next example.
>>> two = Two()
>>> type(two)
<class '__main__.Two'>
You can see that a class very clearly functions as a type because it can be returned from type. Here's another example.
>>> Three = type('Three', (Two, ), {'foo': 'bar'})
>>> type(Three)
<type 'type'>
>>> three = Three()
>>> type(three)
<class '__main__.Three'>
You can see that type is a class that can be instantiated. Its constructor takes three arguments: the name of the class, a tuple of base classes and a dictionary containing the class attributes. It returns a new type aka class.
As to your final question,
What happens when you pass a class
rather and an instance into a method?
You're going to have to be more specific. Classes are just instances of type and so are first class objects. Asking what happens if I pass a class into a method is like asking what happens if I pass an integer into a method: It depends entirely on what the method is expecting.
A:
I am confused though. Wasn't apply() deprecated since 2.3
http://www.python.org/dev/peps/pep-0290/
We don't need this any more.
apply(f, args, kwds) --> f(*args, **kwds)
Others have been moved / considered deprecated in modern usage:
buffer()
coerce()
and intern()
Simply use : Classname() to create an object.
| Python Reflection and callable objects | I have a two part question.
>>> class One(object):
... pass
...
>>> class Two(object):
... pass
...
>>> def digest(constr):
... c = apply(constr)
... print c.__class__.__name__
... print constr.__class__.__name__
...
>>> digest(Two)
Two
type
How would one create object 'Two'? Neither constr() or c() work; and it seems that apply turns it into a type.
What happens when you pass a class rather and an instance into a method?
| [
"Classes are high level objects, so you can simply pass them like this:\ndef createMyClass ( myClass ):\n obj = myClass()\n return obj\n\nclass A ( object ):\n pass\n\n>>> x = createMyClass( A )\n>>> type( x )\n<class '__main__.A'>\n\n",
"Just another one example:\ndef InstanceFactory(classname):\n cls... | [
5,
1,
1,
0
] | [] | [] | [
"class",
"oop",
"python",
"reflection"
] | stackoverflow_0004104156_class_oop_python_reflection.txt |
Q:
Best Practice for dealing with app engine cold start problem
After a period of inactivity the first request takes about 5 to 10 secs to come through.
Is there any best practice solutions to overcome this problem?
I'm using Python version of App Engine.
A:
Reduce the set of libraries you require in order to serve requests as much as you can.
For expensive libraries that are only used in some places, put the import statement inside the function that uses them. This way, the library is only imported the first time it's needed.
If your framework supports it, do just-in-time importing of handlers, so you don't have to import them all when your app starts up.
Look forward to reserved instances / warmup requests, coming soon!
| Best Practice for dealing with app engine cold start problem | After a period of inactivity the first request takes about 5 to 10 secs to come through.
Is there any best practice solutions to overcome this problem?
I'm using Python version of App Engine.
| [
"\nReduce the set of libraries you require in order to serve requests as much as you can.\nFor expensive libraries that are only used in some places, put the import statement inside the function that uses them. This way, the library is only imported the first time it's needed.\nIf your framework supports it, do jus... | [
6
] | [] | [] | [
"google_app_engine",
"python"
] | stackoverflow_0004104751_google_app_engine_python.txt |
Q:
Remove duplicate entries from nested dictionary, if two values are the same, in Python
Consider this dictionary format.
{1:{'name':'chrome', 'author':'google', 'url':'http://www.google.com/' },
2:{'name':'firefox','author':'mozilla','url':'http://www.mozilla.com/'}}
I want to remove all items which have the same name and author.
I can easily remove duplicate entries based on keys by putting all keys in a set, and maybe expand this to work on a specific value, but this seems like a costly operation which iterates over a dictionary multiple times. I wouldn't know how to do this with two values in an efficient way. It's a dictionary with thousands of items.
A:
Iterate through the dictionary, keeping track of encountered (name, author) tuples as you go and remove those that you have already encountered:
def remove_duplicates(d):
encountered_entries = set()
for key, entry in d.items():
if (entry['name'], entry['author']) in encountered_entries:
del d[key]
else:
encountered_entries.add((entry['name'], entry['author']))
A:
Let's see if this works...
from itertools import groupby
def entry_key(entry):
key, value = entry
return (value['name'], value['author'])
def nub(d):
items = d.items()
items.sort(key=entry_key)
grouped = groupby(items, entry_key)
return dict([grouper.next() for (key, grouper) in grouped])
| Remove duplicate entries from nested dictionary, if two values are the same, in Python | Consider this dictionary format.
{1:{'name':'chrome', 'author':'google', 'url':'http://www.google.com/' },
2:{'name':'firefox','author':'mozilla','url':'http://www.mozilla.com/'}}
I want to remove all items which have the same name and author.
I can easily remove duplicate entries based on keys by putting all keys in a set, and maybe expand this to work on a specific value, but this seems like a costly operation which iterates over a dictionary multiple times. I wouldn't know how to do this with two values in an efficient way. It's a dictionary with thousands of items.
| [
"Iterate through the dictionary, keeping track of encountered (name, author) tuples as you go and remove those that you have already encountered:\ndef remove_duplicates(d):\n encountered_entries = set()\n for key, entry in d.items():\n if (entry['name'], entry['author']) in encountered_entries:\n ... | [
3,
1
] | [] | [] | [
"dictionary",
"python",
"python_2.5"
] | stackoverflow_0004104957_dictionary_python_python_2.5.txt |
Q:
PyQt QTableWidget keyboard events while editing
I want to navigate QTableWidget in a similar way to MS Excel.
For example, when the user presses the right arrow key while editing a cell, the editing will finish and the next cell to the right will be selected. I have searched the Qt docs, but can't seem to find out how.
A:
from PyQt4.QtCore import QEvent, Qt
from PyQt4.QtGui import QTableWidget, QWidget, QVBoxLayout, QApplication
class MyTableWidget(QTableWidget):
def __init__(self):
QTableWidget.__init__(self)
self.keys = [Qt.Key_Left,
Qt.Key_Right]
# We need this to allow navigating without editing
self.catch = False
def focusInEvent(self, event):
self.catch = False
return QTableWidget.focusInEvent(self, event)
def focusOutEvent(self, event):
self.catch = True
return QTableWidget.focusOutEvent(self, event)
def event(self, event):
if self.catch and event.type() == QEvent.KeyRelease and event.key() in self.keys:
self._moveCursor(event.key())
return QTableWidget.event(self, event)
def keyPressEvent(self, event):
if not self.catch:
return QTableWidget.keyPressEvent(self, event)
self._moveCursor(event.key())
def _moveCursor(self, key):
row = self.currentRow()
col = self.currentColumn()
if key == Qt.Key_Left and col > 0:
col -= 1
elif key == Qt.Key_Right and col < self.columnCount():
col += 1
elif key == Qt.Key_Up and row > 0:
row -= 1
elif key == Qt.Key_Down and row < self.rowCount():
row += 1
else:
return
self.setCurrentCell(row, col)
self.edit(self.currentIndex())
class Widget(QWidget):
def __init__(self, parent=None):
QWidget.__init__(self)
tableWidget = MyTableWidget()
tableWidget.setRowCount(10)
tableWidget.setColumnCount(10)
layout = QVBoxLayout()
layout.addWidget(tableWidget)
self.setLayout(layout)
app = QApplication([])
widget = Widget()
widget.show()
app.exec_()
Not sure if you still need this, but here goes.
| PyQt QTableWidget keyboard events while editing | I want to navigate QTableWidget in a similar way to MS Excel.
For example, when the user presses the right arrow key while editing a cell, the editing will finish and the next cell to the right will be selected. I have searched the Qt docs, but can't seem to find out how.
| [
"from PyQt4.QtCore import QEvent, Qt\nfrom PyQt4.QtGui import QTableWidget, QWidget, QVBoxLayout, QApplication\n\n\nclass MyTableWidget(QTableWidget):\n def __init__(self):\n QTableWidget.__init__(self)\n\n self.keys = [Qt.Key_Left,\n Qt.Key_Right]\n\n # We need this to a... | [
5
] | [] | [] | [
"pyqt",
"pyside",
"python",
"qt"
] | stackoverflow_0003901829_pyqt_pyside_python_qt.txt |
Q:
problem using Python to increase virtual memory for my java application
I have created a java application in Eclipse which when I increase the VM arguments to -Xmx1024m runs fine. When I try to run the application via the command promt using the following path:
c:\python27\python c:\jars2run\run.py c:\jars2run\myown\ClassTree.jar LiveSimulator2/Live_PairsEngine3 java -Xmx1024m
I get the following error message:
Exception in thread "main" java.lang.OutOfMemoryError: Java heap space
at java.nio.CharBuffer.wrap(Unknown Source)
at java.nio.CharBuffer.wrap(Unknown Source)
at java.lang.StringCoding$StringDecoder.dec… Source)
at java.lang.StringCoding.decode(Unknown Source)
at java.lang.String.<init>(Unknown Source)
at java.lang.String.<init>(Unknown Source)
at com.mysql.jdbc.ResultSet.getStringIntern…
at com.mysql.jdbc.ResultSet.getString(Resul…
at com.mysql.jdbc.ResultSet.getString(Resul…
at LiveSimulator2.Timeseries2.<init>(Timese…
at LiveSimulator2.Live_PairsEngine3.main(Li…
I have found out that I need to add the heap memory requirement in the python script but cannot figure out where in the scipt I have to put the 'java -Xmx1024m' or what ever is needed and therefore the java application still falls over due to lack of memory.
See below for the python script, at the moment the python script just copies the external jars need to run my java application.
import sys
import os
classfile=sys.argv[2];
jar=sys.argv[1];
cp='%s' % jar
FILES=os.listdir('c:/jars2run/3rdparty');
os.chdir('c:/jars2run/3rdparty');
for i in FILES:
if (i.endswith('jar')):
cp='%s;%s' % (cp, i)
cmd='java -classpath "%s" %s' % (cp, classfile)
print('%s' % cmd)
os.system(cmd)
Could someone let me know where the memory increase needs to should go please.
Very grateful for any assistance.
A:
Change this line:
cmd='java -classpath "%s" %s' % (cp, classfile)
to
cmd='java -Xmx1024m -classpath "%s" %s' % (cp, classfile)
BTW: some pointers on Python:
You don't need semicolons on the ends of lines, and you don't need to wrap the if condition in parentheses.
If your format string is only "%s", then you aren't gaining anything by formatting, just use the string as is.
You can append to a string with +=.
The Python stdlib includes the glob module for finding files with shell wildcard patterns.
Using these (and a few others), we can clean up your script:
import sys
import os
import glob
cp = sys.argv[1]
classfile = sys.argv[2]
os.chdir('c:/jars2run/3rdparty')
for f in glob.glob("*.jar"):
cp += ';%s' % f
cmd = 'java -classpath "%s" %s' % (cp, classfile)
print(cmd)
os.system(cmd)
| problem using Python to increase virtual memory for my java application | I have created a java application in Eclipse which when I increase the VM arguments to -Xmx1024m runs fine. When I try to run the application via the command promt using the following path:
c:\python27\python c:\jars2run\run.py c:\jars2run\myown\ClassTree.jar LiveSimulator2/Live_PairsEngine3 java -Xmx1024m
I get the following error message:
Exception in thread "main" java.lang.OutOfMemoryError: Java heap space
at java.nio.CharBuffer.wrap(Unknown Source)
at java.nio.CharBuffer.wrap(Unknown Source)
at java.lang.StringCoding$StringDecoder.dec… Source)
at java.lang.StringCoding.decode(Unknown Source)
at java.lang.String.<init>(Unknown Source)
at java.lang.String.<init>(Unknown Source)
at com.mysql.jdbc.ResultSet.getStringIntern…
at com.mysql.jdbc.ResultSet.getString(Resul…
at com.mysql.jdbc.ResultSet.getString(Resul…
at LiveSimulator2.Timeseries2.<init>(Timese…
at LiveSimulator2.Live_PairsEngine3.main(Li…
I have found out that I need to add the heap memory requirement in the python script but cannot figure out where in the scipt I have to put the 'java -Xmx1024m' or what ever is needed and therefore the java application still falls over due to lack of memory.
See below for the python script, at the moment the python script just copies the external jars need to run my java application.
import sys
import os
classfile=sys.argv[2];
jar=sys.argv[1];
cp='%s' % jar
FILES=os.listdir('c:/jars2run/3rdparty');
os.chdir('c:/jars2run/3rdparty');
for i in FILES:
if (i.endswith('jar')):
cp='%s;%s' % (cp, i)
cmd='java -classpath "%s" %s' % (cp, classfile)
print('%s' % cmd)
os.system(cmd)
Could someone let me know where the memory increase needs to should go please.
Very grateful for any assistance.
| [
"Change this line:\ncmd='java -classpath \"%s\" %s' % (cp, classfile)\n\nto\ncmd='java -Xmx1024m -classpath \"%s\" %s' % (cp, classfile)\n\nBTW: some pointers on Python:\n\nYou don't need semicolons on the ends of lines, and you don't need to wrap the if condition in parentheses.\nIf your format string is only \"%s... | [
2
] | [] | [] | [
"python"
] | stackoverflow_0004105193_python.txt |
Q:
Advice for Python programmer writing C#
I've seen this question about advice for C# programmers writing Python code but I am going the opposite direction.
What are some tips, tricks, caveats for a Python programmer writing C# code?
A:
Here are some examples I meant by my question:
enumerate() in C#
another possibility:
"abc".Where((x,i) => true).Select((x, i) => string.Format("{0}: {1}", i, x))
0: a
1: b
2: c
list comprehension in C#
List<Foo> fooList = new List<Foo>();
IEnumerable<Foo> extract = from foo in fooList where foo.Bar > 10 select Foo.Name.ToUpper();
| Advice for Python programmer writing C# | I've seen this question about advice for C# programmers writing Python code but I am going the opposite direction.
What are some tips, tricks, caveats for a Python programmer writing C# code?
| [
"Here are some examples I meant by my question:\n\nenumerate() in C#\nanother possibility:\n\"abc\".Where((x,i) => true).Select((x, i) => string.Format(\"{0}: {1}\", i, x))\n\n0: a\n1: b\n2: c\n\nlist comprehension in C#\nList<Foo> fooList = new List<Foo>();\nIEnumerable<Foo> extract = from foo in fooList where foo... | [
2
] | [] | [] | [
"c#",
"python"
] | stackoverflow_0004104885_c#_python.txt |
Q:
IDE don't see all the functions
i'm using Elcipse+PyDev and Pyscripter sometimes for Python 2.7
Yesterday i installed PyTables from compiled binaries and :
import tables
h5f = tables.openFile(r'D:\sample.h5','w')
h5f.createGroup('/','Box')
h5f.
So, when I type "h5f." IDE don't show me all the methods, only a few!
Can't do anything with It, installed PyTables few times,same result...
Method h5f.CreateGroup() works perfectly, but IDE dont see it so don't display it in drop-down list! Eclipse and Python both behave same...
A:
The thing with Pydev and Eclipse is that when you install a new package or library and if you want to use the auto-complete with it, you will have to recreate the system PYTHONPATH in eclipse.
For that go to: Window -> Preferences -> Pydev -> Interpreted Python and in the tab libraries, in System PYTHONPATH you will not see your new installed library because pydev just do a copy of the PYTHONPATH the first time that you have configured and now each time you installed a new package you will have to resynchronize pydev with the new PYTHONPATH.
So to resynchronize you will have to click on the button Apply so that eclipse export (again) all the library (between them your new installed one) from PYTHONPATH to eclipse.
So now eclipse should know your library and you should work with it just fine.
Hope this will help :)
| IDE don't see all the functions | i'm using Elcipse+PyDev and Pyscripter sometimes for Python 2.7
Yesterday i installed PyTables from compiled binaries and :
import tables
h5f = tables.openFile(r'D:\sample.h5','w')
h5f.createGroup('/','Box')
h5f.
So, when I type "h5f." IDE don't show me all the methods, only a few!
Can't do anything with It, installed PyTables few times,same result...
Method h5f.CreateGroup() works perfectly, but IDE dont see it so don't display it in drop-down list! Eclipse and Python both behave same...
| [
"The thing with Pydev and Eclipse is that when you install a new package or library and if you want to use the auto-complete with it, you will have to recreate the system PYTHONPATH in eclipse.\nFor that go to: Window -> Preferences -> Pydev -> Interpreted Python and in the tab libraries, in System PYTHONPATH you w... | [
2
] | [] | [] | [
"eclipse",
"pyscripter",
"python"
] | stackoverflow_0004104345_eclipse_pyscripter_python.txt |
Q:
wxpython filebrowsedialog button in Control Desk from dSPACE
iam working on a project and need to add a filebrowserdialog to my programm in control desk from dSPACE...
there is a way to do this in wxpython, but the problem is:
i dont know how to implement this in my control desk program..
i need to be able to add a button, when i click on it, it should show a filebrowserdialog and the selected file should appear in a textbox ..
anyone knows how to make it ?
thanks in advance
A:
You can create a FileDialog like so:
import os
dlg = wx.FileDialog(
self, message="Choose a file",
defaultDir=os.getcwd(),
defaultFile="",
style=wx.OPEN | wx.CHANGE_DIR
)
if dlg.ShowModal() == wx.ID_OK:
path = dlg.GetPath()
#Set your textCtrl with the value of path here!
dlg.Destroy()
Obviously you'll need to create a button and bind it to a handler which calls the above code.
Then you can set a wx.TextCtrl with the path you get when you call GetPath() on your FileDialog.
wx.FileDialog Documentation:
http://wxpython.org/docs/api/wx.FileDialog-class.html
http://xoomer.virgilio.it/infinity77/wxPython/Widgets/wx.FileDialog.html
Edit:
I just noticed the mention of DSPACE, I don't know anything about that, but the above method is how its done in regular wxPython.
| wxpython filebrowsedialog button in Control Desk from dSPACE | iam working on a project and need to add a filebrowserdialog to my programm in control desk from dSPACE...
there is a way to do this in wxpython, but the problem is:
i dont know how to implement this in my control desk program..
i need to be able to add a button, when i click on it, it should show a filebrowserdialog and the selected file should appear in a textbox ..
anyone knows how to make it ?
thanks in advance
| [
"You can create a FileDialog like so:\n import os\n\n dlg = wx.FileDialog(\n self, message=\"Choose a file\",\n defaultDir=os.getcwd(),\n defaultFile=\"\",\n style=wx.OPEN | wx.CHANGE_DIR\n )\n\n if dlg.ShowModal() == wx.ID_OK:\n ... | [
2
] | [] | [] | [
"python",
"wxpython"
] | stackoverflow_0004104535_python_wxpython.txt |
Q:
Archives for Model in python to appengine
I'm a noob in python, and i'm creating a app into appengine with python.
I define class form Model's bug i don't know how order archives, normally, i create diferrent archives with all entities of my model, buy i don't know if in python is normal do the same think.
I think is normal define Model for all app in one file and then import it when you need, but i'm very noob in python and i can't find information about it.
And what it's the normal structure of files in python projects ?
Thx and sorry for my poor english.
A:
I found a "simple" project of google, with a example:
http://code.google.com/p/google-app-engine-samples/source/browse/#svn/trunk/overheard
| Archives for Model in python to appengine | I'm a noob in python, and i'm creating a app into appengine with python.
I define class form Model's bug i don't know how order archives, normally, i create diferrent archives with all entities of my model, buy i don't know if in python is normal do the same think.
I think is normal define Model for all app in one file and then import it when you need, but i'm very noob in python and i can't find information about it.
And what it's the normal structure of files in python projects ?
Thx and sorry for my poor english.
| [
"I found a \"simple\" project of google, with a example:\nhttp://code.google.com/p/google-app-engine-samples/source/browse/#svn/trunk/overheard\n"
] | [
0
] | [] | [] | [
"data_modeling",
"google_app_engine",
"python"
] | stackoverflow_0004105793_data_modeling_google_app_engine_python.txt |
Q:
BeautifulSoup not working
i am trying to import the content of my blog using BeautifulSoup,using the the syntax as given below
import urllib2
from BeautifulSoup import BeautifulSoup
response=urllib2.urlopen('http://www.bugsandbrains.blogspot.com')
html=response.read()
soup=BeautifulSoup(html)
Every thing worked fine two or three time after that it started throwing HtmlParseError
i see it highly unlikely that the structure of the page might have changed within a few minutes what else can might be causing this problem ?
i am enclosing the trace as well.
Traceback (most recent call last):
File "<console>", line 1, in <module>
File "/usr/lib/pymodules/python2.6/BeautifulSoup.py", line 1499, in __init__
BeautifulStoneSoup.__init__(self, *args, **kwargs)
File "/usr/lib/pymodules/python2.6/BeautifulSoup.py", line 1230, in __init__
self._feed(isHTML=isHTML)
File "/usr/lib/pymodules/python2.6/BeautifulSoup.py", line 1263, in _feed
self.builder.feed(markup)
File "/usr/lib/python2.6/HTMLParser.py", line 108, in feed
self.goahead(0)
File "/usr/lib/python2.6/HTMLParser.py", line 150, in goahead
k = self.parse_endtag(i)
File "/usr/lib/python2.6/HTMLParser.py", line 317, in parse_endtag
self.error("bad end tag: %r" % (rawdata[i:j],))
File "/usr/lib/python2.6/HTMLParser.py", line 115, in error
raise HTMLParseError(message, self.getpos())
HTMLParseError: bad end tag: u"</scr' + 'ipt>", at line 1152, column 16
A:
I just tried your code on Windows with:
Python: 2.6 (same as yours)
BeautiSoup: 3.0.8.1 (latest)
I can't reproduce this. Are you using the latest code 3.0 series which is meant for Python 2.6, not 3.1 series which is for Python 3 [0]. Sorry, but can't think of any other clues right now.
[0] http://www.crummy.com/software/BeautifulSoup/#Download
A:
I have tried your code, and it works. My env: ActivePython 2.6.6.15, BeautifulSoup 3.0.8.1. I printed out soup variable and it contains content of "Boredom Induced Post". When I tested http://www.bugsandbrains.blogspot.com with browsers they shows Wave Sandbox login page. No clue about what is wrong :(
| BeautifulSoup not working | i am trying to import the content of my blog using BeautifulSoup,using the the syntax as given below
import urllib2
from BeautifulSoup import BeautifulSoup
response=urllib2.urlopen('http://www.bugsandbrains.blogspot.com')
html=response.read()
soup=BeautifulSoup(html)
Every thing worked fine two or three time after that it started throwing HtmlParseError
i see it highly unlikely that the structure of the page might have changed within a few minutes what else can might be causing this problem ?
i am enclosing the trace as well.
Traceback (most recent call last):
File "<console>", line 1, in <module>
File "/usr/lib/pymodules/python2.6/BeautifulSoup.py", line 1499, in __init__
BeautifulStoneSoup.__init__(self, *args, **kwargs)
File "/usr/lib/pymodules/python2.6/BeautifulSoup.py", line 1230, in __init__
self._feed(isHTML=isHTML)
File "/usr/lib/pymodules/python2.6/BeautifulSoup.py", line 1263, in _feed
self.builder.feed(markup)
File "/usr/lib/python2.6/HTMLParser.py", line 108, in feed
self.goahead(0)
File "/usr/lib/python2.6/HTMLParser.py", line 150, in goahead
k = self.parse_endtag(i)
File "/usr/lib/python2.6/HTMLParser.py", line 317, in parse_endtag
self.error("bad end tag: %r" % (rawdata[i:j],))
File "/usr/lib/python2.6/HTMLParser.py", line 115, in error
raise HTMLParseError(message, self.getpos())
HTMLParseError: bad end tag: u"</scr' + 'ipt>", at line 1152, column 16
| [
"I just tried your code on Windows with:\n\nPython: 2.6 (same as yours)\nBeautiSoup: 3.0.8.1 (latest)\n\nI can't reproduce this. Are you using the latest code 3.0 series which is meant for Python 2.6, not 3.1 series which is for Python 3 [0]. Sorry, but can't think of any other clues right now.\n[0] http://www.crum... | [
1,
1
] | [] | [] | [
"beautifulsoup",
"html",
"python"
] | stackoverflow_0004105377_beautifulsoup_html_python.txt |
Q:
Is there a way to group several keys which points to the same value in a dictionary?
Is there a way to group several keys which points to the same value in a dictionary?
A:
from collections import defaultdict
newdict = defaultdict(list)
for k,v in originaldict.items():
newdict[v].append(k)
A:
Not exactly sure you want the result structured, but here's one guess:
from collections import defaultdict
mydict = {'a': 1, 'b': 2, 'c': 3, 'd': 2, 'e': 4, 'f': 2, 'g': 4}
tempdict = defaultdict(list)
for k,v in mydict.iteritems():
tempdict[v].append(k)
groupedkeysdict = {}
for k,v in tempdict.iteritems():
groupedkeysdict[tuple(v) if len(v)>1 else v[0]] = k
print groupedkeysdict
# {'a': 1, 'c': 3, ('e', 'g'): 4, ('b', 'd', 'f'): 2}
| Is there a way to group several keys which points to the same value in a dictionary? | Is there a way to group several keys which points to the same value in a dictionary?
| [
"from collections import defaultdict\n\nnewdict = defaultdict(list)\nfor k,v in originaldict.items():\n newdict[v].append(k)\n\n",
"Not exactly sure you want the result structured, but here's one guess:\nfrom collections import defaultdict\n\nmydict = {'a': 1, 'b': 2, 'c': 3, 'd': 2, 'e': 4, 'f': 2, 'g': 4}\n\... | [
3,
2
] | [] | [] | [
"dictionary",
"python"
] | stackoverflow_0004105376_dictionary_python.txt |
Q:
Manage #TODO (lots of files) with VIM
I use VIM/GVIM to develop my python projects and I randomly I leave #TODO comments in my code.
Is there any way to manage (search, list and link) all the #TODO occurrences inside VIM? I tried the tasklist plugin, it's almost what I need, but it only lists the current file #TODO occurrences. Generally my projects has some sub-folders and many .py files, so I'd like to find a way to search through all folders and files in the current working directory and list them.
A:
If you just want a list of the occurences of "TODO" in .py files in the working directory, you can just use :vimgrep like so:
:vimgrep TODO **/*.py
Then open the quickfix window with:
:cw
(it might open it automatically anyway, not sure) and just scroll through the results, hitting Enter to go to each occurrence.
For more complicated management, I'd probably recommend setting up an issue tracker.
| Manage #TODO (lots of files) with VIM | I use VIM/GVIM to develop my python projects and I randomly I leave #TODO comments in my code.
Is there any way to manage (search, list and link) all the #TODO occurrences inside VIM? I tried the tasklist plugin, it's almost what I need, but it only lists the current file #TODO occurrences. Generally my projects has some sub-folders and many .py files, so I'd like to find a way to search through all folders and files in the current working directory and list them.
| [
"If you just want a list of the occurences of \"TODO\" in .py files in the working directory, you can just use :vimgrep like so:\n:vimgrep TODO **/*.py\n\nThen open the quickfix window with:\n:cw\n\n(it might open it automatically anyway, not sure) and just scroll through the results, hitting Enter to go to each oc... | [
52
] | [] | [] | [
"comments",
"python",
"todo",
"vim"
] | stackoverflow_0004106137_comments_python_todo_vim.txt |
Q:
Read a number of random lines from a file in Python
Could someone show me how I could read a random number of lines from a file in Python?
A:
Your requirement is a bit vague, so here's another slightly different method (for inspiration if nothing else):
from random import random
lines = [line for line in open("/some/file") if random() >= .5]
Compared with the other solutions, the number of lines varies less (distribution around half the total number of lines) but each line is chosen with 50% probability, and only one pass through the file is required.
A:
To get a number of lines at random from your file you could do something like the following:
import random
with open('file.txt') as f:
lines = random.sample(f.readlines(),5)
The above example returns 5 lines but you can easily change that to the number you require. You could also change it to randint() to get a random number of lines in addition to a number of random lines, but you'd have to make sure the sample size isn't bigger than the number of lines in the file. Depending on your input this might be trivial or a little more complex.
Note that the lines could appear in lines in a different order to which they appear in the file.
A:
import linecache
import random
import sys
# number of line to get.
NUM_LINES_GET = 5
# Get number of line in the file.
with open('file_name') as f:
number_of_lines = len(f.readlines())
if NUM_LINES_GET > number_of_lines:
print "are you crazy !!!!"
sys.exit(1)
# Choose a random number of a line from the file.
for i in random.sample(range(1, number_of_lines+1), NUM_LINES_GET)
print linecache.getline('file_name', i)
linecache.clearcache()
A:
import os,random
def getrandfromMem(filename) :
fd = file(filename,'rb')
l = fd.readlines()
pos = random.randint(0,len(l))
fd.close()
return (pos,l[pos])
def getrandomline2(filename) :
filesize = os.stat(filename)[6]
if filesize < 4096 : # Seek may not be very useful
return getrandfromMem(filename)
fd = file(filename,'rb')
for _ in range(10) : # Try 10 times
pos = random.randint(0,filesize)
fd.seek(pos)
fd.readline() # Read and ignore
line = fd.readline()
if line != '' :
break
if line != '' :
return (pos,line)
else :
getrandfromMem(filename)
getrandomline2("shaks12.txt")
A:
Assuming the offset is always at the beginning of the file:
import random
lines = file('/your/file').read().splitlines()
n_lines = random.randrange(len(lines))
random_lines = lines[:n_lines]
Note that this will read the entire file into memory.
| Read a number of random lines from a file in Python | Could someone show me how I could read a random number of lines from a file in Python?
| [
"Your requirement is a bit vague, so here's another slightly different method (for inspiration if nothing else):\nfrom random import random\nlines = [line for line in open(\"/some/file\") if random() >= .5]\n\nCompared with the other solutions, the number of lines varies less (distribution around half the total num... | [
17,
15,
2,
0,
0
] | [] | [] | [
"python"
] | stackoverflow_0004105778_python.txt |
Q:
Getting NppExec to understand path of the current file in Notepad++ (for Python scripts)
Using windows for the first time in quite awhile and have picked up notepad++ and am using the nppexec plugin to run python scripts. However, I noticed that notepad++ doesn't pick up the directory that my script is saved in. For example, I place "script.py" in 'My Documents' however os.getcwd() prints "Program Files \ Notepad++"
Does anyone know how to change this behavior? Not exactly used to it in Mac.
A:
Notepad++ >nppexec >follow $(current directory)
A:
You could put something like this at the beginning of your script:
import os
os.chdir(os.path.dirname(__file__))
| Getting NppExec to understand path of the current file in Notepad++ (for Python scripts) | Using windows for the first time in quite awhile and have picked up notepad++ and am using the nppexec plugin to run python scripts. However, I noticed that notepad++ doesn't pick up the directory that my script is saved in. For example, I place "script.py" in 'My Documents' however os.getcwd() prints "Program Files \ Notepad++"
Does anyone know how to change this behavior? Not exactly used to it in Mac.
| [
"Notepad++ >nppexec >follow $(current directory)\n",
"You could put something like this at the beginning of your script:\nimport os\nos.chdir(os.path.dirname(__file__))\n\n"
] | [
15,
2
] | [] | [] | [
"notepad++",
"nppexec",
"python"
] | stackoverflow_0004103085_notepad++_nppexec_python.txt |
Q:
intermittent smtp broken pipe (errno 32)
I have a python script that sends out a few sets of emails (to different addresses with different contents) using smtplib periodically throughout the day. Somewhat frequently (say about 1 in 5 times when sending out batches of more than one email at the same time), I get a IOError (errno: broken pipe). I try reseting and quitting the SMTP server and then connect to the server again and attempt to resend, but that always fails if it failed the first time (with the same exception). The SMTP server is maintained by the college and should be reliable (and allows loginless emails as long as you are on the intranet).
Ignoring the ugliness of the code below (lack of DRY), can anyone suggest a more reliable way to connect?
I create a class called EmailSet which will send a batch of a few emails that has a member function send_emails:
class EmailSet(object):
...
def send_emails(self):
try: # Connect to server
server = smtplib.SMTP( smtp_server_name_str, 25)
server.set_debuglevel(self.verbose)
server.ehlo()
for email in self.email_set:
try: # send 1st mail
logging.debug("Sending email to %r" % email.recipients)
response_dict = server.sendmail(email.fromaddr, email.recipients, email.msg_str())
logging.info("Sent email to %r" % email.recipients)
except Exception as inst:
logging.error('RD: %r' % response_dict)
logging.error("Email Sending Failed")
logging.error("%r %s" % ( type(inst), inst ) )
try: # send second mail
logging.info("Second Attempt to send to %r" % email.recipients)
try:
server.rset()
server.quit()
except:
pass
time.sleep(60) # wait 60s
server = smtplib.SMTP( smtp_server_name_str, 25)
server.set_debuglevel(self.verbose)
server.ehlo()
response_dict = server.sendmail(email.fromaddr, email.recipients, email.msg_str())
logging.info("Sent email to %r (2nd Attempt)" % email.recipients)
except Exception as inst:
try:
logging.error('RD: %r' % response_dict)
except:
pass
logging.error("Second Attempt Email Sending Failed")
except:
logging.debug("Can't connect to server")
finally:
logging.debug("Reseting and Quitting Server")
server.rset()
server.quit()
logging.debug("Successfully Quit Server")
return True
Any thoughts on how to proceed debugging this? The stmp server isn't maintained by me, though should be well-maintained (used for ~10k person organization). I originally connected and disconnected from the smtpserver after sending each email, but that produced more errors than this method.
Also would it be safer to use /usr/sbin/sendmail rather than smtplib?
A:
Also would it be safer to use /usr/sbin/sendmail rather than smtplib?
From the point of view of handling a message queue and a queue-runner for retries. Yes, sendmail or another local MTA could handle this for you.
Any thoughts on how to proceed debugging this?
Packet capture. Use wireshark to capture the smtp traffic, see whats going on. You've got a lot of broad exception handling that isn't necessarily showing you the exact error.
| intermittent smtp broken pipe (errno 32) | I have a python script that sends out a few sets of emails (to different addresses with different contents) using smtplib periodically throughout the day. Somewhat frequently (say about 1 in 5 times when sending out batches of more than one email at the same time), I get a IOError (errno: broken pipe). I try reseting and quitting the SMTP server and then connect to the server again and attempt to resend, but that always fails if it failed the first time (with the same exception). The SMTP server is maintained by the college and should be reliable (and allows loginless emails as long as you are on the intranet).
Ignoring the ugliness of the code below (lack of DRY), can anyone suggest a more reliable way to connect?
I create a class called EmailSet which will send a batch of a few emails that has a member function send_emails:
class EmailSet(object):
...
def send_emails(self):
try: # Connect to server
server = smtplib.SMTP( smtp_server_name_str, 25)
server.set_debuglevel(self.verbose)
server.ehlo()
for email in self.email_set:
try: # send 1st mail
logging.debug("Sending email to %r" % email.recipients)
response_dict = server.sendmail(email.fromaddr, email.recipients, email.msg_str())
logging.info("Sent email to %r" % email.recipients)
except Exception as inst:
logging.error('RD: %r' % response_dict)
logging.error("Email Sending Failed")
logging.error("%r %s" % ( type(inst), inst ) )
try: # send second mail
logging.info("Second Attempt to send to %r" % email.recipients)
try:
server.rset()
server.quit()
except:
pass
time.sleep(60) # wait 60s
server = smtplib.SMTP( smtp_server_name_str, 25)
server.set_debuglevel(self.verbose)
server.ehlo()
response_dict = server.sendmail(email.fromaddr, email.recipients, email.msg_str())
logging.info("Sent email to %r (2nd Attempt)" % email.recipients)
except Exception as inst:
try:
logging.error('RD: %r' % response_dict)
except:
pass
logging.error("Second Attempt Email Sending Failed")
except:
logging.debug("Can't connect to server")
finally:
logging.debug("Reseting and Quitting Server")
server.rset()
server.quit()
logging.debug("Successfully Quit Server")
return True
Any thoughts on how to proceed debugging this? The stmp server isn't maintained by me, though should be well-maintained (used for ~10k person organization). I originally connected and disconnected from the smtpserver after sending each email, but that produced more errors than this method.
Also would it be safer to use /usr/sbin/sendmail rather than smtplib?
| [
"Also would it be safer to use /usr/sbin/sendmail rather than smtplib?\nFrom the point of view of handling a message queue and a queue-runner for retries. Yes, sendmail or another local MTA could handle this for you.\nAny thoughts on how to proceed debugging this?\nPacket capture. Use wireshark to capture the smtp ... | [
1
] | [] | [] | [
"python",
"smtp",
"smtplib"
] | stackoverflow_0004106141_python_smtp_smtplib.txt |
Q:
How to use property of object... Python!
In a module I defined a class with the following __init__ method:
class RMLoader(object):
def __init__(self):
self.now=datetime.datetime.now()
then I'm importing that module in console:
>>> from video.remmedia.loader import RMLoader
>>> loader=RMLoader()
>>> loader.now
datetime.datetime(2010, 11, 4, 17, 40, 36, 523000)
the question is why it not gives me standard datetime object?
but when i do print it act like standard datetime object:
>>> print loader.now
2010-11-04 17:40:36.523000
But I steel cant use it in function where i need datetime object...
How can I use that attribute like standard datetime?
A:
It is a standard datetime object all the time. The difference is that loader.now will invoke repr, and print loader.now will invoke str. The first one is designed to give an accurate representation of the object, ideally one that would evaluate to an identical object. The second one is designed to provide a readable representation of the object.
There is documentation on this here.
| How to use property of object... Python! | In a module I defined a class with the following __init__ method:
class RMLoader(object):
def __init__(self):
self.now=datetime.datetime.now()
then I'm importing that module in console:
>>> from video.remmedia.loader import RMLoader
>>> loader=RMLoader()
>>> loader.now
datetime.datetime(2010, 11, 4, 17, 40, 36, 523000)
the question is why it not gives me standard datetime object?
but when i do print it act like standard datetime object:
>>> print loader.now
2010-11-04 17:40:36.523000
But I steel cant use it in function where i need datetime object...
How can I use that attribute like standard datetime?
| [
"It is a standard datetime object all the time. The difference is that loader.now will invoke repr, and print loader.now will invoke str. The first one is designed to give an accurate representation of the object, ideally one that would evaluate to an identical object. The second one is designed to provide a readab... | [
8
] | [] | [] | [
"datetime",
"python"
] | stackoverflow_0004106308_datetime_python.txt |
Q:
How can store a file on Google Storage from URL on Google App Engine?
I want to create a service on Google App Engine (Python) that will receive a URL of an image and store it on Google Storage. I managed to upload from a local file using boto or gsutil command line, but not by retrieving the file via URL. I tried doing it using the HTTP requests (PUT) and I'm getting error responses for wrong signatures. Obviously I'm doing something wrong, but unfortunately I have no idea where.
So my question is: How can I retrieve a file from a URL and store it on Google Storage using Python for Google App Angine?
Here is what I've done (using another answer):
class ImportPhoto(webapp.RequestHandler):
def get(self):
self.response.headers['Content-Type'] = 'text/plain'
srow = self.response.out.write
url = self.request.get('url')
srow('URL: %s\n' % (url))
image_response = urlfetch.fetch(url)
m = md5.md5()
m.update(image_response.content)
hash = m.hexdigest()
time = "%s" % datetime.utcnow().strftime("%a, %d %b %Y %H:%M:%S GMT")
str_to_sig = "PUT\n" + hash + "\n\n" +
time + "\nx-goog-acl:public-read\n/lipis/8418.png"
sig = base64.b64encode(hmac.new(
config_credentials.GS_SECRET_ACCESS_KEY,
str_to_sig, hashlib.sha1).digest())
total = len(image_response.content)
srow('Size: %d bytes\n' % (total))
header = {"Date": time,
"x-goog-acl": "public-read",
"Content-MD5": hash,
'Content-Length': total,
'Authorization': "GOOG1 %s:%s" %
(config_credentials.GS_ACCESS_KEY_ID, sig)}
conn = httplib.HTTPConnection("lipis.commondatastorage.googleapis.com")
conn.set_debuglevel(2)
conn.putrequest('PUT', "/8418.png")
for h in header:
conn.putheader(h, header[h])
conn.endheaders()
conn.send(image_response.content + '\r\n')
res = conn.getresponse()
srow('\n\n%d: %s\n' % (res.status, res.reason))
data = res.read()
srow(data)
conn.close()
And I'm getting as a response:
URL: https://stackoverflow.com/users/flair/8418.png
Size: 9605 bytes
400: Bad Request
<?xml version='1.0' encoding='UTF-8'?><Error><Code>BadDigest</Code><Message>The Content-MD5 you specified did not match what we received.</Message><Details>lipis/hello.jpg</Details></Error>
A:
Have you read the docs on how to sign requests? The string to sign must include the Content-MD5, Content-Type and Date headers, in addition to the custom headers and the resource path.
A:
Content-MD5 header is optional for PUT requests. Try leaving this out for a test.
Also, required headers are Authorization, Date and Host. It seems that your request is missing Host header.
| How can store a file on Google Storage from URL on Google App Engine? | I want to create a service on Google App Engine (Python) that will receive a URL of an image and store it on Google Storage. I managed to upload from a local file using boto or gsutil command line, but not by retrieving the file via URL. I tried doing it using the HTTP requests (PUT) and I'm getting error responses for wrong signatures. Obviously I'm doing something wrong, but unfortunately I have no idea where.
So my question is: How can I retrieve a file from a URL and store it on Google Storage using Python for Google App Angine?
Here is what I've done (using another answer):
class ImportPhoto(webapp.RequestHandler):
def get(self):
self.response.headers['Content-Type'] = 'text/plain'
srow = self.response.out.write
url = self.request.get('url')
srow('URL: %s\n' % (url))
image_response = urlfetch.fetch(url)
m = md5.md5()
m.update(image_response.content)
hash = m.hexdigest()
time = "%s" % datetime.utcnow().strftime("%a, %d %b %Y %H:%M:%S GMT")
str_to_sig = "PUT\n" + hash + "\n\n" +
time + "\nx-goog-acl:public-read\n/lipis/8418.png"
sig = base64.b64encode(hmac.new(
config_credentials.GS_SECRET_ACCESS_KEY,
str_to_sig, hashlib.sha1).digest())
total = len(image_response.content)
srow('Size: %d bytes\n' % (total))
header = {"Date": time,
"x-goog-acl": "public-read",
"Content-MD5": hash,
'Content-Length': total,
'Authorization': "GOOG1 %s:%s" %
(config_credentials.GS_ACCESS_KEY_ID, sig)}
conn = httplib.HTTPConnection("lipis.commondatastorage.googleapis.com")
conn.set_debuglevel(2)
conn.putrequest('PUT', "/8418.png")
for h in header:
conn.putheader(h, header[h])
conn.endheaders()
conn.send(image_response.content + '\r\n')
res = conn.getresponse()
srow('\n\n%d: %s\n' % (res.status, res.reason))
data = res.read()
srow(data)
conn.close()
And I'm getting as a response:
URL: https://stackoverflow.com/users/flair/8418.png
Size: 9605 bytes
400: Bad Request
<?xml version='1.0' encoding='UTF-8'?><Error><Code>BadDigest</Code><Message>The Content-MD5 you specified did not match what we received.</Message><Details>lipis/hello.jpg</Details></Error>
| [
"Have you read the docs on how to sign requests? The string to sign must include the Content-MD5, Content-Type and Date headers, in addition to the custom headers and the resource path.\n",
"Content-MD5 header is optional for PUT requests. Try leaving this out for a test.\nAlso, required headers are Authorization... | [
1,
1
] | [] | [] | [
"boto",
"google_app_engine",
"google_cloud_storage",
"python"
] | stackoverflow_0004105901_boto_google_app_engine_google_cloud_storage_python.txt |
Q:
HTML Generator, Gallery Generator or Templating?
SMALL VERSION OF THE QUESTION: " I need a lib for python or program (pref. for Linux) that receives a list of urls for images and gives me the hmtl for a table (maybe easy to configure(rows and look))
LONG VERSION OF THE QUESTION:
I have and array with a list of url's for images, and I want to make a table (I don't know if this is the best practice, but I think it's the easiest).
I don't care if the thumbs are the same file as the big one (just forced to be small). And I don't need to copy the images to anywhere.
I use the following code( d= ["http://.....jpg","http://.....jpg","http://.....jpg","http://.....jpg"]):
def stupidtable(d):
d = list(set(d))
antes=' <tr> <td><a href="'
dp11='"><img src="'
dp12= '" width="100%" /></a></td> <td><a href="'
dp21= '"><img src="'
dp22='" width="100%" /></a></td>'
bb=['<table border="0"> ']
ii=len( d)
i=0
while i<ii-1:
bb.append(antes)
bb.append(d[i])
bb.append(dp11)
bb.append(d[i])
bb.append(dp12)
bb.append(d[i+1])
bb.append(dp21)
bb.append(d[i+1])
bb.append(dp22)
i=i+2
return bb
(I know the code is shady and it skips the last one if it's an odd number... but it's caffeine fueled code and I just needed to get it done... nothing I'm proud of:)
I know there must be a better way(and prettier.. 'cus this looks really ugly), and a way that I can specify the number of columns, and other options.
I couldn't find a gallery generator for my case (all I tested copied the files to new directory).
Should I learn a templating lang? Is it worth it?
Or Should I use an HTML Generator?
Or should I look into better coding HTML?
What Would you do if you had my problem?
This is the solution I came up with (after adpting the code from kind Mr MatToufoutu):
from jinja2 import Template
my_template = Template("""
<html>
<style type="text/css">
img {border: none;}
</style>
<body>
<table border="0" cellpadding="0" and cellspacing="0">
<tr>
{% for url in urls %}
<td><a href="{{ url }}"><img width="100%" src="{{ url }}"/></td>
{% if loop.index is divisibleby cols %}
</tr><tr>
{% endif %}
{% endfor %}
</tr>
</table>
""")
cols=3
urls =["./a.jpg","./a.jpg","./a.jpg","./a.jpg","./a.jpg","./a.jpg","./a.jpg"]
html = my_template.render(cols=cols,urls=urls)
A:
I think the easiest way to achieve this would be to use a template language like Mako, Cheetah or Jinja. Personally i'd choose Jinja, because it is very similar to the Django template language, but they are all very powerful.
A very simple example of what you want, using Jinja, would look like this:
from jinja2 import Template
my_template = Template("""
<html>
<body>
<table border="0">
<tr>
{% for url in urls %}
<td><a href="{{ url }}">{{ url }}</td>
{% endfor %}
</tr>
</table>
""")
urls = ["http://.....jpg","http://.....jpg","http://.....jpg","http://.....jpg"]
rendered_html = my_template.render(urls=urls)
Which is way more readable than building the html by hand like you did.
A:
Spare a few minutes to learn a template engine like Jinja2. It really pays up, because you can focus on code and leave the layout to webdesigners.
| HTML Generator, Gallery Generator or Templating? | SMALL VERSION OF THE QUESTION: " I need a lib for python or program (pref. for Linux) that receives a list of urls for images and gives me the hmtl for a table (maybe easy to configure(rows and look))
LONG VERSION OF THE QUESTION:
I have and array with a list of url's for images, and I want to make a table (I don't know if this is the best practice, but I think it's the easiest).
I don't care if the thumbs are the same file as the big one (just forced to be small). And I don't need to copy the images to anywhere.
I use the following code( d= ["http://.....jpg","http://.....jpg","http://.....jpg","http://.....jpg"]):
def stupidtable(d):
d = list(set(d))
antes=' <tr> <td><a href="'
dp11='"><img src="'
dp12= '" width="100%" /></a></td> <td><a href="'
dp21= '"><img src="'
dp22='" width="100%" /></a></td>'
bb=['<table border="0"> ']
ii=len( d)
i=0
while i<ii-1:
bb.append(antes)
bb.append(d[i])
bb.append(dp11)
bb.append(d[i])
bb.append(dp12)
bb.append(d[i+1])
bb.append(dp21)
bb.append(d[i+1])
bb.append(dp22)
i=i+2
return bb
(I know the code is shady and it skips the last one if it's an odd number... but it's caffeine fueled code and I just needed to get it done... nothing I'm proud of:)
I know there must be a better way(and prettier.. 'cus this looks really ugly), and a way that I can specify the number of columns, and other options.
I couldn't find a gallery generator for my case (all I tested copied the files to new directory).
Should I learn a templating lang? Is it worth it?
Or Should I use an HTML Generator?
Or should I look into better coding HTML?
What Would you do if you had my problem?
This is the solution I came up with (after adpting the code from kind Mr MatToufoutu):
from jinja2 import Template
my_template = Template("""
<html>
<style type="text/css">
img {border: none;}
</style>
<body>
<table border="0" cellpadding="0" and cellspacing="0">
<tr>
{% for url in urls %}
<td><a href="{{ url }}"><img width="100%" src="{{ url }}"/></td>
{% if loop.index is divisibleby cols %}
</tr><tr>
{% endif %}
{% endfor %}
</tr>
</table>
""")
cols=3
urls =["./a.jpg","./a.jpg","./a.jpg","./a.jpg","./a.jpg","./a.jpg","./a.jpg"]
html = my_template.render(cols=cols,urls=urls)
| [
"I think the easiest way to achieve this would be to use a template language like Mako, Cheetah or Jinja. Personally i'd choose Jinja, because it is very similar to the Django template language, but they are all very powerful.\nA very simple example of what you want, using Jinja, would look like this:\nfrom jinja2 ... | [
4,
0
] | [] | [] | [
"html",
"python",
"templating_engine"
] | stackoverflow_0004106367_html_python_templating_engine.txt |
Q:
In Google App Engine, how do you select entities where an attribute does not exist?
Using the python version of GAE and extending models from db.Model, how do you fetch entities where an attribute equals None or does not exist?
#This works
#Fetch 10 entities where duration == 0.0
entities = MyModel.all().filter('duration = ', 0.0).fetch(10)
#This doesn't. How can I do the equivalent?
#Fetch 10 entities where duration == None
entities = MyModel.all().filter('duration = ', None).fetch(10)
A:
You have entities without duration property (can't be filtered because index can't refer to them) and entities with duration set to None (can be filtered).
Since you have changed MyModel schema, you should fix the entities stored without duration property with something like this:
entities = MyModel.all()
for entity in entities :
if not entity.duration :
entity.duration = None
entity.put()
Have a look to appengine-mapreduce library to accomplish this long running task.
A:
I think the usual way to do this is to add a boolean flag field to your model and filter on that. In your case, that would be something like
class MyModel(db.Model):
duration = db.FloatProperty()
has_duration = db.BooleanProperty(default=False)
# ... etc ...
where you could then do your second query with
entities = MyModel.all().filter('has_duration = ', False).fetch(10)
You'll have to take care to update the has_duration field when creating/editing your entities, though.
| In Google App Engine, how do you select entities where an attribute does not exist? | Using the python version of GAE and extending models from db.Model, how do you fetch entities where an attribute equals None or does not exist?
#This works
#Fetch 10 entities where duration == 0.0
entities = MyModel.all().filter('duration = ', 0.0).fetch(10)
#This doesn't. How can I do the equivalent?
#Fetch 10 entities where duration == None
entities = MyModel.all().filter('duration = ', None).fetch(10)
| [
"You have entities without duration property (can't be filtered because index can't refer to them) and entities with duration set to None (can be filtered).\nSince you have changed MyModel schema, you should fix the entities stored without duration property with something like this:\nentities = MyModel.all()\nfor e... | [
3,
0
] | [] | [] | [
"google_app_engine",
"python"
] | stackoverflow_0004106500_google_app_engine_python.txt |
Q:
passing boolean condition as parameter
I have these
def MsgBox1_YesChosen(sender,e):
if e.Key != "A": function0()
else:
function1()
function2()
function3()
def MsgBox1_NoChosen(sender,e):
if e.Key == "A": function0()
else:
function1()
function2()
function3()
can both def be merged together? The only difference between them is "==" , "!="
A:
Yes, in a very generalized fashion - you just need to wrap your head around the facts that (1) functions are first-class values and (2) operators are just functions with special syntactic treatment. For example:
def make_handler(predicate)
def handler(sender, e):
if predicate(e.Key, 'A'):
function0()
else:
function1()
function2()
function3()
return handler
Use like (after importing operator - you can do this with a lambda, but for operators the operator module is the cleaner solution) MsgBox1_YesChosen = make_handler(operator.ne) (that's a horrible name btw).
A:
def MsgBox1_WhatIsChosen(sender, e, yesOrNo):
if (e.Key != 'A') == yesOrNo:
function0()
else:
function1()
function2()
function3()
def MsgBox1_YesChosen(sender,e):
return MsgBox1_WhatIsChosen(sender, e, True)
def MsgBox1_NoChosen(sender,e):
return MsgBox1_WhatIsChosen(sender, e, False)
A:
Pass the comparisson operator as a parameter.
You can pass not only an operator, but any other functions - -but both "equal" and "not equal" , as well as all other comparisson or arithmetic operators are already defined as proper functions in the "operator" module - your code could become:
import operator
def MsgBox1_Action(sender,e, comparisson):
if comparisson(e.Key, "A"): function0()
else:
function1()
function2()
function3()
MsgBox1_YesChosen = lambda sender, e: MsgBox1_Action(sender, e, operator.eq)
MsgBox1_NoChosen = lambda sender, e: MsgBox1_Action(sender, e, operator.ne)
A:
I'm assuming this is some event based code, in which case you can't directly modify the number of parameters the event takes. However, you still have two possibilities:
1) You might be able to inspect the e parameter to find what type of event occured (yes or no button click). Check the documentation for whatever library you're using.
2) You can add the third parameter, then use lambdas to provide the third argument when you bind the events (example code assumes Tkinter):
def MsgBox1_Chosen(sender, e, yes_chosen):
if (e.Key != "A") == yes_chosen: function0()
else:
function1()
function2()
function3()
msg_box.bind('<Event-Yes>', lambda s,e: MsgBox1_Chosen(s,e,True))
msg_box.bind('<Event-No>', lambda s,e: MsgBox1_Chosen(s,e,False))
| passing boolean condition as parameter | I have these
def MsgBox1_YesChosen(sender,e):
if e.Key != "A": function0()
else:
function1()
function2()
function3()
def MsgBox1_NoChosen(sender,e):
if e.Key == "A": function0()
else:
function1()
function2()
function3()
can both def be merged together? The only difference between them is "==" , "!="
| [
"Yes, in a very generalized fashion - you just need to wrap your head around the facts that (1) functions are first-class values and (2) operators are just functions with special syntactic treatment. For example:\ndef make_handler(predicate)\n def handler(sender, e):\n if predicate(e.Key, 'A'):\n ... | [
4,
1,
1,
0
] | [] | [] | [
"python"
] | stackoverflow_0004106723_python.txt |
Q:
startswith on a constant in sqlalchemy
I'm trying to do something like this:
Session.query(some_table).filter("/some/path/to/element".startswith(some_table.path)).all()
That is, get all "parent" elements of a certain path. I tried doing it like this:
Session.query(some_table).filter(sqlalchemy.sql.expression.literal("/some/path/to/element").startswith(some_table.path)).all()
But I get some weird exceptions with it. I wonder if what I want is actually even possible.
A:
i don't understand what you are try to do, because it not that filter just get a boolean filter should get an expression that will loop over it to filter data.
look at this example (i don't think you want this one but maybe it can give you some Hint):
Session.query(some_table).filter(some_table.path.like('%/some/path/to/element'))
or this example because if i understand well you want to get all parent path of a given path:
import os
a = '/some/path/to/element'
parent_path = []
# Get all parent path
while a != '/':
a = os.path.split(a)[0]
parent_path.append(a)
Session.query(some_table).filter(some_table.path.in_(parent_path))
Hope this will help
A:
Actually the second example that I gave works, I just made a silly mistake in the column name. I'm sorry for wasting your time.
| startswith on a constant in sqlalchemy | I'm trying to do something like this:
Session.query(some_table).filter("/some/path/to/element".startswith(some_table.path)).all()
That is, get all "parent" elements of a certain path. I tried doing it like this:
Session.query(some_table).filter(sqlalchemy.sql.expression.literal("/some/path/to/element").startswith(some_table.path)).all()
But I get some weird exceptions with it. I wonder if what I want is actually even possible.
| [
"i don't understand what you are try to do, because it not that filter just get a boolean filter should get an expression that will loop over it to filter data.\nlook at this example (i don't think you want this one but maybe it can give you some Hint):\nSession.query(some_table).filter(some_table.path.like('%/some... | [
0,
0
] | [] | [] | [
"python",
"sql",
"sqlalchemy",
"startswith"
] | stackoverflow_0004106499_python_sql_sqlalchemy_startswith.txt |
Q:
Collecting, storing, and retrieving large amounts of numeric data
I am about to start collecting large amounts of numeric data in real-time (for those interested, the bid/ask/last or 'tape' for various stocks and futures). The data will later be retrieved for analysis and simulation. That's not hard at all, but I would like to do it efficiently and that brings up a lot of questions. I don't need the best solution (and there are probably many 'bests' depending on the metric, anyway). I would just like a solution that a computer scientist would approve of. (Or not laugh at?)
(1) Optimize for disk space, I/O speed, or memory?
For simulation, the overall speed is important. We want the I/O (really, I) speed of the data just faster than the computational engine, so we are not I/O limited.
(2) Store text, or something else (binary numeric)?
(3) Given a set of choices from (1)-(2), are there any standout language/library combinations to do the job-- Java, Python, C++, or something else?
I would classify this code as "write and forget", so more points for efficiency over clarity/compactness of code. I would very, very much like to stick with Python for the simulation code (because the sims do change a lot and need to be clear). So bonus points for good Pythonic solutions.
Edit: this is for a Linux system (Ubuntu)
Thanks
A:
Optimizing for disk space and IO speed is the same thing - these days, CPUs are so fast compared to IO that it's often overall faster to compress data before storing it (you may actually want to do that). I don't really see memory playing a big role (though you should probably use a reasonably-sized buffer to ensure you're doing sequential writes).
Binary is more compact (and thus faster). Given the amount of data, I doubt whether being human-readable has any value. The only advantage of a text format would be that it's easier to figure out and correct if it gets corrupted or you lose the parsing code.
A:
Fame is an often-used commercial solution for time-series storage.
If you are serious about this, building your own will be a big job. HDF might be useful, they claim that it is suitable for tick data handling, and have C++ access. There is Python support here.
Useful real-life experience from somebody with the same problem here, including HDF5 refs.
A:
Actually, this is quite similar to what I'm doing, which is monitoring changes players make to the world in a game. I'm currently using an sqlite database with python.
At the start of the program, I load the disk database into memory, for fast writing procedures. Each change is put in to two lists. These lists are for both the memory database and the disk database. Every x or so updates, the memory database is updated, and a counter is pushed up one. This is repeated, and when the counter equals 5, it's reset and the list with changes for the disk is flushed to the disk database and the list is cleared.I have found this works well if I also set the writing more to WOL(Write Ahead Logging). This method can stand about 100-300 updates a second if I update memory every 100 updates and the disk counter is set to update every 5 memory updates. You should probobly choose binary, sense, unless you have faults in your data sources, would be most logical
A:
Using D-Bus format to send the information may be to your advantage. The format is standard, binary, and D-Bus is implemented in multiple languages, and can be used to send both over the network and inter-process on the same machine.
A:
If you are just storing, then use system tools. Don't write your own. If you need to do some real-time processing of the data before it is stored, then that's something completely different.
A:
It just occurred to me after reading this thread on storing integers efficiently given certain conditions that we are wasting a lot of bits when we store tick data as doubles or floats or whatever. THE PRICES ARE QUANTIZED! And quite severely, at that. For example, yesterday's NQ range was from about 2175-2191, or about 26 points, quantized by 0.25. So that limits the ticks to ~100 different prices. See where I'm going with this? You only need one byte for each price. Stocks are quantized by 0.01 so you'd need ~ 1 byte for each dollar in the daily range.
So the method I'm outlining is:
(1) store high price, low price, and increment as one line header
(2) store tick data after that as two bytes, with the two left-most bits used to encode the tick type (00 = last, 01 = bid, 11 = ask)
I think this is something a CS would approve of!
| Collecting, storing, and retrieving large amounts of numeric data | I am about to start collecting large amounts of numeric data in real-time (for those interested, the bid/ask/last or 'tape' for various stocks and futures). The data will later be retrieved for analysis and simulation. That's not hard at all, but I would like to do it efficiently and that brings up a lot of questions. I don't need the best solution (and there are probably many 'bests' depending on the metric, anyway). I would just like a solution that a computer scientist would approve of. (Or not laugh at?)
(1) Optimize for disk space, I/O speed, or memory?
For simulation, the overall speed is important. We want the I/O (really, I) speed of the data just faster than the computational engine, so we are not I/O limited.
(2) Store text, or something else (binary numeric)?
(3) Given a set of choices from (1)-(2), are there any standout language/library combinations to do the job-- Java, Python, C++, or something else?
I would classify this code as "write and forget", so more points for efficiency over clarity/compactness of code. I would very, very much like to stick with Python for the simulation code (because the sims do change a lot and need to be clear). So bonus points for good Pythonic solutions.
Edit: this is for a Linux system (Ubuntu)
Thanks
| [
"\nOptimizing for disk space and IO speed is the same thing - these days, CPUs are so fast compared to IO that it's often overall faster to compress data before storing it (you may actually want to do that). I don't really see memory playing a big role (though you should probably use a reasonably-sized buffer to en... | [
3,
1,
1,
1,
0,
0
] | [] | [] | [
"c++",
"java",
"python",
"simulation",
"storage"
] | stackoverflow_0004098509_c++_java_python_simulation_storage.txt |
Q:
Dictionary acting weird, and how to pack into binary
I have the code
from struct import pack
self.data = {'SYNC' : 0x16, 'SOH' : 0x01,
'FnCode' : 0x55, 'pacingState' : 0,
'pacingMode' : 6, 'hysteresis' : 0,
'hysteresisInterval' : 300, 'lowrateInterval' : 1000,
'vPaceAmp' : 3500, 'vPaceWidth' : 4,
'VRP' : 320, 'spare' : '\x00\x00\x00\x00\x00'}
print(self.data.keys())
print(self.data.values())
pack('BBBBBBHHHHH5s', self.data.values())
I get the output,
dict_keys(['pacingState', 'SYNC', 'hysteresis', 'FnCode', 'spare', 'lowrateInterval', 'vPaceWidth', 'VRP', 'SOH', 'pacingMode', 'hysteresisInterval', 'vPaceAmp'])
dict_values([0, 22, 0, 85, '\x00\x00\x00\x00\x00', 1000, 4, 320, 1, 6, 300, 3500])
Why arent values in the order that I wrote them in in the dictionary (and how can I get them in order)?
Also when i try to do the pack function, i says that pack needs 12 arguments, and data.values has 12 values so Im not sure why its giving me an error.
I tried making a dict with a reference to an array that contained the values(so I could pass the array in since it's in the right order), but changing the dictionary values didnt affect the actual value array it was referencing so that idea is out...
Thanks in advance.
A:
Dictionaries do not maintain insertion order of keys, as they are hash tables and do not keep track of key insertion order. If you need an ordered dictionary, Python 2.7 and 3.1 has collections.OrderedDict. If you are using an older Python version, check out this ActiveState recipe.
As to why your pack is complaining - you are not actually passing it 12 arguments (as long as your format string is), you are passing it a single argument which is a list.
edit delnan's post shows you how to unpack your values.
A:
Dictionaries are unordered. Well, they don't suddenly re-order when they feel like it, but they don't preserve order of insertion or are sorted or anything. Always treat them as if order was random. You can use collections.OrderedDict (or if you use an old version that doesn't have them in the standard library, there are various implementations all over the internet). Or maybe you can just use a list of the values (assuming you don't need the keys and only use them for documentation), which is ordered.
Concerining pack needing 12 arguments: You only give it one argument, data.values(). That's one argument, even though it happen to be a collection of 12 objects. Use pack(... ,*data.values()) to unpack the sequence of length 12 into 12 seperate arguments.
| Dictionary acting weird, and how to pack into binary | I have the code
from struct import pack
self.data = {'SYNC' : 0x16, 'SOH' : 0x01,
'FnCode' : 0x55, 'pacingState' : 0,
'pacingMode' : 6, 'hysteresis' : 0,
'hysteresisInterval' : 300, 'lowrateInterval' : 1000,
'vPaceAmp' : 3500, 'vPaceWidth' : 4,
'VRP' : 320, 'spare' : '\x00\x00\x00\x00\x00'}
print(self.data.keys())
print(self.data.values())
pack('BBBBBBHHHHH5s', self.data.values())
I get the output,
dict_keys(['pacingState', 'SYNC', 'hysteresis', 'FnCode', 'spare', 'lowrateInterval', 'vPaceWidth', 'VRP', 'SOH', 'pacingMode', 'hysteresisInterval', 'vPaceAmp'])
dict_values([0, 22, 0, 85, '\x00\x00\x00\x00\x00', 1000, 4, 320, 1, 6, 300, 3500])
Why arent values in the order that I wrote them in in the dictionary (and how can I get them in order)?
Also when i try to do the pack function, i says that pack needs 12 arguments, and data.values has 12 values so Im not sure why its giving me an error.
I tried making a dict with a reference to an array that contained the values(so I could pass the array in since it's in the right order), but changing the dictionary values didnt affect the actual value array it was referencing so that idea is out...
Thanks in advance.
| [
"Dictionaries do not maintain insertion order of keys, as they are hash tables and do not keep track of key insertion order. If you need an ordered dictionary, Python 2.7 and 3.1 has collections.OrderedDict. If you are using an older Python version, check out this ActiveState recipe.\nAs to why your pack is complai... | [
3,
3
] | [] | [] | [
"python",
"struct"
] | stackoverflow_0004107008_python_struct.txt |
Q:
Django Annotations For Group By Through Another Model
I'm having a hard time trying to figure out how to use annotations in the Django ORM to achieve grouping through a model.
from django.db import models
class Customer(models.Model):
name = models.CharField(max_length=255)
class Store(models.Model):
name = models.CharField(max_length=255)
class Order(models.Model):
customer = models.ForeignKey(Customer)
store = models.ForeignKey(Store)
order_date = models.DateTimeField()
If my Stores are Los Angeles, Denver, Houston & Atlanta, how do I get a count of
Customers by store using the latest order date?
Los Angeles: 25
Denver: 210
Houston: 400
Atlanta: 6
A:
Define a ManyToMany field on either Customer or Store, pointing to the other model, with Order as the through table. For example:
class Store(models.Model):
name = models.CharField(max_length=255)
orders = models.ManyToManyField(Customer, through=Order)
Now you can do:
from django.db.models import Count
Store.objects.annotate(Count("orders__customer"))
| Django Annotations For Group By Through Another Model | I'm having a hard time trying to figure out how to use annotations in the Django ORM to achieve grouping through a model.
from django.db import models
class Customer(models.Model):
name = models.CharField(max_length=255)
class Store(models.Model):
name = models.CharField(max_length=255)
class Order(models.Model):
customer = models.ForeignKey(Customer)
store = models.ForeignKey(Store)
order_date = models.DateTimeField()
If my Stores are Los Angeles, Denver, Houston & Atlanta, how do I get a count of
Customers by store using the latest order date?
Los Angeles: 25
Denver: 210
Houston: 400
Atlanta: 6
| [
"Define a ManyToMany field on either Customer or Store, pointing to the other model, with Order as the through table. For example:\nclass Store(models.Model):\n name = models.CharField(max_length=255)\n orders = models.ManyToManyField(Customer, through=Order)\n\nNow you can do:\nfrom django.db.models import C... | [
0
] | [] | [] | [
"annotations",
"django",
"group_by",
"orm",
"python"
] | stackoverflow_0004107070_annotations_django_group_by_orm_python.txt |
Q:
Amend a csv file in Python
So I have a CSV file with a bunch on IP's in it:
192.168.0.1,192.168.0.2,192.168.0.3,192.168.0.4,192.168.0.5,192.168.0.6,192.168.0.7,192.168.0.8,192.168.0.9,192.168.0.10
And I would like to add a new ip to the end of this csv file. Currently I am using this code to read in the data:
requests = csv.reader(open("file.csv", "rb"))
for request in requests:
for ip in request:
print "In List: " + str(ip)
This will print:
In List: 192.168.0.1
In List: 192.168.0.2
In List: 192.168.0.3
In List: 192.168.0.4
In List: 192.168.0.5
...
And then to write one to the end I've tried many methods, including this:
requestWriter = csv.writer(open("file.csv", "w"))
requestWriter.writerow(["192.168.0.X"])
This however replaces the whole file with the new entry. I then tried to loop through existing records and add them to the new file but this split the IP's up by their .'s! Am I missing something here? Surely there is an amend option for the csv reader/writer?
Thanks
A:
Why don't you just append a new row?
fd = open('file.csv','a')
fd.write(yourCsvRowWithNewIP)
fd.close()
| Amend a csv file in Python | So I have a CSV file with a bunch on IP's in it:
192.168.0.1,192.168.0.2,192.168.0.3,192.168.0.4,192.168.0.5,192.168.0.6,192.168.0.7,192.168.0.8,192.168.0.9,192.168.0.10
And I would like to add a new ip to the end of this csv file. Currently I am using this code to read in the data:
requests = csv.reader(open("file.csv", "rb"))
for request in requests:
for ip in request:
print "In List: " + str(ip)
This will print:
In List: 192.168.0.1
In List: 192.168.0.2
In List: 192.168.0.3
In List: 192.168.0.4
In List: 192.168.0.5
...
And then to write one to the end I've tried many methods, including this:
requestWriter = csv.writer(open("file.csv", "w"))
requestWriter.writerow(["192.168.0.X"])
This however replaces the whole file with the new entry. I then tried to loop through existing records and add them to the new file but this split the IP's up by their .'s! Am I missing something here? Surely there is an amend option for the csv reader/writer?
Thanks
| [
"Why don't you just append a new row?\nfd = open('file.csv','a')\nfd.write(yourCsvRowWithNewIP)\nfd.close()\n\n"
] | [
9
] | [] | [] | [
"csv",
"python"
] | stackoverflow_0004107096_csv_python.txt |
Q:
Logging strategy for GUI program
I'm thinking it may be beneficial to sprinkle some debug logging throughout my app (a painting-type program), and to have this info written to a file. My current debugging strategy is to hook up a custom exception listener (sys.excepthook) and to allow the user to e-mail me a copy of the stack trace that caused the crash.
This has been pretty handy at seeing what the user's done to cause the program to crash, but I feel that a log file could certainly help.
I'm wondering what the best way to do this is. I'm thinking of enabling logging via a command-line switch and to create a log per "run" of the program, and to e-mail myself a copy of the log when a crash occurs. However, the log's won't help if the app's not in debug mode!
I'm a little worried of the log filling up too fast - if I place logging inside some mouse motion event handlers, then it'll create many entries. Also, a log file may grow pretty large, and just be filled with irrelevant information to me when examining a bug report.
How do you guys deal with this? I'm interested in the frequency of logging - since my app responds to many events (e.g. mouse movement; depending on user input) I don't want to create excess logging.
A:
As said before you can use the logger module. You can set a default level of logging (for example Warning) and put all kind of messages in you code, since debug until critical. As humble explanation, if you set your logging level as Warning, even if your code log debug messages they will not appear in the file (or stdout). That's because the logging module will log only messages with priority higher or equal to Warning (Warning, Error and critical).
As a simple explanation look at this code:
import logging
import logging.handlers as handlers
logger = logging.getLogger('myapp')
hdlr = logging.FileHandler('/tmp/myapp.log')
formatter = logging.Formatter('%(asctime)s %(levelname)s: %(message)s')
hdlr.setFormatter(formatter)
logger.addHandler(hdlr)
logger.setLevel(logging.WARNING)
logger.debug('debug!')
logger.info('info!')
logger.warning('warning!')
logger.error('error!')
logger.critical('critical!')
It creates a file called myapp.log:
magun@~: cat /tmp/myapp.log
2010-11-05 12:27:25,359 WARNING: warning!
2010-11-05 12:27:25,362 ERROR: error!
2010-11-05 12:27:26,071 CRITICAL: critical!
magun@~:
If you're worried about the file size you can use a rotating log, witch will discard the oldest logs based in your criteria:
import logging
import logging.handlers as handlers
logger = logging.getLogger('myapp')
hdlr = handlers.RotatingFileHandler('/tmp/log/myapp.log', maxBytes=100, backupCount=5)
formatter = logging.Formatter('%(asctime)s %(levelname)s: %(message)s')
hdlr.setFormatter(formatter)
logger.addHandler(hdlr)
logger.setLevel(logging.WARNING)
for i in range(20):
logger.debug('debug%i!'%i)
logger.info('info%i!'%i)
logger.warning('warning%i!'%i)
logger.error('error%i!'%i)
logger.critical('critical%i!'%i)
In this case I used a log file with a max size of 100 bytes (pretty small, you should raise it) and a backup count of 5. This means when a log reaches 100bytes it will be "rotated": a new (and empty) myapp.log will created and the old one will become myapp.log.1. In the next rotation myapp.log.1 will become myapp.log.2, the myapp.log will be come the new myapp.log.1. It will repeat until we have myapp.log, myapp.log.1, myapp.log.2, ... myapp.log.n (in this example the limit will be myapp.log.5). When we hit this the, and log need to be rotated, the myapp.log.5 file will be discarded. So, the size limit if 5*100bytes.
Take a look of what happened:
magun@~: ls /tmp/log/
myapp.log myapp.log.1 myapp.log.2 myapp.log.3 myapp.log.4 myapp.log.5
magun@~: cat /tmp/log/myapp.log
2010-11-05 12:33:52,369 ERROR: error19!
2010-11-05 12:33:52,376 CRITICAL: critical19!
magun@~: cat /tmp/log/myapp.log.1
2010-11-05 12:33:52,362 CRITICAL: critical18!
2010-11-05 12:33:52,369 WARNING: warning19!
magun@~: cat /tmp/log/myapp.log.2
2010-11-05 12:33:52,355 WARNING: warning18!
2010-11-05 12:33:52,362 ERROR: error18!
magun@~: cat /tmp/log/myapp.log.3
2010-11-05 12:33:52,348 ERROR: error17!
2010-11-05 12:33:52,355 CRITICAL: critical17!
magun@~: cat /tmp/log/myapp.log.4
2010-11-05 12:33:52,340 CRITICAL: critical16!
2010-11-05 12:33:52,348 WARNING: warning17!
magun@~: cat /tmp/log/myapp.log.5
2010-11-05 12:33:52,333 WARNING: warning16!
2010-11-05 12:33:52,340 ERROR: error16!
magun@~:
As you can see we lost many logs (0-15), but the most recent are there, preserving the user free space. Don't forget to read the log from bottom up:)
A:
Use this: http://docs.python.org/library/logging.html#memoryhandler.
| Logging strategy for GUI program | I'm thinking it may be beneficial to sprinkle some debug logging throughout my app (a painting-type program), and to have this info written to a file. My current debugging strategy is to hook up a custom exception listener (sys.excepthook) and to allow the user to e-mail me a copy of the stack trace that caused the crash.
This has been pretty handy at seeing what the user's done to cause the program to crash, but I feel that a log file could certainly help.
I'm wondering what the best way to do this is. I'm thinking of enabling logging via a command-line switch and to create a log per "run" of the program, and to e-mail myself a copy of the log when a crash occurs. However, the log's won't help if the app's not in debug mode!
I'm a little worried of the log filling up too fast - if I place logging inside some mouse motion event handlers, then it'll create many entries. Also, a log file may grow pretty large, and just be filled with irrelevant information to me when examining a bug report.
How do you guys deal with this? I'm interested in the frequency of logging - since my app responds to many events (e.g. mouse movement; depending on user input) I don't want to create excess logging.
| [
"As said before you can use the logger module. You can set a default level of logging (for example Warning) and put all kind of messages in you code, since debug until critical. As humble explanation, if you set your logging level as Warning, even if your code log debug messages they will not appear in the file (or... | [
6,
0
] | [] | [] | [
"logging",
"python",
"user_interface"
] | stackoverflow_0004004353_logging_python_user_interface.txt |
Q:
Python: Write 1,000,000 ints to file
What is the most compact way to write 1,000,000 ints (0, 1, 2...) to file using Python without zipping etc? My answer is: 1,000,000 * 3 bytes using struct module, but it seems like interviewer expected another answer...
Edit. Numbers from 1 to 1,000,000 in random order (so transform like 5, 6, 7 -> 5-7 can be applied in rare case). You can use any writing method you know, but the resulting file should have minimum size.
A:
Actually, you can do A LOT better than 2.5MB, since not all orderings are possible. One might argue that beating 5% would involve compression, since one is not storing the sequence itself. Basically, you would want to store the canonical sequence number. 8 numbers from 0-7 in random order normally takes 24 bits (log(8^8)/log(2)), but with a canonical sequence number it would take 16 bits (log(8!)/log(2)).
Basically, this involves coming up with an algorithm which can translate any sequence of integers into a giant number. Example of a possible numbering for 8 number sequence would be ordering by value:
01234567 : 0
01234576 : 1
01234657 : 2
01234675 : 3
01234756 : 4
01234765 : 5
...
The cost of this strategy is log(1000000!)/log(2) (i.e., log_2(1000000!)).
The standard solution usually costs about log(1000000^1000000)/log(2) .
You can also squeeze a tiny bit more space by treating 0000 0000 1111 1111 and 1111 1111 differently, but the amount of space saved by doing so is incredibly tiny.
Edit: A quick and dirty calculation indicates this optimization brings the size down to about 2.204MiB.
Due to the pigeonhole principle, I do not believe it is possible to do better than this strategy, regardless of whether you use compression or some other technique.
A:
Well, your solution takes three bytes (= 24 bits) per integer. Theoretically, 20 bits are enough (since 2^19 < 1.000.000 < 2^20).
EDIT: Oops, just noticed Neil’s comment stating the same. I’m making this answer CW since it really belongs to him.
A:
Assuming you do have to remember their order and that the numbers are in the range of 1 to 1,000,000, it would only take 20 bits or 2½ bytes to write each one since 1,000,000 is 0xF4240 in hexadecimal. You'd have to pack them together to not waste any space with this approach, but by doing so it would only take 2.5 * 1,000,000 bytes.
A:
the question is clearly incomplete. here is my very compact attempt:
f = open('numbers.dat', 'w')
f.write('list(range(1,1000000))')
f.close()
loading the file:
f = open('numbers.dat', 'r')
numbers = eval(f.read().strip())
f.close()
that should do it.
in fact, i don't see why 'python' is important here. if the interviewer is concerned about the size of the resulting file, the solution may be written in any language. the question does not specify if the interviewer wants compact output or compact code...
A:
I would only write the start and end of the given range, in this case 1 and 1,000,000, because nowhere has the interviewer mentioned order is important.
A:
What is the most compact way to write 1,000,000 ints (0, 1, 2...) to file using Python without zipping etc
If you interpret the 1,000,000 ints as "I didn't specify that they have to be different", you can just use a for loop to write 0 one million times.
A:
Maybe they meant something like this
pythonic-way-to-convert-a-list-of-integers-into-a-string-of-comma-separated-range but then you said that consecutive sequences are rare, so perhaps not
| Python: Write 1,000,000 ints to file | What is the most compact way to write 1,000,000 ints (0, 1, 2...) to file using Python without zipping etc? My answer is: 1,000,000 * 3 bytes using struct module, but it seems like interviewer expected another answer...
Edit. Numbers from 1 to 1,000,000 in random order (so transform like 5, 6, 7 -> 5-7 can be applied in rare case). You can use any writing method you know, but the resulting file should have minimum size.
| [
"Actually, you can do A LOT better than 2.5MB, since not all orderings are possible. One might argue that beating 5% would involve compression, since one is not storing the sequence itself. Basically, you would want to store the canonical sequence number. 8 numbers from 0-7 in random order normally takes 24 bits... | [
4,
2,
2,
1,
0,
0,
0
] | [] | [] | [
"python"
] | stackoverflow_0004104898_python.txt |
Q:
Python - Iteration Testing a SOAP service; need to use different variables per iteration
Ok here's my scenario (be kind, only been using Python for a short while):
I have a service I'm calling and need to run several iterations of the same test with a different variable passed to the method. I am able to run iterations against a single method just fine but I need the variable to change per each test and without counting the call to get a random variable as an iteration. I'm probably going about this the wrong way but I'd love any help I can get.
Here's my code thus far:
data = ""
class MyTestWorkFlow:
global data
def Data(self):
low = 1
high = 1000
pid = random.randrange(low,high)
data = linecache.getline('c:/tmp/testData.csv', pid)
def Run(self):
client = Client(wsdl)
result = client.service.LookupData(data)
f = open('/tmp/content','w')
f.write (str(result))
f.close()
f = open('/tmp/content','r')
for i in f:
print i
f.close()
test = MyTestWorkFlow()
for i in range(1,2):
test.Run()
A:
There's a lot we could talk about regarding automated testing in Python, but the problem here is that you don't seem to be invoking your Data method.
If you change your code like this:
def Run(self)
self.Data()
client = Client(wsdl)
...
does it do what you need?
| Python - Iteration Testing a SOAP service; need to use different variables per iteration | Ok here's my scenario (be kind, only been using Python for a short while):
I have a service I'm calling and need to run several iterations of the same test with a different variable passed to the method. I am able to run iterations against a single method just fine but I need the variable to change per each test and without counting the call to get a random variable as an iteration. I'm probably going about this the wrong way but I'd love any help I can get.
Here's my code thus far:
data = ""
class MyTestWorkFlow:
global data
def Data(self):
low = 1
high = 1000
pid = random.randrange(low,high)
data = linecache.getline('c:/tmp/testData.csv', pid)
def Run(self):
client = Client(wsdl)
result = client.service.LookupData(data)
f = open('/tmp/content','w')
f.write (str(result))
f.close()
f = open('/tmp/content','r')
for i in f:
print i
f.close()
test = MyTestWorkFlow()
for i in range(1,2):
test.Run()
| [
"There's a lot we could talk about regarding automated testing in Python, but the problem here is that you don't seem to be invoking your Data method.\nIf you change your code like this:\ndef Run(self)\n self.Data()\n client = Client(wsdl)\n ...\n\ndoes it do what you need?\n"
] | [
1
] | [] | [] | [
"automated_tests",
"iteration",
"python",
"testing"
] | stackoverflow_0004107132_automated_tests_iteration_python_testing.txt |
Q:
Wx.Widgets AUIMananger Toggle Panes
I'm having trouble toggling panes with the AUIManager.
Here's basically what I'm doing:
class foo(wx.Frame):
def __init__(self, parent, title):
wx.Frame.__init__(self,parent,wx.ID_ANY,title,size=wx.Size(800,600))
self.menubar = wx.MenuBar()
self._mgr = wx.aui.AuiManager(self)
self._mgr.AddPane(self.randomwidget, wx.LEFT, 'Widget Name')
self._mgr.Update()
self.menu_view = wx.Menu()
self.menu_view_randomwidget = wx.MenuItem(self.menu_view,wx.ID_ANY, 'Widget Name', kind=wx.ITEM_CHECK)
self.menu_view.AppendItem(self.menu_view_randomwidget)
self.Bind(wx.EVT_MENU, self.togglePane, id=self.menu_view_randomwidget.GetId())
self.menubar.Append(self.menu_view, '&View')
def togglePane(self,event):
if self._mgr.GetPane('Widget Name').IsShown():
self._mgr.GetPane('Widget Name').Hide()
else:
self._mgr.GetPane('Widget Name).Show()
print self._mgr.GetPane('Widget Name').IsOk()
This always results in a 'False' output. Is there a more appropriate way to toggle various aui panes?
A:
This method works fine for me. It should for you too if you call Update() on your window manager after you show or hide your pane.
def togglePane(self,event):
if self._mgr.GetPane('Widget Name').IsShown():
self._mgr.GetPane('Widget Name').Hide()
else:
self._mgr.GetPane('Widget Name).Show()
print self._mgr.GetPane('Widget Name').IsOk()
self._mgr.Update()#<--------------It should work if you add this line
| Wx.Widgets AUIMananger Toggle Panes | I'm having trouble toggling panes with the AUIManager.
Here's basically what I'm doing:
class foo(wx.Frame):
def __init__(self, parent, title):
wx.Frame.__init__(self,parent,wx.ID_ANY,title,size=wx.Size(800,600))
self.menubar = wx.MenuBar()
self._mgr = wx.aui.AuiManager(self)
self._mgr.AddPane(self.randomwidget, wx.LEFT, 'Widget Name')
self._mgr.Update()
self.menu_view = wx.Menu()
self.menu_view_randomwidget = wx.MenuItem(self.menu_view,wx.ID_ANY, 'Widget Name', kind=wx.ITEM_CHECK)
self.menu_view.AppendItem(self.menu_view_randomwidget)
self.Bind(wx.EVT_MENU, self.togglePane, id=self.menu_view_randomwidget.GetId())
self.menubar.Append(self.menu_view, '&View')
def togglePane(self,event):
if self._mgr.GetPane('Widget Name').IsShown():
self._mgr.GetPane('Widget Name').Hide()
else:
self._mgr.GetPane('Widget Name).Show()
print self._mgr.GetPane('Widget Name').IsOk()
This always results in a 'False' output. Is there a more appropriate way to toggle various aui panes?
| [
"This method works fine for me. It should for you too if you call Update() on your window manager after you show or hide your pane.\n def togglePane(self,event):\n if self._mgr.GetPane('Widget Name').IsShown():\n self._mgr.GetPane('Widget Name').Hide()\n else:\n self._mgr.GetPane('Widget Name... | [
1
] | [] | [] | [
"python",
"wxpython"
] | stackoverflow_0001875396_python_wxpython.txt |
Q:
Django Question
Can you take things like the poll app from the tutorial and display them in an iframe or frameset? The tutorial is great and the app is very nice, but, how often do you go to a site with a whole page dedicated to a poll? I was trying to think about how you do it using the urls.py file, but couldn't wrap my head around it. Just wondering if anyone has done this or knows of any tutorials that cover this issue? Thanks.
A:
Placing poll data in an extra iframe won't be necessary. You can write a templatetag, to display it on everywhere you need to.
edit
The chapter "inclusion tags" refers to the poll example app.
See http://docs.djangoproject.com/en/1.2/howto/custom-template-tags/
A:
Put the poll page in its own view, connect to the view via urls.py, and set up your frame or iframe to source from that URL.
| Django Question | Can you take things like the poll app from the tutorial and display them in an iframe or frameset? The tutorial is great and the app is very nice, but, how often do you go to a site with a whole page dedicated to a poll? I was trying to think about how you do it using the urls.py file, but couldn't wrap my head around it. Just wondering if anyone has done this or knows of any tutorials that cover this issue? Thanks.
| [
"Placing poll data in an extra iframe won't be necessary. You can write a templatetag, to display it on everywhere you need to.\nedit\nThe chapter \"inclusion tags\" refers to the poll example app.\nSee http://docs.djangoproject.com/en/1.2/howto/custom-template-tags/\n",
"Put the poll page in its own view, connec... | [
2,
0
] | [] | [] | [
"django",
"python"
] | stackoverflow_0004107644_django_python.txt |
Q:
Understanding objects in Python
I am a little confused by the object model of Python. I have two classes, one inherits from the other.
class Node():
def __init__(identifier):
self.identifier = identifier
class Atom(Node):
def __init__(symbol)
self.symbol = symbol
What I am trying to do is not to override the __init__() method, but to create an instance of atom that will have attributes symbol and identifier.
Like this:
Atom("Fe", 1) # will create an atom with symbol "Fe" and identifier "1"
Thus I want to be able to access Atom.identifier and Atom.symbol once an instance of Atom is created.
How can I do that?
A:
>>> class Node(object):
... def __init__(self, id_):
... self.id_ = id_
...
>>> class Atom(Node):
... def __init__(self, symbol, id_):
... super(Atom, self).__init__(id_)
... self.symbol = symbol
...
>>> a = Atom("FE", 1)
>>> a.symbol
'FE'
>>> a.id_
1
>>> type(a)
<class '__main__.Atom'>
>>>
It's a good idea to inherit from object in your code.
A:
You have to call the __init__-method of the super-class manually.
class Atom(Node):
def __init__(self, symbol, identifier)
Node.__init__(self, identifier)
self.symbol = symbol
A:
When creating a class you need to use the self word in the declaration. After that you can define the other arguments. To inherit call the super init method:
>>> class Node():
... def __init__(self, identifier):
... self.identifier = identifier
...
>>>
>>> class Atom(Node):
... def __init__(self, symbol, identifier):
... Node.__init__(self, identifier)
... self.symbol = symbol
...
>>>
>>>
>>> fe = Atom("Fe", 1)
>>> fe.symbol
'Fe'
>>> fe.identifier
1
>>>
A:
You have two missing things in your code:
methods belonging to a class have to have an explicit self parameter, which you are missing
Your derived 'Atom' class also needs to accept the parameter it needs to use to initialize the base class.
Something more like:
class Node():
def __init__(self, identifier):
self.identifier = identifier
class Atom(Node):
def __init__(self, identifier, symbol)
Node.__init__(self, identifier)
self.symbol = symbol
A:
class Node():
def __init__(self, identifier):
self.identifier = identifier
class Atom(Node):
def __init__(self, symbol, *args, **kwargs)
super(Atom, self).__init__(*args, **kwargs)
self.symbol = symbol
See here for an explanation of the *args and **kwargs. By using super, you can access the base class (superclass) of the Atom class and call it's __init__. Also, the self parameter needs to be included as well.
A:
class Node(object):
def __init__(self, identifier):
self.identifier = identifier
class Atom(Node):
def __init__(self, symbol, *args, **kwargs)
super(Atom, self).__init__(*args, **kwargs)
self.symbol = symbol
Points:
Node should inherit from object.
Use super to call parent classes' __init__ functions.
Class member functions take self as the first parameter in Python.
| Understanding objects in Python | I am a little confused by the object model of Python. I have two classes, one inherits from the other.
class Node():
def __init__(identifier):
self.identifier = identifier
class Atom(Node):
def __init__(symbol)
self.symbol = symbol
What I am trying to do is not to override the __init__() method, but to create an instance of atom that will have attributes symbol and identifier.
Like this:
Atom("Fe", 1) # will create an atom with symbol "Fe" and identifier "1"
Thus I want to be able to access Atom.identifier and Atom.symbol once an instance of Atom is created.
How can I do that?
| [
">>> class Node(object):\n... def __init__(self, id_):\n... self.id_ = id_\n... \n>>> class Atom(Node):\n... def __init__(self, symbol, id_):\n... super(Atom, self).__init__(id_)\n... self.symbol = symbol\n... \n>>> a = Atom(\"FE\", 1)\n>>> a.symbol\n'FE'\n>>> a.id_\n1\n>... | [
7,
6,
3,
2,
1,
1
] | [] | [] | [
"object",
"object_model",
"python"
] | stackoverflow_0004107740_object_object_model_python.txt |
Q:
Access to class attributes of parent classes
I would like to know what is the best way to get all the attributes of a class when I don't know the name of them.
Let's say I have:
#!/usr/bin/python2.4
class A(object):
outerA = "foobar outerA"
def __init__(self):
self.innerA = "foobar innerA"
class B(A):
outerB = "foobar outerB"
def __init__(self):
super(B, self).__init__()
self.innerB = "foobar innerB"
if __name__ == '__main__':
b = B()
Using hasattr/getattr to get the "outerA" class field of my b instance works fine:
>>> print hasattr(b, "outerA")
>>> True
>>> print str(getattr(b, "outerA"))
>>> foobar outerA
Ok, that's good.
But what if I don't exactly know that b has inherited a field called "outerA" but I still want to get it?
To access b's inner fields, I usually use b.__dict__ . To get b.outerB, I can use b.__class__.__dict__ but that still doesn't show "outerA" among it fields:
>>> print "-------"
>>> for key, val in b.__class__.__dict__.iteritems():
... print str(key) + " : " + str(val)
>>> print "-------\n"
Shows:
-------
__module__ : __main__
__doc__ : None
__init__ : <function __init__ at 0xb752aaac>
outerB : foobar outerB
-------
Where's my outerA?? :D
I am sure I can keep "climbing" the class hierarchy and get all the fields, but that doesn't seem like the greatest solution...
As there are hasattr(), getattr()... isn't there something like a listattr() that would give all the available attributes of an instance?
Thank you!
A:
I think you're looking for dir() - it works just as well within code as in the shell.
A:
Try dir(b). The resulting list includes inherited attributes.
| Access to class attributes of parent classes | I would like to know what is the best way to get all the attributes of a class when I don't know the name of them.
Let's say I have:
#!/usr/bin/python2.4
class A(object):
outerA = "foobar outerA"
def __init__(self):
self.innerA = "foobar innerA"
class B(A):
outerB = "foobar outerB"
def __init__(self):
super(B, self).__init__()
self.innerB = "foobar innerB"
if __name__ == '__main__':
b = B()
Using hasattr/getattr to get the "outerA" class field of my b instance works fine:
>>> print hasattr(b, "outerA")
>>> True
>>> print str(getattr(b, "outerA"))
>>> foobar outerA
Ok, that's good.
But what if I don't exactly know that b has inherited a field called "outerA" but I still want to get it?
To access b's inner fields, I usually use b.__dict__ . To get b.outerB, I can use b.__class__.__dict__ but that still doesn't show "outerA" among it fields:
>>> print "-------"
>>> for key, val in b.__class__.__dict__.iteritems():
... print str(key) + " : " + str(val)
>>> print "-------\n"
Shows:
-------
__module__ : __main__
__doc__ : None
__init__ : <function __init__ at 0xb752aaac>
outerB : foobar outerB
-------
Where's my outerA?? :D
I am sure I can keep "climbing" the class hierarchy and get all the fields, but that doesn't seem like the greatest solution...
As there are hasattr(), getattr()... isn't there something like a listattr() that would give all the available attributes of an instance?
Thank you!
| [
"I think you're looking for dir() - it works just as well within code as in the shell.\n",
"Try dir(b). The resulting list includes inherited attributes.\n"
] | [
2,
1
] | [] | [] | [
"attributes",
"inheritance",
"oop",
"python"
] | stackoverflow_0004107996_attributes_inheritance_oop_python.txt |
Q:
Overwrite property using Python
How do you overwrite the getter of the property in Python ?
I've tried to do:
class Vehicule(object):
def _getSpatials(self):
pass
def _setSpatials(self, newSpatials):
pass
spatials = property(_getSpatials, _setSpatials)
class Car(Vehicule)
def _getSpatials(self):
spatials = super(Car, self).spatials()
return spatials
But the getter is calling the method of Vehicule and not of Car.
What should I change ?
A:
It looks like you want Car's spatial property's getter to call Vehicule's
spatial property's getter. You can achieve that with
class Vehicule(object):
def __init__(self):
self._spatials = 1
def _getSpatials(self):
print("Calling Vehicule's spatials getter")
return self._spatials
def _setSpatials(self,value):
print("Calling Vehicule's spatials setter")
self._spatials=value
spatials=property(_getSpatials,_setSpatials)
class Car(Vehicule):
def __init__(self):
super(Car,self).__init__()
def _getSpatials(self):
print("Calling Car's spatials getter")
return super(Car,self).spatials
spatials=property(_getSpatials)
v=Vehicule()
c=Car()
print(c.spatials)
# Calling Car's spatials getter
# Calling Vehicule's spatials getter
# 1
On the other hand, calling Vehicule's setter from within Car's setter is more difficult.
The obvious thing to do does not work:
class Car(Vehicule):
def __init__(self):
super(Car,self).__init__()
def _getSpatials(self):
print("Calling Car's spatials getter")
return super(Car,self).spatials
def _setSpatials(self,value):
print("Calling Car's spatials setter")
super(Car,self).spatials=value
spatials=property(_getSpatials,_setSpatials)
v=Vehicule()
c=Car()
print(c.spatials)
c.spatials = 10
AttributeError: 'super' object has no attribute 'spatials'
Instead, the trick is to call super(Car,self)._setSpatials:
class Car(Vehicule):
def __init__(self):
super(Car,self).__init__()
def _getSpatials(self):
print("Calling Car's spatials getter")
return super(Car,self).spatials
def _setSpatials(self,value):
print("Calling Car's spatials setter")
super(Car,self)._setSpatials(value)
spatials=property(_getSpatials,_setSpatials)
v=Vehicule()
c=Car()
print(c.spatials)
# Calling Car's spatials getter
# Calling Vehicule's spatials getter
# 1
c.spatials = 10
# Calling Car's spatials setter
# Calling Vehicule's spatials setter
print(c.spatials)
# Calling Car's spatials getter
# Calling Vehicule's spatials getter
# 10
A:
This might help: python properties and inheritance
| Overwrite property using Python | How do you overwrite the getter of the property in Python ?
I've tried to do:
class Vehicule(object):
def _getSpatials(self):
pass
def _setSpatials(self, newSpatials):
pass
spatials = property(_getSpatials, _setSpatials)
class Car(Vehicule)
def _getSpatials(self):
spatials = super(Car, self).spatials()
return spatials
But the getter is calling the method of Vehicule and not of Car.
What should I change ?
| [
"It looks like you want Car's spatial property's getter to call Vehicule's\nspatial property's getter. You can achieve that with\nclass Vehicule(object):\n def __init__(self):\n self._spatials = 1\n def _getSpatials(self):\n print(\"Calling Vehicule's spatials getter\")\n return self._spa... | [
3,
2
] | [] | [] | [
"inheritance",
"python"
] | stackoverflow_0004107988_inheritance_python.txt |
Q:
Why are some callable attributes not listed by the dir() function?
How come the dir() function in Python doesn't show all of the callable attributes?
import win32com.client
iTunes = win32com.client.gencache.EnsureDispatch("iTunes.Application")
currentTrack = win32com.client.CastTo(iTunes.CurrentTrack,"IITFileOrCDTrack")
print dir(currentTrack)
Result:
['AddArtworkFromFile', 'CLSID', 'Delete', 'GetITObjectIDs', 'Play', 'Reveal', 'UpdateInfoFromFile', 'UpdatePodcastFeed', '_ApplyTypes_', '__doc__', '__eq__', '__getattr__', '__init__', '__module__', '__ne__', '__repr__', '__setattr__', '_get_good_object_', '_get_good_single_object_', '_oleobj_', '_prop_map_get_', '_prop_map_put_', 'coclass_clsid']
print currentTrack.Location
Location is callable and returns the file path, but is not listed in the first result. It also doesn't show up with code completion tools. Is it because it's being fetched through a getter method? I see it listed under _prop_map_get_ and _prop_map_put_.
Also, why does currentTrack.Location return a file path when currentTrack._prop_map_get_['Location'] returns "(1610874880, 2, (8, 0), (), 'Location', None)?" Where is it getting the file path string?
A:
In python, an object can have a __getattr__ method. It will be invoked for any attribute access for a non-existent attribute. It looks like this object is using _prop_map_get_ as part of its implementation of __getattr__.
Since __getattr__ can do arbitrary computation to satisfy the attribute request, and can raise AttributeError for names it can't handle, there's no way from the outside to list all attributes that are available.
A:
Good one. Dir() does function correctly and the behavior is explainable.
Location is a property of currentTrack but is accessible only via currentTrack._prop_map_get_. The callable _prop_map_get_ is listed in dir(currentTrack). See getattr which is some how mapped to currentTrack._prop_map_get_
you will find various such cases in win32com which is a wrapper.
| Why are some callable attributes not listed by the dir() function? | How come the dir() function in Python doesn't show all of the callable attributes?
import win32com.client
iTunes = win32com.client.gencache.EnsureDispatch("iTunes.Application")
currentTrack = win32com.client.CastTo(iTunes.CurrentTrack,"IITFileOrCDTrack")
print dir(currentTrack)
Result:
['AddArtworkFromFile', 'CLSID', 'Delete', 'GetITObjectIDs', 'Play', 'Reveal', 'UpdateInfoFromFile', 'UpdatePodcastFeed', '_ApplyTypes_', '__doc__', '__eq__', '__getattr__', '__init__', '__module__', '__ne__', '__repr__', '__setattr__', '_get_good_object_', '_get_good_single_object_', '_oleobj_', '_prop_map_get_', '_prop_map_put_', 'coclass_clsid']
print currentTrack.Location
Location is callable and returns the file path, but is not listed in the first result. It also doesn't show up with code completion tools. Is it because it's being fetched through a getter method? I see it listed under _prop_map_get_ and _prop_map_put_.
Also, why does currentTrack.Location return a file path when currentTrack._prop_map_get_['Location'] returns "(1610874880, 2, (8, 0), (), 'Location', None)?" Where is it getting the file path string?
| [
"In python, an object can have a __getattr__ method. It will be invoked for any attribute access for a non-existent attribute. It looks like this object is using _prop_map_get_ as part of its implementation of __getattr__.\nSince __getattr__ can do arbitrary computation to satisfy the attribute request, and can r... | [
7,
4
] | [] | [] | [
"itunes",
"python",
"win32com"
] | stackoverflow_0004108298_itunes_python_win32com.txt |
Q:
Python: Adding Dictionary Items.
When we add dictionary Items,
we use x.items()+y.items(), but there was something I don't understand.
for example
if x={2:2,1:3} and y={1:3,3:1} x.items()+y.items() gives {3:1,2:2,1:3}
so, as you can see, the answer mathematically could have been 6x+2x^2+x^3,
but the dictionary gives x^3+2x^2+3x,
can any one tell me any better method which works better?
A:
Let's be clear what's going on here!
In [7]: x.items()
Out[7]: [(1, 3), (2, 2)]
In [8]: y.items()
Out[8]: [(1, 3), (3, 1)]
In [9]: x.items() + y.items()
Out[9]: [(1, 3), (2, 2), (1, 3), (3, 1)]
In [10]: dict(x.items() + y.items())
Out[10]: {1: 3, 2: 2, 3: 1}
items() produces a list of (key, value) tuples, and + concatenates the lists. You can then make that list back into a dictionary, which will deal with duplicate keys by taking the last value with a given key. Since it's a duplicate value this time, it doesn't matter, but it could:
In [11]: z = {1:4, 3:1}
In [12]: dict(x.items() + z.items())
Out[12]: {1: 4, 2: 2, 3: 1}
In which case the 1:3 entry is discarded...
(Not clear what your analogy to polynomials is... If you really want to represent polynomials that add arithmetically, you might want to check out the numpy class poly1d or collections.Counter described by @adw.)
A:
When you call dict(x.items()+y.items()), the duplicate keys simply get set twice and the latest set value (the one from y) overwrites the older one (from x).
Since a Python dictionary can have anything as its keys or values (as long as the keys are hashable), how would it know how to combine the old and new value when a key gets replaced?
In Python 2.7 and 3, there is a dictionary subclass called Counter which can only have numbers as values. And when you add two of those together, it does add the values together for duplicate keys:
>>> from collections import Counter
>>> Counter({2:2,1:3}) + Counter({1:3,3:1})
Counter({1: 6, 2: 2, 3: 1})
A:
You could create your own subclass of dict to implement the add operator to do what you wanted:
import copy
class AddingDict(dict):
def __add__(self, d2):
new_dict = copy.deepcopy(self)
for key, value in d2.iteritems():
if key in new_dict:
new_dict[key] += value
else:
new_dict[key] = value
return new_dict
And now:
>>> x = AddingDict({2:2,1:3})
>>> y = AddingDict({1:3,3:1})
>>> x+y
{1: 6, 2: 2, 3: 1}
Edit
If you needed extra efficiency, checking if each key is in the new_dict for each key in the original is inefficient, and you could convert each list of keys to a set and take the intersection, but the code would be more complicated and the efficiency is likely not needed. The actual implementation is left as an exercise to the reader.
| Python: Adding Dictionary Items. | When we add dictionary Items,
we use x.items()+y.items(), but there was something I don't understand.
for example
if x={2:2,1:3} and y={1:3,3:1} x.items()+y.items() gives {3:1,2:2,1:3}
so, as you can see, the answer mathematically could have been 6x+2x^2+x^3,
but the dictionary gives x^3+2x^2+3x,
can any one tell me any better method which works better?
| [
"Let's be clear what's going on here!\nIn [7]: x.items()\nOut[7]: [(1, 3), (2, 2)]\n\nIn [8]: y.items()\nOut[8]: [(1, 3), (3, 1)]\n\nIn [9]: x.items() + y.items()\nOut[9]: [(1, 3), (2, 2), (1, 3), (3, 1)]\n\nIn [10]: dict(x.items() + y.items())\nOut[10]: {1: 3, 2: 2, 3: 1}\n\nitems() produces a list of (key, value... | [
5,
3,
1
] | [] | [] | [
"dictionary",
"python"
] | stackoverflow_0004106896_dictionary_python.txt |
Q:
Create shortcut to .pyw file from within python
I was wondering how to create a shortcut in python to .pyw extensions and .exe's.
A:
You need to create and use a IShellLink via COM.
| Create shortcut to .pyw file from within python | I was wondering how to create a shortcut in python to .pyw extensions and .exe's.
| [
"You need to create and use a IShellLink via COM.\n"
] | [
2
] | [] | [] | [
"python",
"pywin32",
"shortcut",
"windows"
] | stackoverflow_0004108336_python_pywin32_shortcut_windows.txt |
Q:
exception handling with NameError
I want to append new input to list SESSION_U without erasing its content. I try this:
...
try:
SESSION_U.append(UNIQUES)
except NameError:
SESSION_U = []
SESSION_U.append(UNIQUES)
...
I would think that at first try I would get the NameError and SESSION_U list would be created and appended; the second time try would work. But it does not. Do you know why? If this is not clear let me know and I will post the script. Thanks.
Edit
# save string s submitted from form to list K:
K = []
s = self.request.get('sentence')
K.append(s)
# clean up K and create 2 new lists with unique items only and find their frequency
K = K[0].split('\r\n')
UNIQUES = f2(K)
COUNTS = lcount(K, UNIQUES)
# append UNIQUES and COUNTS TO session lists.
# Session lists should not be initialized with each new submission
SESSION_U.append(UNIQUES)
SESSION_C.append(COUNTS)
If I put SESSION_U and SESSION_C after K = [] their content is erased with each submission; if not; I get NameError. I am looking for help about the standard way to handle this situation. Thank you. (I am working Google App Engine)
A:
It appears that the code you posted is probably contained within a request handler. What are your requirements regarding this SESSION_U list? Clearly you want it to be preserved across requests, but there are several ways to do this and the best choice depends on your requirements.
I suspect you want to store SESSION_U in the datastore. You will need to use a transaction to atomically update the list (since multiple requests may try to simultaneously update it). Storing SESSION_U in the datastore makes it durable (i.e., it will persist across requests).
Alternatively, you could use memcache if you aren't worried about losing the list periodically. You could even store the list in a global variable (due to app caching, it will be maintained between requests to a particular instance and will be lost when the instance terminates).
| exception handling with NameError | I want to append new input to list SESSION_U without erasing its content. I try this:
...
try:
SESSION_U.append(UNIQUES)
except NameError:
SESSION_U = []
SESSION_U.append(UNIQUES)
...
I would think that at first try I would get the NameError and SESSION_U list would be created and appended; the second time try would work. But it does not. Do you know why? If this is not clear let me know and I will post the script. Thanks.
Edit
# save string s submitted from form to list K:
K = []
s = self.request.get('sentence')
K.append(s)
# clean up K and create 2 new lists with unique items only and find their frequency
K = K[0].split('\r\n')
UNIQUES = f2(K)
COUNTS = lcount(K, UNIQUES)
# append UNIQUES and COUNTS TO session lists.
# Session lists should not be initialized with each new submission
SESSION_U.append(UNIQUES)
SESSION_C.append(COUNTS)
If I put SESSION_U and SESSION_C after K = [] their content is erased with each submission; if not; I get NameError. I am looking for help about the standard way to handle this situation. Thank you. (I am working Google App Engine)
| [
"It appears that the code you posted is probably contained within a request handler. What are your requirements regarding this SESSION_U list? Clearly you want it to be preserved across requests, but there are several ways to do this and the best choice depends on your requirements.\nI suspect you want to store S... | [
0
] | [] | [] | [
"exception_handling",
"google_app_engine",
"python"
] | stackoverflow_0004107698_exception_handling_google_app_engine_python.txt |
Q:
Generating an ascending list of numbers of arbitrary length in python
Is there a function I can call that returns a list of ascending numbers? I.e., function(10) would return [0,1,2,3,4,5,6,7,8,9]?
A:
You want range().
A:
range(10) is built in.
A:
If you want an iterator that gives you a series of indeterminate length, there is itertools.count(). Here I am iterating with range() so there is a limit to the loop.
>>> import itertools
>>> for x, y in zip(range(10), itertools.count()):
... print x, y
...
0 0
1 1
2 2
3 3
4 4
5 5
6 6
7 7
8 8
9 9
Later: also, range() returns an iterator, not a list, in python 3.x. in that case, you want list(range(10)).
| Generating an ascending list of numbers of arbitrary length in python | Is there a function I can call that returns a list of ascending numbers? I.e., function(10) would return [0,1,2,3,4,5,6,7,8,9]?
| [
"You want range().\n",
"range(10) is built in.\n",
"If you want an iterator that gives you a series of indeterminate length, there is itertools.count(). Here I am iterating with range() so there is a limit to the loop.\n>>> import itertools\n>>> for x, y in zip(range(10), itertools.count()):\n... print x, y... | [
33,
12,
9
] | [] | [] | [
"list",
"python",
"range"
] | stackoverflow_0004108341_list_python_range.txt |
Q:
Using a .net regex in Python
I have some regular expressions written for the Microsoft's .net regex format and I want to use them in a python program on a Linux machine. Is there a compatibly library or a method of covering them? If I have to do it by hand, do you know of a cheat sheet or a guide?
A:
Most of the features in .NET regexes are available in Python; however there are a few things missing:
Python doesn't support variable repetition inside lookbehinds, only fixed-length.
Python uses a different syntax for named captures.
Python matches Unicode characters differently.
Python doesn't have atomic groups (?>...) or possessive quantifiers ++, *+, ?+.
In Python, use r"..." raw strings for regular expressions, or you'll trip up on backslashes.
A comprehensive list of differences can be found here.
And if you need to do regex conversions often, RegexBuddy can do it for you (as long as you're not using features the destination regex engine doesn't have, of course).
A:
The docs for the re module cover Python regex syntax. FWIW, the syntax is very similar, except for the substitutions.
A:
In terms of implementation I think the CLR and Python regex engines are very close, more so than either of them to other languages like Perl or the PCRE. For example, I've used Expresso to create and test complicated regular expressions that I've later adapted to Python code.
That said, I don't think I've ever seen an actual converter, but since they're so similar it should be relatively easy to convert them manually (again, more so than if we were talking about other implementations).
This page has good comparisons between the different engines, although it focuses on capabilities rather than similarity of syntax.
A:
Are you sure there's an incompatibility? At least for the basic to middle-level stuff in regexes, all the implementations pretty much agree on the syntax, except for maybe whether parens should be escaped or not.
| Using a .net regex in Python | I have some regular expressions written for the Microsoft's .net regex format and I want to use them in a python program on a Linux machine. Is there a compatibly library or a method of covering them? If I have to do it by hand, do you know of a cheat sheet or a guide?
| [
"Most of the features in .NET regexes are available in Python; however there are a few things missing:\n\nPython doesn't support variable repetition inside lookbehinds, only fixed-length.\nPython uses a different syntax for named captures.\nPython matches Unicode characters differently.\nPython doesn't have atomic ... | [
6,
1,
1,
0
] | [] | [] | [
".net",
"pcre",
"python",
"regex"
] | stackoverflow_0004108542_.net_pcre_python_regex.txt |
Q:
How to exclude a character from a regex group?
I want to strip all non-alphanumeric characters EXCEPT the hyphen from a string (python).
How can I change this regular expression to match any non-alphanumeric char except the hyphen?
re.compile('[\W_]')
Thanks.
A:
You could just use a negated character class instead:
re.compile(r"[^a-zA-Z0-9-]")
This will match anything that is not in the alphanumeric ranges or a hyphen. It also matches the underscore, as per your current regex.
>>> r = re.compile(r"[^a-zA-Z0-9-]")
>>> s = "some#%te_xt&with--##%--5 hy-phens *#"
>>> r.sub("",s)
'sometextwith----5hy-phens'
Notice that this also replaces spaces (which may certainly be what you want).
Edit: SilentGhost has suggested it may likely be cheaper for the engine to process with a quantifier, in which case you can simply use:
re.compile(r"[^a-zA-Z0-9-]+")
The + will simply cause any runs of consecutively matched characters to all match (and be replaced) at the same time.
A:
\w matches alphanumerics, add in the hyphen, then negate the entire set: r"[^\w-]"
| How to exclude a character from a regex group? | I want to strip all non-alphanumeric characters EXCEPT the hyphen from a string (python).
How can I change this regular expression to match any non-alphanumeric char except the hyphen?
re.compile('[\W_]')
Thanks.
| [
"You could just use a negated character class instead:\nre.compile(r\"[^a-zA-Z0-9-]\")\n\nThis will match anything that is not in the alphanumeric ranges or a hyphen. It also matches the underscore, as per your current regex.\n>>> r = re.compile(r\"[^a-zA-Z0-9-]\")\n>>> s = \"some#%te_xt&with--##%--5 hy-phens *#\"... | [
42,
9
] | [] | [] | [
"python",
"regex"
] | stackoverflow_0004108561_python_regex.txt |
Q:
How to query for a row with a specific DateTime value using GQL?
I tried just using the date's string representation but it didn't work (i.e. no results):
gql = "SELECT * from Shout where when='2010-11-05 16:57:45.675612'"
This is my Shout class:
class Shout(db.Model):
message= db.StringProperty(required=True)
when = db.DateTimeProperty(auto_now_add=True)
who = db.StringProperty()
A:
gql = "SELECT * FROM Shout WHERE when = DATETIME('2010-11-05 16:57:45')"
Per documentation, use the following for date/time literals:
DATETIME() with timestamps,
DATE() with dates,
TIME() with times
An alternative syntax is:
SELECT * FROM Shout WHERE when = DATETIME(2010,11,5,16,57,45)
| How to query for a row with a specific DateTime value using GQL? | I tried just using the date's string representation but it didn't work (i.e. no results):
gql = "SELECT * from Shout where when='2010-11-05 16:57:45.675612'"
This is my Shout class:
class Shout(db.Model):
message= db.StringProperty(required=True)
when = db.DateTimeProperty(auto_now_add=True)
who = db.StringProperty()
| [
"gql = \"SELECT * FROM Shout WHERE when = DATETIME('2010-11-05 16:57:45')\"\n\nPer documentation, use the following for date/time literals: \n\nDATETIME() with timestamps, \nDATE() with dates, \nTIME() with times\n\nAn alternative syntax is:\nSELECT * FROM Shout WHERE when = DATETIME(2010,11,5,16,57,45)\n\n"
] | [
1
] | [] | [] | [
"datetime",
"google_app_engine",
"gql",
"python"
] | stackoverflow_0004108581_datetime_google_app_engine_gql_python.txt |
Q:
Split Regular expression after each repetition
I'm experimenting arround with template engines lately and am stuck in a very early stage at a regular expression.
The first Step in my template engine should be to extract all template constructs. So I wrote following regular expression:
# Split all relevant parts apart to merger them later on.
exp_tags = re.compile(r'({[%|{](.*)[}|%]})')
print exp_tags.split(body)
which works fine, until 2 template constructs are in one line. The expression then merges them together and doesn't split one by one.
Example:
<section>
{{title}}{{text}}
</section>
Should result in:
{'<section>', '{{title}}', 'title', '{{text}}', 'text', '</section>'}
But results in:
{'<section>', '{{title}}{{text}}', 'title}}{{text', '</section>'}
Anyone know how to achieve my goals with regular expressions?
A:
Regular expression quantifiers are greedy by default. Either use the non-greedy variant of * by appending ? to it:
r'({[%|{](.*?)[}|%]})'
Or use a negated character class to exclude the end delimiters.
By the way: The character class [a|b] does not mean either a or b but one of the set of {a, |, b} as the | is not interpreted as alternation but as a literal character.
| Split Regular expression after each repetition | I'm experimenting arround with template engines lately and am stuck in a very early stage at a regular expression.
The first Step in my template engine should be to extract all template constructs. So I wrote following regular expression:
# Split all relevant parts apart to merger them later on.
exp_tags = re.compile(r'({[%|{](.*)[}|%]})')
print exp_tags.split(body)
which works fine, until 2 template constructs are in one line. The expression then merges them together and doesn't split one by one.
Example:
<section>
{{title}}{{text}}
</section>
Should result in:
{'<section>', '{{title}}', 'title', '{{text}}', 'text', '</section>'}
But results in:
{'<section>', '{{title}}{{text}}', 'title}}{{text', '</section>'}
Anyone know how to achieve my goals with regular expressions?
| [
"Regular expression quantifiers are greedy by default. Either use the non-greedy variant of * by appending ? to it:\nr'({[%|{](.*?)[}|%]})'\n\nOr use a negated character class to exclude the end delimiters.\nBy the way: The character class [a|b] does not mean either a or b but one of the set of {a, |, b} as the | i... | [
3
] | [] | [] | [
"python",
"regex",
"templates"
] | stackoverflow_0004108674_python_regex_templates.txt |
Q:
Difference between '' and "" in Python
What is the difference between apostrophes and quotation marks in Python?
So far I've only been able to find one difference
print "'"
print '"'
print '''
print """
The first print statement will output ' while the second ". However the third statement starts a comment block.
Any other differences I should be aware of?
A:
print 'Hello' and print "Hello" are the same and what you use is your personal preference. """ and ''' are for multiline strings.
>>> print """First
Second
Third"""
First
Second
Third
A:
Python has a facility multiline string that starts with triple quotes.
They are also commonly used for docstrings.
http://www.python.org/dev/peps/pep-0257/
An example of multiline string:
>>> x = """ wdd2ed
... 2wdqd
... d
... dd
... d
... """
>>>
>>> print x
wdd2ed
2wdqd
d
dd
d
>>>
String literals can be enclosed in matching single quotes (') or double quotes (").
So "string" and 'string' are same.
The following provides all the details: http://docs.python.org/reference/lexical_analysis.html#string-literals
A:
Triple-quotes aren't for comments, they are the syntax for multi-line strings. They are often used for docstrings, which serve a similar role as block comments in other languages. But multi-line strings can be used as data just as the other string syntaxes can.
A:
'...' strings and "..." are identical except that you don't need to escape ' inside a " string, nor vice versa.
Triple quotes start a multi-line string. These are often used for docstrings, which is probably where you got the idea that they're comments.
A:
' and " can be used interchangably to start and end a string (be sure to close with the same one you opened with). It's provided as a convenience so you don't need to escape quote in most cases.
For example, if you wanted the string say "hello" in languages that don't provide the alternative option, you would need to escape it with something like "say \"hello\"" which is somewhat ugly compared to 'say "hello"'
Likewise if you could only use ' (not sure of any language that does this) then a string to say bill's pony would be 'bill\'s pony' instead of "bill's pony".
A:
Note: in PHP string quoted by single-quotes ' don't interpret escapes like '\n' '\r' etc. In python you can use 'r' modifier. So, str=r'some \n string containing "\n" inside'
- is RAW string and it does not contain newline characters.
| Difference between '' and "" in Python | What is the difference between apostrophes and quotation marks in Python?
So far I've only been able to find one difference
print "'"
print '"'
print '''
print """
The first print statement will output ' while the second ". However the third statement starts a comment block.
Any other differences I should be aware of?
| [
"print 'Hello' and print \"Hello\" are the same and what you use is your personal preference. \"\"\" and ''' are for multiline strings. \n>>> print \"\"\"First\nSecond\nThird\"\"\"\n\nFirst\nSecond\nThird\n\n",
"\nPython has a facility multiline string that starts with triple quotes.\n\nThey are also commonly use... | [
14,
8,
5,
3,
2,
1
] | [] | [] | [
"python"
] | stackoverflow_0004108743_python.txt |
Q:
Django's introspecting administrator: How does it work?
I don't really want to know Django I am actually more interested in the administrator. The thing that interests me is how they introspect the models to create the administrator back-end.
I browsed through the Django source code and found a little info but since it's such a big project I was wondering if there are smaller examples of how they do it?
This is just a personal project to get to understand Python better. I thought that learning about introspecting objects would be a good way to do this.
A:
With Django it's a bit more than introspection actually. The models use a metaclass to register themselves, I will spare you the complexities of everything involved but the admin does not introspect the models as you browse through it.
Instead, the registering process creates a _meta object on the model with all the data needed for the admin and ORM. You can see the ModelBase metaclass in django/db/models/base.py, as you can see in the __new__ function it walks through all the fields to add them to the _meta object. The _meta object itself is generated dynamically using the Meta class definition on the model.
You can see the result with print SomeModel._meta or print SomeModel._meta.fields
A:
This might get you started:
>>> class Foo:
... x = 7
...
>>> f = Foo()
>>> dir(f)
['__doc__', '__module__', 'x']
>>> getattr(f, 'x')
7
A:
If you really want to know how it works in order to learn Python, I would suggest looking at the source code. It is actually pretty well documented.
http://code.djangoproject.com/browser/django/trunk/django/contrib/admin
| Django's introspecting administrator: How does it work? | I don't really want to know Django I am actually more interested in the administrator. The thing that interests me is how they introspect the models to create the administrator back-end.
I browsed through the Django source code and found a little info but since it's such a big project I was wondering if there are smaller examples of how they do it?
This is just a personal project to get to understand Python better. I thought that learning about introspecting objects would be a good way to do this.
| [
"With Django it's a bit more than introspection actually. The models use a metaclass to register themselves, I will spare you the complexities of everything involved but the admin does not introspect the models as you browse through it.\nInstead, the registering process creates a _meta object on the model with all ... | [
4,
1,
0
] | [] | [] | [
"django",
"python"
] | stackoverflow_0004108852_django_python.txt |
Q:
How can I test if a list contains another list with particular items in Python?
I have a list of lists and want to check if it already contains a list with particular items.
Everything should be clear from this example:
list = [[1,2],[3,4],[4,5],[6,7]]
for test in [[1,1],[1,2],[2,1]]:
if test in list:
print True
else:
print False
#Expected:
# False
# True
# True
#Reality:
# False
# True
# False
Is there a function that compares the items of the list regardless how they are sorted?
A:
What you want to use is a set:
set([1,2]) == set([2,1])
returns True.
So
list = [set([1,2]),set([3,4]),set([4,5]),set([6,7])]
set([2,1]) in list
also returns True.
A:
If they're really sets, use the set type
# This returns True
set([2,1]) <= set([1,2,3])
<= means 'is a subset of' when dealing with sets. For more see the operations on set types.
A:
if you want to get [1,2] = [2,1] you should not use list. Set is the correct type. In list, the order of the components matter, in set they don't. That's why you don't get 'False True True'.
| How can I test if a list contains another list with particular items in Python? | I have a list of lists and want to check if it already contains a list with particular items.
Everything should be clear from this example:
list = [[1,2],[3,4],[4,5],[6,7]]
for test in [[1,1],[1,2],[2,1]]:
if test in list:
print True
else:
print False
#Expected:
# False
# True
# True
#Reality:
# False
# True
# False
Is there a function that compares the items of the list regardless how they are sorted?
| [
"What you want to use is a set:\nset([1,2]) == set([2,1])\nreturns True.\nSo\nlist = [set([1,2]),set([3,4]),set([4,5]),set([6,7])]\nset([2,1]) in list\n\nalso returns True.\n",
"If they're really sets, use the set type\n# This returns True \nset([2,1]) <= set([1,2,3])\n\n<= means 'is a subset of' when dealing wit... | [
6,
5,
1
] | [] | [] | [
"list",
"python",
"sorting"
] | stackoverflow_0004108950_list_python_sorting.txt |
Q:
Django - Customising the display of FormSet objects?
I have a formset with can_delete set, i.e. I want to allow people to be able to delete the objects. I want to customise the layout of each of the forms, like this: http://docs.djangoproject.com/en/dev/topics/forms/#customizing-the-form-template . I can add the fields for each form with {{ form.name_of_field }}, etc. However I'm not sure what to put (in the template) for the 'delete' checkbox. This field comes up normally when you go {{ form.as_ul }}.
What's the value for the delete field?
A:
{{ form.DELETE }}
| Django - Customising the display of FormSet objects? | I have a formset with can_delete set, i.e. I want to allow people to be able to delete the objects. I want to customise the layout of each of the forms, like this: http://docs.djangoproject.com/en/dev/topics/forms/#customizing-the-form-template . I can add the fields for each form with {{ form.name_of_field }}, etc. However I'm not sure what to put (in the template) for the 'delete' checkbox. This field comes up normally when you go {{ form.as_ul }}.
What's the value for the delete field?
| [
"{{ form.DELETE }}\n\n"
] | [
4
] | [] | [] | [
"django",
"django_forms",
"django_templates",
"python"
] | stackoverflow_0004107534_django_django_forms_django_templates_python.txt |
Q:
Google App Engine Data Store Model Reference Another Class
So that you can understand the data model, I basically have cities and within each one I'll have categories and then inside each category I'll have listings. Here's what I have so far.
from google.appengine.ext import db
class City(db.Model):
name = db.StringProperty(required=True)
connections = db.ListProperty()
categories = db.ListProperty()
So Next, I want to add:
class Category(db.Model)
name = db.StringProperty(required=True)
But do I need to specify that only Category should be in categories or something to that effect?
A:
You want to look at a custom property named KeyListProperty in App Engine Patch. That will give you the sort of many-to-many relationship you want.
A:
You need to throw the categories property from your City and use a ReferenceProperty in your Category class:
class Category(db.Model)
name = db.StringProperty(required=True)
city = db.ReferenceProperty(City, collection_name = 'categories')
This will also automatically add categories collection for your City model.
| Google App Engine Data Store Model Reference Another Class | So that you can understand the data model, I basically have cities and within each one I'll have categories and then inside each category I'll have listings. Here's what I have so far.
from google.appengine.ext import db
class City(db.Model):
name = db.StringProperty(required=True)
connections = db.ListProperty()
categories = db.ListProperty()
So Next, I want to add:
class Category(db.Model)
name = db.StringProperty(required=True)
But do I need to specify that only Category should be in categories or something to that effect?
| [
"You want to look at a custom property named KeyListProperty in App Engine Patch. That will give you the sort of many-to-many relationship you want.\n",
"You need to throw the categories property from your City and use a ReferenceProperty in your Category class:\nclass Category(db.Model)\n name = db.StringProp... | [
1,
0
] | [] | [] | [
"google_app_engine",
"google_cloud_datastore",
"python"
] | stackoverflow_0004107660_google_app_engine_google_cloud_datastore_python.txt |
Q:
How do I make Selenium RC to not move the browser window?
Is there a way to specify where Selenium RC spawns the browser window?
When I run my test script, Selenium RC opens 2 windows in the browser, the Selenium RC window and the AUT, and the Selenium RC window takes up most of my screen space. Ideally, I want to control where their location and size separately, but if not, it would be nice to at least make the AUT maximized so that I can eyeball some stuff. Is there a way to do this?
I have tried window_maximize(). Although it does make the AUT window bigger, it is located in the bottom of the screen - only the top 1/4 is visible. I am using Selenium RC with Python on a Mac if that matters.
A:
This works from java:
selenium.getEval("this.browserbot.getCurrentWindow().moveTo((" + h + "),(" + v + "))");
selenium.getEval("this.browserbot.getCurrentWindow().resizeTo(" + w + "," + h + ")");
| How do I make Selenium RC to not move the browser window? | Is there a way to specify where Selenium RC spawns the browser window?
When I run my test script, Selenium RC opens 2 windows in the browser, the Selenium RC window and the AUT, and the Selenium RC window takes up most of my screen space. Ideally, I want to control where their location and size separately, but if not, it would be nice to at least make the AUT maximized so that I can eyeball some stuff. Is there a way to do this?
I have tried window_maximize(). Although it does make the AUT window bigger, it is located in the bottom of the screen - only the top 1/4 is visible. I am using Selenium RC with Python on a Mac if that matters.
| [
"This works from java:\nselenium.getEval(\"this.browserbot.getCurrentWindow().moveTo((\" + h + \"),(\" + v + \"))\");\nselenium.getEval(\"this.browserbot.getCurrentWindow().resizeTo(\" + w + \",\" + h + \")\");\n\n"
] | [
1
] | [] | [] | [
"python",
"selenium",
"selenium_rc",
"window"
] | stackoverflow_0003962832_python_selenium_selenium_rc_window.txt |
Q:
Finding usb gps in cross platform python
I'm working on a python app that's reading from a gps usb dongle. This far everything has been running in ubuntu/debian based systems where I communicated with the gps in a rather blunt way of scanning all of /dev/ttyUSB0-9 with pySerial for something speaking NMEA sentences on 38400 baud. Now I have been asked to get this app working cross platform and I'm a bit confused on which would be the best way of finding the gps dongle.
I have considered something along the lines of:
if os.name == "posix":
self.conn = serial.Serial("/dev/ttyUSB%i" % usb)
elif os.name == "nt":
...
But I would rather have a single solution that works cross platform. Does anyone know of such a solution?
A:
You could use the comports function from the scanwin32.py module provided in the pySerial documentation to figure out which COM ports are available, and then, using the returned informations about the open ports, find which one is your GPS dongle.
Edit: The documentation also provides a scan.py module which contains only a very simple function that probes each 256 ports to find which ones are open, maybe it would be sufficient for what you need.
A:
I would guess that in the long run you may have more use of a cross platform anyway so go for why not stay with it?
| Finding usb gps in cross platform python | I'm working on a python app that's reading from a gps usb dongle. This far everything has been running in ubuntu/debian based systems where I communicated with the gps in a rather blunt way of scanning all of /dev/ttyUSB0-9 with pySerial for something speaking NMEA sentences on 38400 baud. Now I have been asked to get this app working cross platform and I'm a bit confused on which would be the best way of finding the gps dongle.
I have considered something along the lines of:
if os.name == "posix":
self.conn = serial.Serial("/dev/ttyUSB%i" % usb)
elif os.name == "nt":
...
But I would rather have a single solution that works cross platform. Does anyone know of such a solution?
| [
"You could use the comports function from the scanwin32.py module provided in the pySerial documentation to figure out which COM ports are available, and then, using the returned informations about the open ports, find which one is your GPS dongle.\nEdit: The documentation also provides a scan.py module which conta... | [
2,
0
] | [] | [] | [
"cross_platform",
"gps",
"pyserial",
"python",
"usb"
] | stackoverflow_0004106065_cross_platform_gps_pyserial_python_usb.txt |
Q:
How would I use a South migration to load data into Django's auth_group table?
I have some new groups that I'd like to add to Django's "auth_group" table and I'd prefer to use South to "migrate" that data into the database. Unfortunately, I'm not sure what steps I should take to create the migration file and then have it load my fixture.
Any thoughts?
A:
The South docs have a section about fixtures that includes this sample:
def forwards(self, orm):
from django.core.management import call_command
call_command("loaddata", "my_fixture.json")
| How would I use a South migration to load data into Django's auth_group table? | I have some new groups that I'd like to add to Django's "auth_group" table and I'd prefer to use South to "migrate" that data into the database. Unfortunately, I'm not sure what steps I should take to create the migration file and then have it load my fixture.
Any thoughts?
| [
"The South docs have a section about fixtures that includes this sample:\ndef forwards(self, orm):\n from django.core.management import call_command\n call_command(\"loaddata\", \"my_fixture.json\")\n\n"
] | [
8
] | [] | [] | [
"django",
"django_south",
"python"
] | stackoverflow_0004109186_django_django_south_python.txt |
Q:
simplejson not escaping single quote on app engine server
I'm trying to generate a properly formatted json object to use in javascript. I've tried simplejson.dumps(string), but it behaves differently on my local machine (in the python shell) vs. on the server (running google app engine). For example, locally i'll get:
>>> s= {u'hello': u"Hi, i'm here"}
>>> simplejson.dumps(s)
'{"hello": "Hi, i\'m here"}'
which all looks good. But when i run it on the server, I get
{"hello": "Hi, i'm here"}
where the single quote is not escaped, which throws an error in my javascript.
Short of doing a secondary string.replace("'", r"\'"), does anyone have suggestions? I'm at a loss and have already spent waay to much time trying to figure it out...
A:
I think you are being confused by the repr behaviour vs the actual output.
>>> s= {u'hello': u"Hi, i'm here"}
>>> simplejson.dumps(s)
'{"hello": "Hi, i\'m here"}'
>>> print simplejson.dumps(s)
{"hello": "Hi, i'm here"}
When you simply ask for the result of the simplejson call, the Python shell prints that result using repr - which escapes it so that you can cut and paste it back in later. However, there isn't actually a backslash in the string produced by dumps.
A:
There's no escape needed for single quotes in JSON, and in fact there's no backslash in the string returned in your example:
>>> print simplejson.dumps(s)
{"hello": "Hi, i'm here"}
So I suspect that your javascript error is something else.
| simplejson not escaping single quote on app engine server | I'm trying to generate a properly formatted json object to use in javascript. I've tried simplejson.dumps(string), but it behaves differently on my local machine (in the python shell) vs. on the server (running google app engine). For example, locally i'll get:
>>> s= {u'hello': u"Hi, i'm here"}
>>> simplejson.dumps(s)
'{"hello": "Hi, i\'m here"}'
which all looks good. But when i run it on the server, I get
{"hello": "Hi, i'm here"}
where the single quote is not escaped, which throws an error in my javascript.
Short of doing a secondary string.replace("'", r"\'"), does anyone have suggestions? I'm at a loss and have already spent waay to much time trying to figure it out...
| [
"I think you are being confused by the repr behaviour vs the actual output.\n>>> s= {u'hello': u\"Hi, i'm here\"}\n>>> simplejson.dumps(s)\n'{\"hello\": \"Hi, i\\'m here\"}'\n>>> print simplejson.dumps(s)\n{\"hello\": \"Hi, i'm here\"}\n\nWhen you simply ask for the result of the simplejson call, the Python shell p... | [
2,
1
] | [] | [] | [
"javascript",
"python",
"simplejson"
] | stackoverflow_0004109047_javascript_python_simplejson.txt |
Q:
Why doesn't my GQL query return any results in my GAE App?
I have mostly followed a tutorial about how to build a gustbook using GAE and Python. Now I only want to show the entries from a particular day, but the GQL query doesn't return anything (although there are entries from that day):
class Shout(db.Model):
message= db.StringProperty(required=True)
when = db.DateTimeProperty(auto_now_add=True)
who = db.StringProperty()
class MainHandler(webapp.RequestHandler):
def get(self):
shouts = db.GqlQuery("SELECT * FROM Shout WHERE when=DATE('2010-11-05')")
# Return something without the WHERE clause
values = {'shouts':shouts}
self.response.out.write(template.render('main.html',values))
def post(self):
self.response.out.write("posted")
shout = Shout(message=self.request.get("message"),who=self.request.get("who"))
shout.put()
This is my main.html:
<form method="post">
<input type="text" name="who"></input>
<input type="text" name="message"></input>
<input type="submit" value="Send"> </input>
</form>
{% for shout in shouts %}
<div>{{shout.message}} from {{shout.who}} on {{shout.when}}</div>
{% endfor %}
A:
There might be another way around this, but I think that because your when property is a datetime you would be better served with something like this:
shouts = db.GqlQuery("""SELECT *
FROM Shout
WHERE when >= DATE('2010-11-05')
AND when < DATE('2010-11-06')""")
A:
Try this:
shouts = db.GqlQuery("SELECT * FROM Shout WHERE when=DATE('2010-11-05')").fetch(5000)
While it is possible to use a Query object as an iterable, it is a better idea to explicitly fetch the rows and not depend on the for in your template to do the work. I suspect that it is not supported in that way.
EDIT:
Now that I look more closely at this, I suspect that the problem is that the field you are querying on is a DateTimeProperty, and by using the DATE operator, you are essentially saying that you want 2010-11-05 00:00:00, and there are no records with that exact date and time, so try this instead:
shouts = db.GqlQuery("SELECT * FROM Shout WHERE when >= DATETIME('2010-11-05 00:00:00') and when <= DATETIME('2010-11-05 23:59:59')")
| Why doesn't my GQL query return any results in my GAE App? | I have mostly followed a tutorial about how to build a gustbook using GAE and Python. Now I only want to show the entries from a particular day, but the GQL query doesn't return anything (although there are entries from that day):
class Shout(db.Model):
message= db.StringProperty(required=True)
when = db.DateTimeProperty(auto_now_add=True)
who = db.StringProperty()
class MainHandler(webapp.RequestHandler):
def get(self):
shouts = db.GqlQuery("SELECT * FROM Shout WHERE when=DATE('2010-11-05')")
# Return something without the WHERE clause
values = {'shouts':shouts}
self.response.out.write(template.render('main.html',values))
def post(self):
self.response.out.write("posted")
shout = Shout(message=self.request.get("message"),who=self.request.get("who"))
shout.put()
This is my main.html:
<form method="post">
<input type="text" name="who"></input>
<input type="text" name="message"></input>
<input type="submit" value="Send"> </input>
</form>
{% for shout in shouts %}
<div>{{shout.message}} from {{shout.who}} on {{shout.when}}</div>
{% endfor %}
| [
"There might be another way around this, but I think that because your when property is a datetime you would be better served with something like this:\nshouts = db.GqlQuery(\"\"\"SELECT * \n FROM Shout \n WHERE when >= DATE('2010-11-05')\n ... | [
2,
1
] | [] | [] | [
"google_app_engine",
"gql",
"python"
] | stackoverflow_0004109272_google_app_engine_gql_python.txt |
Q:
Python/Tikinter: Can't use a button to update a graph?
Simplified question: For some reason the plot isn't updating when I hit my generate plots button.
global f
master = Tk()
plotFrame = Frame(master)
plotFrame.pack(side=TOP)
f = Figure()
canvas = FigureCanvasTkAgg(f, plotFrame)
canvas.get_tk_widget().pack()
toolbar = NavigationToolbar2TkAgg(canvas,master)
toolbar.pack(side=BOTTOM)
def grph():
graph1 = f.add_subplot(111)
graph1.plot([1,2,3])
genButton = Button(master, text="Generate plots...", command=grph)
genButton.pack(side=LEFT,anchor=W)
master.mainloop()
A:
Add this line:
def grph():
graph1 = f.add_subplot(111)
graph1.plot([1,2,3])
canvas.draw()
| Python/Tikinter: Can't use a button to update a graph? | Simplified question: For some reason the plot isn't updating when I hit my generate plots button.
global f
master = Tk()
plotFrame = Frame(master)
plotFrame.pack(side=TOP)
f = Figure()
canvas = FigureCanvasTkAgg(f, plotFrame)
canvas.get_tk_widget().pack()
toolbar = NavigationToolbar2TkAgg(canvas,master)
toolbar.pack(side=BOTTOM)
def grph():
graph1 = f.add_subplot(111)
graph1.plot([1,2,3])
genButton = Button(master, text="Generate plots...", command=grph)
genButton.pack(side=LEFT,anchor=W)
master.mainloop()
| [
"Add this line:\ndef grph():\n graph1 = f.add_subplot(111)\n graph1.plot([1,2,3])\n canvas.draw()\n\n"
] | [
1
] | [] | [] | [
"button",
"python",
"tkinter"
] | stackoverflow_0004106546_button_python_tkinter.txt |
Q:
Python dictionary isn't updating
def mergeDict(object):
dict1 = {}
for i in range(len(object)):
dict1.update({'id': object[i].id, 'name': object[i].name, 'age': object[i].age, 'location': object[i].location})
return dict1
merged_dict = mergeDict(details_sorted)
But this doesn't work.
I want to get something like this:
{1: {'id': 1, 'name': 'John', 'age': '25'; 'location': 'somewhere'},
2: {'id': 2, 'name': ......}}
A:
It looks like the return statement is in the for loop, which means it will only ever return the update of the first dict.
A:
You don't want to update the dict; you just want to insert a value on key i. Also, the return goes after the for, not in it. Here is a modified version:
def mergeDict(object):
dict1 = {}
for i in range(len(object)):
dict1[i] = {'id': object[i].id, 'name': object[i].name, 'age': object[i].age, 'location': object[i].location}
return dict1
merged_dict = mergeDict(details_sorted)
Your update version would have updated the id, name, age and location keys of dict1 -- and you don't want that. You want to update the id key of dict1 with another dictionary containing the keys id, name, age and location.
A:
Do a bit of experiment.
def mergeDict(object):
dict1 = {}
dict1.update({'id': 'object[i].id', 'name': 'object[i].name', 'age': 'object[i].age', 'location': 'object[i].location'})
dict1.update({'id': 'object[j].id', 'name': 'object[j].name', 'age': 'object[j].age', 'location': 'object[j].location'})
return dict1
merged_dict = mergeDict(None)
print merged_dict
Output:
{'name': 'object[j].name', 'age': 'object[j].age', 'location': 'object[j].location', 'id': 'object[j].id'}
Errors:
Only last object values are retained as the keys are same for all objects. So the for loop has no effect.
It's like saying
x = {}
x['k'] = y
x['k'] = z
There is only one key - k and it's latest value is z
A:
One-liner in Python 3.0:
merged_dict = {i: dict(id=o.id, name=o.name, age=o.age, location=o.location)
for i, o in enumerate(details_sorted)}
If the result keys are consecutive integers, why not a list instead of dict?
merged = [ dict(id=o.id, name=o.name, age=o.age, location=o.location)
for i, o in enumerate(details_sorted) ]
A list has the added benefit of preserving sort order.
| Python dictionary isn't updating | def mergeDict(object):
dict1 = {}
for i in range(len(object)):
dict1.update({'id': object[i].id, 'name': object[i].name, 'age': object[i].age, 'location': object[i].location})
return dict1
merged_dict = mergeDict(details_sorted)
But this doesn't work.
I want to get something like this:
{1: {'id': 1, 'name': 'John', 'age': '25'; 'location': 'somewhere'},
2: {'id': 2, 'name': ......}}
| [
"It looks like the return statement is in the for loop, which means it will only ever return the update of the first dict.\n",
"You don't want to update the dict; you just want to insert a value on key i. Also, the return goes after the for, not in it. Here is a modified version:\ndef mergeDict(object):\n dict... | [
5,
3,
1,
1
] | [] | [] | [
"python"
] | stackoverflow_0004109712_python.txt |
Q:
Where should I put configuration details? [Python]
I'm fairly new to Python and Django, and I'm working on a webapp now that will be run on multiple servers. Each server has it's own little configuration details (commands, file paths, etc.) that I would like to just be able to store in a settings file, and then have a different copy of the file on each system.
I know that in Django, there's a settings file. However, is that only for Django-related things? Or am I supposed to put this type of stuff in there too?
A:
This page discusses yours and several other situations involving configurations on Django servers: http://code.djangoproject.com/wiki/SplitSettings
A:
It's for any type of settings, but it's better to put local settings in a separate file so that version upgrades don't clobber them. Have the global settings file detect the presence of the local settings file and then either import everything from it or just execfile() it.
A:
There isn't a standard place to put config files. You can easily create your own config file as needed though. ConfigParser might suit your needs (and is a Python built-in).
Regardless of the format that I use for my config file, I usually have my scripts that depend on settings get the config file path from environment variables
(using bash):
export MY_APP_CONFIG_PATH=/path/to/config/file/on/this/system
and then my scripts pick up the settings like so:
import os
path_to_config = os.environ['MY_APP_CONFIG_PATH']
| Where should I put configuration details? [Python] | I'm fairly new to Python and Django, and I'm working on a webapp now that will be run on multiple servers. Each server has it's own little configuration details (commands, file paths, etc.) that I would like to just be able to store in a settings file, and then have a different copy of the file on each system.
I know that in Django, there's a settings file. However, is that only for Django-related things? Or am I supposed to put this type of stuff in there too?
| [
"This page discusses yours and several other situations involving configurations on Django servers: http://code.djangoproject.com/wiki/SplitSettings\n",
"It's for any type of settings, but it's better to put local settings in a separate file so that version upgrades don't clobber them. Have the global settings fi... | [
2,
1,
1
] | [] | [] | [
"django",
"python"
] | stackoverflow_0004109532_django_python.txt |
Q:
Plugging values into ModelForm fields at __init__ time
I want to add first_name, last_name, and email fields to the UserProfile admin page. So you can change all the user's details from within the UserProfile admin instead of having to go to a different page to change email and some other fields.
This is what my custom form looks like:
class CustomProfileForm(forms.ModelForm):
first_name = forms.CharField(max_length=30)
last_name = forms.CharField(max_length=30)
email = forms.EmailField()
class Meta:
model = UserProfile
def __init__(self, *a, **k):
super(CustomProfileForm, self).__init__(*a, **k)
self.user_instance = None
if self.instance:
self.user_instance = self.instance.user
def clean_first_name(self):
self.user_instance.first_name = self.cleaned_data['first_name']
def clean_first_name(self):
self.user_instance.last_name = self.cleaned_data['laset_name']
def clean(self):
self.user_instance.save()
return self.cleaned_data
class UserProfileAdmin(admin.ModelAdmin):
form = CustomProfileForm
I don't know what to do to complete this. I need to give the user_instance details to the proper form class.
A:
To set the initial values in the init method you can use the fields dictionary.
def __init__(self, *a, **k):
# < snip >
self.fields[ 'email' ].initial = self.user_instance.email
# ... and any others
| Plugging values into ModelForm fields at __init__ time | I want to add first_name, last_name, and email fields to the UserProfile admin page. So you can change all the user's details from within the UserProfile admin instead of having to go to a different page to change email and some other fields.
This is what my custom form looks like:
class CustomProfileForm(forms.ModelForm):
first_name = forms.CharField(max_length=30)
last_name = forms.CharField(max_length=30)
email = forms.EmailField()
class Meta:
model = UserProfile
def __init__(self, *a, **k):
super(CustomProfileForm, self).__init__(*a, **k)
self.user_instance = None
if self.instance:
self.user_instance = self.instance.user
def clean_first_name(self):
self.user_instance.first_name = self.cleaned_data['first_name']
def clean_first_name(self):
self.user_instance.last_name = self.cleaned_data['laset_name']
def clean(self):
self.user_instance.save()
return self.cleaned_data
class UserProfileAdmin(admin.ModelAdmin):
form = CustomProfileForm
I don't know what to do to complete this. I need to give the user_instance details to the proper form class.
| [
"To set the initial values in the init method you can use the fields dictionary.\ndef __init__(self, *a, **k):\n # < snip >\n self.fields[ 'email' ].initial = self.user_instance.email\n # ... and any others\n\n"
] | [
2
] | [] | [] | [
"django",
"django_admin",
"django_forms",
"python"
] | stackoverflow_0004108822_django_django_admin_django_forms_python.txt |
Q:
pygtk FileChooserDialog slows down interpreter
I'm trying to use FileChooserDialog to get a native gnome dialog box in a python script. After the script executes, my ipython -pylab prompt experiences a significant slow down. This problem also exists from a plain python prompt. I've isolated the problem to the dialog box. The following example (which has been posted elsewhere as a pygtk example) illustrates the issue:
import pygtk
pygtk.require('2.0')
import gtk
class FileChooserDialog:
def __init__(self):
filechooserdialog = gtk.FileChooserDialog("FileChooserDialog Example", None, gtk.FILE_CHOOSER_ACTION_OPEN, (gtk.STOCK_CANCEL, gtk.RESPONSE_CANCEL, gtk.STOCK_OK, gtk.RESPONSE_OK))
response = filechooserdialog.run()
if response == gtk.RESPONSE_OK:
print "Selected filepath: %s" % filechooserdialog.get_filename()
filechooserdialog.destroy()
if __name__ == "__main__":
FileChooserDialog()
After running the script, my hard drive light seems to flash after any key is typed in from the keyboard - very strange behavior! I do not have the problem with deprecated gtk.FileSelection or any other gtk window objects.
I'm currently running, python 2.6.5, gtk 2.21.1, pygtk 2.17.0 in ubuntu 10.04. In general this dialog seems to be flaky; I've also had some issues with the window not destroying itself when executed certain ways within scripts. Any help would be greatly appreciated!
A:
From running this in the IDLE, here's the steps I can see going on for me -
The script starts and the file chooser loads
The interpreter locks as it waits for FileChooserDialog.run()
The interpreter resumes when I click to remove it
Which is nothing what like you describe, so I can only assume it is some esoteric, weird error.
I'm on a little older system (and a totally different distro), so I run:
Python 2.6.4
PyGTK 2.16.0
GTK 2.18.7
Just for correctness (not necessairly dealing with the problem, though who knows...) remember to call .destroy() for the dialog after you call .run() on it.P
| pygtk FileChooserDialog slows down interpreter | I'm trying to use FileChooserDialog to get a native gnome dialog box in a python script. After the script executes, my ipython -pylab prompt experiences a significant slow down. This problem also exists from a plain python prompt. I've isolated the problem to the dialog box. The following example (which has been posted elsewhere as a pygtk example) illustrates the issue:
import pygtk
pygtk.require('2.0')
import gtk
class FileChooserDialog:
def __init__(self):
filechooserdialog = gtk.FileChooserDialog("FileChooserDialog Example", None, gtk.FILE_CHOOSER_ACTION_OPEN, (gtk.STOCK_CANCEL, gtk.RESPONSE_CANCEL, gtk.STOCK_OK, gtk.RESPONSE_OK))
response = filechooserdialog.run()
if response == gtk.RESPONSE_OK:
print "Selected filepath: %s" % filechooserdialog.get_filename()
filechooserdialog.destroy()
if __name__ == "__main__":
FileChooserDialog()
After running the script, my hard drive light seems to flash after any key is typed in from the keyboard - very strange behavior! I do not have the problem with deprecated gtk.FileSelection or any other gtk window objects.
I'm currently running, python 2.6.5, gtk 2.21.1, pygtk 2.17.0 in ubuntu 10.04. In general this dialog seems to be flaky; I've also had some issues with the window not destroying itself when executed certain ways within scripts. Any help would be greatly appreciated!
| [
"From running this in the IDLE, here's the steps I can see going on for me -\n\nThe script starts and the file chooser loads\nThe interpreter locks as it waits for FileChooserDialog.run()\nThe interpreter resumes when I click to remove it\n\nWhich is nothing what like you describe, so I can only assume it is some ... | [
0
] | [] | [] | [
"ipython",
"pygtk",
"python"
] | stackoverflow_0004020745_ipython_pygtk_python.txt |
Q:
What features does Django have that Pylons doesn't?
From what I understand, Pylons is more of a 'bare bones' framework (where you can choose your ORM and template engine), and Django is a little more rich in nature.
What exactly are the features/frameworky elements that Django has that Pylons doesn't?
(other than its own ORM, and its auto-admin page generation)
A:
This question overlaps heavily with "Pros/Cons of Django vs Pylons," and I think that part of the answer you're looking for is in Ben Bangeret's answer to that question. Pylons addresses a larger problem domain than Django does, so there are web apps that are so nontrivial to build in Django that you might as well not even start. On the other hand, if you're working on a problem that is within Django's ambit - basically content-management sites - then Django will probably work out well for you.
A:
The main difference is Django's scaffolding and auto-admin interface. Both of these allow you to quickly start managing data in the website without having to create lots of views etc.
A:
The ability to ask a question about it on Stackoverflow. Django has over 10,000 tagged questions, Pylon has just under 400.
| What features does Django have that Pylons doesn't? | From what I understand, Pylons is more of a 'bare bones' framework (where you can choose your ORM and template engine), and Django is a little more rich in nature.
What exactly are the features/frameworky elements that Django has that Pylons doesn't?
(other than its own ORM, and its auto-admin page generation)
| [
"This question overlaps heavily with \"Pros/Cons of Django vs Pylons,\" and I think that part of the answer you're looking for is in Ben Bangeret's answer to that question. Pylons addresses a larger problem domain than Django does, so there are web apps that are so nontrivial to build in Django that you might as w... | [
3,
1,
1
] | [] | [] | [
"django",
"pylons",
"python"
] | stackoverflow_0003718695_django_pylons_python.txt |
Q:
Design of a python pickleable object that describes a file
I would like to create a class that describes a file resource and then pickle it. This part is straightforward. To be concrete, let's say that I have a class "A" that has methods to operate on a file. I can pickle this object if it does not contain a file handle. I want to be able to create a file handle in order to access the resource described by "A". If I have an "open()" method in class "A" that opens and stores the file handle for later use, then "A" is no longer pickleable. (I add here that opening the file includes some non-trivial indexing which cannot be cached--third party code--so closing and reopening when needed is not without expense). I could code class "A" as a factory that can generate file handles to the described file, but that could result in multiple file handles accessing the file contents simultaneously. I could use another class "B" to handle the opening of the file in class "A", including locking, etc. I am probably overthinking this, but any hints would be appreciated.
A:
The question isn't too clear; what it looks like is that:
you have a third-party module which has picklable classes
those classes may contain references to files, which makes the classes themselves not picklable because open files aren't picklable.
Essentially, you want to make open files picklable. You can do this fairly easily, with certain caveats. Here's an incomplete but functional sample:
import pickle
class PicklableFile(object):
def __init__(self, fileobj):
self.fileobj = fileobj
def __getattr__(self, key):
return getattr(self.fileobj, key)
def __getstate__(self):
ret = self.__dict__.copy()
ret['_file_name'] = self.fileobj.name
ret['_file_mode'] = self.fileobj.mode
ret['_file_pos'] = self.fileobj.tell()
del ret['fileobj']
return ret
def __setstate__(self, dict):
self.fileobj = open(dict['_file_name'], dict['_file_mode'])
self.fileobj.seek(dict['_file_pos'])
del dict['_file_name']
del dict['_file_mode']
del dict['_file_pos']
self.__dict__.update(dict)
f = PicklableFile(open("/tmp/blah"))
print f.readline()
data = pickle.dumps(f)
f2 = pickle.loads(data)
print f2.read()
Caveats and notes, some obvious, some less so:
This class should operate directly on the file object you got from open. If you're using wrapper classes on files, like gzip.GzipFile, those should go above this, not below it. Logically, treat this as a decorator class on top of file.
If the file doesn't exist when you unpickle, it can't be unpickled and will throw an exception.
If it's a different file, the behavior may or may not make sense.
If the file mode includes file creation ('w+'), and the file doesn't exist, it'll be created; we don't know what file permissions to use, since that's not stored with the file. If this is important--it probably shouldn't be--then store the correct permissions in the class when you first create it.
If the file isn't seekable, trying to seek to the old position may raise IOError; if you're using a file like that you'll need to decide how to handle that.
The file classes in Python 2 and Python 3 are different; there's no file class in Python 3. Even if you're only using Python 2 right now, don't subclass file.
I'd steer away from doing this; having pickled data dependent on external files not changing and staying in the same place is brittle. This makes it difficult to even relocate files, since your pickled data won't make sense.
A:
If you open a pointer to a file, pickle it, then attempt to reconstitute is later, there is no guarantee that file will still be available for opening.
To elaborate, the file pointer really represents a connection to the file. Just like a database connection, you can't "pickle" the other end of the connection, so this won't work.
Is it possible to keep the file pointer around in memory in its own process instead?
A:
It sounds like you know you can't pickle the handle, and you're ok with that, you just want to pickle the part that can be pickled. As your object stands now, it can't be pickled because it has the handle. Do I have that right? If so, read on.
The pickle module will let your class describe its own state to pickle, for exactly these cases. You want to define your own __getstate__ method. The pickler will invoke it to get the state to be pickled, only if the method is missing does it go ahead and do the default thing of trying to pickle all the attributes.
| Design of a python pickleable object that describes a file | I would like to create a class that describes a file resource and then pickle it. This part is straightforward. To be concrete, let's say that I have a class "A" that has methods to operate on a file. I can pickle this object if it does not contain a file handle. I want to be able to create a file handle in order to access the resource described by "A". If I have an "open()" method in class "A" that opens and stores the file handle for later use, then "A" is no longer pickleable. (I add here that opening the file includes some non-trivial indexing which cannot be cached--third party code--so closing and reopening when needed is not without expense). I could code class "A" as a factory that can generate file handles to the described file, but that could result in multiple file handles accessing the file contents simultaneously. I could use another class "B" to handle the opening of the file in class "A", including locking, etc. I am probably overthinking this, but any hints would be appreciated.
| [
"The question isn't too clear; what it looks like is that:\n\nyou have a third-party module which has picklable classes\nthose classes may contain references to files, which makes the classes themselves not picklable because open files aren't picklable.\n\nEssentially, you want to make open files picklable. You ca... | [
6,
1,
1
] | [] | [] | [
"pickle",
"python"
] | stackoverflow_0004109848_pickle_python.txt |
Q:
Build Boost and Exempi on a Mac
In order to install Python XMP Toolkit,
I
need to install Exempi on my Mac, but doing this is becoming a real nightmare...
After a lot of trouble, i finally made it with boost, and had the fantastic
The Boost C++ Libraries were successfully built!
The following directory should be added to compiler include paths:
/usr/local/boost_1_44_0
The following directory should be added to linker library paths:
/usr/local/boost_1_44_0/stage/lib
Right now I'm trying to configure Exempi, with the command
./configure --with-boost=/usr/local/boost_1_44_0/
but it always get stuck on this:
checking for Boost headers version >= 1.33.0... /usr/local/boost_1_44_0/
checking for Boost's header version... 1_44
checking for the toolset name used by Boost for g++... gcc40
checking boost/test/unit_test.hpp usability... yes
checking boost/test/unit_test.hpp presence... yes
checking for boost/test/unit_test.hpp... yes
checking for the Boost unit_test_framework library... no
configure: error: Could not find the flags to link with Boost unit_test_framework
I've been googlin for a couple of days, but I couldn't find anything useful...
Anyone had the same problem before? I would die for a helping hand... every hint is welcome!
EDIT:
I've made it with port and now it finally says exempi @2.1.1_0 (active).
The problem is that when I try to load the XMP toolkit, it doesn't find exempi, and raises an error, as reported on the installation guide:
in case you haven’t installed Exempi you will get an ExempiLoadError exception once you try to load libxmp.
What can I do?
A:
I'm assuming that you installed Boost manually, given that it's in /usr/local. I was able to install both Boost and Exempi through MacPorts.
A:
Looks like you didn't build the boost test library when you built boost. You need to add --with-test to your bjam invokation:
./bjam --with-test
| Build Boost and Exempi on a Mac | In order to install Python XMP Toolkit,
I
need to install Exempi on my Mac, but doing this is becoming a real nightmare...
After a lot of trouble, i finally made it with boost, and had the fantastic
The Boost C++ Libraries were successfully built!
The following directory should be added to compiler include paths:
/usr/local/boost_1_44_0
The following directory should be added to linker library paths:
/usr/local/boost_1_44_0/stage/lib
Right now I'm trying to configure Exempi, with the command
./configure --with-boost=/usr/local/boost_1_44_0/
but it always get stuck on this:
checking for Boost headers version >= 1.33.0... /usr/local/boost_1_44_0/
checking for Boost's header version... 1_44
checking for the toolset name used by Boost for g++... gcc40
checking boost/test/unit_test.hpp usability... yes
checking boost/test/unit_test.hpp presence... yes
checking for boost/test/unit_test.hpp... yes
checking for the Boost unit_test_framework library... no
configure: error: Could not find the flags to link with Boost unit_test_framework
I've been googlin for a couple of days, but I couldn't find anything useful...
Anyone had the same problem before? I would die for a helping hand... every hint is welcome!
EDIT:
I've made it with port and now it finally says exempi @2.1.1_0 (active).
The problem is that when I try to load the XMP toolkit, it doesn't find exempi, and raises an error, as reported on the installation guide:
in case you haven’t installed Exempi you will get an ExempiLoadError exception once you try to load libxmp.
What can I do?
| [
"I'm assuming that you installed Boost manually, given that it's in /usr/local. I was able to install both Boost and Exempi through MacPorts.\n",
"Looks like you didn't build the boost test library when you built boost. You need to add --with-test to your bjam invokation:\n./bjam --with-test\n"
] | [
1,
0
] | [] | [] | [
"boost",
"boost_python",
"macos",
"python"
] | stackoverflow_0004019243_boost_boost_python_macos_python.txt |
Q:
Can I improve on the current Python code?
I am just starting out with Python and decided to try this little project from Python Wiki:
Write a password guessing program to keep track of how many times the user has entered the password wrong. If it is more than 3 times, print You have been denied access. and terminate the program. If the password is correct, print You have successfully logged in. and terminate the program.
Here's my code. It works but it just doesn't feel right with these loop breaks and nested if statements.
# Password Guessing Program
# Python 2.7
count = 0
while count < 3:
password = raw_input('Please enter a password: ')
if password != 'SecretPassword':
count = count + 1;
print 'You have entered invalid password %i times.' % (count)
if count == 3:
print 'Access Denied'
break
else:
print 'Access Granted'
break
A:
You can replace your while loop with the following function:
def login():
for i in range(3):
password = raw_input('Please enter a password: ')
if password != 'SecretPassword':
print 'You have entered invalid password {0} times.'.format(i + 1)
else:
print 'Access Granted'
return True
print 'Access Denied'
return False
You may also want to consider using the getpass module.
A:
I'm not against the "imperative" feel of loop/if, but I would separate your "business logic" from your "presentation":
count = 0
# Business logic
# The correct password and the maximum number of tries is placed here
DENIED, VALID, INVALID = range(3)
def verifyPassword(userPassword):
global count
count += 1
if count > 3:
return DENIED
elif password == 'SecretPassword':
return VALID
return INVALID
# Presentation
# Here you do the IO with the user
check = INVALID
while (check == INVALID):
password = raw_input('Please enter a password: ')
check = verifyPassword(password)
if check == INVALID:
print 'You have entered invalid password %i times.' % (count)
elif check == VALID:
print 'Access Granted'
else # check == DENIED
print 'Access Denied'
A:
granted = False # default condition should be the least dangerous
for count in range(3):
password = raw_input('Please enter a password: ')
if password == 'SecretPassword': # no need to test for wrong answer
granted = True
break
print 'You have entered invalid password %i times.' % (count+1) # else
if granted:
print 'Access Granted'
else:
print 'Access Denied'
A:
You can bring the if statement out of the while loop.
# Password Guessing Program
# Python 2.7
count = 0
access = False
while count < 3 and not access:
password = raw_input('Please enter a password: ')
if password != 'SecretPassword':
count += 1
print 'You have entered invalid password %i times.' % (count)
else:
access = True
if access:
print 'Access Granted'
else:
print 'Access Denied'
| Can I improve on the current Python code? | I am just starting out with Python and decided to try this little project from Python Wiki:
Write a password guessing program to keep track of how many times the user has entered the password wrong. If it is more than 3 times, print You have been denied access. and terminate the program. If the password is correct, print You have successfully logged in. and terminate the program.
Here's my code. It works but it just doesn't feel right with these loop breaks and nested if statements.
# Password Guessing Program
# Python 2.7
count = 0
while count < 3:
password = raw_input('Please enter a password: ')
if password != 'SecretPassword':
count = count + 1;
print 'You have entered invalid password %i times.' % (count)
if count == 3:
print 'Access Denied'
break
else:
print 'Access Granted'
break
| [
"You can replace your while loop with the following function:\ndef login():\n for i in range(3):\n password = raw_input('Please enter a password: ')\n if password != 'SecretPassword':\n print 'You have entered invalid password {0} times.'.format(i + 1)\n else:\n print '... | [
7,
3,
2,
0
] | [] | [] | [
"conditional",
"loops",
"python"
] | stackoverflow_0004110477_conditional_loops_python.txt |
Q:
Using pipes to redirect a function-generated SQL query to the psql command
I have a script that generates an SQL query as text e.g.
...
return "SELECT COUNT(*) FROM important_table"
which I would then like to run on a PostgreSQL database. I can do this in two lines like this:
python SQLgeneratingScript.py parameters > temp.sql
psql -f temp.sql -d my_database
But seems like I should be able to one-line it with pipes, but I don't know how.
A:
python SQLgeneratingScript.py parameters|psql -d my_database
A:
i don't know why you are not using a python postgresql connector like psycopg2 ,but well if you want to do what you are trying to do using Unix command redirection you will have to do it like this in your code
...
print "SELECT COUNT(*) FROM important_table" # or use sys.stdout.write()
this will write in your file temp.sql if you have ran your command like this:
python SQLgeneratingScript.py parameters > temp.sql
but well i will suggest writing in you file in python like this
def generate_sql():
...
return "SELECT COUNT(*) FROM important_table"
with open('temp.sql', 'w') as f
sql = generate_sql()
f.write(sql)
or more use psycopg2 to execute directly your sql
import psycopg2
def generate_sql():
...
return "SELECT COUNT(*) FROM important_table"
conn = psycopg2.connect("dbname= ...")
cur = conn.cursor()
sql = generate_sql()
cur.execute(sql)
conn.close()
| Using pipes to redirect a function-generated SQL query to the psql command | I have a script that generates an SQL query as text e.g.
...
return "SELECT COUNT(*) FROM important_table"
which I would then like to run on a PostgreSQL database. I can do this in two lines like this:
python SQLgeneratingScript.py parameters > temp.sql
psql -f temp.sql -d my_database
But seems like I should be able to one-line it with pipes, but I don't know how.
| [
"python SQLgeneratingScript.py parameters|psql -d my_database\n\n",
"i don't know why you are not using a python postgresql connector like psycopg2 ,but well if you want to do what you are trying to do using Unix command redirection you will have to do it like this in your code\n...\nprint \"SELECT COUNT(*) FROM ... | [
2,
0
] | [] | [] | [
"pipe",
"postgresql",
"python",
"sql"
] | stackoverflow_0004110511_pipe_postgresql_python_sql.txt |
Q:
Generic iterator over the values (instead of over the keys) of any iterable
Is there a generic way of getting an iterator that always iterates over the values (preferably, although it may work iterating the keys too) of either dictionaries or other iterables (lists, sets...)?
Let me elaborate: When you execute "iter(list)" you get an iterator over the values (not the indexes, which sound pretty similar to the "key" in the dictionary) but when you do "iter(dict)" you get the keys.
Is there an instruction, attribute... whatever... which always iterates over the values (or the keys) of an iterable, no matter what type of iterable it is?
I have a code with an "append" method that needs to accept several different types of iterable types, and the only solution I've been able to come up with is something like this:
#!/usr/bin/python2.4
class Sample(object):
def __init__(self):
self._myListOfStuff = list()
def addThings(self, thingsToAdd):
myIterator = None
if (isinstance(thingsToAdd, list) or
isinstance(thingsToAdd, set) or
isinstance(thingsToAdd, tuple)):
myIterator = iter(thingsToAdd)
elif isinstance(thingsToAdd, dict):
myIterator = thingsToAdd.itervalues()
if myIterator:
for element in myIterator:
self._myListOfStuff.append(element)
if __name__ == '__main__':
sample = Sample()
myList = list([1,2])
mySet = set([3,4])
myTuple = tuple([5,6])
myDict = dict(
a= 7,
b= 8
)
sample.addThings(myList)
sample.addThings(mySet)
sample.addThings(myTuple)
sample.addThings(myDict)
print sample._myListOfStuff
#Outputs [1, 2, 3, 4, 5, 6, 7, 8]
I don't know... It looks a little bit... clunky to me
It would be great to be able to get a common iterator for cases like this, so I could write something like...
def addThings(self, thingsToAdd):
for element in iter(thingsToAdd):
self._myListOfStuff.append(element)
... if the iterator always gave the values, or...
def addThings(self, thingsToAdd):
for element in iter(thingsToAdd):
self._myListOfStuff.append(thingsToAdd[element])
... if the iterator returned the keys (I know the concept of key in a set is kind of "special", that's why I would prefer iterating over the values but still... maybe it could return the hash of the stored value).
Is there such thing in Python? (I have to use Python2.4, by the way)
Thank you all in advance
A:
I don't know of anything built in that does this. I suppose you could do something like:
def itervalues(x):
if hasattr(x, 'itervalues'): return x.itervalues()
if hasattr(x, 'values'): return iter(x.values())
return iter(x)
A:
Most collections have no concept or "keys" or "values". They just store items, and iterating over them gives you those items. Only mappings (dict-likes) provide "keys" and "values". And the default way of iterating them uses the keys because for x in collection: assert x in collection should be an invariant (and a (key, value) in d rarely makes sense, as opposed to key in d). So there is no method to iterate over the values only, because the least collections have things called "values".
You can, however, choose to ignore the keys in mappings. Since you have to use Python 2.4, using ABCs is out of questions... I fear the simplest way would be:
def iter_values(it):
if hasattr(it, 'itervalues'):
return it.itervalues()
return iter(x)
Which can still break, but handles dicts and similar mappings.
A:
What you're looking for is the dict.items() method, which return (key, value) tuples.
Here is a usage example:
d = {'a': 1, 'b': 2, 'c': 3}
for k, v in d.items():
print "key:", k, "- value:", v
Which, as you can imagine, would output
key: a - value: 1
key: b - value: 2
key: c - value: 3
Edit: if you want to get a real iterator and not just a sequence, you can also use the dict.iteritems() method, which works the same way.
Edit2: seems i misunderstood your question, as you seem to ask for a generic function that would work with any iterable, forget my answer ;-)
| Generic iterator over the values (instead of over the keys) of any iterable | Is there a generic way of getting an iterator that always iterates over the values (preferably, although it may work iterating the keys too) of either dictionaries or other iterables (lists, sets...)?
Let me elaborate: When you execute "iter(list)" you get an iterator over the values (not the indexes, which sound pretty similar to the "key" in the dictionary) but when you do "iter(dict)" you get the keys.
Is there an instruction, attribute... whatever... which always iterates over the values (or the keys) of an iterable, no matter what type of iterable it is?
I have a code with an "append" method that needs to accept several different types of iterable types, and the only solution I've been able to come up with is something like this:
#!/usr/bin/python2.4
class Sample(object):
def __init__(self):
self._myListOfStuff = list()
def addThings(self, thingsToAdd):
myIterator = None
if (isinstance(thingsToAdd, list) or
isinstance(thingsToAdd, set) or
isinstance(thingsToAdd, tuple)):
myIterator = iter(thingsToAdd)
elif isinstance(thingsToAdd, dict):
myIterator = thingsToAdd.itervalues()
if myIterator:
for element in myIterator:
self._myListOfStuff.append(element)
if __name__ == '__main__':
sample = Sample()
myList = list([1,2])
mySet = set([3,4])
myTuple = tuple([5,6])
myDict = dict(
a= 7,
b= 8
)
sample.addThings(myList)
sample.addThings(mySet)
sample.addThings(myTuple)
sample.addThings(myDict)
print sample._myListOfStuff
#Outputs [1, 2, 3, 4, 5, 6, 7, 8]
I don't know... It looks a little bit... clunky to me
It would be great to be able to get a common iterator for cases like this, so I could write something like...
def addThings(self, thingsToAdd):
for element in iter(thingsToAdd):
self._myListOfStuff.append(element)
... if the iterator always gave the values, or...
def addThings(self, thingsToAdd):
for element in iter(thingsToAdd):
self._myListOfStuff.append(thingsToAdd[element])
... if the iterator returned the keys (I know the concept of key in a set is kind of "special", that's why I would prefer iterating over the values but still... maybe it could return the hash of the stored value).
Is there such thing in Python? (I have to use Python2.4, by the way)
Thank you all in advance
| [
"I don't know of anything built in that does this. I suppose you could do something like:\ndef itervalues(x):\n if hasattr(x, 'itervalues'): return x.itervalues()\n if hasattr(x, 'values'): return iter(x.values())\n return iter(x)\n\n",
"Most collections have no concept or \"keys\" or \"values\". They just sto... | [
3,
3,
0
] | [] | [] | [
"coding_style",
"iterator",
"python"
] | stackoverflow_0004110544_coding_style_iterator_python.txt |
Q:
Redirect print in Python: val = print(arg) to output mixed iterable to file
So lets say I have an incredibly nested iterable of lists/dictionaries. I would like to print them to a file as easily as possible. Why can't I just redirect print to a file?
val = print(arg)
gets a SyntaxError.
Is there a way to access stdinput?
And why does print take forever with massive strings? Bad programming on my side for outputting massive strings, but quick debugging--and isn't that leveraging the strength of an interactive prompt?
There's probably also an easier way than my gripe. Has the hive-mind an answer?
A:
You could look into the logging module of Python. Perhaps that's the perfect match in this case.
A:
Seeing how you're using print as function, docs say that you can redirect to file like this:
print(arg, file=open('fname', 'w'))
A:
In Python 3.*, to redirect one print call to an open file object destination,
print(arg, file=destination)
In Python 2.*, where print is a statement, the syntax is
print>>destination, arg
I imagine you're using 2.* because in 3.* assigning print's result is not a syntax error (it's just useless, since that result is None, but allowed). In 2.* print is a statement, not a function, so the code snippet you give is indeed a syntax error.
I'm not sure what the assignment is supposed to mean. If you want to redirect one or more print statements (or calls) to get the formatted result as an in-memory string, you can set sys.stdout to a StringIO (or cStringIO) instance; but you specifically mention "to a file" so I'm really perplexed as to the intended meaning of that assignment. Clarify pls?
A:
You don't typically use print for writing to a file (though you technically can). You would use a file object for this.
with open(filename, 'w') as f:
f.write(repr(your_thingy))
If print is taking forever to display a massive string, it is likely that it's not exactly print's fault, but the result of having to display all that to screen.
A:
I tried both examples with no success using python 2.7
To begin I created a file in C:\goat.text using notepad
Next I tried the following
import sys
print>>"C:\goat.txt", "test"
error
AttributeError: 'str' object has no attribute 'write'
print("test", file=open('C:\goat.txt', 'w'))
SyntaxError: ("no viable alternative at input '='", ('C:\Users\mike\AppData\Local\Temp\sikuli-tmp5165417708161227735.py', 3, 18, 'print("test", file=open(\'C:\\goat.txt\', \'w\')) \n'))
I've tried multiple variants annd can't solve this.
| Redirect print in Python: val = print(arg) to output mixed iterable to file | So lets say I have an incredibly nested iterable of lists/dictionaries. I would like to print them to a file as easily as possible. Why can't I just redirect print to a file?
val = print(arg)
gets a SyntaxError.
Is there a way to access stdinput?
And why does print take forever with massive strings? Bad programming on my side for outputting massive strings, but quick debugging--and isn't that leveraging the strength of an interactive prompt?
There's probably also an easier way than my gripe. Has the hive-mind an answer?
| [
"You could look into the logging module of Python. Perhaps that's the perfect match in this case.\n",
"Seeing how you're using print as function, docs say that you can redirect to file like this:\nprint(arg, file=open('fname', 'w'))\n\n",
"In Python 3.*, to redirect one print call to an open file object destina... | [
2,
1,
1,
1,
0
] | [] | [] | [
"dictionary",
"iterable",
"list",
"python"
] | stackoverflow_0002476931_dictionary_iterable_list_python.txt |
Q:
Python regex: string does not contain "jpg" and must have "-" and lowercase
I'm having troubles figuring out a python regex for django urls. I have a certain criteria, but can't seem to come up with the magic formula. In the end its so I can identify which page is a CMS page and pass to the django function the alias url it should load.
Here are some examples of valid strings which would match:
about-us
contact-us
terms-and-conditions
info/learn-more-pg2
info/my-example-url
Criteria:
Must be all lowercase
Must contain a dash "-"
Can contain numbers, letters and a slash "/"
Must be at least 4 characters long and a max of 30 characters
Cannot contain special characters
Cannot contain the words:
.jpg
.gif
.png
.css
.js
Examples which should not match:
About-Us (has upper case)
contactus (doesn't have a dash)
pg (less than 4 characters)
img/bg.gif (contains ".gif")
files/my-styles.css (contains ".css")
my-page@ (has a character other than letters, numbers, dash or slash)
I know this isn't even close yet, but this is as far as I've gotten:
(?P<alias>([a-z/-]{4,30}))
I apologize for having large requirements, but I just can't get my head wrapped around this regex stuff.
Thanks!
A:
I'm puzzled as to why several of the commentators find that this is hard to do in a regex. This is exactly what regular expressions are good at.
if re.match(
r"""^ # match start of the string
(?=.*-) # assert that there is a dash
(?!.*\.(?:jpg|gif|png|css|js)) # assert that these words can't be matched
[a-z0-9/-]{4,30} # match 4-30 of the allowed characters
$ # match the end of the string""",
subject, re.VERBOSE):
# Successful match at the start of the string
else:
# Match attempt failed
It is true however that since the . isn't among the allowed characters, the check for the forbidden file extensions is not really necessary.
A:
Here’s my first post on SO.
Pleeaaase, correct my english whenever it will be needed, I do ask you.
I think that any of the following REs fits right:
'(?=.{4,30}\Z)(?=.*-)[-a-z0-9/]+\Z'
'(?=.{4,30}\Z)[a-z0-9/]\*-[-a-z0-9/]\*\Z'
'(?=.{4,30}\Z)(?:[a-z0-9/]+|)-[-a-z0-9/]*\Z'
| Python regex: string does not contain "jpg" and must have "-" and lowercase | I'm having troubles figuring out a python regex for django urls. I have a certain criteria, but can't seem to come up with the magic formula. In the end its so I can identify which page is a CMS page and pass to the django function the alias url it should load.
Here are some examples of valid strings which would match:
about-us
contact-us
terms-and-conditions
info/learn-more-pg2
info/my-example-url
Criteria:
Must be all lowercase
Must contain a dash "-"
Can contain numbers, letters and a slash "/"
Must be at least 4 characters long and a max of 30 characters
Cannot contain special characters
Cannot contain the words:
.jpg
.gif
.png
.css
.js
Examples which should not match:
About-Us (has upper case)
contactus (doesn't have a dash)
pg (less than 4 characters)
img/bg.gif (contains ".gif")
files/my-styles.css (contains ".css")
my-page@ (has a character other than letters, numbers, dash or slash)
I know this isn't even close yet, but this is as far as I've gotten:
(?P<alias>([a-z/-]{4,30}))
I apologize for having large requirements, but I just can't get my head wrapped around this regex stuff.
Thanks!
| [
"I'm puzzled as to why several of the commentators find that this is hard to do in a regex. This is exactly what regular expressions are good at.\nif re.match(\n r\"\"\"^ # match start of the string\n (?=.*-) # assert that there is a dash\n (?!.*\\.(?:jpg|gif|png|css|js)) # assert th... | [
9,
0
] | [] | [] | [
"django",
"django_urls",
"python",
"regex"
] | stackoverflow_0004109088_django_django_urls_python_regex.txt |
Q:
Using RPC over email?
Can someone tell me how they have done this in some form, be it XML-RPC, SOAP, bespoke etc. Not too worried on the packet format.
I am interested in doing some sort of RPC over email, setting up a program to receive commands via email from another application(s) or even from users on a subscription list. Basically the idea is you give someone the email address and then send messages to active commands, and the response is back in email. A good example of where I would be taking this is maybe a chess program, where time is irrelevant but delivery is everything and sequential ordering of moves is a given.
I would be most interested in the experiences of others, especially with the nature of email and any idiosyncratic behaviour that I should be aware of.
I have quite a bit of experience of RPC over Message Queues and asynchronous delivery, but would like to come up with a solution where I shift the communications on to hotmail or gmail, freeing up my servers and the headache of the asynchronous intercoms.
A:
You could use fetchmail like this:
#!/bin/bash
while sleep 1
do
fetchmail --idle --mda python program_that_accepts_email_with_headers_on_stdin.py
done
Then Your program can do various things from querying database, through using some http services, to sending an email to someone. The way it works is first it sleeps for a second, then it checks the email box according to settings You need to place in ~/.fetchmailrc (read man fetchmail for info on how to do that). If it finds any email, it invokes Your program, if not and the loop goes back to the start point. If it doesn't find any emails, it waits until an email will arrive (or the mail server will restart).
The bottom line is that if the said system is not heavily loaded, it will almost instantly react to emails (usually You send an email with command, wait 3 seconds and You have a reply in Your inbox).
NOTE: halting (--idle) only works with IMAP servers. With pop servers You could do the same but sleep 10 seconds instead of 1. Sleeping for 1 second is good because Your program may be ultra-fast and may create an infinite loop with other program (f.e. mailer daemon saying someone is on vacation) and usually it would be good to at least limit their looping frenzy to 1 email/second. I learned it the hard way :) Sleeping will be bad if You would like to process more than 1 email/second. If so, switch sleep 1 to true.
A:
I'm already doing this with Google AppEngine and Python. It's really simple.
In your app.yaml file you need to setup that you will using the email service and you file to manage them:
application: appname
version: 1
runtime: python
api_version: 1
handlers:
- url: /_ah/mail/.+
script: mail.py
login: admin
inbound_services:
- mail
Then create a mail.py file with something like this:
#!/usr/bin/env python
import rfc822
import logging
from google.appengine.ext import db
from google.appengine.ext import webapp
from google.appengine.ext.webapp.mail_handlers import InboundMailHandler
from google.appengine.ext.webapp.util import run_wsgi_app
class LogSenderHandler(InboundMailHandler):
def receive(self, message):
service_name, service_email = rfc822.parseaddr(message.to)
service_request = service_email.split('@').pop(0)
sender_name, sender_email = rfc822.parseaddr(message.sender)
logging.info('Service `%s` activated by `%s`.' % (service_request, sender_email))
if __name__ == '__main__':
application = webapp.WSGIApplication(
[LogSenderHandler.mapping()])
run_wsgi_app(application)
All you need to do is send an email to servicename@appname.appspotmail.com. Voila!
| Using RPC over email? | Can someone tell me how they have done this in some form, be it XML-RPC, SOAP, bespoke etc. Not too worried on the packet format.
I am interested in doing some sort of RPC over email, setting up a program to receive commands via email from another application(s) or even from users on a subscription list. Basically the idea is you give someone the email address and then send messages to active commands, and the response is back in email. A good example of where I would be taking this is maybe a chess program, where time is irrelevant but delivery is everything and sequential ordering of moves is a given.
I would be most interested in the experiences of others, especially with the nature of email and any idiosyncratic behaviour that I should be aware of.
I have quite a bit of experience of RPC over Message Queues and asynchronous delivery, but would like to come up with a solution where I shift the communications on to hotmail or gmail, freeing up my servers and the headache of the asynchronous intercoms.
| [
"You could use fetchmail like this:\n#!/bin/bash\nwhile sleep 1\ndo\n fetchmail --idle --mda python program_that_accepts_email_with_headers_on_stdin.py\ndone\n\nThen Your program can do various things from querying database, through using some http services, to sending an email to someone. The way it works is fi... | [
2,
2
] | [] | [] | [
"asynchronous",
"email",
"python",
"web_services"
] | stackoverflow_0004066513_asynchronous_email_python_web_services.txt |
Q:
how to use python xml.etree.ElementTree to parse eBay API response?
I am trying to use xml.etree.ElementTree to parse responses from eBay finding API, findItemsByProduct. After lengthy trial and error, I came up with this code which prints some data:
import urllib
from xml.etree import ElementTree as ET
appID = 'xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx'
isbn = '3868731342'
namespace = '{http://www.ebay.com/marketplace/search/v1/services}'
url = 'http://svcs.ebay.com/services/search/FindingService/v1?' \
+ 'OPERATION-NAME=findItemsByProduct' \
+ '&SERVICE-VERSION=1.0.0' \
+ '&GLOBAL-ID=EBAY-DE' \
+ '&SECURITY-APPNAME=' + appID \
+ '&RESPONSE-DATA-FORMAT=XML' \
+ '&REST-PAYLOAD' \
+ '&productId.@type=ISBN&productId=' + isbn
root = ET.parse(urllib.urlopen(url)).getroot()
for parts in root:
if parts.tag == (namespace + 'searchResult'):
for item in list(parts):
for a in list(item):
if a.tag == (namespace + 'itemId'):
print 'itemId: ' + a.text
if a.tag == (namespace + 'title'):
print 'title: ' + a.text
But that seems not very elegant, how can I get the 'itemId' and 'title' without looping over all attributes and checking if it is the one I want? I tried using things like .get(namespace + 'itemId') and .find(namespace + 'itemId') and .attrib.get(namespace + 'itemId') but nothing really worked.
Can someone maybe show me how to do this using some python wrapper for this API?
I saw easyBay, ebay-sdk-python and pyeBay but I didn't manage to get any of them to do what I want. Is there any eBay python API which is worthwhile to use for this?
A:
You can use ElementTree. If you want to get the items you can use findall and the path to the items, then iterate over the list of items:
items = root.findall(namespace+'searchResult/'+namespace+'item')
for item in items:
item.find(namespace+'itemId').text
item.find(namespace+'title').text
To get directly to the first itemId from the root:
root.find(namespace+'searchResult/'+namespace+'item/'+namespace+'itemId')
Basically, the find method uses XPath to retrieve elements more than one level below the subelements. See also Effbot's explanation of XPath support in ElementTree
| how to use python xml.etree.ElementTree to parse eBay API response? | I am trying to use xml.etree.ElementTree to parse responses from eBay finding API, findItemsByProduct. After lengthy trial and error, I came up with this code which prints some data:
import urllib
from xml.etree import ElementTree as ET
appID = 'xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx'
isbn = '3868731342'
namespace = '{http://www.ebay.com/marketplace/search/v1/services}'
url = 'http://svcs.ebay.com/services/search/FindingService/v1?' \
+ 'OPERATION-NAME=findItemsByProduct' \
+ '&SERVICE-VERSION=1.0.0' \
+ '&GLOBAL-ID=EBAY-DE' \
+ '&SECURITY-APPNAME=' + appID \
+ '&RESPONSE-DATA-FORMAT=XML' \
+ '&REST-PAYLOAD' \
+ '&productId.@type=ISBN&productId=' + isbn
root = ET.parse(urllib.urlopen(url)).getroot()
for parts in root:
if parts.tag == (namespace + 'searchResult'):
for item in list(parts):
for a in list(item):
if a.tag == (namespace + 'itemId'):
print 'itemId: ' + a.text
if a.tag == (namespace + 'title'):
print 'title: ' + a.text
But that seems not very elegant, how can I get the 'itemId' and 'title' without looping over all attributes and checking if it is the one I want? I tried using things like .get(namespace + 'itemId') and .find(namespace + 'itemId') and .attrib.get(namespace + 'itemId') but nothing really worked.
Can someone maybe show me how to do this using some python wrapper for this API?
I saw easyBay, ebay-sdk-python and pyeBay but I didn't manage to get any of them to do what I want. Is there any eBay python API which is worthwhile to use for this?
| [
"You can use ElementTree. If you want to get the items you can use findall and the path to the items, then iterate over the list of items:\nitems = root.findall(namespace+'searchResult/'+namespace+'item')\nfor item in items: \n item.find(namespace+'itemId').text\n item.find(namespace+'title').text\n\nTo get... | [
4
] | [] | [] | [
"ebay_api",
"python",
"xml",
"xmlhttprequest"
] | stackoverflow_0004110440_ebay_api_python_xml_xmlhttprequest.txt |
Q:
Parse a datetime string from amazon mechanical turk to django orm
Mechanical turk provides strings like this:
'Wed Nov 03 17:14:17 PDT 2010'
Django datetime model fields require
YYYY-MM-DD HH:MM[:ss[.uuuuuu]]
What's the right way to take in the 1st string and create the 2nd?
A:
t = time.strptime("Wed Nov 03 17:14:17 PDT 2010", "%a %b %d %H:%M:%S %Z %Y")
time.strftime("%Y-%m-%d %H:%M:%S", t)
A:
Sounds like a job for time.strptime() and time.strftime() !
| Parse a datetime string from amazon mechanical turk to django orm | Mechanical turk provides strings like this:
'Wed Nov 03 17:14:17 PDT 2010'
Django datetime model fields require
YYYY-MM-DD HH:MM[:ss[.uuuuuu]]
What's the right way to take in the 1st string and create the 2nd?
| [
"t = time.strptime(\"Wed Nov 03 17:14:17 PDT 2010\", \"%a %b %d %H:%M:%S %Z %Y\") \ntime.strftime(\"%Y-%m-%d %H:%M:%S\", t)\n\n",
"Sounds like a job for time.strptime() and time.strftime() !\n"
] | [
3,
0
] | [] | [] | [
"datetime",
"django_models",
"mechanicalturk",
"python"
] | stackoverflow_0004110725_datetime_django_models_mechanicalturk_python.txt |
Q:
How do I use Python 3.1.2 in Textmate?
TextMate 1.5.9 seems to use Python 2.6.1. How do you configure it to use 3.1 instead? I've already installed the 3.1 package and I can use IDLE for interactive sessions, but I want to use TextMate now. I've already seen the post that directs you to define a project variable (TM_PYTHON : interpreter path). I tried this, but when i use Cmd+r to run a script in Textmate I still see Python 2.6.1 as the version number (top/right). Even the Terminal uses 2.7!
Help!
A:
I assume you are referring to this post. It should work but make sure you are using the right path to the Python 3.1 you installed. Check with:
$ which python3
/usr/local/bin/python3
If you used the python.org 3.1 installer, it should be available at /usr/local/bin/python3. Other methods may vary, for instance, the MacPorts python3.1 would normally be at /opt/local/bin/python3.
UPDATE: Since you indicate that it still doesn't work for you, my guess is that we are using different versions of TextMate's Python bundle. Using the TextMate Bundle Editor (menu item Bundles -> Bundle Editor -> Show Bundle Editor) then selecting the Python bundle's Run Script command, I see the following command snippet:
#!/usr/bin/env ruby
require ENV["TM_SUPPORT_PATH"] + "/lib/tm/executor"
require ENV["TM_SUPPORT_PATH"] + "/lib/tm/save_current_document"
TextMate.save_current_document
TextMate::Executor.make_project_master_current_document
ENV["PYTHONPATH"] = ENV["TM_BUNDLE_SUPPORT"] + (ENV.has_key?("PYTHONPATH") ? ":" + ENV["PYTHONPATH"] : "")
is_test_script = ENV["TM_FILEPATH"] =~ /(?:\b|_)(?:test)(?:\b|_)/ or
File.read(ENV["TM_FILEPATH"]) =~ /\bimport\b.+(?:unittest)/
TextMate::Executor.run(ENV["TM_PYTHON"] || "python", "-u", ENV["TM_FILEPATH"]) do |str, type|
if is_test_script and type == :err
if str =~ /\A[\.F]*\Z/
str.gsub!(/(\.|F)/, "<span class=\"test ok\">\\1</span>")
str + "<br/>\n"
elsif str =~ /\A(FAILED.*)\Z/
"<div class=\"test fail\">#{htmlize $1}</div>\n"
elsif str =~ /\A(OK.*)\Z/
"<div class=\"test ok\">#{htmlize $1}</div>\n"
elsif str =~ /^(\s+)File "(.+)", line (\d+), in (.*)/
indent = $1
file = $2
line = $3
method = $4
indent += " " if file.sub!(/^\"(.*)\"/,"\1")
url = "&url=file://" + e_url(file)
display_name = ENV["TM_DISPLAYNAME"]
"#{htmlize(indent)}<a class=\"near\" href=\"txmt://open?line=#{line + url}\">" +
(method ? "method #{CGI::escapeHTML method}" : "<em>at top level</em>") +
"</a> in <strong>#{CGI::escapeHTML display_name}</strong> at line #{line}<br/>\n"
end
end
end
Check and see if you have the same. If not, you should consider updating TextMate and/or the bundle. The GetBundle bundle makes it easy to keep bundles up-to-date as described here.
A:
#! /usr/bin/python
Take away this normal she bang from your script then run it you will then have version 3 show up in textmates window. The default shebang overrides the variable and sends you back to osx default version 2.6.1. It is all a bit weird....
| How do I use Python 3.1.2 in Textmate? | TextMate 1.5.9 seems to use Python 2.6.1. How do you configure it to use 3.1 instead? I've already installed the 3.1 package and I can use IDLE for interactive sessions, but I want to use TextMate now. I've already seen the post that directs you to define a project variable (TM_PYTHON : interpreter path). I tried this, but when i use Cmd+r to run a script in Textmate I still see Python 2.6.1 as the version number (top/right). Even the Terminal uses 2.7!
Help!
| [
"I assume you are referring to this post. It should work but make sure you are using the right path to the Python 3.1 you installed. Check with:\n$ which python3\n/usr/local/bin/python3\n\nIf you used the python.org 3.1 installer, it should be available at /usr/local/bin/python3. Other methods may vary, for inst... | [
1,
1
] | [] | [] | [
"python",
"textmate"
] | stackoverflow_0003581802_python_textmate.txt |
Q:
Enable python support while installing opencv using mac ports
I installed opencv in my mac using mac ports by the following command
sudo port install opencv
It took around 2 hours and it installed properly. But the problem is that the python bindings are not enabled.
So please let me know how to install opencv in mac using ports and also enable the python bindings. Thanks
PS: I tried to manually compile opencv from source but I am getting lot of errors and I am not able to do it.
A:
be sure to have py26-numpy installed to have support for basic functions such as cv.fromarray :
sudo port install py26-numpy
opencv will compile silently without numpy (it's not strictly a dependency).
sudo port install -v opencv +python26
there you can check that the binding to numpy is effective.
A:
It's possible to compile opencv using cmake on macos (I'm actually doing this) but there is a problem with the videoWriter ...
Have a look there http://www.tsd.net.au/blog/opencv-python-bindings-macports
should be helpful.
A:
I am still not able to compile opencv properly. At last, I found some pre-compiled dmg files from http://vislab.cs.vt.edu/~vislab/wiki/index.php?title=Vision which is working pretty decently.
| Enable python support while installing opencv using mac ports | I installed opencv in my mac using mac ports by the following command
sudo port install opencv
It took around 2 hours and it installed properly. But the problem is that the python bindings are not enabled.
So please let me know how to install opencv in mac using ports and also enable the python bindings. Thanks
PS: I tried to manually compile opencv from source but I am getting lot of errors and I am not able to do it.
| [
"be sure to have py26-numpy installed to have support for basic functions such as cv.fromarray :\nsudo port install py26-numpy\n\nopencv will compile silently without numpy (it's not strictly a dependency).\nsudo port install -v opencv +python26\n\nthere you can check that the binding to numpy is effective.\n",
"... | [
2,
0,
0
] | [] | [] | [
"macos",
"macports",
"opencv",
"python"
] | stackoverflow_0003184128_macos_macports_opencv_python.txt |
Q:
Flex Regular Expression Conversion Help
I'm having a problem converting a regular expression from Python into Flex. My string is something like this:
SELECT "col", othercol,\n "othercol3" FROM doesn'tmatter...
Python matches just fine:
>>> re.search('select(.*?)from', 'SELECT "col", othercol,\n "othercol3" FROM doesn\'tmatter...', re.DOTALL|re.IGNORECASE).groups()[0]
' "col", othercol,\n "othercol3" '
But when I try it in Flex:
var pattern:RegExp = /select(.*?)from/ig;
var match:Array = pattern.exec('SELECT "col", othercol,\n "othercol3" FROM doesn\'tmatter...');
trace(match);
match always ends up null. What am I doing wrong? I'm sure it's obvious to a seasoned Flex programmer...
A:
Try one of the many Flex regular expression testers out there:
http://www.idsklijnsma.nl/regexps/
For one thing, you're using dotall, etc., so you might want to know that Flex use the "s" flag for that. And the "x" flag ignores whitespace, etc. For example,
pattern:RegExp = /select.+?from/gis;
works for me on your example.
| Flex Regular Expression Conversion Help | I'm having a problem converting a regular expression from Python into Flex. My string is something like this:
SELECT "col", othercol,\n "othercol3" FROM doesn'tmatter...
Python matches just fine:
>>> re.search('select(.*?)from', 'SELECT "col", othercol,\n "othercol3" FROM doesn\'tmatter...', re.DOTALL|re.IGNORECASE).groups()[0]
' "col", othercol,\n "othercol3" '
But when I try it in Flex:
var pattern:RegExp = /select(.*?)from/ig;
var match:Array = pattern.exec('SELECT "col", othercol,\n "othercol3" FROM doesn\'tmatter...');
trace(match);
match always ends up null. What am I doing wrong? I'm sure it's obvious to a seasoned Flex programmer...
| [
"Try one of the many Flex regular expression testers out there:\nhttp://www.idsklijnsma.nl/regexps/\nFor one thing, you're using dotall, etc., so you might want to know that Flex use the \"s\" flag for that. And the \"x\" flag ignores whitespace, etc. For example,\npattern:RegExp = /select.+?from/gis;\nworks for me... | [
0
] | [] | [] | [
"apache_flex",
"python",
"regex"
] | stackoverflow_0004111096_apache_flex_python_regex.txt |
Q:
Python how to iterate through a list and compare lists of strings found within
If I have a nested list that looks like this:
bigstringlist = [['rob', 'bob', 'sam', 'angie'], ['jim', 'angie', 'tom', 'sam'], ['sam', 'mary', 'angie', 'sally']]
How do I iterate through this list and extract a list of names that appear in all the nested lists? i.e.:
finallist = ['sam', 'angie']
Would this be better accomplished by typecasting this nested list as a set?
A:
reduce(set.intersection, map(set , bigstringlist))
A:
A variation on singularity's solution, maybe a little faster:
bigstringiter = iter(bigstringlist)
reduce(set.intersection, bigstringiter, set(next(bigstringiter)))
| Python how to iterate through a list and compare lists of strings found within | If I have a nested list that looks like this:
bigstringlist = [['rob', 'bob', 'sam', 'angie'], ['jim', 'angie', 'tom', 'sam'], ['sam', 'mary', 'angie', 'sally']]
How do I iterate through this list and extract a list of names that appear in all the nested lists? i.e.:
finallist = ['sam', 'angie']
Would this be better accomplished by typecasting this nested list as a set?
| [
"reduce(set.intersection, map(set , bigstringlist))\n\n",
"A variation on singularity's solution, maybe a little faster:\nbigstringiter = iter(bigstringlist)\nreduce(set.intersection, bigstringiter, set(next(bigstringiter)))\n\n"
] | [
11,
0
] | [] | [] | [
"iteration",
"nested_lists",
"python"
] | stackoverflow_0004111129_iteration_nested_lists_python.txt |
Q:
Python Eclipse type casting intellisense work-around
Say I have the following two classes.
class TopClass:
def __init__(self):
self.items = []
class ItemClass:
def __init__(self):
self.name = None
And I want to use that in the following way:
def do_something():
myTop = TopClass()
# create two items
item1 = ItemClass()
item1.name = "Tony"
item2 = ItemClass()
item2.name = "Mike"
# add these to top class
myTop.items.append(item1)
myTop.items.append(item2)
# up until this point, access class members is effortless as the
# IDE (Eclipse) automatically recognizes the type of the object
# and can interpret the correct member variables. -- Awesome!
# now let's try and do a for loop
for myItem in myTop.items:
myItem.name # <- I HAD TO TYPE the ".name" IN MANUALLY,
# THIS IS ANNOYING, I could have misspelled
# something and not found out until
# I actually ran the script.
# Hacky way of making this easier
myItemT = ItemClass()
for myItemT in myTop.items:
myItemT.name = "bob" # <- Woah, it automatically filled in the
# ".name" part. This is nice, but I have the
# dummy line just above that is serving absolutely
# no purpose other than giving the
# Eclipse intellisense input.
Any opinions on the above? Is there a better way of making this work?
A:
I could have misspelled something and not found out until I actually ran the script.
Short-sighted and false.
You could have misspelled something and never found out until you endured a lawsuit because you did no unit testing.
"actually ran the script" is not the time when you learn if you did it right.
Typing code with or without Eclipse intellisense is not when you find the problems.
Running the script is not when you find the problems.
Unit testing is when you find the problems.
Please stop relying on Eclipse intellisense. Please start unit testing.
A:
IntelliSense just can't know what you want it to know. Think of this code:
class Foo(object):
def __init__(self):
self.name = None
class Bar(object):
def __init__(self):
self.blub = None
bar1 = Bar()
bar2 = Bar()
bar1.blub = 'joe'
bar2.blub = 'jim'
items = [bar1, bar2]
each = Foo()
for each in items:
each.name = 'Wha?' # here Eclipse also filled in the name attribute,
# although each is never a Foo in this loop.
# And funny, this is perfectly valid Python.
# All items now have a name attribute, despite being Bars.
A:
Issue 1: You could pass arguments to __init__
class ItemClass:
def __init__(self, name):
self.name = name
item1 = ItemClass("tony") # this is better
Issue 2: Make editor work for you and not structure your code for editor.
myItemT = ItemClass() # this is misleading !!
# myItemT here is not same as above. What is some one changes this to x?
for myItemT in myTop.items:
.....
This can cause an issue later on due to different mistake and editor will not help you there.
myItemT = ItemClass()
for myItemT in myTop.items:
do_something_with myItemT ...
# an indentation mistake
# This myItemT refers to the one outside for block
do_anotherthing_with myItemT ...
| Python Eclipse type casting intellisense work-around | Say I have the following two classes.
class TopClass:
def __init__(self):
self.items = []
class ItemClass:
def __init__(self):
self.name = None
And I want to use that in the following way:
def do_something():
myTop = TopClass()
# create two items
item1 = ItemClass()
item1.name = "Tony"
item2 = ItemClass()
item2.name = "Mike"
# add these to top class
myTop.items.append(item1)
myTop.items.append(item2)
# up until this point, access class members is effortless as the
# IDE (Eclipse) automatically recognizes the type of the object
# and can interpret the correct member variables. -- Awesome!
# now let's try and do a for loop
for myItem in myTop.items:
myItem.name # <- I HAD TO TYPE the ".name" IN MANUALLY,
# THIS IS ANNOYING, I could have misspelled
# something and not found out until
# I actually ran the script.
# Hacky way of making this easier
myItemT = ItemClass()
for myItemT in myTop.items:
myItemT.name = "bob" # <- Woah, it automatically filled in the
# ".name" part. This is nice, but I have the
# dummy line just above that is serving absolutely
# no purpose other than giving the
# Eclipse intellisense input.
Any opinions on the above? Is there a better way of making this work?
| [
"\nI could have misspelled something and not found out until I actually ran the script.\n\nShort-sighted and false.\nYou could have misspelled something and never found out until you endured a lawsuit because you did no unit testing.\n\"actually ran the script\" is not the time when you learn if you did it right.\n... | [
1,
1,
0
] | [] | [] | [
"eclipse",
"instance_variables",
"intellisense",
"python"
] | stackoverflow_0004110975_eclipse_instance_variables_intellisense_python.txt |
Q:
c system() return from python script - confusing!
I need to call through to a python script from C and be able to catch return values from it. it doesn't particularly matter what the values are, they may as well be an enum, but the values I got out of a test case confused me, and I wanted to get to the bottom of what I was seeing.
So, here is the C:
#include <stdlib.h>
#include <stdio.h>
int main(void)
{
int out = 0;
out = system("python /1.py");
printf("script 1 returned %d\n", out);
return 0;
}
and here is /1.py :
import sys
sys.exit(1)
The output of these programs is this:
script 1 returned 256
some other values:
2 -> 512
800 -> 8192
8073784 -> 14336
Assuming that it is...reading in little rather than big endian, or something? how can I write a c function (or trick python in)to correctly returning and interpret the numbers?
A:
From the Linux documentation on system():
... return status is in the format specified in wait(2). Thus, the exit code of the command will be WEXITSTATUS(status) ...
From following the link on wait, we get the following:
WEXITSTATUS(status): returns the exit status of the child. ... This macro should only be employed if WIFEXITED returned true.
What this amounts to is that you can't use the return value of system() directly, but must use macros to manipulate them. And, since this is conforming to the C standard and not just the Linux implementation, you will need to use the same procedure for any operating environment that you are using.
A:
The system() call return value is in the format specified by waitpid(). The termination status is not as defined for the sh utility. I can't recall but it works something like:
int exit_value, signal_num, dumped_core;
...
exit_value = out >> 8;
signal_num = out & 127;
dumped_core = out & 128;
| c system() return from python script - confusing! | I need to call through to a python script from C and be able to catch return values from it. it doesn't particularly matter what the values are, they may as well be an enum, but the values I got out of a test case confused me, and I wanted to get to the bottom of what I was seeing.
So, here is the C:
#include <stdlib.h>
#include <stdio.h>
int main(void)
{
int out = 0;
out = system("python /1.py");
printf("script 1 returned %d\n", out);
return 0;
}
and here is /1.py :
import sys
sys.exit(1)
The output of these programs is this:
script 1 returned 256
some other values:
2 -> 512
800 -> 8192
8073784 -> 14336
Assuming that it is...reading in little rather than big endian, or something? how can I write a c function (or trick python in)to correctly returning and interpret the numbers?
| [
"From the Linux documentation on system():\n\n... return status is in the format specified in wait(2). Thus, the exit code of the command will be WEXITSTATUS(status) ...\n\nFrom following the link on wait, we get the following:\n\nWEXITSTATUS(status): returns the exit status of the child. ... This macro should only... | [
2,
1
] | [] | [] | [
"c",
"python",
"return_value"
] | stackoverflow_0004111279_c_python_return_value.txt |
Q:
Python/Tkinter: Building a toolbar that provides edit cut, copy, paste commands
I'm looking for suggestions on how one might implement a toolbar that provides edit cut, copy, paste commands using the Tkinter framework. I understand how to build a toolbar and bind the toolbar commands, but I'm confused over how the toolbar button bound commands will know which widget to apply the cut, copy, or paste action because the widget with edit activity will lose focus when the toolbar button is clicked. My first thought was to have each widget with potential edit activity set a global variable when the widget gains focus and have other widgets (without edit activity, eg. buttons, sliders, checkbox/radiobox, etc) clear this global variable. But this sounds complicated to maintain unless I build a framework of widgets that inherit this behavior.
Is there a simpler way to go about this or am I on the right track?
A:
You don't have to maintain a big framework, you can create a single binding on the root widget for <FocusIn> and put all the logic in that binding. Or, use focus_class and bind to the class all.
Binding on the root will only affect children of the root, binding to all will affect all widgets in the entire app. That only matters if you have more than one toplevel widget.
A:
You can tell the toolbar buttons to not take the focus; it's a configuration option and no UI guidelines I've ever seen have had toolbar buttons with focus. (Instead, the functionality is always available through some other keyboard-activatable mechanism, e.g., a hotkey combo.)
| Python/Tkinter: Building a toolbar that provides edit cut, copy, paste commands | I'm looking for suggestions on how one might implement a toolbar that provides edit cut, copy, paste commands using the Tkinter framework. I understand how to build a toolbar and bind the toolbar commands, but I'm confused over how the toolbar button bound commands will know which widget to apply the cut, copy, or paste action because the widget with edit activity will lose focus when the toolbar button is clicked. My first thought was to have each widget with potential edit activity set a global variable when the widget gains focus and have other widgets (without edit activity, eg. buttons, sliders, checkbox/radiobox, etc) clear this global variable. But this sounds complicated to maintain unless I build a framework of widgets that inherit this behavior.
Is there a simpler way to go about this or am I on the right track?
| [
"You don't have to maintain a big framework, you can create a single binding on the root widget for <FocusIn> and put all the logic in that binding. Or, use focus_class and bind to the class all. \nBinding on the root will only affect children of the root, binding to all will affect all widgets in the entire app. ... | [
2,
1
] | [] | [] | [
"clipboard",
"python",
"tkinter",
"toolbar"
] | stackoverflow_0004111049_clipboard_python_tkinter_toolbar.txt |
Q:
How to explore a package in python
import pkg
dir(pkg)
such a statement in python won't show all the classes / functions / subpackages in the package pkg because some of them might be loaded just in time.So what is the best way to explore a package in python?
A:
Have you try pydoc
pydoc package
Is the same as calling the help function but you can do it from the command line,
and of course you can browse to a module, class or function level with the dot notation.
A:
You can use help(pkg), or obviously doc if it's available.
A:
Read the source, read the module docs.
| How to explore a package in python | import pkg
dir(pkg)
such a statement in python won't show all the classes / functions / subpackages in the package pkg because some of them might be loaded just in time.So what is the best way to explore a package in python?
| [
"Have you try pydoc\n\npydoc package\n\nIs the same as calling the help function but you can do it from the command line,\nand of course you can browse to a module, class or function level with the dot notation.\n",
"You can use help(pkg), or obviously doc if it's available.\n",
"Read the source, read the modu... | [
4,
2,
2
] | [] | [] | [
"python"
] | stackoverflow_0004110849_python.txt |
Q:
Python Struct, size changed by alignment.
Here's the hex code I am trying to unpack.
b'ABCDFGHa\x00a\x00a\x00a\x00a\x00\x00\x00\x00\x00\x00\x01' (it's not supposed to make any sense)
labels = unpack('BBBBBBBHHHHH5sB', msg)
struct.error: unpack requires a bytes argument of length 24
From what I counted, both of those are length = 23, both the format in my unpack function and the length of the hex values. I don't understand.
Thanks in advance
A:
Most processors access data faster when the data is on natural boundaries, meaning data of size 2 should be on even addresses, data of size 4 should be accessed on addresses divisible by four, etc.
struct by default maintains this alignment. Since your structure starts out with 7 'B', a padding byte is added to align the next 'H' on an even address. To prevent this in Python, precede your string with '='.
Example:
>>> import struct
>>> struct.calcsize('BBB')
3
>>> struct.calcsize('BBBH')
6
>>> struct.calcsize('=BBBH')
5
A:
I think H is enforcing 2-byte alignment after your 7 B
Aha, the alignment info is at the top of http://docs.python.org/library/struct.html, not down by the definition of the format characters.
| Python Struct, size changed by alignment. | Here's the hex code I am trying to unpack.
b'ABCDFGHa\x00a\x00a\x00a\x00a\x00\x00\x00\x00\x00\x00\x01' (it's not supposed to make any sense)
labels = unpack('BBBBBBBHHHHH5sB', msg)
struct.error: unpack requires a bytes argument of length 24
From what I counted, both of those are length = 23, both the format in my unpack function and the length of the hex values. I don't understand.
Thanks in advance
| [
"Most processors access data faster when the data is on natural boundaries, meaning data of size 2 should be on even addresses, data of size 4 should be accessed on addresses divisible by four, etc.\nstruct by default maintains this alignment. Since your structure starts out with 7 'B', a padding byte is added to ... | [
5,
3
] | [] | [] | [
"python",
"struct"
] | stackoverflow_0004110378_python_struct.txt |
Q:
Python: conditionally delete elements from list
Suppose I have a list of tuples:
x = [(1,2), (3,4), (7,4), (5,4)]
Of all tuples that share the second element, I want to preserve the tuple with the largest first element:
y = [(1,2), (7,4)]
What is the best way to achieve this in Python?
Thanks for the answers.
The tuples could be two-element lists instead, if that makes a difference.
All elements are nonnegative integers.
I like the current answers. I should really learn more about what collections has to offer!
A:
use collections.defaultdict
import collections
max_elements = collections.defaultdict(tuple)
for item in x:
if item > max_elements[item[1]]:
max_elements[item[1]] = item
y = max_elements.values()
A:
Similar to Aaron's answer
>>> from collections import defaultdict
>>> x = [(1,2), (3,4), (7,4), (5,4)]
>>> d = defaultdict(int)
>>> for v,k in x:
... d[k] = max(d[k],v)
...
>>> y=[(k,v) for v,k in d.items()]
>>> y
[(1, 2), (7, 4)]
note that the order is not preserved with this method. To preserve the order use this instead
>>> y = [(k,v) for k,v in x if d[v]==k]
>>> y
[(1, 2), (7, 4)]
here is another way. It uses more storage, but has less calls to max, so it may be faster
>>> d = defaultdict(list)
>>> for k,v in x:
... d[v].append(k)
...
>>> y = [(max(k),v) for v,k in d.items()]
>>> y
[(1, 2), (7, 4)]
Again, a simple modification preserves the order
>>> y = [(k,v) for k,v in x if max(d[v])==k]
>>> y
[(1, 2), (7, 4)]
A:
If you can make the assumption that tuples with identical second elements appear in contiguous order in the original list x, you can leverage itertools.groupby:
import itertools
import operator
def max_first_elem(x):
groups = itertools.groupby(x, operator.itemgetter(1))
y = [max(g[1]) for g in groups]
return y
Note that this will guarantee preservation of the order of the groups (by the second tuple element), if that is a desired constraint for the output.
A:
My own attempt, slightly inspired by aaronsterling:
(oh yeah, all elements are nonnegative)
def processtuples(x):
d = {}
for item in x:
if x[0] > d.get(x[1],-1):
d[x[1]] = x[0]
y = []
for k in d:
y.append((d[k],k))
y.sort()
return y
A:
>>> from collections import defaultdict
>>> d = defaultdict(tuple)
>>> x = [(1,2), (3,4), (7,4), (5,4)]
>>> for a, b in x:
... d[b] = max(d[b], (a, b))
...
>>> d.values()
[(1, 2), (7, 4)
| Python: conditionally delete elements from list | Suppose I have a list of tuples:
x = [(1,2), (3,4), (7,4), (5,4)]
Of all tuples that share the second element, I want to preserve the tuple with the largest first element:
y = [(1,2), (7,4)]
What is the best way to achieve this in Python?
Thanks for the answers.
The tuples could be two-element lists instead, if that makes a difference.
All elements are nonnegative integers.
I like the current answers. I should really learn more about what collections has to offer!
| [
"use collections.defaultdict\nimport collections\n\nmax_elements = collections.defaultdict(tuple)\n\nfor item in x:\n if item > max_elements[item[1]]:\n max_elements[item[1]] = item\n\ny = max_elements.values()\n\n",
"Similar to Aaron's answer\n>>> from collections import defaultdict\n>>> x = [(1,2), (3... | [
5,
5,
2,
0,
0
] | [] | [] | [
"list",
"python"
] | stackoverflow_0004111207_list_python.txt |
Q:
Having some kind of XML/Json file to compile into Graphiz / Finite State Automaton. Any suggestions?
I have a task where I need to take some existing pictures[ which show some automata (DFA, NFA, Turing machines)] and somehow convert them into a format, which enables me to use the data to represent it as an automata as well as compile it into some graphical representation. Has any of you done something similar before? Are there any Python libs/frameworks which let me present some automata data graphically?
A:
Graphviz can provide a solution. The data representation for a Directed Acyclic Graph (DAG) is direct and simple from the picture. It can readily be "read" off the diagram if you are doing it by hand as your comment suggests. The representation of a complex diagram (several distinct panels each containing an independent DAG is listed below. As @Constantin says, DFA and NFA can be represented as DAGs. I'm not sure about what notation is used for Turing machines, but several sorts of structured diagram can be read off in a similar fashion, eg tree structures; undirected graphs. I also attach a copy of the resulting diagram. The individual lines of the .dot file are the data items you are seeking.
Digraph {
graph [label="Problem Frame\nmapping editor\n",labelloc=t,fontsize=18,compound=true];
node[shape = record,fontsize = 10];
edge[arrowtail=none,arrowhead=none,arrowsize=0.8,color=ivory4,fontsize=8];
subgraph "cluster0" {
graph [label = "Model Fragment"];
A01 [label = "{Domain|class::marking\lisTemplate::boolean default false\lname::name\ltype::domain type\l}"];
A02 [label = "{Requirement|isTemplate::boolean default false\lname::name\l}"];
A03 [label = "{Requirement Reference\n\<\<associative\>\>|content::name\lis template::boolean default false\ltype::requirement reference type\l}",shape=Mrecord,style=dotted];
A04 [label = "{Shared Phenomena Set\n\<\<associative\>\>|content::name\lis template::boolean default false\ltype::phenomena type\l}",shape=Mrecord,style=dotted];
/* 1:1-0:M */
edge[dir=both,arrowhead=crowodot,arrowtail=none];
A01 -> A03 [style=dashed];
A01 -> A04 [style = dashed];
A01 -> A04 [style = dashed];
A02 -> A03 [style = dashed];
}
subgraph "cluster1" {
graph [label = "\>\>\>",fontsize = 24];
B01 [label = "{Domain}"];
B02 [label = "{Requirement}"];
B03 [label = "{Requirement\nReference\n}",shape=Mrecord,style=dotted];
B04 [label = "{Shared\nPhenomena\nSet\n}",shape=Mrecord,style=dotted];
F01 [label = "{C0001|if \[-\> controls -\> describes.isTemplate\]\l}"];
F02 [label = "{C0002|if not \[-\> controls -\> describes.isTemplate\]\l}"];
F03 [label = "{C0003|if \[-\> controls -\> describes.type = designed\]\l}"];
F04 [label = "{C0004|if \[-\> controls -\> describes.type = given\]\l}"];
F05 [label = "{C0005|if \[-\> controls -\> describes.type = machine\]\l}"];
F06 [label = "{C0006|if \[-\> controls -\> describes.marking = biddable\]\l}"];
F07 [label = "{C0007|if \[-\> controls -\> describes.marking = causal\]\l}"];
F08 [label = "{C0008|if \[-\> controls -\> describes.marking = lexical\]\l}"];
F09 [label = "{C0009|if \[-\> controls -\> describes.marking = null\]\l}"];
F10 [label = "{C0010|if \[-\> controls -\> describes.isTemplate\]\l}"];
F11 [label = "{C0011|if not \[-\> controls -\> describes.isTemplate\]\l}"];
F12 [label = "{C0012|if \[-\> controls -\> describes.isTemplate\]\l}"];
F13 [label = "{C0013|if not \[-\> controls -\> describes.isTemplate\]\l}"];
F14 [label = "{C0014|if \[-\> controls -\> describes.type = non-constraining\]\l}"];
F15 [label = "{C0015|if not \[-\> controls -\> describes.type = constraining\]\l}"];
F16 [label = "{C0016|if \[-\> controls -\> describes.isTemplate\]\l}"];
F17 [label = "{C0017|if not \[-\> controls -\> describes.isTemplate\]\l}"];
F18 [label = "{C0018|if \[-\> controls -\> describes.type = causal\]\l}"];
F19 [label = "{C0019|if \[-\> controls -\> describes.type = event\]\l}"];
F20 [label = "{C0020|if \[-\> controls -\> describes.type = symbolic\]\l}"];
edge [style = solid];
B01 -> F01 -> F02 -> F03 -> F04 -> F05 -> F06 -> F07 -> F08 -> F09;
B02 -> F10 -> F11;
B03 -> F12 -> F13 -> F14 -> F15;
B04 -> F16 -> F17 -> F18 -> F19 -> F20;
edge [style = invis];
B01 -> B02 -> B03 -> B04;
}
subgraph "cluster2" {
graph [label = "\<\<\<",fontsize = 24];
C01 [label = "{Edge|name := Constraining Reference\larrowtail := normal\ldir := both\lpermitted node1 := domain icon\lpermitted node2 := requirement icon\lstyle := dotted\l}"];
D02 [label = "{Attribute|name::oName\lvalue::-\> describes\l-\> described by.content\l}"];
C02 [label = "{Diagram|name := Frame Diagram\l}"];
C03 [label = "{Node|name := Domain Icon\lcolor = gray\lfillcolor = gold\lfontsize := 12\llabel := describes.preLabel\l + oName + describes.postLabel\lshape := Mrecord\lstyle := filled\l}"];
D03 [label = "{Attribute|name::oClass\lvalue :=-\> describes\l-\> described by.class\l}"];
D04 [label = "{Attribute|name::oName\lvalue := -\> describes\l-\> described by.name\l}"];
D05 [label = "{Attribute|name::postlabel\lvalue := \}\"\l}"];
D06 [label = "{Attribute|name::postlabel\lvalue := \|\{\|b\}\}\"\l}"];
D07 [label = "{Attribute|name::postlabel\lvalue := \|\{\|c\}\}\"\l}"];
D08 [label = "{Attribute|name::postlabel\lvalue := \|\{\|x\}\}\"\l}"];
D09 [label = "{Attribute|name::prelabel\lvalue := \"\{\|\l}"];
D10 [label = "{Attribute|name::prelabel\lvalue := \"\{\l}"];
D11 [label = "{Attribute|name::prelabel\lvalue := \"\{\|\|\l}"];
D12 [label = "{Attribute|name::oType\lvalue := -\> describes \l-\> described by.type\l}"];
C04 [label = "{Holding Box|name := Domain Template\lcolor := slategray\lfillcolor := white\lfontcolor := slategray\lfontsize := 9\llabel := oName\lreadonly := true\l}"];
D13 [label = "{Attribute|name::oName\lvalue := -\> describes \l-\> described by.name\l}"];
C05 [label = "{Edge|name := Edge Template\lcolor := white\llabel = oName\lstyle := invis\l}"];
D14 [label = "{Attribute|name::oName\lvalue := -\> describes \l-\> described by.contents\l}"];
C06 [label = "{Node|name := Phenomena\l}"];
D15 [label = "{Attribute|name::oName\lvalue::-\> describes\l\-\> described by.contents\l}"];
C07 [label = "{Edge|name := Reference\l}"];
D16 [label = "{Attribute|name::oName\lvalue := -\> describes \l-\> described by.contents\l}"];
C08 [label = "{Node|name := Requirement Icon\l}"];
D17 [label = "{Attribute|name::oName\lvalue := -\> describes \l-\> described by.name\l}"];
C09 [label = "{Edge|name := Shared Phenomena\l}"];
D18 [label = "{Attribute|name::oName\lvalue := -\> describes \l-\> described by.contents\l}"];
D19 [label = "{Attribute|name::oType\lvalue := C\l}"];
D20 [label = "{Attribute|name::oType\lvalue := E\l}"];
D21 [label = "{Attribute|name::oType\lvalue := Y\l}"];
C01 -> D02;
C03 -> D03 -> D04 -> D05 -> D06 -> D07 -> D08 -> D09 -> D10 -> D11 -> D12;
C04 -> D13;
C05 -> D14;
C06 -> D15;
C07 -> D16;
C08 -> D17;
C09 -> D18 -> D19 -> D20 -> D21;
edge[style="invis"];
C01 -> C02 -> C03 -> C04 -> C05 -> C06 -> C07 -> C08 -> C09;
}
subgraph "cluster5" {
graph [label = "Editor Elements"];
E01 [label = "{Node\n|color::color\lfillcolor::fillcolor\lfontname::font\lfontsize::fontsize\llabel::name\lname::name\lreadonly::boolean default false\lshape::shape\lstyle::style\l}"];
E02 [label = "{Edge\n|arrowtail::edge end\ldir::dir\lname::name\lpermitted node1::name\lpermitted node2::name\lstyle::style\l}"];
E03 [label = "{Attribute\n|name::name\lvalue::text\l}"];
E04 [label = "{Diagram\n|defaults::attributes\ledge defaults::attributes\lname::name\lnode attributes::attributes\l}"];
E05 [label = "{Holding Box|color::color\lfillcolor::fillcolor\lfontname::font\lfontsize::fontsize\llabel::name\lname::name\lreadonly::boolean default false\lshape::shape\lstyle::style\l}"];
/* 0:1-N:M */
E01 -> E02 [arrowhead = crowodot, label = "links", taillabel = " 2:2"];
/* 1:1-0:M */
edge[dir=both,arrowtail=none,arrowhead=crowodot];
E04 -> E01 [label = nodes];
E04 -> E02 [label = edges];
E04 -> E05 [label = "holding boxes"];
/* 0:1-0:M */
edge[dir=both,arrowtail=odot,arrowhead=crowodot];
E05 -> E01 [label = "contained nodes"];
E05 -> E02 [label = "contained edges"];
E05 -> E05 [label = contains];
/* 0:1-0:M */
edge[dir=both,arrowtail=odot,arrowhead=crowodot];
E01 -> E03 [label = characteristics];
E02 -> E03 [label = parameters];
E04 -> E03 [label = attributes];
E04 -> E03 [label = attributes];
E04 -> E03 [label = attributes];
}
{rank = min B01 C01}
edge[style="solid"];
F01 -> C04 [ltail = cluster1];
F02 -> C03 [ltail = cluster1];
F03 -> D09 [ltail = cluster1];
F04 -> D10 [ltail = cluster1];
F05 -> D11 [ltail = cluster1];
F06 -> D06 [ltail = cluster1];
F07 -> D07 [ltail = cluster1];
F08 -> D08 [ltail = cluster1];
F09 -> D05 [ltail = cluster1];
F10 -> C04 [ltail = cluster1];
F11 -> C06 [ltail = cluster1];
F11 -> C08 [ltail = cluster1];
F12 -> C05 [ltail = cluster1];
F14 -> C07 [ltail = cluster1];
F15 -> C01 [ltail = cluster1];
F16 -> C05 [ltail = cluster1];
F17 -> C06 [ltail = cluster1];
F17 -> C09 [ltail = cluster1];
F18 -> D19 [ltail = cluster1];
F19 -> D20 [ltail = cluster1];
F20 -> D21 [ltail = cluster1];
}
| Having some kind of XML/Json file to compile into Graphiz / Finite State Automaton. Any suggestions? | I have a task where I need to take some existing pictures[ which show some automata (DFA, NFA, Turing machines)] and somehow convert them into a format, which enables me to use the data to represent it as an automata as well as compile it into some graphical representation. Has any of you done something similar before? Are there any Python libs/frameworks which let me present some automata data graphically?
| [
"Graphviz can provide a solution. The data representation for a Directed Acyclic Graph (DAG) is direct and simple from the picture. It can readily be \"read\" off the diagram if you are doing it by hand as your comment suggests. The representation of a complex diagram (several distinct panels each containing an ind... | [
1
] | [] | [] | [
"automata",
"depth_first_search",
"python",
"turing_machines"
] | stackoverflow_0004077117_automata_depth_first_search_python_turing_machines.txt |
Q:
Sneaking unsigned values from Jython, through Java, to C and back again
I'm involved in a project where we're binding a C API into Jython (through Java). We've run into issues with unsigned values (since Java doesn't support them). We can use casting between Java and C, but moving from Jython to Java is a harder task.
I wrote some 'casting' functions in Python. They convert a bit pattern representing a signed or unsigned value into the SAME BIT PATTERN representing the opposite sign.
For example:
>>> u2s(0xFFFFFFFF)
-1L
>>> hex(s2u(-1))
'0xffffffffL'
Is there a more elegant way to handle these sorts of sign conversions between Jython and Java? Has any one tried to do this before?
Here's the entire module:
__all__ = ['u2s', 's2u']
def u2s(v,width=32):
"""
Convert a bit pattern representing an unsigned value to the
SAME BIT PATTERN representing a signed value.
>>> u2s(0xFFFFFFFF)
-1L
>>> u2s(0x7FFFFFFF)
2147483647L
"""
msb = int("1" + ((width - 1) * '0'), 2)
msk = int("1" * width, 2)
nv = v & msk
if 0 < (msb & nv):
return -1 * ((nv ^ msk) + 1)
else:
return nv
def s2u(v,width=32):
"""
Convert a bit pattern representing a signed value to the
SAME BIT PATTERN representing an unsinged value.
>>> hex(s2u(-1))
'0xffffffffL'
>>> hex(s2u(1))
'0x1L'
"""
msk = int("1" * width, 2)
if 0 > v:
return msk & (((-1 * v) ^ msk) + 1)
else:
return msk & v
if __name__ == "__main__":
import doctest
doctest.testmod()
I went and benchmarked my code VS the accepted answer in Jython. The accepted answer performs about 1/3 better! I only tested the version with explicitly defined widths.
Edit my supplied code with the following to run the benchmark for yourself:
def _u2s(v, width=32):
fmt = {8: "B", 16: "H", 32: "I", 64: "Q"}[width]
return struct.unpack(fmt.lower(), struct.pack(fmt, v))[0]
def _s2u(v, width=32):
fmt = {8: "B", 16: "H", 32: "I", 64: "Q"}[width]
return struct.unpack(fmt, struct.pack(fmt.lower(), v))[0]
if __name__ == "__main__":
import doctest
doctest.testmod()
import time
x = range(-1000000,1000000)
t1 = time.clock()
y = map(s2u, x)
t2 = time.clock()
print t2 - t1
_t1 = time.clock()
z = map(_s2u, x)
_t2 = time.clock()
print _t2 - _t1
A:
The struct module is a natural fit for this
import struct
def u2s(v):
return struct.unpack("i", struct.pack("I", v))[0]
def s2u(v):
return struct.unpack("I", struct.pack("i", v))[0]
To support all the common widths
import struct
def u2s(v, width=32):
fmt = {8: "B", 16: "H", 32: "I", 64: "Q"}[width]
return struct.unpack(fmt.lower(), struct.pack(fmt, v))[0]
def s2u(v, width=32):
fmt = {8: "B", 16: "H", 32: "I", 64: "Q"}[width]
return struct.unpack(fmt, struct.pack(fmt.lower(), v))[0]
To support any width up to 64 bits
import struct
def u2s(v, width=32):
return struct.unpack("q",struct.pack("Q",v<<(64-width)))[0]>>(64-width)
def s2u(v, width=32):
return struct.unpack("Q",struct.pack("q",v<<(64-width)))[0]>>(64-width)
If you need to support widths above 64 bit
def u2s(v, width=32):
return v if v < (1L<<(width-1)) else v - (1L<<width)
def s2u(v, width=32):
return v if v >= 0 else v + (1L<<width)
| Sneaking unsigned values from Jython, through Java, to C and back again | I'm involved in a project where we're binding a C API into Jython (through Java). We've run into issues with unsigned values (since Java doesn't support them). We can use casting between Java and C, but moving from Jython to Java is a harder task.
I wrote some 'casting' functions in Python. They convert a bit pattern representing a signed or unsigned value into the SAME BIT PATTERN representing the opposite sign.
For example:
>>> u2s(0xFFFFFFFF)
-1L
>>> hex(s2u(-1))
'0xffffffffL'
Is there a more elegant way to handle these sorts of sign conversions between Jython and Java? Has any one tried to do this before?
Here's the entire module:
__all__ = ['u2s', 's2u']
def u2s(v,width=32):
"""
Convert a bit pattern representing an unsigned value to the
SAME BIT PATTERN representing a signed value.
>>> u2s(0xFFFFFFFF)
-1L
>>> u2s(0x7FFFFFFF)
2147483647L
"""
msb = int("1" + ((width - 1) * '0'), 2)
msk = int("1" * width, 2)
nv = v & msk
if 0 < (msb & nv):
return -1 * ((nv ^ msk) + 1)
else:
return nv
def s2u(v,width=32):
"""
Convert a bit pattern representing a signed value to the
SAME BIT PATTERN representing an unsinged value.
>>> hex(s2u(-1))
'0xffffffffL'
>>> hex(s2u(1))
'0x1L'
"""
msk = int("1" * width, 2)
if 0 > v:
return msk & (((-1 * v) ^ msk) + 1)
else:
return msk & v
if __name__ == "__main__":
import doctest
doctest.testmod()
I went and benchmarked my code VS the accepted answer in Jython. The accepted answer performs about 1/3 better! I only tested the version with explicitly defined widths.
Edit my supplied code with the following to run the benchmark for yourself:
def _u2s(v, width=32):
fmt = {8: "B", 16: "H", 32: "I", 64: "Q"}[width]
return struct.unpack(fmt.lower(), struct.pack(fmt, v))[0]
def _s2u(v, width=32):
fmt = {8: "B", 16: "H", 32: "I", 64: "Q"}[width]
return struct.unpack(fmt, struct.pack(fmt.lower(), v))[0]
if __name__ == "__main__":
import doctest
doctest.testmod()
import time
x = range(-1000000,1000000)
t1 = time.clock()
y = map(s2u, x)
t2 = time.clock()
print t2 - t1
_t1 = time.clock()
z = map(_s2u, x)
_t2 = time.clock()
print _t2 - _t1
| [
"The struct module is a natural fit for this\nimport struct\n\ndef u2s(v):\n return struct.unpack(\"i\", struct.pack(\"I\", v))[0]\n\ndef s2u(v):\n return struct.unpack(\"I\", struct.pack(\"i\", v))[0]\n\nTo support all the common widths\nimport struct\n\ndef u2s(v, width=32):\n fmt = {8: \"B\", 16: \"H\",... | [
4
] | [] | [] | [
"java",
"java_native_interface",
"jython",
"python"
] | stackoverflow_0004111595_java_java_native_interface_jython_python.txt |
Q:
Python Setuptools, easy_install setup mac
Okay, so I'm not sure at all what is going on here. I just got my MAC, and I am trying to download and install setuptools, so I can download different python packages (using easy_install). So, following the instructions here (http://pypi.python.org/pypi/setuptools):
I currently have version 2.6
I downloaded the following egg: setuptools-0.6c11-py2.6.egg (md5)
I placed the file on my desktop (File Name: setuptools-0.6c11-py2.6.egg.sh)
I navigate to the desktop on the directory, and use the following command line, as suggested by the above link:
sh setuptools-0.6c11-py2.6.egg
I get an error: No such file or directory, so then I use this other command
sh setuptools-0.6c11-py2.6.egg.sh
Then, I get the following error:
setuptools-0.6c11-py2.6.egg.sh is not the correct name for this egg file.
Please rename it back to setuptools-0.6c11-py2.6.egg and try again.
I am really not sure at all what to do here. Any help would be appreciated! Thanks!
A:
edit Try this from a command line
Here is an easier thing to do that might work better for you. Open a terminal (Applications->Utilities->Terminal) and run this as a shell script. You can also run the individual commands.
#!/bin/sh
cd ~
# Downloads python setuptools for 2.6
curl -o setuptools-0.6c11-py2.6.egg http://pypi.python.org/packages/2.6/s/setuptools/setuptools-0.6c11-py2.6.egg#md5=bfa92100bd772d5a213eedd356d64086
# installs it, will probably prompt you for password
sudo sh setuptools-0.6c11-py2.6.egg
# clean up and delete egg
rm setuptools-0.6c11-py2.6.egg
Stuff below was original response
I just did this on my own Mac machine, and installation went off without a problem. Did you open a terminal to do this?
I downloaded setuptools to my Downloads folder, and then opened a terminal, and did this:
> cd ~/Downloads
> sudo sh setuptools-0.6c11-py2.6.egg
Password:
Processing setuptools-0.6c11-py2.6.egg
Removing /Library/Python/2.6/site-packages/setuptools-0.6c11-py2.6.egg
Copying setuptools-0.6c11-py2.6.egg to /Library/Python/2.6/site-packages
setuptools 0.6c11 is already the active version in easy-install.pth
Installing easy_install script to /usr/local/bin
Installing easy_install-2.6 script to /usr/local/bin
Installed /Library/Python/2.6/site-packages/setuptools-0.6c11-py2.6.egg
Processing dependencies for setuptools==0.6c11
Finished processing dependencies for setuptools==0.6c11
A:
Try this
mv setuptools-0.6c11-py2.6.egg.sh setuptools-0.6c11-py2.6.egg
sh setuptools-0.6c11-py2.6.egg
| Python Setuptools, easy_install setup mac | Okay, so I'm not sure at all what is going on here. I just got my MAC, and I am trying to download and install setuptools, so I can download different python packages (using easy_install). So, following the instructions here (http://pypi.python.org/pypi/setuptools):
I currently have version 2.6
I downloaded the following egg: setuptools-0.6c11-py2.6.egg (md5)
I placed the file on my desktop (File Name: setuptools-0.6c11-py2.6.egg.sh)
I navigate to the desktop on the directory, and use the following command line, as suggested by the above link:
sh setuptools-0.6c11-py2.6.egg
I get an error: No such file or directory, so then I use this other command
sh setuptools-0.6c11-py2.6.egg.sh
Then, I get the following error:
setuptools-0.6c11-py2.6.egg.sh is not the correct name for this egg file.
Please rename it back to setuptools-0.6c11-py2.6.egg and try again.
I am really not sure at all what to do here. Any help would be appreciated! Thanks!
| [
"edit Try this from a command line\nHere is an easier thing to do that might work better for you. Open a terminal (Applications->Utilities->Terminal) and run this as a shell script. You can also run the individual commands.\n#!/bin/sh\n\ncd ~\n\n# Downloads python setuptools for 2.6\ncurl -o setuptools-0.6c11-py2.6... | [
6,
1
] | [] | [] | [
"python"
] | stackoverflow_0004111737_python.txt |
Q:
Convert datetime fields in Chrome history file (sqlite) to readable format
Working on a script to collect users browser history with time stamps ( educational setting).
Firefox 3 history is kept in a sqlite file, and stamps are in UNIX epoch time... getting them and converting to readable format via a SQL command in python is pretty straightforward:
sql_select = """ SELECT datetime(moz_historyvisits.visit_date/1000000,'unixepoch','localtime'),
moz_places.url
FROM moz_places, moz_historyvisits
WHERE moz_places.id = moz_historyvisits.place_id
"""
get_hist = list(cursor.execute (sql_select))
Chrome also stores history in a sqlite file.. but it's history time stamp is apparently formatted as the number of microseconds since midnight UTC of 1 January 1601....
How can this timestamp be converted to a readable format as in the Firefox example (like 2010-01-23 11:22:09)? I am writing the script with python 2.5.x ( the version on OS X 10.5 ), and importing sqlite3 module....
A:
Try this:
sql_select = """ SELECT datetime(last_visit_time/1000000-11644473600,'unixepoch','localtime'),
url
FROM urls
ORDER BY last_visit_time DESC
"""
get_hist = list(cursor.execute (sql_select))
Or something along those lines
seems to be working for me.
A:
This is a more pythonic and memory-friendly way to do what you described (by the way, thanks for the initial code!):
#!/usr/bin/env python
import os
import datetime
import sqlite3
import opster
from itertools import izip
SQL_TIME = 'SELECT time FROM info'
SQL_URL = 'SELECT c0url FROM pages_content'
def date_from_webkit(webkit_timestamp):
epoch_start = datetime.datetime(1601,1,1)
delta = datetime.timedelta(microseconds=int(webkit_timestamp))
return epoch_start + delta
@opster.command()
def import_history(*paths):
for path in paths:
assert os.path.exists(path)
c = sqlite3.connect(path)
times = (row[0] for row in c.execute(SQL_TIME))
urls = (row[0] for row in c.execute(SQL_URL))
for timestamp, url in izip(times, urls):
date_time = date_from_webkit(timestamp)
print date_time, url
c.close()
if __name__=='__main__':
opster.dispatch()
The script can be used this way:
$ ./chrome-tools.py import-history ~/.config/chromium/Default/History* > history.txt
Of course Opster can be thrown out but seems handy to me :-)
A:
The sqlite module returns datetime objects for datetime fields, which have a format method for printing readable strings called strftime.
You can do something like this once you have the recordset:
for record in get_hist:
date_string = record[0].strftime("%Y-%m-%d %H:%M:%S")
url = record[1]
A:
This may not be the most Pythonic code in the world, but here's a solution: Cheated by adjusting for time zone (EST here) by doing this:
utctime = datetime.datetime(1601,1,1) + datetime.timedelta(microseconds = ms, hours =-5)
Here's the function : It assumes that the Chrome history file has been copied from another account into /Users/someuser/Documents/tmp/Chrome/History
def getcr():
connection = sqlite3.connect('/Users/someuser/Documents/tmp/Chrome/History')
cursor = connection.cursor()
get_time = list(cursor.execute("""SELECT last_visit_time FROM urls"""))
get_url = list(cursor.execute("""SELECT url from urls"""))
stripped_time = []
crf = open ('/Users/someuser/Documents/tmp/cr/cr_hist.txt','w' )
itr = iter(get_time)
itr2 = iter(get_url)
while True:
try:
newdate = str(itr.next())
stripped1 = newdate.strip(' (),L')
ms = int(stripped1)
utctime = datetime.datetime(1601,1,1) + datetime.timedelta(microseconds = ms, hours =-5)
stripped_time.append(str(utctime))
newurl = str(itr2.next())
stripped_url = newurl.strip(' ()')
stripped_time.append(str(stripped_url))
crf.write('\n')
crf.write(str(utctime))
crf.write('\n')
crf.write(str(newurl))
crf.write('\n')
crf.write('\n')
crf.write('********* Next Entry *********')
crf.write('\n')
except StopIteration:
break
crf.close()
shutil.copy('/Users/someuser/Documents/tmp/cr/cr_hist.txt' , '/Users/parent/Documents/Chrome_History_Logs')
os.rename('/Users/someuser/Documents/Chrome_History_Logs/cr_hist.txt','/Users/someuser/Documents/Chrome_History_Logs/%s.txt' % formatdate)
| Convert datetime fields in Chrome history file (sqlite) to readable format | Working on a script to collect users browser history with time stamps ( educational setting).
Firefox 3 history is kept in a sqlite file, and stamps are in UNIX epoch time... getting them and converting to readable format via a SQL command in python is pretty straightforward:
sql_select = """ SELECT datetime(moz_historyvisits.visit_date/1000000,'unixepoch','localtime'),
moz_places.url
FROM moz_places, moz_historyvisits
WHERE moz_places.id = moz_historyvisits.place_id
"""
get_hist = list(cursor.execute (sql_select))
Chrome also stores history in a sqlite file.. but it's history time stamp is apparently formatted as the number of microseconds since midnight UTC of 1 January 1601....
How can this timestamp be converted to a readable format as in the Firefox example (like 2010-01-23 11:22:09)? I am writing the script with python 2.5.x ( the version on OS X 10.5 ), and importing sqlite3 module....
| [
"Try this:\nsql_select = \"\"\" SELECT datetime(last_visit_time/1000000-11644473600,'unixepoch','localtime'),\n url \n FROM urls\n ORDER BY last_visit_time DESC\n \"\"\"\nget_hist = list(cursor.execute (sql_select))\n\nOr something along those lines... | [
16,
4,
1,
1
] | [] | [] | [
"datetime",
"python",
"sqlite"
] | stackoverflow_0002141537_datetime_python_sqlite.txt |
Q:
What is the most efficient way to concatenate two strings and remove everything before the first ',' in Python?
In Python, I have a string which is a comma separated list of values. e.g. '5,2,7,8,3,4'
I need to add a new value onto the end and remove the first value,
e.g.
'5,22,7,814,3,4' -> '22,7,814,3,4,1'
Currently, I do this as follows:
mystr = '5,22,7,814,3,4'
latestValue='1'
mylist = mystr.split(',')
mystr = ''
for i in range(len(mylist)-1):
if i==0:
mystr += mylist[i+1]
if i>0:
mystr += ','+mylist[i+1]
mystr += ','+latestValue
This runs millions of times in my code and I've identified it as a bottleneck, so I'm keen to optimize it to make it run faster.
What is the most efficient to do this (in terms of runtime)?
A:
Use this:
if mystr == '':
mystr = latestValue
else:
mystr = mystr[mystr.find(",")+1:] + "," + latestValue
This should be much faster than any solution which splits the list. It only finds the first occurrence of , and "removes" the beginning of the string. Also, if the list is empty, then mystr will be just latestValue (insignificant overhead added by this) -- thanks Paulo Scardine for pointing that out.
A:
mystr = mystr.partition(",")[2]+","+latestValue
improvement suggested by Paulo to work if mystr has < 2 elements.
In the case of 0 elements, it does extend mystr to hold one element.
_,_,mystr = (mystr+','+latestValue).partition(',')
$ python -m timeit -s "mystr = '5,22,7,814,3,4';latestValue='1'" "mystr[mystr.find(',')+1:]+','+latestValue"
1000000 loops, best of 3: 0.847 usec per loop
$ python -m timeit -s "mystr = '5,22,7,814,3,4';latestValue='1'" "mystr = mystr.partition(',')[2]+','+latestValue"
1000000 loops, best of 3: 0.703 usec per loop
A:
_, sep, rest = mystr.partition(",")
mystr = rest + sep + latestValue
It also works without any changes if mystr is empty or a single item (without comma after it) due to str.partition returns empty sep if there is no sep in mystr.
You could use mystr.rstrip(",") before calling partition() if there might be a trailing comma in the mystr.
A:
best version: gnibbler's answer
Since you need speed (millions of times is a lot), I profiled. This one is about twice as fast as splitting the list:
i = 0
while 1:
if mystr[i] == ',': break
i += 1
mystr = mystr[i+1:] + ', ' + latest_value
It assumes that there is one space after each comma. If that's a problem, you can use:
i = 0
while 1:
if mystr[i] == ',': break
i += 1
mystr = mystr[i+1:].strip() + ', ' + latest_value
which is only slightly slower than the original but much more robust. It's really up to you to decide how much speed you need to squeeze out of it. They both assume that there will be a comma in the string and will raise an IndexError if one fails to appear. The safe version is:
i = 0
while 1:
try:
if mystr[i] == ',': break
except IndexError:
i = -1
break
i += 1
mystr = mystr[i+1:].strip() + ', ' + latest_value
Again, this is still significantly faster than than splitting the string but does add robustness at the cost of speed.
Here's the timeit results. You can see that the fourth method is noticeably faster than the third (most robust) method, but slightly slower than the first two methods. It's the fastest of the two robust solutions though so unless you are sure that your strings will have commas in them (i.e. it would already be considered an error if they didn't) then I would use it anyway.
$ python -mtimeit -s'from strings import tests, method1' 'method1(tests[0], "10")'
1000000 loops, best of 3: 1.34 usec per loop
$ python -mtimeit -s'from strings import tests, method2' 'method2(tests[0], "10")'
1000000 loops, best of 3: 1.34 usec per loop
$ python -mtimeit -s'from strings import tests, method3' 'method3(tests[0], "10")'
1000000 loops, best of 3: 1.5 usec per loop
$ python -mtimeit -s'from strings import tests, method4' 'method4(tests[0], "10")'
1000000 loops, best of 3: 1.38 usec per loop
$ python -mtimeit -s'from strings import tests, method5' 'method5(tests[0], "10")'
100000 loops, best of 3: 1.18 usec per loop
This is gnibbler's answer
A:
mylist = mystr.split(',')
mylist.append(latestValue);
mystr = ",".join(mylist[1:])
String concatenation in python isn't very efficient (since strings are immutable). It's easier to work with them as lists (and more efficient). Basically in your code you are copying your string over and over again each time you concatenate to it.
A:
Edited:
Not the best, but I love one-liners. :-)
mystr = ','.join(mystr.split(',')[1:]+[latestValue])
Before testing I would bet it would perform better.
> python -m timeit "mystr = '5,22,7,814,3,4'" "latestValue='1'" \
"mylist = mystr.split(',')" "mylist.append(latestValue);" \
"mystr = ','.join(mylist[1:])"
1000000 loops, best of 3: 1.37 usec per loop
> python -m timeit "mystr = '5,22,7,814,3,4'" "latestValue='1'"\
"','.join(mystr.split(',')[1:]+[latestValue])"
1000000 loops, best of 3: 1.5 usec per loop
> python -m timeit "mystr = '5,22,7,814,3,4'" "latestValue='1'"\
'mystr=mystr[mystr.find(",")+1:]+","+latestValue'
1000000 loops, best of 3: 0.625 usec per loop
| What is the most efficient way to concatenate two strings and remove everything before the first ',' in Python? | In Python, I have a string which is a comma separated list of values. e.g. '5,2,7,8,3,4'
I need to add a new value onto the end and remove the first value,
e.g.
'5,22,7,814,3,4' -> '22,7,814,3,4,1'
Currently, I do this as follows:
mystr = '5,22,7,814,3,4'
latestValue='1'
mylist = mystr.split(',')
mystr = ''
for i in range(len(mylist)-1):
if i==0:
mystr += mylist[i+1]
if i>0:
mystr += ','+mylist[i+1]
mystr += ','+latestValue
This runs millions of times in my code and I've identified it as a bottleneck, so I'm keen to optimize it to make it run faster.
What is the most efficient to do this (in terms of runtime)?
| [
"Use this:\nif mystr == '':\n mystr = latestValue\nelse:\n mystr = mystr[mystr.find(\",\")+1:] + \",\" + latestValue\n\nThis should be much faster than any solution which splits the list. It only finds the first occurrence of , and \"removes\" the beginning of the string. Also, if the list is empty, then myst... | [
9,
6,
6,
4,
2,
2
] | [] | [] | [
"algorithm",
"concatenation",
"python"
] | stackoverflow_0004111711_algorithm_concatenation_python.txt |
Q:
How to zip lists in a list
I want to zip the following list of lists:
>>> zip([[1,2], [3,4], [5,6]])
[[1,3,5], [2,4,6]]
This could be achieved with the current zip implementation only if the list is split into individual components:
>>> zip([1,2], [3,4], [5,6])
(1, 3, 5), (2, 4, 6)]
Can't figure out how to split the list and pass the individual elements to zip. A functional solution is preferred.
A:
Try this:
>>> zip(*[[1,2], [3,4], [5,6]])
[(1, 3, 5), (2, 4, 6)]
See Unpacking Argument Lists:
The reverse situation occurs when the arguments are already in a list or tuple but need to be unpacked for a function call requiring separate positional arguments. For instance, the built-in range() function expects separate start and stop arguments. If they are not available separately, write the function call with the *-operator to unpack the arguments out of a list or tuple:
>>> range(3, 6) # normal call with separate arguments
[3, 4, 5]
>>> args = [3, 6]
>>> range(*args) # call with arguments unpacked from a list
[3, 4, 5]
| How to zip lists in a list | I want to zip the following list of lists:
>>> zip([[1,2], [3,4], [5,6]])
[[1,3,5], [2,4,6]]
This could be achieved with the current zip implementation only if the list is split into individual components:
>>> zip([1,2], [3,4], [5,6])
(1, 3, 5), (2, 4, 6)]
Can't figure out how to split the list and pass the individual elements to zip. A functional solution is preferred.
| [
"Try this:\n>>> zip(*[[1,2], [3,4], [5,6]])\n[(1, 3, 5), (2, 4, 6)]\n\nSee Unpacking Argument Lists:\n\nThe reverse situation occurs when the arguments are already in a list or tuple but need to be unpacked for a function call requiring separate positional arguments. For instance, the built-in range() function expe... | [
176
] | [] | [] | [
"functional_programming",
"python"
] | stackoverflow_0004112265_functional_programming_python.txt |
Q:
How to find the max object as per some custom criterion?
I can do max(s) to find the max of a sequence. But suppose I want to compute max according to my own function, something like:
currmax = 0
def mymax(s):
for i in s :
#assume arity() attribute is present
currmax = i.arity() if i.arity() > currmax else currmax
Is there a clean pythonic way of doing this?
A:
max(s, key=operator.methodcaller('arity'))
or
max(s, key=lambda x: x.arity())
A:
For instance,
max (i.arity() for i in s)
A:
You can still use the max function:
max_arity = max(s, key=lambda i: i.arity())
A:
I think the generator expression of doublep is better, but we seldom get to use methodcaller, so...
from operator import methodcaller
max(map(methodcaller('arity'), s))
| How to find the max object as per some custom criterion? | I can do max(s) to find the max of a sequence. But suppose I want to compute max according to my own function, something like:
currmax = 0
def mymax(s):
for i in s :
#assume arity() attribute is present
currmax = i.arity() if i.arity() > currmax else currmax
Is there a clean pythonic way of doing this?
| [
"max(s, key=operator.methodcaller('arity'))\n\nor\nmax(s, key=lambda x: x.arity())\n\n",
"For instance,\nmax (i.arity() for i in s)\n\n",
"You can still use the max function:\nmax_arity = max(s, key=lambda i: i.arity())\n\n",
"I think the generator expression of doublep is better, but we seldom get to use met... | [
40,
12,
9,
2
] | [] | [] | [
"python"
] | stackoverflow_0002931985_python.txt |
Q:
Strange urllib2.urlopen() behavior on Ubuntu 10.10
I am experiencing strange behavior with urllib2.urlopen() on Ubuntu 10.10. The first request to a url goes fast but the second takes a long time to connect. I think between 5 and 10 seconds. On windows this just works normal?
Does anybody have an idea what could cause this issue?
Thanks, Onno
A:
5 seconds sounds suspiciously like the DNS resolving timeout.
A hunch, It's possible that it's cycling through the DNS servers in your /etc/resolv.conf and if one of them is broken, the default timeout is 5 seconds on linux, after which it will try the next one, looping back to the top when it's tried them all.
If you have multiple DNS servers listed in resolv.conf, try removing all but one. If this fixes it; then after that see why you're being assigned incorrect resolving servers.
A:
you can enable debugging of the urllib2 maybe it can help you found out the problem
import urllib2
opener = urllib2.build_opener(urllib2.HTTPHandler(debuglevel=1))
opener.open('http://www.google.com')
| Strange urllib2.urlopen() behavior on Ubuntu 10.10 | I am experiencing strange behavior with urllib2.urlopen() on Ubuntu 10.10. The first request to a url goes fast but the second takes a long time to connect. I think between 5 and 10 seconds. On windows this just works normal?
Does anybody have an idea what could cause this issue?
Thanks, Onno
| [
"5 seconds sounds suspiciously like the DNS resolving timeout. \nA hunch, It's possible that it's cycling through the DNS servers in your /etc/resolv.conf and if one of them is broken, the default timeout is 5 seconds on linux, after which it will try the next one, looping back to the top when it's tried them all.\... | [
3,
1
] | [] | [] | [
"python",
"ubuntu",
"ubuntu_10.10",
"urllib2"
] | stackoverflow_0004110992_python_ubuntu_ubuntu_10.10_urllib2.txt |
Q:
Cannot resolve Django "NoReverseMatch" exception with kwargs
I have am unable to get Django to reverse-resolve the following named url -
URLconf entry :
url(r'^shotmanager/(?P<shotid>\d+)/$', 'ctac.views.shotManager', {'message': "", 'errors': []}, name = 'shot-manager')
HttpResponseRedirect call:
return HttpResponseRedirect(reverse("shot-manager", kwargs={'shotid': id, 'message': s, 'errors': errorList}))
I see nothing in the Django docs that suggests I cannot mix kwargs in the url and the dictionary entry in the url. For some reason, reverse will resolve fine if I only send it "shotid".
I have already visited the following thread
Reversing Django URLs With Extra Options
and have studied it. It is unclear if it was resolved either.
A:
reverse returns a URL populated with the values you pass in the args or kwargs. But the URL you are trying to generate hasn't got a space for message. Where would it go in the generated URL?
Edit in response to comment
If you want to pass messages between page views, the correct way to do it is not via the URL, but by via the session. Django even includes a messaging framework to manage this for you.
| Cannot resolve Django "NoReverseMatch" exception with kwargs | I have am unable to get Django to reverse-resolve the following named url -
URLconf entry :
url(r'^shotmanager/(?P<shotid>\d+)/$', 'ctac.views.shotManager', {'message': "", 'errors': []}, name = 'shot-manager')
HttpResponseRedirect call:
return HttpResponseRedirect(reverse("shot-manager", kwargs={'shotid': id, 'message': s, 'errors': errorList}))
I see nothing in the Django docs that suggests I cannot mix kwargs in the url and the dictionary entry in the url. For some reason, reverse will resolve fine if I only send it "shotid".
I have already visited the following thread
Reversing Django URLs With Extra Options
and have studied it. It is unclear if it was resolved either.
| [
"reverse returns a URL populated with the values you pass in the args or kwargs. But the URL you are trying to generate hasn't got a space for message. Where would it go in the generated URL?\nEdit in response to comment\nIf you want to pass messages between page views, the correct way to do it is not via the URL, ... | [
4
] | [] | [] | [
"django",
"django_views",
"python"
] | stackoverflow_0004111403_django_django_views_python.txt |
Q:
"compiler" module py3k
I am trying to port a codebase which uses the "compiler" module from 2.x over to 3.1 ; I get an ImportError at
import compiler
as the module does not exist in Python3.x ; Has the same functionality been integrated into another module within the standard library?
Or has it been completely removed?
[EDIT]
I require an equivalent for compiler.parse.getChildren in Py3k.
A:
According to the docs, the module has been deprecated since 2.6 and been completely removed in 3.0.
From PEP 3108:
Having to maintain both the built-in compiler and the stdlib package is redundant (24).
The AST created by the compiler is available (23).
Mechanism to compile from an AST needs to be added.
A:
It depends on what you want to do. The abstract syntax tree stuff has largely been moved into the ast module.
Apparently the compile built in function can compile an AST object to bytecode which (coarsely) handles the remaining functionality of the compiler module. I've also never done this so YMMV.
| "compiler" module py3k | I am trying to port a codebase which uses the "compiler" module from 2.x over to 3.1 ; I get an ImportError at
import compiler
as the module does not exist in Python3.x ; Has the same functionality been integrated into another module within the standard library?
Or has it been completely removed?
[EDIT]
I require an equivalent for compiler.parse.getChildren in Py3k.
| [
"According to the docs, the module has been deprecated since 2.6 and been completely removed in 3.0.\nFrom PEP 3108:\n\nHaving to maintain both the built-in compiler and the stdlib package is redundant (24).\nThe AST created by the compiler is available (23).\nMechanism to compile from an AST needs to be added.\n\n... | [
7,
5
] | [] | [] | [
"python",
"python_3.x"
] | stackoverflow_0004112458_python_python_3.x.txt |
Q:
Python memory problem
i started programming on python but i have a memory problem (sorry for my bad english).
I made a while loop on my algorithm, but on every cicle, the program consummes a lot of memory. I have 3Gb of RAM an AMD 64 x2 processor, and Windows 7 64 bits.
For every cicle, it consummes about 800 Mb of RAM, it's too much i think.
Part of my code is here
from sympy import Symbol, diff, flatten
import numpy as np
from numpy import linalg
from math import log, sqrt, cos, pi
import matplotlib.pyplot as plt
L = 7 #numero de variables
X = [Symbol('x%d' % i) for i in range(L*(L+1))] #Las variables simbolicas
XX = [X[i] for i in xrange(L)]
LAM = []
# Parametros
Pr = 10
Eps = 0
Ome = 5
LL = 0.5
b = 2
Gam = 0.2*2*(pi**2)
ran1 = xrange(L)
ran2 = xrange(L*L)
ran3 = xrange(0,L*(L-1)+1,L)
ran4 = xrange(L,2*L,1)
dt = 0.01
TMAX = 60
def f(x,R,Tau):
return [Pr*((1 + Eps*cos(Ome*Tau))*x[2] - LL*x[0] - (1 -LL*x[5])) , \
Pr*((1 + Eps*cos(Ome*Tau))*x[3] - LL*x[1] - (1 - LL)*x[6]),\
R*x[0] - x[2] - x[0]*x[4],R*x[1] - x[3] - x[1]*x[4],(x[0]*x[2] + x[1]*x[3])/2 - b*x[4],\
(1/Gam)*(x[0] - x[5]),(1/Gam)*(x[1] - x[6])]
def Jacobian(f,x): #num son los numeros en el que se evalua la matriz jacobiana, x las variables y f la funcion
return [[diff(f[i],x[n]) for i in ran1] for n in ran1]
def Y(x):
return[[x[i+j] for j in ran3] for i in ran4]
#Ahora la multiplicacion de Y traspuesto por Jacobian traspuesto
def JY(r,Tau):
J = flatten((np.dot(np.array(Jacobian(f(XX,r,Tau),XX)),np.array(Y(X)))).T)
return [J[i] for i in ran2]
def Func(x,r,Tau): #Expandemos las funciones en un solo arreglo
FFF = []
map(lambda g: FFF.append(g),f(XX,r,Tau))
map(lambda g: FFF.append(g),JY(r,Tau))
return map(lambda f: f.evalf(subs={X[j]:x[j] for j in xrange(L*(L+1))}),FFF)
def RKutta(xi,r):
i = 1
while i <= int(TMAX/dt):
Tau = 0
YY = xi
k1 = np.array(Func(YY,r,Tau))*dt
k2 = (np.array(Func(YY + k1/2,r,Tau/2)))*dt
k3 = (np.array(Func(YY + k2/2,r,Tau/2)))*dt
k4 = (np.array(Func(YY + k3,r,Tau)))*dt
xi = YY + (k1/6) + (k2/3) + (k3/3) + (k4/6)
Tau = Tau + dt
i = i + 1
return [xi[j] for j in xrange(len(xi))]
def lyap(xxi):
u = [i for i in flatten(np.random.rand(1,L))]
PhiT = (np.array([[float(xxi[i+j]) for j in ran3] for i in ran4])).T
PU = np.dot(PhiT,u)
summ = 0
jj = 0
while jj < len(PU):
summ += (float(PU[jj]))**2
jj = jj + 1
lam = log(sqrt(summ))/TMAX
return lam
R = 46.5
Rmax = 48.5
Rstep = 0.5
while R <= Rmax:
xi = [5,5,5,5,5,5,5] #Condiciones Iniciales
for i in ran2:
xi.append(None)
for i in ran4:
for j in ran3:
if (i+j+1)%(L+1) == 0:
xi[i+j] = 1
else:
xi[i+j] = 0
#Ahora el Runge Kutta para integrar todo el sistema
#Y.append([r for r in xx])
# savetxt('butterfly.txt', Y, fmt="%12.6G")
#print Y
XI = RKutta(xi,R)
lamb = lyap(XI)
LAM.append([R,lamb])
print [R,lamb]
R = R + Rstep
#print LAM
#x = [LAM[i][0] for i in xrange(len(LAM))]
#y = [LAM[i][1] for i in xrange(len(LAM))]
np.savetxt('lyap3.txt', LAM, fmt="%12.6G")
#plt.axis([10,30,-3,3]);
#plt.scatter(x,y)
#plt.show()
I don't know where the problem could be. Maybe at the Runge Kutta steps or an architecture problem. The memory don't seem to be cleaned at every step and i'm not storing anything, just a pair of numbers at the end of the code.
I hope i expressed myself well.
#
OK, i edited this and posted the whole code, i hope someone can help :) . I changed a lot of things, but i still have the memory problem. Each cicle uses about 600 Mb of RAM.
#
Thanks in advance
A:
It's a little tricky to follow the code without context, seeing as you've apparently used numpy in multiple places (both as np and without prefix), and evalf might be from sympy.. but we don't see your imports.
At a very vague guess, some of your list comprehensions build temporary lists that stick around longer than expected. You could perhaps convert those into generators. Another technique is using map() or similar as much as possible.
I also notice a bit of unpythonic index iteration where it's not needed. Func first builds a list called FFF, one item at a time (fairly expensive), then iterates through it by index for no real reason. Use [f(item) for item in seq] rather than [f(seq[i]) for i in xrange(len(seq))], or better yet, map(f, seq), and in this case, try not building the temporary list at all.
A:
What's L? Much of your code uses O(L^2) storage, so if L is large that will be it.
A:
Seems like you are instantiating very large lists. Look if you can't replace some of the list comprehensions with iterators.
| Python memory problem | i started programming on python but i have a memory problem (sorry for my bad english).
I made a while loop on my algorithm, but on every cicle, the program consummes a lot of memory. I have 3Gb of RAM an AMD 64 x2 processor, and Windows 7 64 bits.
For every cicle, it consummes about 800 Mb of RAM, it's too much i think.
Part of my code is here
from sympy import Symbol, diff, flatten
import numpy as np
from numpy import linalg
from math import log, sqrt, cos, pi
import matplotlib.pyplot as plt
L = 7 #numero de variables
X = [Symbol('x%d' % i) for i in range(L*(L+1))] #Las variables simbolicas
XX = [X[i] for i in xrange(L)]
LAM = []
# Parametros
Pr = 10
Eps = 0
Ome = 5
LL = 0.5
b = 2
Gam = 0.2*2*(pi**2)
ran1 = xrange(L)
ran2 = xrange(L*L)
ran3 = xrange(0,L*(L-1)+1,L)
ran4 = xrange(L,2*L,1)
dt = 0.01
TMAX = 60
def f(x,R,Tau):
return [Pr*((1 + Eps*cos(Ome*Tau))*x[2] - LL*x[0] - (1 -LL*x[5])) , \
Pr*((1 + Eps*cos(Ome*Tau))*x[3] - LL*x[1] - (1 - LL)*x[6]),\
R*x[0] - x[2] - x[0]*x[4],R*x[1] - x[3] - x[1]*x[4],(x[0]*x[2] + x[1]*x[3])/2 - b*x[4],\
(1/Gam)*(x[0] - x[5]),(1/Gam)*(x[1] - x[6])]
def Jacobian(f,x): #num son los numeros en el que se evalua la matriz jacobiana, x las variables y f la funcion
return [[diff(f[i],x[n]) for i in ran1] for n in ran1]
def Y(x):
return[[x[i+j] for j in ran3] for i in ran4]
#Ahora la multiplicacion de Y traspuesto por Jacobian traspuesto
def JY(r,Tau):
J = flatten((np.dot(np.array(Jacobian(f(XX,r,Tau),XX)),np.array(Y(X)))).T)
return [J[i] for i in ran2]
def Func(x,r,Tau): #Expandemos las funciones en un solo arreglo
FFF = []
map(lambda g: FFF.append(g),f(XX,r,Tau))
map(lambda g: FFF.append(g),JY(r,Tau))
return map(lambda f: f.evalf(subs={X[j]:x[j] for j in xrange(L*(L+1))}),FFF)
def RKutta(xi,r):
i = 1
while i <= int(TMAX/dt):
Tau = 0
YY = xi
k1 = np.array(Func(YY,r,Tau))*dt
k2 = (np.array(Func(YY + k1/2,r,Tau/2)))*dt
k3 = (np.array(Func(YY + k2/2,r,Tau/2)))*dt
k4 = (np.array(Func(YY + k3,r,Tau)))*dt
xi = YY + (k1/6) + (k2/3) + (k3/3) + (k4/6)
Tau = Tau + dt
i = i + 1
return [xi[j] for j in xrange(len(xi))]
def lyap(xxi):
u = [i for i in flatten(np.random.rand(1,L))]
PhiT = (np.array([[float(xxi[i+j]) for j in ran3] for i in ran4])).T
PU = np.dot(PhiT,u)
summ = 0
jj = 0
while jj < len(PU):
summ += (float(PU[jj]))**2
jj = jj + 1
lam = log(sqrt(summ))/TMAX
return lam
R = 46.5
Rmax = 48.5
Rstep = 0.5
while R <= Rmax:
xi = [5,5,5,5,5,5,5] #Condiciones Iniciales
for i in ran2:
xi.append(None)
for i in ran4:
for j in ran3:
if (i+j+1)%(L+1) == 0:
xi[i+j] = 1
else:
xi[i+j] = 0
#Ahora el Runge Kutta para integrar todo el sistema
#Y.append([r for r in xx])
# savetxt('butterfly.txt', Y, fmt="%12.6G")
#print Y
XI = RKutta(xi,R)
lamb = lyap(XI)
LAM.append([R,lamb])
print [R,lamb]
R = R + Rstep
#print LAM
#x = [LAM[i][0] for i in xrange(len(LAM))]
#y = [LAM[i][1] for i in xrange(len(LAM))]
np.savetxt('lyap3.txt', LAM, fmt="%12.6G")
#plt.axis([10,30,-3,3]);
#plt.scatter(x,y)
#plt.show()
I don't know where the problem could be. Maybe at the Runge Kutta steps or an architecture problem. The memory don't seem to be cleaned at every step and i'm not storing anything, just a pair of numbers at the end of the code.
I hope i expressed myself well.
#
OK, i edited this and posted the whole code, i hope someone can help :) . I changed a lot of things, but i still have the memory problem. Each cicle uses about 600 Mb of RAM.
#
Thanks in advance
| [
"It's a little tricky to follow the code without context, seeing as you've apparently used numpy in multiple places (both as np and without prefix), and evalf might be from sympy.. but we don't see your imports.\nAt a very vague guess, some of your list comprehensions build temporary lists that stick around longer ... | [
1,
0,
0
] | [] | [] | [
"memory",
"python"
] | stackoverflow_0004110423_memory_python.txt |
Q:
class definition inside a class?
class ItemForm(djangoforms.ModelForm):
class Meta:
model = Item
exclude = ['added_by']
i can not understand what this piece of code is doing .i understood that ItemForm is inheriting Modelform but then a class definition inside a class ??
The Item class is :
class Item(db.Model):
name = db.StringProperty()
quantity = db.IntegerProperty(default=1)
target_price = db.FloatProperty()
priority = db.StringProperty(default='Medium',choices=[
'High', 'Medium', 'Low'])
entry_time = db.DateTimeProperty(auto_now_add=True)
added_by = db.UserProperty()
A:
It's part of Django's magic. The metaclass for ModelForm (among other classes) looks for an inner Meta class and uses it to make various changes to the outer class. It's one of the deeper parts of Python that most people will never have to deal with first-hand.
A:
In Python you can define classes within other classes as a way of encapsulating the inner class. The way Django is using this is actually quite excellent.
See this link for more info: http://www.geekinterview.com/question_details/64739
A:
Meta is a special class definition.
In this example, it is a simple inheritance model. ModelForm creates a form based on a Model class, so via giving a class definiton to ModelForm class, it creates the form elements according to related Model class definiton.
| class definition inside a class? | class ItemForm(djangoforms.ModelForm):
class Meta:
model = Item
exclude = ['added_by']
i can not understand what this piece of code is doing .i understood that ItemForm is inheriting Modelform but then a class definition inside a class ??
The Item class is :
class Item(db.Model):
name = db.StringProperty()
quantity = db.IntegerProperty(default=1)
target_price = db.FloatProperty()
priority = db.StringProperty(default='Medium',choices=[
'High', 'Medium', 'Low'])
entry_time = db.DateTimeProperty(auto_now_add=True)
added_by = db.UserProperty()
| [
"It's part of Django's magic. The metaclass for ModelForm (among other classes) looks for an inner Meta class and uses it to make various changes to the outer class. It's one of the deeper parts of Python that most people will never have to deal with first-hand.\n",
"In Python you can define classes within other ... | [
3,
1,
0
] | [] | [] | [
"django_forms",
"python"
] | stackoverflow_0004112524_django_forms_python.txt |
Q:
I change python code, but python doesn't seem to read the changes
So, I've been programming in python and I've run into this really annoying issue. I wrote a small matrix library and started using it in another module (eg, import matrixlib). I'd find a bug, fix it and run the program again. Bug still there.
I'd throw in a few print statements to see what's going on, but they wouldn't print. I eventually figured out that my changes weren't registering with python. So I started deleting .pyc files (precompiled python) but that didn't help.
I eventually gave up and just started programming straight from the matrix lib file, but now that issue has come back. I threw in a print statement to figure out what was going on with a method, fixed the issue, and took it out. But it still prints. I even did a search for 'print' in a different text editor than IDLE, but found only not a single print statement in the code.
This isn't really a code issue per say, I've probably mucked up my python install somehow. (This only happens on my windows box, not my linux box). If you want to see the code anyway, feel free. The hiesenbug-print statement is commented out in my code, yet still executes.
def det(self):
#Had better be a square matrix.
if self.colCount() != self.rowCount():
return None
#Are we a 1x1 matrix?
if self.colCount() == self.rowCount() == 1:
return self.a[0][0]
#Are we a 2x2 matrix?
if self.colCount() == self.rowCount() == 2:
return self.a[0][0]*self.a[1][1]-self.a[1][0]*self.a[0][1]
#Not a 2x2... so lets start recursing.
d = 0
for e in range(0,self.colCount()):
tmp = partition(self.a, 0, e)
if e%2 == 0:
d = d + self.a[0][e]*self.detRecursive(tmp)
else:
d = d - self.a[0][e]*self.detRecursive(tmp)
#print d
return d
def detRecursive(self, matrix):
m = Matrix()
m.setMatrix(matrix)
return m.det()
def partition(a, r, c):
out = []
for row in range(0, len(a)):
if r != row:
out.append([])
for col in range(0, len(a[0])):
if col != c:
out[-1].append(a[row][col])
return out
A:
i think that when you have installed your package the first time you did:
python setup.py install
rather than:
python setup.py develop
because when you do setup.py install the setup.py just copy the package files in the system path so every time you do a change in the package file you have to rerun setup.py install
in the other hand setup.py develop install your package in 'development mode' which mean that it just create a link (an eggs) to your "local" package files so every changes in the library "local" files is detected (it just a link)
Hope this will help :)
A:
Right after you import matrixlib in your main program:
print(repr(matrixlib))
raise SystemExit
Check the location of the actual loaded module.
| I change python code, but python doesn't seem to read the changes | So, I've been programming in python and I've run into this really annoying issue. I wrote a small matrix library and started using it in another module (eg, import matrixlib). I'd find a bug, fix it and run the program again. Bug still there.
I'd throw in a few print statements to see what's going on, but they wouldn't print. I eventually figured out that my changes weren't registering with python. So I started deleting .pyc files (precompiled python) but that didn't help.
I eventually gave up and just started programming straight from the matrix lib file, but now that issue has come back. I threw in a print statement to figure out what was going on with a method, fixed the issue, and took it out. But it still prints. I even did a search for 'print' in a different text editor than IDLE, but found only not a single print statement in the code.
This isn't really a code issue per say, I've probably mucked up my python install somehow. (This only happens on my windows box, not my linux box). If you want to see the code anyway, feel free. The hiesenbug-print statement is commented out in my code, yet still executes.
def det(self):
#Had better be a square matrix.
if self.colCount() != self.rowCount():
return None
#Are we a 1x1 matrix?
if self.colCount() == self.rowCount() == 1:
return self.a[0][0]
#Are we a 2x2 matrix?
if self.colCount() == self.rowCount() == 2:
return self.a[0][0]*self.a[1][1]-self.a[1][0]*self.a[0][1]
#Not a 2x2... so lets start recursing.
d = 0
for e in range(0,self.colCount()):
tmp = partition(self.a, 0, e)
if e%2 == 0:
d = d + self.a[0][e]*self.detRecursive(tmp)
else:
d = d - self.a[0][e]*self.detRecursive(tmp)
#print d
return d
def detRecursive(self, matrix):
m = Matrix()
m.setMatrix(matrix)
return m.det()
def partition(a, r, c):
out = []
for row in range(0, len(a)):
if r != row:
out.append([])
for col in range(0, len(a[0])):
if col != c:
out[-1].append(a[row][col])
return out
| [
"i think that when you have installed your package the first time you did:\npython setup.py install\n\nrather than:\npython setup.py develop\n\nbecause when you do setup.py install the setup.py just copy the package files in the system path so every time you do a change in the package file you have to rerun setup.p... | [
5,
1
] | [] | [] | [
"python"
] | stackoverflow_0004110733_python.txt |
Q:
How do I derive from hashlib.sha256 in Python?
A naive attempt fails miserably:
import hashlib
class fred(hashlib.sha256):
pass
-> TypeError: Error when calling the metaclass bases
cannot create 'builtin_function_or_method' instances
Well, it turns out that hashlib.sha256 is a callable, not a class. Trying something a bit more creative doesn't work either:
import hashlib
class fred(type(hashlib.sha256())):
pass
f = fred
-> TypeError: cannot create 'fred' instances
Hmmm...
So, how do I do it?
Here is what I want to actually achieve:
class shad_256(sha256):
"""Double SHA - sha256(sha256(data).digest())
Less susceptible to length extension attacks than sha256 alone."""
def digest(self):
return sha256(sha256.digest(self)).digest()
def hexdigest(self):
return sha256(sha256.digest(self)).hexdigest()
Basically I want everything to pass through except when someone calls for a result I want to insert an extra step of my own. Is there a clever way I can accomplish this with __new__ or metaclass magic of some sort?
I have a solution I'm largely happy with that I posted as an answer, but I'm really interested to see if anybody can think of anything better. Either much less verbose with very little cost in readability or much faster (particularly when calling update) while still being somewhat readable.
Update: I ran some tests:
# test_sha._timehash takes three parameters, the hash object generator to use,
# the number of updates and the size of the updates.
# Built in hashlib.sha256
$ python2.7 -m timeit -n 100 -s 'import test_sha, hashlib' 'test_sha._timehash(hashlib.sha256, 20000, 512)'
100 loops, best of 3: 104 msec per loop
# My wrapper based approach (see my answer)
$ python2.7 -m timeit -n 100 -s 'import test_sha, hashlib' 'test_sha._timehash(test_sha.wrapper_shad_256, 20000, 512)'
100 loops, best of 3: 108 msec per loop
# Glen Maynard's getattr based approach
$ python2.7 -m timeit -n 100 -s 'import test_sha, hashlib' 'test_sha._timehash(test_sha.getattr_shad_256, 20000, 512)'
100 loops, best of 3: 103 msec per loop
A:
Make a new class, derive from object, create a hashlib.sha256 member var in init, then define methods expected of a hash class and proxy to the same methods of the member variable.
Something like:
import hashlib
class MyThing(object):
def __init__(self):
self._hasher = hashlib.sha256()
def digest(self):
return self._hasher.digest()
And so on for the other methods.
A:
Just use __getattr__ to cause all attributes that you don't define yourself to fall back on the underlying object:
import hashlib
class shad_256(object):
"""
Double SHA - sha256(sha256(data).digest())
Less susceptible to length extension attacks than sha256 alone.
>>> s = shad_256('hello world')
>>> s.digest_size
32
>>> s.block_size
64
>>> s.sha256.hexdigest()
'b94d27b9934d3e08a52e52d7da7dabfac484efe37a5380ee9088f7ace2efcde9'
>>> s.hexdigest()
'bc62d4b80d9e36da29c16c5d4d9f11731f36052c72401a76c23c0fb5a9b74423'
>>> s.nonexistant()
Traceback (most recent call last):
...
AttributeError: '_hashlib.HASH' object has no attribute 'nonexistant'
>>> s2 = s.copy()
>>> s2.digest() == s.digest()
True
>>> s2.update("text")
>>> s2.digest() == s.digest()
False
"""
def __init__(self, data=None):
self.sha256 = hashlib.sha256()
if data is not None:
self.update(data)
def __getattr__(self, key):
return getattr(self.sha256, key)
def _get_final_sha256(self):
return hashlib.sha256(self.sha256.digest())
def digest(self):
return self._get_final_sha256().digest()
def hexdigest(self):
return self._get_final_sha256().hexdigest()
def copy(self):
result = shad_256()
result.sha256 = self.sha256.copy()
return result
if __name__ == "__main__":
import doctest
doctest.testmod()
This mostly eliminates the overhead for update calls, but not completely. If you want to completely eliminate it, add this to __init__ (and correspondingly in copy):
self.update = self.sha256.update
That will eliminate the extra __getattr__ call when looking up update.
This all takes advantage of one of the more useful and often overlooked properties of Python member functions: function binding. Recall that you can do this:
a = "hello"
b = a.upper
b()
because taking a reference to a member function doesn't return the original function, but a binding of that function to its object. That's why, when __getattr__ above returns self.sha256.update, the returned function correctly operates on self.sha256, not self.
A:
So, here is the answer I came up with that's based on Glen's answer, which is the one I awarded him the bounty for:
import hashlib
class _double_wrapper(object):
"""This wrapper exists because the various hashes from hashlib are
factory functions and there is no type that can be derived from.
So this class simulates deriving from one of these factory
functions as if it were a class and then implements the 'd'
version of the hash function which avoids length extension attacks
by applying H(H(text)) instead of just H(text)."""
__slots__ = ('_wrappedinstance', '_wrappedfactory', 'update')
def __init__(self, wrappedfactory, *args):
self._wrappedfactory = wrappedfactory
self._assign_instance(wrappedfactory(*args))
def _assign_instance(self, instance):
"Assign new wrapped instance and set update method."
self._wrappedinstance = instance
self.update = instance.update
def digest(self):
"return the current digest value"
return self._wrappedfactory(self._wrappedinstance.digest()).digest()
def hexdigest(self):
"return the current digest as a string of hexadecimal digits"
return self._wrappedfactory(self._wrappedinstance.digest()).hexdigest()
def copy(self):
"return a copy of the current hash object"
new = self.__class__()
new._assign_instance(self._wrappedinstance.copy())
return new
digest_size = property(lambda self: self._wrappedinstance.digest_size,
doc="number of bytes in this hashes output")
digestsize = digest_size
block_size = property(lambda self: self._wrappedinstance.block_size,
doc="internal block size of hash function")
class shad_256(_double_wrapper):
"""
Double SHA - sha256(sha256(data))
Less susceptible to length extension attacks than SHA2_256 alone.
>>> import binascii
>>> s = shad_256('hello world')
>>> s.name
'shad256'
>>> int(s.digest_size)
32
>>> int(s.block_size)
64
>>> s.hexdigest()
'bc62d4b80d9e36da29c16c5d4d9f11731f36052c72401a76c23c0fb5a9b74423'
>>> binascii.hexlify(s.digest()) == s.hexdigest()
True
>>> s2 = s.copy()
>>> s2.digest() == s.digest()
True
>>> s2.update("text")
>>> s2.digest() == s.digest()
False
"""
__slots__ = ()
def __init__(self, *args):
super(shad_256, self).__init__(hashlib.sha256, *args)
name = property(lambda self: 'shad256', doc='algorithm name')
This is a little verbose, but results in a class that works very nicely from a documentation perspective and has a relatively clear implementation. With Glen's optimization, update is as fast as it possibly can be.
There is one annoyance, which is that the update function shows up as a data member and doesn't have a docstring. I think that's a readability/efficiency tradeoff that's acceptable.
A:
from hashlib import sha256
class shad_256(object):
def __init__(self, data=''):
self._hash = sha256(data)
def __getattr__(self, attr):
setattr(self, attr, getattr(self._hash, attr))
return getattr(self, attr)
def copy(self):
ret = shad_256()
ret._hash = self._hash.copy()
return ret
def digest(self):
return sha256(self._hash.digest()).digest()
def hexdigest(self):
return sha256(self._hash.digest()).hexdigest()
Any attributes that are not found on an instance are bound lazily by __getattr__. copy() needs to be treated specially of course.
| How do I derive from hashlib.sha256 in Python? | A naive attempt fails miserably:
import hashlib
class fred(hashlib.sha256):
pass
-> TypeError: Error when calling the metaclass bases
cannot create 'builtin_function_or_method' instances
Well, it turns out that hashlib.sha256 is a callable, not a class. Trying something a bit more creative doesn't work either:
import hashlib
class fred(type(hashlib.sha256())):
pass
f = fred
-> TypeError: cannot create 'fred' instances
Hmmm...
So, how do I do it?
Here is what I want to actually achieve:
class shad_256(sha256):
"""Double SHA - sha256(sha256(data).digest())
Less susceptible to length extension attacks than sha256 alone."""
def digest(self):
return sha256(sha256.digest(self)).digest()
def hexdigest(self):
return sha256(sha256.digest(self)).hexdigest()
Basically I want everything to pass through except when someone calls for a result I want to insert an extra step of my own. Is there a clever way I can accomplish this with __new__ or metaclass magic of some sort?
I have a solution I'm largely happy with that I posted as an answer, but I'm really interested to see if anybody can think of anything better. Either much less verbose with very little cost in readability or much faster (particularly when calling update) while still being somewhat readable.
Update: I ran some tests:
# test_sha._timehash takes three parameters, the hash object generator to use,
# the number of updates and the size of the updates.
# Built in hashlib.sha256
$ python2.7 -m timeit -n 100 -s 'import test_sha, hashlib' 'test_sha._timehash(hashlib.sha256, 20000, 512)'
100 loops, best of 3: 104 msec per loop
# My wrapper based approach (see my answer)
$ python2.7 -m timeit -n 100 -s 'import test_sha, hashlib' 'test_sha._timehash(test_sha.wrapper_shad_256, 20000, 512)'
100 loops, best of 3: 108 msec per loop
# Glen Maynard's getattr based approach
$ python2.7 -m timeit -n 100 -s 'import test_sha, hashlib' 'test_sha._timehash(test_sha.getattr_shad_256, 20000, 512)'
100 loops, best of 3: 103 msec per loop
| [
"Make a new class, derive from object, create a hashlib.sha256 member var in init, then define methods expected of a hash class and proxy to the same methods of the member variable.\nSomething like:\nimport hashlib\n\nclass MyThing(object):\n def __init__(self):\n self._hasher = hashlib.sha256()\n\n de... | [
7,
6,
2,
0
] | [] | [] | [
"cryptography",
"python",
"security"
] | stackoverflow_0004029632_cryptography_python_security.txt |
Q:
Boost.Python: Ownership of pointer variables
I'm exposing a C++ tree class using Boost.Python to python. The node class holds a list of child nodes and provides a method
void add_child(Node *node)
The Node class takes ownership of the provided Node pointer and deletes it's child nodes when the destuctor gets called.
I'm exposing the add_child method as:
.def("addChild", &Node::add_child)
My actual question is: How do i tell Boost.Python that the Node class takes ownership of the child nodes?
Because if i execute the following code in python:
parentNode = Node()
node = Node()
parentNode.addChild(node)
the object referenced by the node variable gets deleted twice at the end of the script. Once when the node variable gets deleted and a second time when the parentNode gets deleted.
A:
Answering my own question:
I've missed an FAQ entry in the Boost.Python documentation that gave me the right hint:
//The node class should be held by std::auto_ptr
class_<Node, std::auto_ptr<Node> >("Node")
Create a thin wrapper function for the add_child method:
void node_add_child(Node& n, std::auto_ptr<Node> child) {
n.add_child(child.get());
child.release();
}
Complete code to expose the node class:
//The node class should be held by std::auto_ptr
class_<Node, std::auto_ptr<Node> >("Node")
//expose the thin wrapper function as node.add_child()
.def("addChild", &node_add_child)
;
| Boost.Python: Ownership of pointer variables | I'm exposing a C++ tree class using Boost.Python to python. The node class holds a list of child nodes and provides a method
void add_child(Node *node)
The Node class takes ownership of the provided Node pointer and deletes it's child nodes when the destuctor gets called.
I'm exposing the add_child method as:
.def("addChild", &Node::add_child)
My actual question is: How do i tell Boost.Python that the Node class takes ownership of the child nodes?
Because if i execute the following code in python:
parentNode = Node()
node = Node()
parentNode.addChild(node)
the object referenced by the node variable gets deleted twice at the end of the script. Once when the node variable gets deleted and a second time when the parentNode gets deleted.
| [
"Answering my own question:\nI've missed an FAQ entry in the Boost.Python documentation that gave me the right hint:\n//The node class should be held by std::auto_ptr\nclass_<Node, std::auto_ptr<Node> >(\"Node\")\n\nCreate a thin wrapper function for the add_child method:\nvoid node_add_child(Node& n, std::auto_ptr... | [
4
] | [] | [] | [
"boost",
"boost_python",
"c++",
"python"
] | stackoverflow_0004112561_boost_boost_python_c++_python.txt |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.