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:
sorting lines based on data in the middle of the line (in python)
I have a list of domains and I want to sort them based on tld. whats the fastest way to do this?
A:
Use the key parameter to .sort() to provide a function that can retrieve the proper data to sort by.
import urlparse
def get_tld_from_domain(domain)
return urlparse.urlparse(domain).netloc.split('.')[-1]
list_of_domains.sort(key=get_tld_from_domain)
# or if you want to make a new list, instead of sorting the old one
sorted_list_of_domains = sorted(list_of_domains, key=get_tld_from_domain)
If you preferred, you could not define the function separately but instead just use a lambda function, but defining it separately can often make your code easier to read, which is always a plus.
A:
Also, remember that it is not trivial to get the TLD from a URL. Please check this link on SO. In python you can use the urlparse to parse URLs.
A:
As Gangadhar says, it's hard to know definitively which part of the netloc is the tld, but in your case I would modify Amber's code slightly. This will sort on the entire domain, by the last level first, then the second to last level, and so on.
This may be good enough for what you need without needing to refer to external lists
import urlparse
def get_reversed_domain(domain)
return urlparse.urlparse(domain).netloc.split('.')[::-1]
sorted_list_of_domains = sorted(list_of_domains, key=get_reversed_domain)
Just reread the OP, if the list is already just domains you can simply use
sorted_list_of_domains = sorted(list_of_domains, key=lambda x:x.split('.')[::-1])
| sorting lines based on data in the middle of the line (in python) | I have a list of domains and I want to sort them based on tld. whats the fastest way to do this?
| [
"Use the key parameter to .sort() to provide a function that can retrieve the proper data to sort by.\nimport urlparse\n\ndef get_tld_from_domain(domain)\n return urlparse.urlparse(domain).netloc.split('.')[-1]\n\nlist_of_domains.sort(key=get_tld_from_domain)\n\n# or if you want to make a new list, instead of so... | [
5,
2,
1
] | [] | [] | [
"python",
"sorting"
] | stackoverflow_0003553581_python_sorting.txt |
Q:
Is there a better trivial Python WebDAV server code snippet than this?
Does anyone have a better code snippet for a trivial Python WebDAV server? The code below (which is cobbled together from some Google search results) appears to work under Python 2.6, but I wonder if someone has something they have used before, a little more tested and complete. I'd prefer a stdlib-only snippet over a third-party package. It is for some test code to hit so does not have to be production-worthy.
import httplib
import BaseHTTPServer
class WebDAV(BaseHTTPServer.BaseHTTPRequestHandler):
"""
Ultra-simplistic WebDAV server.
"""
def do_PUT(self):
path = os.path.normpath(self.path)
if os.path.isabs(path):
path = path[1:] # safe assumption due to normpath above
directory = os.path.dirname(path)
if not os.path.isdir(directory):
os.makedirs(directory)
content_length = int(self.headers['Content-Length'])
with open(path, "w") as f:
f.write(self.rfile.read(content_length))
self.send_response(httplib.OK)
def server_main(server_class=BaseHTTPServer.HTTPServer,
handler_class=WebDAV):
server_class(('', 9231), handler_class).serve_forever()
A:
Or try WsgiDAV which is a refactored version of PyFileServer.
A:
You can try akaDAV. It is a WebDAV module for Twisted.
I think it is not maintained anymore, but I've got it to work and it supports most operations (except locks).
A:
WsgiDAV
| Is there a better trivial Python WebDAV server code snippet than this? | Does anyone have a better code snippet for a trivial Python WebDAV server? The code below (which is cobbled together from some Google search results) appears to work under Python 2.6, but I wonder if someone has something they have used before, a little more tested and complete. I'd prefer a stdlib-only snippet over a third-party package. It is for some test code to hit so does not have to be production-worthy.
import httplib
import BaseHTTPServer
class WebDAV(BaseHTTPServer.BaseHTTPRequestHandler):
"""
Ultra-simplistic WebDAV server.
"""
def do_PUT(self):
path = os.path.normpath(self.path)
if os.path.isabs(path):
path = path[1:] # safe assumption due to normpath above
directory = os.path.dirname(path)
if not os.path.isdir(directory):
os.makedirs(directory)
content_length = int(self.headers['Content-Length'])
with open(path, "w") as f:
f.write(self.rfile.read(content_length))
self.send_response(httplib.OK)
def server_main(server_class=BaseHTTPServer.HTTPServer,
handler_class=WebDAV):
server_class(('', 9231), handler_class).serve_forever()
| [
"Or try WsgiDAV which is a refactored version of PyFileServer.\n",
"You can try akaDAV. It is a WebDAV module for Twisted.\nI think it is not maintained anymore, but I've got it to work and it supports most operations (except locks).\n",
"WsgiDAV\n"
] | [
5,
1,
1
] | [] | [] | [
"python",
"webdav"
] | stackoverflow_0000702780_python_webdav.txt |
Q:
Django / Python, using variablized object names
I'm confused on how to do this, I'm passing in a dictionary with different values, such as "app" which is the name of the app (so that I can better decouple code for easier modularization).. so this is just a simplified example and its not working so I'm wondering how to use the variable "app" within the string that is calling the models import.. thanks for any advice
infodict={'app':'myappname'}
app = infodict['app']
from web1.app.models import modelname
A:
You probably need something like importlib (Python 2.7). If you version of Python doesn't have importlib then you can use plain old __import__.
For example:
import sys
module_name = "web1.%s.models" % app
__import__(module_name)
models = sys.modules[module_name]
models.modelname
A:
you should use contenttypes
| Django / Python, using variablized object names | I'm confused on how to do this, I'm passing in a dictionary with different values, such as "app" which is the name of the app (so that I can better decouple code for easier modularization).. so this is just a simplified example and its not working so I'm wondering how to use the variable "app" within the string that is calling the models import.. thanks for any advice
infodict={'app':'myappname'}
app = infodict['app']
from web1.app.models import modelname
| [
"You probably need something like importlib (Python 2.7). If you version of Python doesn't have importlib then you can use plain old __import__.\nFor example:\nimport sys\nmodule_name = \"web1.%s.models\" % app\n__import__(module_name)\nmodels = sys.modules[module_name]\nmodels.modelname\n\n",
"you should use con... | [
1,
1
] | [] | [] | [
"django",
"import",
"object",
"python"
] | stackoverflow_0003554233_django_import_object_python.txt |
Q:
How to best pickle/unpickle in class hierarchies if parent and child class instances are pickled
Assume I have a class A and a class B that is derived from A. I want to pickle/unpickle an instance of class B. Both A and B define the __getstate__/__setstate__ methods (Let's assume A and B are complex, which makes the use of __getstate__ and __setstate__ necessary). How should B call the __getstate__/__setstate__ methods of A? My current, but perhaps not the 'right' approach:
class A(object):
def __init__():
self.value=1
def __getstate__(self):
return (self.value)
def __setstate__(self, state):
(self.value) = state
class B(A):
def __init__():
self.anothervalue=2
def __getstate__(self):
return (A.__getstate__(self), self.anothervalue)
def __setstate__(self, state):
superstate, self.anothervalue = state
A.__setstate__(self, superstate)
A:
I would use super(B,self) to get instances of B to call the methods of A:
import cPickle
class A(object):
def __init__(self):
self.value=1
def __getstate__(self):
return self.value
def __setstate__(self, state):
self.value = state
class B(A):
def __init__(self):
super(B,self).__init__()
self.anothervalue=2
def __getstate__(self):
return (super(B,self).__getstate__(), self.anothervalue)
def __setstate__(self, state):
superstate, self.anothervalue = state
super(B,self).__setstate__(superstate)
b=B()
with open('a','w') as f:
cPickle.dump(b,f)
with open('a','r') as f:
c=cPickle.load(f)
print(b.value)
print(b.anothervalue)
See this article for more info on method resolution order (MRO) and super.
| How to best pickle/unpickle in class hierarchies if parent and child class instances are pickled | Assume I have a class A and a class B that is derived from A. I want to pickle/unpickle an instance of class B. Both A and B define the __getstate__/__setstate__ methods (Let's assume A and B are complex, which makes the use of __getstate__ and __setstate__ necessary). How should B call the __getstate__/__setstate__ methods of A? My current, but perhaps not the 'right' approach:
class A(object):
def __init__():
self.value=1
def __getstate__(self):
return (self.value)
def __setstate__(self, state):
(self.value) = state
class B(A):
def __init__():
self.anothervalue=2
def __getstate__(self):
return (A.__getstate__(self), self.anothervalue)
def __setstate__(self, state):
superstate, self.anothervalue = state
A.__setstate__(self, superstate)
| [
"I would use super(B,self) to get instances of B to call the methods of A:\nimport cPickle\nclass A(object):\n def __init__(self):\n self.value=1\n def __getstate__(self):\n return self.value\n def __setstate__(self, state):\n self.value = state\n\nclass B(A):\n def __init__(self):\... | [
4
] | [] | [] | [
"persistence",
"pickle",
"python"
] | stackoverflow_0003554310_persistence_pickle_python.txt |
Q:
Integrating messenger to an existing website
For an existing website and the users in it,how to integrate a chat application like yahoo or gmail or any other with minimum code changes.
A:
Ajax IM looks very good for this.
Alternatively, maybe something like PHP121?
These are both instant messenger style chat systems. If you're looking for something more like a chatroom, I have used Ajax Chat successfully in the past.
I think you'll need a fair bit of code changes however you approach this, if you want to support your existing groups of users.
| Integrating messenger to an existing website | For an existing website and the users in it,how to integrate a chat application like yahoo or gmail or any other with minimum code changes.
| [
"Ajax IM looks very good for this.\nAlternatively, maybe something like PHP121?\nThese are both instant messenger style chat systems. If you're looking for something more like a chatroom, I have used Ajax Chat successfully in the past.\nI think you'll need a fair bit of code changes however you approach this, if y... | [
1
] | [] | [] | [
"api",
"gmail",
"jquery",
"python",
"yahoo_messenger"
] | stackoverflow_0003554640_api_gmail_jquery_python_yahoo_messenger.txt |
Q:
Histogram Equalization
I am a beginner in Python. I want to make a small project on histogram equalisation. Basically I want to include changing contrast, color and crop option etc in my project. I am blank right now. Please suggest something. I am very keen to make this project but how to start?
A:
Python's PIL module has methods for controlling contrast, color, and cropping.
A:
You can use PythonMagick. It suports histogram equalization:
import PythonMagick
img = PythonMagick.Image("original.png")
img.equalize()
img.write("equalized.png")
PythonMagick is not very well documented itself, but its API directly corresponds to Magick++ API. Use Magick++ documentation for reference.
If PIL is enough for you, stick with PIL, it is better supported. I installed PythonMagick from the Ubuntu package, the project page does not open for me.
| Histogram Equalization | I am a beginner in Python. I want to make a small project on histogram equalisation. Basically I want to include changing contrast, color and crop option etc in my project. I am blank right now. Please suggest something. I am very keen to make this project but how to start?
| [
"Python's PIL module has methods for controlling contrast, color, and cropping.\n",
"You can use PythonMagick. It suports histogram equalization:\nimport PythonMagick\nimg = PythonMagick.Image(\"original.png\")\nimg.equalize()\nimg.write(\"equalized.png\")\n\nPythonMagick is not very well documented itself, but i... | [
3,
3
] | [] | [] | [
"image_processing",
"python"
] | stackoverflow_0003554763_image_processing_python.txt |
Q:
Get a list of the absolute paths of all the images in a page using BeautifulSoup
Could someone show me how to get a list of aboslute paths for all the images in a webpage using BeautifulSoup?
It's simple to get all the images. I'm doing this:
page_images = [image["src"] for image in soup.findAll("img")]
...but I'm having difficulties getting the absolute paths. Any help?
Thank you.
A:
You will have to normalize the paths after getting them. This can be done using urlparse.urljoin. For example:
>>> urlparse.urljoin("http://google.com/some/path/", "../../img/icon.png")
'http://google.com/img/icon.png'
A:
This is not using BeautifulSoup, but the more elegant (and well-maintained) lxml+pyquery:
import pyquery
from urlparse import urljoin
def make_images_absolute(self):
self('img').each(lambda: self(this).attr('src',
urljoin(self.base_url, self(this).attr('src'))))
url="http://lwn.net"
pq = pyquery.PyQuery(url)
for i in pq("img"):
print i.attrib["src"]
make_images_absolute(pq)
for i in pq("img"):
print i.attrib["src"]
| Get a list of the absolute paths of all the images in a page using BeautifulSoup | Could someone show me how to get a list of aboslute paths for all the images in a webpage using BeautifulSoup?
It's simple to get all the images. I'm doing this:
page_images = [image["src"] for image in soup.findAll("img")]
...but I'm having difficulties getting the absolute paths. Any help?
Thank you.
| [
"You will have to normalize the paths after getting them. This can be done using urlparse.urljoin. For example:\n>>> urlparse.urljoin(\"http://google.com/some/path/\", \"../../img/icon.png\")\n'http://google.com/img/icon.png'\n\n",
"This is not using BeautifulSoup, but the more elegant (and well-maintained) lxml+... | [
5,
0
] | [] | [] | [
"beautifulsoup",
"python"
] | stackoverflow_0003554826_beautifulsoup_python.txt |
Q:
unmount fuse fs from python script
I have developed fuse fs with python and now want to write tests for it. Before testing I mount fs to some dir:
fs = MyFuseFS()
fs.parse(errex=1, ['some_dir'])
fs.main()
After testing I want unmount my fs, want to do something like this:
fs.unmount()
Is it something like "unmount" method? Maybe there is another ways to unmount fs?
A:
http://packages.python.org/fs/expose/fuse.html
you can see what you need from this link.
>>> from fs.memoryfs import MemoryFS
>>> from fs.expose import fuse
>>> fs = MemoryFS()
>>> mp = fuse.mount(fs,"/mnt/my-memory-fs")
>>> mp.unmount()
you guessed the function name right :)
| unmount fuse fs from python script | I have developed fuse fs with python and now want to write tests for it. Before testing I mount fs to some dir:
fs = MyFuseFS()
fs.parse(errex=1, ['some_dir'])
fs.main()
After testing I want unmount my fs, want to do something like this:
fs.unmount()
Is it something like "unmount" method? Maybe there is another ways to unmount fs?
| [
"http://packages.python.org/fs/expose/fuse.html\nyou can see what you need from this link.\n>>> from fs.memoryfs import MemoryFS\n>>> from fs.expose import fuse\n>>> fs = MemoryFS()\n>>> mp = fuse.mount(fs,\"/mnt/my-memory-fs\")\n>>> mp.unmount()\n\nyou guessed the function name right :)\n"
] | [
3
] | [] | [] | [
"filesystems",
"fuse",
"linux",
"python",
"unit_testing"
] | stackoverflow_0003156264_filesystems_fuse_linux_python_unit_testing.txt |
Q:
Why does a meta class change the way issubclass() work?
OK, so I'm writing a framework that looks for python files in sub directories that are named task.py and then look for classes that are derived from the base class Task and collect them.
I decided that I needed to add a meta class to Task, but then the issubclass() started to behave in a weird way.
Here is how the directory layout looks:
start.py
tasks/__init__.py
tasks/base.py
tasks/sub/__init__.py # empty
tasks/sub/task.py
start.py:
#!/usr/bin/env python
from tasks.base import Task1, Task2
from tasks.sub.task import SubTask1, SubTask2
print "Normal import:"
print "is SubTask1 sub class of Task1? %s" % issubclass(SubTask1, Task1)
print "is SubTask2 sub class of Task2? %s" % issubclass(SubTask2, Task2)
from tasks import setup
print "Imp import:"
setup()
tasks/init.py
import os.path, imp, types
from tasks.base import Task1, Task2
# Find all task definitions
ALL_TASK1 = { }
ALL_TASK2 = { }
def _append_class(d, task, base):
if (type(task) == types.TypeType) and issubclass(task, base):
if task == base:
return
if not task.name in d:
d[task.name] = task
this_dir = os.path.dirname(os.path.abspath(__file__))
for root, dirs, files in os.walk(this_dir):
if not "task.py" in files:
continue
mod_name = "task"
f, pathname, description = imp.find_module(mod_name, [ root ])
m = imp.load_module(mod_name, f, pathname, description)
f.close()
for task in m.__dict__.itervalues():
_append_class(ALL_TASK1, task, Task1)
_append_class(ALL_TASK2, task, Task2)
def setup():
print "All Task1: %s" % ALL_TASK1
print "All Task2: %s" % ALL_TASK2
tasks/base.py
class MetaClass (type):
def __init__(cls, name, bases, attrs):
pass
class Base (object):
__metaclass__ = MetaClass
def method_using_metaclass_stuff(self):
pass
class Task1 (Base):
pass
class Task2 (object):
pass
tasks/sub/task.py
from tasks.base import Task1, Task2
class SubTask1 (Task1): # Derived from the __metaclass__ class
name = "subtask1"
class SubTask2 (Task2):
name = "subtask2"
When I run setup.py I got the following output (ALL_TASK1 dict is empty!):
Normal import:
is SubTask1 sub class of Task1? True
is SubTask2 sub class of Task2? True
Imp import:
All Task1: {}
All Task2: {'subtask2': <class 'task.SubTask2'>}
But when I comment out the __metaclass__ line in the class Base (Task1's base class) I got the output I expected (ALL_TASK1 dict isn't empty):
Normal import:
is SubTask1 sub class of Task1? True
is SubTask2 sub class of Task2? True
Imp import:
All Task1: {'subtask1': <class 'task.SubTask1'>}
All Task2: {'subtask2': <class 'task.SubTask2'>}
I don't understand how the meta class can affect issubclass() when the module is imported via the imp functions, but not when the module is imported with the normal import.
Can someone explain this to me (I'm using python 2.6.1)?
A:
Your code doesn't work via normal import either.
>>> from tasks.base import Task1
>>> type(Task1)
<class 'tasks.base.MetaClass'>
>>> from types import TypeType
>>> type(Task1) == TypeType
False
>>> issubclass(type(Task1), TypeType)
True
>>>
When you instantiate the metaclass (as a class), the instance doesn't have type TypeType, it has type tasks.base.MetaClass. if you test for that in addition to TypeType, then your code works as expected.
def _append_class(d, task, base):
if (issubclass(type(task), types.TypeType) and issubclass(task, base):
This yields the same output as when you commented out the metaclass line and has an advantage over your origninal code in that it allows your users to define their own metaclasses and have them function as tasks. If you want to explicitly dissallow this (and please don't, I might want to use your framework someday) you can just check for both your metaclass or TypeType specifically.
A:
When you define __metaclass__ in Base, the type(Base) becomes tasks.base.MetaClass, rather than types.TypeType.
It seems in _append_class that all you really care about is grabbing those tasks which are subclasses of base. So instead of
if (type(task) == types.TypeType) and issubclass(task, base):
you could just test issubclass(task,base) and catch exceptions otherwise:
try: isbase=issubclass(task, base)
except TypeError: isbase=False
if isbase:
| Why does a meta class change the way issubclass() work? | OK, so I'm writing a framework that looks for python files in sub directories that are named task.py and then look for classes that are derived from the base class Task and collect them.
I decided that I needed to add a meta class to Task, but then the issubclass() started to behave in a weird way.
Here is how the directory layout looks:
start.py
tasks/__init__.py
tasks/base.py
tasks/sub/__init__.py # empty
tasks/sub/task.py
start.py:
#!/usr/bin/env python
from tasks.base import Task1, Task2
from tasks.sub.task import SubTask1, SubTask2
print "Normal import:"
print "is SubTask1 sub class of Task1? %s" % issubclass(SubTask1, Task1)
print "is SubTask2 sub class of Task2? %s" % issubclass(SubTask2, Task2)
from tasks import setup
print "Imp import:"
setup()
tasks/init.py
import os.path, imp, types
from tasks.base import Task1, Task2
# Find all task definitions
ALL_TASK1 = { }
ALL_TASK2 = { }
def _append_class(d, task, base):
if (type(task) == types.TypeType) and issubclass(task, base):
if task == base:
return
if not task.name in d:
d[task.name] = task
this_dir = os.path.dirname(os.path.abspath(__file__))
for root, dirs, files in os.walk(this_dir):
if not "task.py" in files:
continue
mod_name = "task"
f, pathname, description = imp.find_module(mod_name, [ root ])
m = imp.load_module(mod_name, f, pathname, description)
f.close()
for task in m.__dict__.itervalues():
_append_class(ALL_TASK1, task, Task1)
_append_class(ALL_TASK2, task, Task2)
def setup():
print "All Task1: %s" % ALL_TASK1
print "All Task2: %s" % ALL_TASK2
tasks/base.py
class MetaClass (type):
def __init__(cls, name, bases, attrs):
pass
class Base (object):
__metaclass__ = MetaClass
def method_using_metaclass_stuff(self):
pass
class Task1 (Base):
pass
class Task2 (object):
pass
tasks/sub/task.py
from tasks.base import Task1, Task2
class SubTask1 (Task1): # Derived from the __metaclass__ class
name = "subtask1"
class SubTask2 (Task2):
name = "subtask2"
When I run setup.py I got the following output (ALL_TASK1 dict is empty!):
Normal import:
is SubTask1 sub class of Task1? True
is SubTask2 sub class of Task2? True
Imp import:
All Task1: {}
All Task2: {'subtask2': <class 'task.SubTask2'>}
But when I comment out the __metaclass__ line in the class Base (Task1's base class) I got the output I expected (ALL_TASK1 dict isn't empty):
Normal import:
is SubTask1 sub class of Task1? True
is SubTask2 sub class of Task2? True
Imp import:
All Task1: {'subtask1': <class 'task.SubTask1'>}
All Task2: {'subtask2': <class 'task.SubTask2'>}
I don't understand how the meta class can affect issubclass() when the module is imported via the imp functions, but not when the module is imported with the normal import.
Can someone explain this to me (I'm using python 2.6.1)?
| [
"Your code doesn't work via normal import either. \n>>> from tasks.base import Task1\n>>> type(Task1)\n<class 'tasks.base.MetaClass'>\n>>> from types import TypeType\n>>> type(Task1) == TypeType\nFalse\n>>> issubclass(type(Task1), TypeType)\nTrue\n>>> \n\nWhen you instantiate the metaclass (as a class), the instanc... | [
2,
0
] | [] | [] | [
"introspection",
"python"
] | stackoverflow_0003555283_introspection_python.txt |
Q:
Python's urllib equivalent in .net
Is there a .net equivalent for urllib I used in Python?
I've seen WebRequest and WebResponse classes but I wonder if there is a simpler wrapper. In urllib you can use dictionary object (tupple) to set POST parameters while in .Net one must fiddle with streams.
Is there any free, small web client library available for .net?
A:
You can use Webclient's UploadValues() or UploadString().
| Python's urllib equivalent in .net | Is there a .net equivalent for urllib I used in Python?
I've seen WebRequest and WebResponse classes but I wonder if there is a simpler wrapper. In urllib you can use dictionary object (tupple) to set POST parameters while in .Net one must fiddle with streams.
Is there any free, small web client library available for .net?
| [
"You can use Webclient's UploadValues() or UploadString().\n"
] | [
2
] | [] | [] | [
".net",
"python",
"webclient"
] | stackoverflow_0003555549_.net_python_webclient.txt |
Q:
Is there a python twitter search library that handle results the right way?
All the libraries I've tested search in twitter, let you specify the rpp (results per page) parameter but only gives you ONE page results.
It'd be cool a Python lib that provide a generator and each time gen.next() is called, a new search result is yielded. If the page is over, jump to the next page alone.
A:
This is what I was talking about: http://github.com/ryanmcgrath/twython/commit/e9aaaa7c39dad0306fec9e83cb377975f5c2d4d5
A:
I'm not sure I understand what you are asking, but I think the limit on what you can get is not a library limitation, but an API limitation (imposed by Twitter). You can read the methods available in their REST API here. Excerpt:
rpp
The number of tweets to return per page, up to a max of 100.
http://search.twitter.com/search.json?rpp=100
page
The page number (starting at 1) to return, up to a max of roughly 1500 results
(based on rpp * page).
http://search.twitter.com/search.json?page=10
| Is there a python twitter search library that handle results the right way? | All the libraries I've tested search in twitter, let you specify the rpp (results per page) parameter but only gives you ONE page results.
It'd be cool a Python lib that provide a generator and each time gen.next() is called, a new search result is yielded. If the page is over, jump to the next page alone.
| [
"This is what I was talking about: http://github.com/ryanmcgrath/twython/commit/e9aaaa7c39dad0306fec9e83cb377975f5c2d4d5\n",
"I'm not sure I understand what you are asking, but I think the limit on what you can get is not a library limitation, but an API limitation (imposed by Twitter). You can read the methods a... | [
1,
0
] | [] | [] | [
"python",
"twitter"
] | stackoverflow_0003552560_python_twitter.txt |
Q:
Better way, than this, to rename files using Python
I am python newbie and am still discovering its wonders.
I wrote a script which renames a number of files :
from Edison_03-08-2010-05-02-00_PM.7z to Edison_08-03-2010-05-02-00_PM.7z
"03-08-2010" is changed to "08-03-2010"
The script is:
import os, os.path
location = "D:/codebase/_Backups"
files = os.listdir(location)
for oldfilename in files:
parts = oldfilename.split("_")
dateparts = parts[1].split("-")
newfilename = parts[0] + "_" + dateparts[1] + "-" + dateparts[0] + "-" + dateparts[2] + "-" + parts[2] + "_" + parts[3]
print oldfilename + " : " + newfilename
os.rename(os.path.join(location, oldfilename), os.path.join(location, newfilename))
What would be a better/more elegant way of doing this ?
A:
datetime's strptime (parse time string) and strftime (format time string) will do most of the heavy lifting for you:
import datetime
_IN_FORMAT = 'Edison_%d-%m-%Y-%I-%M-%S_%p.7z'
_OUT_FORMAT = 'Edison_%m-%d-%Y-%I-%M-%S_%p.7z'
oldfilename = 'Edison_03-08-2010-05-02-00_PM.7z'
# Parse to datetime.
dt = datetime.datetime.strptime(oldfilename, _IN_FORMAT)
# Format to new format.
newfilename = dt.strftime(_OUT_FORMAT)
>>> print newfilename
Edison_08-03-2010-05-02-00_PM.7z
Edit: Originally I was using %H (Hour, 24-hour clock) where I should have used %I (Hour, 12-hour clock) because the OP used AM/PM. This is why my example output incorrectly contained AM instead of PM. This is all corrected now.
A:
How about this:
name, timestamp = oldfilename.split('_', 1)
day, month, timestamp = timestamp.split('-', 2)
newfilename = '%s_%s-%s-%s' % (name, day, month, timestamp)
| Better way, than this, to rename files using Python | I am python newbie and am still discovering its wonders.
I wrote a script which renames a number of files :
from Edison_03-08-2010-05-02-00_PM.7z to Edison_08-03-2010-05-02-00_PM.7z
"03-08-2010" is changed to "08-03-2010"
The script is:
import os, os.path
location = "D:/codebase/_Backups"
files = os.listdir(location)
for oldfilename in files:
parts = oldfilename.split("_")
dateparts = parts[1].split("-")
newfilename = parts[0] + "_" + dateparts[1] + "-" + dateparts[0] + "-" + dateparts[2] + "-" + parts[2] + "_" + parts[3]
print oldfilename + " : " + newfilename
os.rename(os.path.join(location, oldfilename), os.path.join(location, newfilename))
What would be a better/more elegant way of doing this ?
| [
"datetime's strptime (parse time string) and strftime (format time string) will do most of the heavy lifting for you:\nimport datetime\n\n_IN_FORMAT = 'Edison_%d-%m-%Y-%I-%M-%S_%p.7z'\n_OUT_FORMAT = 'Edison_%m-%d-%Y-%I-%M-%S_%p.7z'\n\noldfilename = 'Edison_03-08-2010-05-02-00_PM.7z'\n\n# Parse to datetime.\ndt = da... | [
8,
3
] | [] | [] | [
"file_io",
"python"
] | stackoverflow_0003556175_file_io_python.txt |
Q:
How to control links2 with Python
How can I execute links2 to open a web page and locate and click a text link with Python?
Is pexpect able to do it? Any examples are appreciated.
A:
Not sure why you want to do this. If you want to grab the web link and process the page content, urllib2 together with an HTML parser (BeautifulSoup for example) may be just fine.
If you do want to simulate moust clicks, you may want to use AutoPy.
A:
Why do you want to use links2? I don't see how you could benefit from that. It is probably better to approach your problem in a different way, like with mechanize or maybe even twill.
Please provide a description of your overall problem instead of that specific question
A:
if you want javascript support use selenium rc with whatever language you are comfortable with
| How to control links2 with Python | How can I execute links2 to open a web page and locate and click a text link with Python?
Is pexpect able to do it? Any examples are appreciated.
| [
"Not sure why you want to do this. If you want to grab the web link and process the page content, urllib2 together with an HTML parser (BeautifulSoup for example) may be just fine. \nIf you do want to simulate moust clicks, you may want to use AutoPy. \n",
"Why do you want to use links2? I don't see how you could... | [
1,
0,
0
] | [] | [] | [
"pexpect",
"python"
] | stackoverflow_0003544596_pexpect_python.txt |
Q:
Adding an array in numpy at a specified location
Is there a fast way in numpy to add array A to array B at a specified location?
For instance, if
B = [
[0, 1, 2],
[2, 3, 4],
[5, 6, 7]
]
and
A = [
[2, 2],
[2, 2]
]
and I want to add A to B starting from point (0, 0) to get
C = [
[2, 3, 2],
[4, 5, 4],
[5, 6, 7],
]
Of course I can do that via extending the array A to match the shape of B and then using numpy.roll, but it seems unnecessarily slow if the size of A is much much smaller then size of B.
EDIT:
potentially with wrapping around - ie such that bottom row of A is added to the top row of B and top row of A is added to the bottom row of B
A:
To modify B in place
B[:2,:2] += A
otherwise
C = B.copy()
C[:2,:2] += A
| Adding an array in numpy at a specified location | Is there a fast way in numpy to add array A to array B at a specified location?
For instance, if
B = [
[0, 1, 2],
[2, 3, 4],
[5, 6, 7]
]
and
A = [
[2, 2],
[2, 2]
]
and I want to add A to B starting from point (0, 0) to get
C = [
[2, 3, 2],
[4, 5, 4],
[5, 6, 7],
]
Of course I can do that via extending the array A to match the shape of B and then using numpy.roll, but it seems unnecessarily slow if the size of A is much much smaller then size of B.
EDIT:
potentially with wrapping around - ie such that bottom row of A is added to the top row of B and top row of A is added to the bottom row of B
| [
"To modify B in place\nB[:2,:2] += A\n\notherwise\nC = B.copy()\nC[:2,:2] += A\n\n"
] | [
1
] | [] | [] | [
"numpy",
"python"
] | stackoverflow_0003556613_numpy_python.txt |
Q:
Bug import main with arguments in Python
In a script I'm trying to import the main module from another script with an argument.
I get the error message "NameError: global name 'model' is not defined".
If someone sees the mistake, I'd be grateful !
My code :
script1
#!/usr/bin/python
import sys
import getopt
import pdb
import shelve
class Car:
""" class representing a car object """
def __init__(self, model):
self.model = model
class Porsche(Car):
""" class representing a Porsche """
def __init__(self, model):
Car.__init__(self, model)
print "I have a Porsche but no driving licence : too bad !"
# Main
def main(argv):
settings = shelve.open('mySettings')
global model
try:
opts, args = getopt.getopt(argv, "m:", ["model="])
except getopt.GetoptError, err:
print " wrong argument, exiting "
sys.exit()
for opt, arg in opts:
if opt in ("-m", "--model"):
model = arg
def choose_car(model):
""" Creates the car"""
my_Porsche = Porsche(model)
choose_car(model)
if __name__ == "__main__":
main(sys.argv[1:])
script2
#!/usr/bin/python
import os
import sample
import sys
def main(argv):
script1.main("-m Carrera")
# Main program
if __name__ == '__main__':
main(sys.argv[1:])
rgds,
A:
argv is a list. Therefore you should call script1.main as
script1.main(['-m', 'Carrera'])
or, equivalently,
script1.main('-m Carrera'.split())
| Bug import main with arguments in Python | In a script I'm trying to import the main module from another script with an argument.
I get the error message "NameError: global name 'model' is not defined".
If someone sees the mistake, I'd be grateful !
My code :
script1
#!/usr/bin/python
import sys
import getopt
import pdb
import shelve
class Car:
""" class representing a car object """
def __init__(self, model):
self.model = model
class Porsche(Car):
""" class representing a Porsche """
def __init__(self, model):
Car.__init__(self, model)
print "I have a Porsche but no driving licence : too bad !"
# Main
def main(argv):
settings = shelve.open('mySettings')
global model
try:
opts, args = getopt.getopt(argv, "m:", ["model="])
except getopt.GetoptError, err:
print " wrong argument, exiting "
sys.exit()
for opt, arg in opts:
if opt in ("-m", "--model"):
model = arg
def choose_car(model):
""" Creates the car"""
my_Porsche = Porsche(model)
choose_car(model)
if __name__ == "__main__":
main(sys.argv[1:])
script2
#!/usr/bin/python
import os
import sample
import sys
def main(argv):
script1.main("-m Carrera")
# Main program
if __name__ == '__main__':
main(sys.argv[1:])
rgds,
| [
"argv is a list. Therefore you should call script1.main as\nscript1.main(['-m', 'Carrera'])\n\nor, equivalently,\nscript1.main('-m Carrera'.split())\n\n"
] | [
3
] | [] | [] | [
"arguments",
"import",
"program_entry_point",
"python"
] | stackoverflow_0003556817_arguments_import_program_entry_point_python.txt |
Q:
How do I use Twitter Streaming API to track new followers of other accounts I don't have login information for?
I'm heavily basing my code off of this excellent tutorial at Ars Technica, so I am able to track my own new followers because my login information is hard-coded in. However, I'd like to track new followers of other people's accounts too. How can I do this without their passwords?
import pycurl, json, StringIO
STREAM_URL = "http://stream.twitter.com/1/statuses/filter.json?follow=[userid1],[userid2]&track=[keyword1],[keyword2]"
REST_URL = "http://api.twitter.com/1/"
class Client:
def __init__(self):
self.friends = []
self.buffer = ""
self.userid = None
self.conn = pycurl.Curl()
def authenticate(self, username, password):
output = StringIO.StringIO()
self.conn.setopt(pycurl.USERPWD, "%s:%s" % (username, password))
self.conn.setopt(pycurl.URL, REST_URL + "account/verify_credentials.json")
self.conn.setopt(pycurl.WRITEFUNCTION, output.write)
self.conn.perform()
data = json.loads(output.getvalue())
if "error" in data: return False
self.userid = data["id"]
return True
def connect(self):
self.conn.setopt(pycurl.URL, STREAM_URL)
self.conn.setopt(pycurl.WRITEFUNCTION, self.on_receive)
self.conn.perform()
def on_receive(self, data):
self.buffer += data
if data.endswith("\r\n") and self.buffer.strip():
content = json.loads(self.buffer)
self.buffer = ""
print content
if "friends" in content:
self.friends = content["friends"]
elif "event" in content and content["event"] == "follow":
id_list = ['[userid1]','[userid2]']
print "NEW FOLLOWER!!"
print "target id:", content["target"]["id"]
if content["target"]["id"] in id_list:
print content
print "New follower:", content["source"]["name"], "(@" + content["source"]["screen_name"] + ")"
elif content["source"]["id"] == self.userid:
self.friends.append(content["target"]["id"])
elif "text" in content:
to = content["in_reply_to_user_id"]
if to and to != self.userid and to not in self.friends: return
if to == self.userid: print "(REPLY)",
print u"{0[user][name]}: {0[text]}".format(content)
client = Client()
if client.authenticate("[username]", "[password]"):
client.connect()
else:
print "Login credentials aren't valid!"
A:
Taylor Singletary of Twitter responded to the same question on the Google group for Twitter Development Talk:
This is unfortunately not currently
possible with the Streaming API.
Given the flexibility of followers/ids
and friends/ids API methods, tracking
changes over time with those methods
would likely be your best avenue.
| How do I use Twitter Streaming API to track new followers of other accounts I don't have login information for? | I'm heavily basing my code off of this excellent tutorial at Ars Technica, so I am able to track my own new followers because my login information is hard-coded in. However, I'd like to track new followers of other people's accounts too. How can I do this without their passwords?
import pycurl, json, StringIO
STREAM_URL = "http://stream.twitter.com/1/statuses/filter.json?follow=[userid1],[userid2]&track=[keyword1],[keyword2]"
REST_URL = "http://api.twitter.com/1/"
class Client:
def __init__(self):
self.friends = []
self.buffer = ""
self.userid = None
self.conn = pycurl.Curl()
def authenticate(self, username, password):
output = StringIO.StringIO()
self.conn.setopt(pycurl.USERPWD, "%s:%s" % (username, password))
self.conn.setopt(pycurl.URL, REST_URL + "account/verify_credentials.json")
self.conn.setopt(pycurl.WRITEFUNCTION, output.write)
self.conn.perform()
data = json.loads(output.getvalue())
if "error" in data: return False
self.userid = data["id"]
return True
def connect(self):
self.conn.setopt(pycurl.URL, STREAM_URL)
self.conn.setopt(pycurl.WRITEFUNCTION, self.on_receive)
self.conn.perform()
def on_receive(self, data):
self.buffer += data
if data.endswith("\r\n") and self.buffer.strip():
content = json.loads(self.buffer)
self.buffer = ""
print content
if "friends" in content:
self.friends = content["friends"]
elif "event" in content and content["event"] == "follow":
id_list = ['[userid1]','[userid2]']
print "NEW FOLLOWER!!"
print "target id:", content["target"]["id"]
if content["target"]["id"] in id_list:
print content
print "New follower:", content["source"]["name"], "(@" + content["source"]["screen_name"] + ")"
elif content["source"]["id"] == self.userid:
self.friends.append(content["target"]["id"])
elif "text" in content:
to = content["in_reply_to_user_id"]
if to and to != self.userid and to not in self.friends: return
if to == self.userid: print "(REPLY)",
print u"{0[user][name]}: {0[text]}".format(content)
client = Client()
if client.authenticate("[username]", "[password]"):
client.connect()
else:
print "Login credentials aren't valid!"
| [
"Taylor Singletary of Twitter responded to the same question on the Google group for Twitter Development Talk:\n\nThis is unfortunately not currently\n possible with the Streaming API. \n Given the flexibility of followers/ids\n and friends/ids API methods, tracking \n changes over time with those methods\n wo... | [
1
] | [] | [] | [
"python",
"twitter"
] | stackoverflow_0003523364_python_twitter.txt |
Q:
need checking and padding sqlite database housekeeping and manipulate code
All,
Update: based on google result and answer, I added more hints, still not finished.
In using sqlite3 and during study of sqlalchemy, I found it is necessary to write below code for those housekeeping purpose for managing data, however, it may be a hard part for me to doing that in sqlalchemy then I turning back to sqlite3 module.
Below code lists 10 more steps as housekeeping jobs and most of them came from WEB, I doubt someone with expertise can checking and padding the missing part for it.
And if someone know how to do it in SQLAlchemy, could you also sharing it pls?
1. testing if the database file existing
import sqlite3
import os
database_name = "newdb.db"
if not os.path.isfile(database_name):
print "the database already exist"
# connect to to db, refer #2
db_connection = sqlite3.connect(database_name)
db_cursor = db_connection.cursor()
2. testing if database file is a valid sqlite3 format
http://stackoverflow.com/questions/1516508/sqlite3-in-python
>>> c.execute("SELECT * FROM tbl")
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
sqlite3.DatabaseError: file is encrypted or is not a database
=========sqlalchemy way ===============
http://www.mail-archive.com/sqlalchemy@googlegroups.com/msg20860.html
import os, os.path as osp
try:
from pysqlite2 import dbapi2 as sqlite
except:
import sqlite3 as sqlite
def isSQLite(filename):
"""True if filename is a SQLite database
File is database if: (1) file exists, (2) length is non-zero,
(3) can connect, (4) has sqlite_master table
"""
# validate file exists
if not osp.isfile(filename):
return False
# is not an empty file
if not os.stat(filename).st_size:
return False
# can open a connection
try:
conn = sqlite.connect(filename)
except:
return False
# has sqlite_master
try:
result = conn.execute('pragma table_info(sqlite_master)').fetchall()
if len(result) == 0:
conn.close()
return False
except:
conn.close()
return False
# looks like a good database
conn.close()
return True
3. check table exist
c=conn.cursor()
if table_name in [row for row in c.execute("SELECT name FROM sqlite_master WHERE type='table' AND name='table_name';")]
4.backup database file in disk
http://stuvel.eu/archive/55/safely-copy-a-sqlite-database
import shutil, os, sqlite3
if not os.path.isdir ( backupdir ):
raise Exception
backupfile = os.path.join ( backupdir, os.path.basename(dbfile) + time.strftime(".%Y%m%d-%H%M") )
db = sqlite3.connect ( dbfile )
cur = db.cursor ()
cur.execute ( 'begin immediate' )
shutil.copyfile ( dbfile, backupfile )
cur.execute ( 'rollback' )
=========or========
http://github.com/husio/python-sqlite3-backup
=========or========
http://docs.python.org/release/2.6/library/sqlite3.html#sqlite3.Connection.iterdump
5. backup table - in same database file
c=conn.cursor()
c.execute("CREATE TABLE demo_backup AS SELECT * FROM demo;")
6. rename table
c.execute("ALTER TABLE foo RENAME TO bar;")
7. copy table to/from different database:
Thanks, MPelletier
Connect to one database
db_connection = sqlite3.connect(database_file)
Attach the second database
db_connection.execute("ATTACH database_file2 AS database_name2")
Insert from one to the other:
db_connection.execute("INSERT INTO FooTable SELECT * FROM database_name2.FooTable")
==========or============
db_connection.execute("INSERT INTO database_name2.FooTable SELECT * FROM FooTable")
========sqlalchemy way======
http://www.mail-archive.com/sqlalchemy@googlegroups.com/msg11563.html
def duplicateToDisk(self, file):
'''Tohle ulozi databazi, ktera byla pouze v pameti, na disk'''
cur = self.connection()
import os
if os.path.exists(file):
os.remove(file)
cur.execute("attach %s as extern" % file)
self.checkTable('extern.dictionary')
cur.execute("insert into extern.dictionary select * from dictionary")
cur.execute("detach extern")
self.commit()
8 test database is locked or not?
#possible?
try:
c = sqlite.connect(database_name, timeout=0)
c.commit()
except OperationalError # OperationalError: database is locked
9. timeout to connect to database, waiting other invoker release the lock
c = sqlite.connect(database_name, timeout=30.0) # default 5sec
10 force all database connections release/commit A.K.A to release all lock?
refer #12
11. multi-threads in using sqlite in python:
http://code.activestate.com/recipes/526618/
http://www.yeraze.com/2009/01/python-sqlite-multiple-threads/
12 get conn from SQLAlchemy?
#from FAQ
#try to reuse the connection pool from SQLAlchemy
engine = create_engine(...)
conn = engine.connect() #****1
conn.connection.<do DBAPI things>
cursor = conn.connection.cursor(<DBAPI specific arguments..>)
===or ==== can out of pool's manage
conn = engine.connect()
conn.detach() # detaches the DBAPI connection from the connection pool
conn.connection.<go nuts>
conn.close() # connection is closed for real, the pool replaces it with a new connect
========and not sure if this works ===========
#from sqlalchemy document #http://www.sqlalchemy.org/docs/reference/sqlalchemy/pooling.html?highlight=connection%20pool
import sqlalchemy.pool as pool
import sqlite3 as sqlite3
conn_proxy = pool.manage(sqlite3)
# then connect normally
connection = conn_proxy.connect(...)
=====================================================================
#****1 : what is #****1 on above code invoked =_=!!
A engine.raw_connection()
=
A pool.unique_connection()
=
A _ConnectionFairy(self).checkout()
=
A return _ConnectionFairy <== cls
= _connection_record.get_connection()
= _ConnectionRecord.connection
= return a pool.creator **which is a callable function that returns a DB-API connection object**
Thanks for your time!
Rgs,
KC
A:
To copy data to/from a different database, the general SQLite approach is:
Connect to one database
db_connection = sqlite3.connect(database_file)
Attach the second database
db_connection.execute("ATTACH database_file2 AS database_name2")
Insert from one to the other:
db_connection.execute("INSERT INTO FooTable SELECT * FROM database_name2.FooTable")
or
db_connection.execute("INSERT INTO database_name2.FooTable SELECT * FROM FooTable")
| need checking and padding sqlite database housekeeping and manipulate code | All,
Update: based on google result and answer, I added more hints, still not finished.
In using sqlite3 and during study of sqlalchemy, I found it is necessary to write below code for those housekeeping purpose for managing data, however, it may be a hard part for me to doing that in sqlalchemy then I turning back to sqlite3 module.
Below code lists 10 more steps as housekeeping jobs and most of them came from WEB, I doubt someone with expertise can checking and padding the missing part for it.
And if someone know how to do it in SQLAlchemy, could you also sharing it pls?
1. testing if the database file existing
import sqlite3
import os
database_name = "newdb.db"
if not os.path.isfile(database_name):
print "the database already exist"
# connect to to db, refer #2
db_connection = sqlite3.connect(database_name)
db_cursor = db_connection.cursor()
2. testing if database file is a valid sqlite3 format
http://stackoverflow.com/questions/1516508/sqlite3-in-python
>>> c.execute("SELECT * FROM tbl")
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
sqlite3.DatabaseError: file is encrypted or is not a database
=========sqlalchemy way ===============
http://www.mail-archive.com/sqlalchemy@googlegroups.com/msg20860.html
import os, os.path as osp
try:
from pysqlite2 import dbapi2 as sqlite
except:
import sqlite3 as sqlite
def isSQLite(filename):
"""True if filename is a SQLite database
File is database if: (1) file exists, (2) length is non-zero,
(3) can connect, (4) has sqlite_master table
"""
# validate file exists
if not osp.isfile(filename):
return False
# is not an empty file
if not os.stat(filename).st_size:
return False
# can open a connection
try:
conn = sqlite.connect(filename)
except:
return False
# has sqlite_master
try:
result = conn.execute('pragma table_info(sqlite_master)').fetchall()
if len(result) == 0:
conn.close()
return False
except:
conn.close()
return False
# looks like a good database
conn.close()
return True
3. check table exist
c=conn.cursor()
if table_name in [row for row in c.execute("SELECT name FROM sqlite_master WHERE type='table' AND name='table_name';")]
4.backup database file in disk
http://stuvel.eu/archive/55/safely-copy-a-sqlite-database
import shutil, os, sqlite3
if not os.path.isdir ( backupdir ):
raise Exception
backupfile = os.path.join ( backupdir, os.path.basename(dbfile) + time.strftime(".%Y%m%d-%H%M") )
db = sqlite3.connect ( dbfile )
cur = db.cursor ()
cur.execute ( 'begin immediate' )
shutil.copyfile ( dbfile, backupfile )
cur.execute ( 'rollback' )
=========or========
http://github.com/husio/python-sqlite3-backup
=========or========
http://docs.python.org/release/2.6/library/sqlite3.html#sqlite3.Connection.iterdump
5. backup table - in same database file
c=conn.cursor()
c.execute("CREATE TABLE demo_backup AS SELECT * FROM demo;")
6. rename table
c.execute("ALTER TABLE foo RENAME TO bar;")
7. copy table to/from different database:
Thanks, MPelletier
Connect to one database
db_connection = sqlite3.connect(database_file)
Attach the second database
db_connection.execute("ATTACH database_file2 AS database_name2")
Insert from one to the other:
db_connection.execute("INSERT INTO FooTable SELECT * FROM database_name2.FooTable")
==========or============
db_connection.execute("INSERT INTO database_name2.FooTable SELECT * FROM FooTable")
========sqlalchemy way======
http://www.mail-archive.com/sqlalchemy@googlegroups.com/msg11563.html
def duplicateToDisk(self, file):
'''Tohle ulozi databazi, ktera byla pouze v pameti, na disk'''
cur = self.connection()
import os
if os.path.exists(file):
os.remove(file)
cur.execute("attach %s as extern" % file)
self.checkTable('extern.dictionary')
cur.execute("insert into extern.dictionary select * from dictionary")
cur.execute("detach extern")
self.commit()
8 test database is locked or not?
#possible?
try:
c = sqlite.connect(database_name, timeout=0)
c.commit()
except OperationalError # OperationalError: database is locked
9. timeout to connect to database, waiting other invoker release the lock
c = sqlite.connect(database_name, timeout=30.0) # default 5sec
10 force all database connections release/commit A.K.A to release all lock?
refer #12
11. multi-threads in using sqlite in python:
http://code.activestate.com/recipes/526618/
http://www.yeraze.com/2009/01/python-sqlite-multiple-threads/
12 get conn from SQLAlchemy?
#from FAQ
#try to reuse the connection pool from SQLAlchemy
engine = create_engine(...)
conn = engine.connect() #****1
conn.connection.<do DBAPI things>
cursor = conn.connection.cursor(<DBAPI specific arguments..>)
===or ==== can out of pool's manage
conn = engine.connect()
conn.detach() # detaches the DBAPI connection from the connection pool
conn.connection.<go nuts>
conn.close() # connection is closed for real, the pool replaces it with a new connect
========and not sure if this works ===========
#from sqlalchemy document #http://www.sqlalchemy.org/docs/reference/sqlalchemy/pooling.html?highlight=connection%20pool
import sqlalchemy.pool as pool
import sqlite3 as sqlite3
conn_proxy = pool.manage(sqlite3)
# then connect normally
connection = conn_proxy.connect(...)
=====================================================================
#****1 : what is #****1 on above code invoked =_=!!
A engine.raw_connection()
=
A pool.unique_connection()
=
A _ConnectionFairy(self).checkout()
=
A return _ConnectionFairy <== cls
= _connection_record.get_connection()
= _ConnectionRecord.connection
= return a pool.creator **which is a callable function that returns a DB-API connection object**
Thanks for your time!
Rgs,
KC
| [
"To copy data to/from a different database, the general SQLite approach is:\n\nConnect to one database \ndb_connection = sqlite3.connect(database_file) \n\nAttach the second database\ndb_connection.execute(\"ATTACH database_file2 AS database_name2\")\n\nInsert from one to the other:\ndb_connection.execute(\"INSERT ... | [
2
] | [] | [] | [
"database",
"python",
"sqlalchemy",
"sqlite"
] | stackoverflow_0003554137_database_python_sqlalchemy_sqlite.txt |
Q:
How to reload the modified files without restarting in pylons?
I'm using pylons, and using this command to start the server:
paster serve --reload development.ini
I found when I modify something, the paster will reload the application. In the console, it shows:
-------------------- Restarting --------------------
Starting server in PID 7476.
serving on http://127.0.0.1:5000
This is convenient but not enough, because it will cost 5 seconds more or less each time. If I refresh that page and the server is not reloaded completely yet, the page will display the old content, and I don't know if it is the lastest content, so I had to refresh the page several times to make sure.
I wonder if there is a better way to read the modified content without reloading, or find a quicker reloading?
A:
To controllers, you can configure Routes to rescan the directory controllers without restart application:
http://pylonshq.com/docs/en/1.0/controllers/#adding-controllers-dynamically
| How to reload the modified files without restarting in pylons? | I'm using pylons, and using this command to start the server:
paster serve --reload development.ini
I found when I modify something, the paster will reload the application. In the console, it shows:
-------------------- Restarting --------------------
Starting server in PID 7476.
serving on http://127.0.0.1:5000
This is convenient but not enough, because it will cost 5 seconds more or less each time. If I refresh that page and the server is not reloaded completely yet, the page will display the old content, and I don't know if it is the lastest content, so I had to refresh the page several times to make sure.
I wonder if there is a better way to read the modified content without reloading, or find a quicker reloading?
| [
"To controllers, you can configure Routes to rescan the directory controllers without restart application:\nhttp://pylonshq.com/docs/en/1.0/controllers/#adding-controllers-dynamically\n"
] | [
1
] | [] | [] | [
"pylons",
"python",
"reload"
] | stackoverflow_0003555032_pylons_python_reload.txt |
Q:
Where can I find a full reference of wxpython?
Sorry the question may sound stupid, but I do need one. Right now I'm just adding a wx.TextCtrl in my GUI program, and I want to know what styles can I add (such as style=wx.TE_MULTILINE|wx.TE_PROCESS_ENTER), so I googled and end up reading this page: http://www.wxpython.org/docs/api/wx.TextCtrl-class.html. It must be the official one, but I wonder why there's NOT a list of available styles in this page. If the official reference doesn't provide enough info, where should I look at?
Although I finally found what I want in wxPython in Action ebook, just want to know if there's a BIG reference which includes almost all stuff. Thanks a lot!
A:
I find Andrea Gavana's (creator of wx.lib.agw ) documentation more comprehensive then the offical wxpython docs.
http://xoomer.virgilio.it/infinity77/wxPython/APIMain.html
Heres the page for the textCtrl which shows all the styles that are available.
A:
The problem is that the official docs are mostly auto-generated with Doxygen from the wxWidgets docs and the Python docstrings. To find styles and such, you'll need to go up the tree of widgets that the TextCtrl inherits from. As volting pointed out, Andrea also has a nice set of docs. Andrea also has docs for his library (agw) here:
http://xoomer.virgilio.it/infinity77/AGW_Docs/
Unfortunately, it appears to be down at the time of this writing. Another handy tool (again from Andrea) is the Windows Styles and Event Hunter, found here:
http://groups.google.com/group/wxPython-dev/browse_thread/thread/7c19477bbcad4ef4
I use it quite a bit. Hope that helps!
A:
wxPython is a binding for wxWidgets. You may need to take a look there.
| Where can I find a full reference of wxpython? | Sorry the question may sound stupid, but I do need one. Right now I'm just adding a wx.TextCtrl in my GUI program, and I want to know what styles can I add (such as style=wx.TE_MULTILINE|wx.TE_PROCESS_ENTER), so I googled and end up reading this page: http://www.wxpython.org/docs/api/wx.TextCtrl-class.html. It must be the official one, but I wonder why there's NOT a list of available styles in this page. If the official reference doesn't provide enough info, where should I look at?
Although I finally found what I want in wxPython in Action ebook, just want to know if there's a BIG reference which includes almost all stuff. Thanks a lot!
| [
"I find Andrea Gavana's (creator of wx.lib.agw ) documentation more comprehensive then the offical wxpython docs.\n http://xoomer.virgilio.it/infinity77/wxPython/APIMain.html\nHeres the page for the textCtrl which shows all the styles that are available.\n",
"The problem is that the official docs are mostly auto-... | [
7,
2,
1
] | [] | [] | [
"python",
"wxpython"
] | stackoverflow_0003556716_python_wxpython.txt |
Q:
Using Mysql and sql server from python
I need to write a python application with use both of the mysql and sql server is there
a general python module or library that can access both mysql and sql server as DBI with perl or should i use 2 libraries and if yes which libraries do you recommend .
A:
I guess you are looking for SQLAlchemy. You will probably need some time getting into it, but it is invaluable once you have covered the basics.
SQLAlchemy acts as a frontend to other, database-specific libraries using the Python DB-API -- but beyond this, it provides a query builder library that abstracts out differences between databases' SQL syntax and permits programmatic query construction while still offering the full power of SQL.
A:
Python RDBMS modules implement DB-API.
A:
If you are looking for which connection drivers to use, I believe the only one that well work for both [MySQL (driver here) and SQLServer (native to windows/FreeTDS for linux) is pyodbc. @igor has the right idea, though, use SQLAlchemy, you can connect to each database using different engines, but use the same code to interact with both.
| Using Mysql and sql server from python | I need to write a python application with use both of the mysql and sql server is there
a general python module or library that can access both mysql and sql server as DBI with perl or should i use 2 libraries and if yes which libraries do you recommend .
| [
"I guess you are looking for SQLAlchemy. You will probably need some time getting into it, but it is invaluable once you have covered the basics.\nSQLAlchemy acts as a frontend to other, database-specific libraries using the Python DB-API -- but beyond this, it provides a query builder library that abstracts out d... | [
3,
0,
0
] | [] | [] | [
"mysql",
"python",
"sql_server"
] | stackoverflow_0003556342_mysql_python_sql_server.txt |
Q:
Printing objects and unicode, what's under the hood ? What are the good guidelines?
I'm struggling with print and unicode conversion. Here is some code executed in the 2.5 windows interpreter.
>>> import sys
>>> print sys.stdout.encoding
cp850
>>> print u"é"
é
>>> print u"é".encode("cp850")
é
>>> print u"é".encode("utf8")
├®
>>> print u"é".__repr__()
u'\xe9'
>>> class A():
... def __unicode__(self):
... return u"é"
...
>>> print A()
<__main__.A instance at 0x0000000002AEEA88>
>>> class B():
... def __repr__(self):
... return u"é".encode("cp850")
...
>>> print B()
é
>>> class C():
... def __repr__(self):
... return u"é".encode("utf8")
...
>>> print C()
├®
>>> class D():
... def __str__(self):
... return u"é"
...
>>> print D()
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
UnicodeEncodeError: 'ascii' codec can't encode character u'\xe9' in position 0: ordinal not in range(128)
>>> class E():
... def __repr__(self):
... return u"é"
...
>>> print E()
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
UnicodeEncodeError: 'ascii' codec can't encode character u'\xe9' in position 0: ordinal not in range(128)
So, when a unicode string is printed, it's not it's __repr__() function which is called and printed.
But when an object is printed __str__() or __repr__() (if __str__ not implemented) is called, not __unicode__(). Both can not return a unicode string.
But why? Why if __repr__() or __str__() return a unicode string, shouldn't it be the same behavior than when we print a unicode string? I other words: why print D() is different from print D().__str__()
Am I missing something?
These samples also show that if you want to print an object represented with unicode strings, you have to encode it to a object string (type str). But for nice printing (avoid the "├®"), it's dependent of the sys.stdout encoding.
So, do I have to add u"é".encode(sys.stdout.encoding) for each of my __str__ or __repr__ method? Or return repr(u"é")?
What if I use piping? Is is the same encoding than sys.stdout?
My main issue is to make a class "printable", i.e. print A() prints something fully readable (not with the \x*** unicode characters).
Here is the bad behavior/code that needs to be modified:
class User(object):
name = u"Luiz Inácio Lula da Silva"
def __repr__(self):
# returns unicode
return "<User: %s>" % self.name
# won't display gracefully
# expl: print repr(u'é') -> u'\xe9'
return repr("<User: %s>" % self.name)
# won't display gracefully
# expl: print u"é".encode("utf8") -> print '\xc3\xa9' -> ├®
return ("<User: %s>" % self.name).encode("utf8")
Thanks!
A:
Python doesn't have many semantic type constraints on given functions and methods, but it has a few, and here's one of them: __str__ (in Python 2.*) must return a byte string. As usual, if a unicode object is found where a byte string is required, the current default encoding (usually 'ascii') is applied in the attempt to make the required byte string from the unicode object in question.
For this operation, the encoding (if any) of any given file object is irrelevant, because what's being returned from __str__ may be about to be printed, or may be going to be subject to completely different and unrelated treatment. Your purpose in calling __str__ does not matter to the call itself and its results; Python, in general, doesn't take into account the "future context" of an operation (what you are going to do with the result after the operation is done) in determining the operation's semantics.
That's because Python doesn't always know your future intentions, and it tries to minimize the amount of surprise. print str(x) and s = str(x); print s (the same operations performed in one gulp vs two), in particular, must have the same effects; if the second case, there will be an exception if str(x) cannot validly produce a byte string (that is, for example, x.__str__() can't), and therefore the exception should also occur in the other case.
print itself (since 2.4, I believe), when presented with a unicode object, takes into consideration the .encoding attribute (if any) of the target stream (by default sys.stdout); other operations, as yet unconnected to any given target stream, don't -- and str(x) (i.e. x.__str__()) is just such an operation.
Hope this helped show the reason for the behavior that is annoying you...
Edit: the OP now clarifies "My main issue is to make a class "printable", i.e. print A() prints something fully readable (not with the \x*** unicode characters).". Here's the approach I think works best for that specific goal:
import sys
DEFAULT_ENCODING = 'UTF-8' # or whatever you like best
class sic(object):
def __unicode__(self): # the "real thing"
return u'Pel\xe9'
def __str__(self): # tries to "look nice"
return unicode(self).encode(sys.stdout.encoding or DEFAULT_ENCODING,
'replace')
def __repr__(self): # must be unambiguous
return repr(unicode(self))
That is, this approach focuses on __unicode__ as the primary way for the class's instances to format themselves -- but since (in Python 2) print calls __str__ instead, it has that one delegate to __unicode__ with the best it can do in terms of encoding. Not perfect, but then Python 2's print statement is far from perfect anyway;-).
__repr__, for its part, must strive to be unambiguous, that is, not to "look nice" at the expense of risking ambiguity (ideally, when feasible, it should return a byte string that, if passed to eval, would make an instance equal to the present one... that's far from always feasible, but the lack of ambiguity is the absolute core of the distinction between __str__ and __repr__, and I strongly recommend respecting that distinction!).
A:
I presume your sys.getdefaultencoding() is still 'ascii'. And I think this is being used whenever str() or repr() of an object are applied. You could change that with sys.setdefaultencoding(). As soon as you write to a stream, though, be it STDOUT or a file, you have to comply with its encoding. This would also apply for piping on the shell, IMO. I assume that 'print' honors the STDOUT encoding, but the exception happens before 'print' is invoked, when constructing its argument.
| Printing objects and unicode, what's under the hood ? What are the good guidelines? | I'm struggling with print and unicode conversion. Here is some code executed in the 2.5 windows interpreter.
>>> import sys
>>> print sys.stdout.encoding
cp850
>>> print u"é"
é
>>> print u"é".encode("cp850")
é
>>> print u"é".encode("utf8")
├®
>>> print u"é".__repr__()
u'\xe9'
>>> class A():
... def __unicode__(self):
... return u"é"
...
>>> print A()
<__main__.A instance at 0x0000000002AEEA88>
>>> class B():
... def __repr__(self):
... return u"é".encode("cp850")
...
>>> print B()
é
>>> class C():
... def __repr__(self):
... return u"é".encode("utf8")
...
>>> print C()
├®
>>> class D():
... def __str__(self):
... return u"é"
...
>>> print D()
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
UnicodeEncodeError: 'ascii' codec can't encode character u'\xe9' in position 0: ordinal not in range(128)
>>> class E():
... def __repr__(self):
... return u"é"
...
>>> print E()
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
UnicodeEncodeError: 'ascii' codec can't encode character u'\xe9' in position 0: ordinal not in range(128)
So, when a unicode string is printed, it's not it's __repr__() function which is called and printed.
But when an object is printed __str__() or __repr__() (if __str__ not implemented) is called, not __unicode__(). Both can not return a unicode string.
But why? Why if __repr__() or __str__() return a unicode string, shouldn't it be the same behavior than when we print a unicode string? I other words: why print D() is different from print D().__str__()
Am I missing something?
These samples also show that if you want to print an object represented with unicode strings, you have to encode it to a object string (type str). But for nice printing (avoid the "├®"), it's dependent of the sys.stdout encoding.
So, do I have to add u"é".encode(sys.stdout.encoding) for each of my __str__ or __repr__ method? Or return repr(u"é")?
What if I use piping? Is is the same encoding than sys.stdout?
My main issue is to make a class "printable", i.e. print A() prints something fully readable (not with the \x*** unicode characters).
Here is the bad behavior/code that needs to be modified:
class User(object):
name = u"Luiz Inácio Lula da Silva"
def __repr__(self):
# returns unicode
return "<User: %s>" % self.name
# won't display gracefully
# expl: print repr(u'é') -> u'\xe9'
return repr("<User: %s>" % self.name)
# won't display gracefully
# expl: print u"é".encode("utf8") -> print '\xc3\xa9' -> ├®
return ("<User: %s>" % self.name).encode("utf8")
Thanks!
| [
"Python doesn't have many semantic type constraints on given functions and methods, but it has a few, and here's one of them: __str__ (in Python 2.*) must return a byte string. As usual, if a unicode object is found where a byte string is required, the current default encoding (usually 'ascii') is applied in the a... | [
8,
0
] | [] | [] | [
"printing",
"python",
"stdout",
"unicode"
] | stackoverflow_0003557095_printing_python_stdout_unicode.txt |
Q:
How to add images/bitmaps to wx.Dialog
I want to add images to wx.Dialog (and then sizer) some like wx.ImageList and display it dynamically.
But I don't want to change already displayed image, I want to add next.
How can I resolve this problem?
A:
I don't think a dialog is a good choice for a growing list of images, but if you have a good argument for that...
Anyway, you should be able to display your images using the wx.StaticBitmap widget. To add another one, use your sizer's Add method, then call the dialog's Layout() method and maybe its Refresh() method. If you plan on displaying many images, then you'll probably want to look at the ScrolledPanel or the ScrolledWindow widgets.
| How to add images/bitmaps to wx.Dialog | I want to add images to wx.Dialog (and then sizer) some like wx.ImageList and display it dynamically.
But I don't want to change already displayed image, I want to add next.
How can I resolve this problem?
| [
"I don't think a dialog is a good choice for a growing list of images, but if you have a good argument for that...\nAnyway, you should be able to display your images using the wx.StaticBitmap widget. To add another one, use your sizer's Add method, then call the dialog's Layout() method and maybe its Refresh() meth... | [
2
] | [] | [] | [
"image",
"python",
"wxpython"
] | stackoverflow_0003555065_image_python_wxpython.txt |
Q:
add nods and attribute list and KeyError!
I have nodes with a list of attributes for each called 'times' in my case.
I made a simple model like this and I get KeyError'times'. I need my graph save each node with a list of 'times' as an attribute. How can I fix it?
import networkx as nx
G = nx.DiGraph()
for u in range(10):
for t in range(5):
if G.has_node(u):
G[u]['times'].append(t)
else:
G.add_node(u,times=[t])
print(G.nodes(data=True))
A:
You can do
G[u].setdefault('times', []).append(t)
instead of
G[u]['times'].append(t)
A:
Try this
import networkx as nx
G = nx.DiGraph()
for u in range(10):
for t in range(5):
if G.has_node(u):
if not 'times' in G[u] # this
G[u]['times'] = [] # and this
G[u]['times'].append(t)
else:
G.add_node(u,times=[t])
print(G.nodes(data=True))
A:
This is what I was looking for, rather easy!
import networkx as nx
G = nx.DiGraph()
for u in range(2):
for t in range(5):
if u in G:
G.node[u]['times'].append(t)
else:
G.add_node(u,times=[t])
print(G.nodes(data=True))
| add nods and attribute list and KeyError! | I have nodes with a list of attributes for each called 'times' in my case.
I made a simple model like this and I get KeyError'times'. I need my graph save each node with a list of 'times' as an attribute. How can I fix it?
import networkx as nx
G = nx.DiGraph()
for u in range(10):
for t in range(5):
if G.has_node(u):
G[u]['times'].append(t)
else:
G.add_node(u,times=[t])
print(G.nodes(data=True))
| [
"You can do\nG[u].setdefault('times', []).append(t)\n\ninstead of\nG[u]['times'].append(t)\n\n",
"Try this\nimport networkx as nx\nG = nx.DiGraph()\nfor u in range(10):\n for t in range(5):\n if G.has_node(u):\n if not 'times' in G[u] # this\n G[u]['times'] = [] # and this\n ... | [
1,
0,
0
] | [] | [] | [
"networkx",
"python"
] | stackoverflow_0003548470_networkx_python.txt |
Q:
Is there a way of having a GUI for bash scripts?
I have some bash scripts, some simple ones to copy, search, write lines to files and so on.
I am an Ubuntu. and I've searched in google, but it seems that everybody is doing that on python.
I could do these on python, but since I am not a python programmer, I just know the basics.
I have no idea of how calling a sh script from a GUI written on python.
If someone has a link or something to say, please drop a line.
regards,
Mario
A:
Is there a way of having a GUI for bash scripts?
You can try using Zenity.
a tool that allows you to display GTK dialog boxes in commandline and shell scripts.
I have no idea of how calling a sh script from a GUI written on python.
You can do this using subprocess.
Personally I would recommend that you learn Python and call the scripts from Python instead of trying to write the GUI in Bash.
A:
basically, all bash does is start other programs (and do symbolic math on the command line). So no, you're going to have to involve some other program.
A:
I do not fully understand what you want. Calling a shell script from python, is like calling any executable from python, using os.system.
In fact there're several 'guis' for bash, namely zenity and others.
A:
If you want to be able to display dialog boxes, calendar selection boxes, etc. you might want to take a look at dialog and whiptail. They are not graphical - they use text mode - but they may be adequate for your needs.
| Is there a way of having a GUI for bash scripts? | I have some bash scripts, some simple ones to copy, search, write lines to files and so on.
I am an Ubuntu. and I've searched in google, but it seems that everybody is doing that on python.
I could do these on python, but since I am not a python programmer, I just know the basics.
I have no idea of how calling a sh script from a GUI written on python.
If someone has a link or something to say, please drop a line.
regards,
Mario
| [
"\nIs there a way of having a GUI for bash scripts?\n\nYou can try using Zenity.\n\na tool that allows you to display GTK dialog boxes in commandline and shell scripts. \n\n\n\nI have no idea of how calling a sh script from a GUI written on python.\n\nYou can do this using subprocess.\nPersonally I would recommend ... | [
7,
0,
0,
0
] | [] | [] | [
"bash",
"python",
"user_interface"
] | stackoverflow_0003556027_bash_python_user_interface.txt |
Q:
Reading a Turtle/N3 RDF File with Python
I'm trying to encode some botanical data in Turtle format, and read this data from Python using RDFLib. However, I'm having trouble, and I'm not sure if it's because my Turtle is malformed or I'm misusing RDFLib.
My test data is:
@PREFIX rdf: <http://www.w3.org/1999/02/22-rdf-syntax-ns#> .
@PREFIX rdfs: <http://www.w3.org/2000/01/rdf-schema#> .
@PREFIX p: <http://www.myplantdomain.com/plant/description> .
p:description a rdfs:Property .
p:name a rdfs:Property .
p:language a rdfs:Property .
p:value a rdfs:Property .
p:gender a rdfs:Property .
p:inforescence a rdfs:Property .
p:color a rdfs:Property .
p:sense a rdfs:Property .
p:type a rdfs:Property .
p:fruit a rdfs:Property .
p:flower a rdfs:Property .
p:dataSource a rdfs:Property .
p:degree a rdfs:Property .
p:date a rdfs:Property .
p:person a rdfs:Property .
p:c2a7b9a3-c54a-41f5-a3b2-155351b3590f
p:description [
p:name [
p:kingdom "Plantae" ;
p:division "Pinophyta" ;
p:class "Pinopsida" ;
p:order "Pinales" ;
p:family "Pinaceae" ;
p:genus "Abies" ;
p:species "A. alba" ;
p:language "latin" ;
p:given_by [
p:person p:source/Philip_Miller ;
p:start_date "1923-1-2"^^<http://www.w3.org/2001/XMLSchema#date>
]
] ;
p:name [
p:language "english" ;
p:value "silver fir"
] ;
p:flower [
p:gender "male"@en ;
p:inflorescence "catkin"@en ;
p:color "brown"@en ;
p:color "yellow"@en ;
p:sense "straight"@en
] ;
p:flower [
p:gender "female"@en ;
p:inflorescence "catkin"@en ;
p:color "pink"@en ;
p:color "yellow"@en ;
p:sense "straight"@en
] ;
p:fruit [
p:type "cone"@en ;
p:color "brown"@en
]
] .
And my Python is:
import rdflib
g = rdflib.Graph()
#result = g.parse('trees.ttl')
#result = g.parse('trees.ttl', format='ttl')
result = g.parse('trees.ttl', format='n3')
print len(g)
for stmt in g:
print stmt
Which gives me the errors:
ValueError: Found @PREFIX when expecting a http://www.w3.org/2000/10/swap/grammar/n3#document . todoStack=[['http://www.w3.org/2000/10/swap/grammar/n3#document', []]]
I've tried varying the parse() parameters, but everything gives me an error. I've found little to no examples on how to parse Turtle. What am I doing wrong?
A:
I think the first problem is w/the uppercase PREFIX-- if you lowercase those it gets past that point. Not sure if it's a bug in rdflib or in the Turtle .ttl, but the Turtle Validator online demo seems to agree it's a problem with the .ttl (says Validation failed: The @PREFIX directive is not supported, line 1 col 0. but that problem goes away if you lowercase them).
Once you're past that hurdle, neither parser likes the part around p:given_by [: "Bad syntax (']' expected) at ^ in:"... per rdflib; Turtle Validator says
Validation failed: Expecting a period, semicolon, comma, close-bracket, or close-brace but found '/', line 31 col 33.
so it specifically dislikes the p:source/Philip_Miller part.
From these two issues (who knows if there are others...!) I think you can conclude that this N3 source (the .ttl file you post) is broken, and turn your attention to whatever system made this file in the first place, and why it's making it in such a multiply broken way.
| Reading a Turtle/N3 RDF File with Python | I'm trying to encode some botanical data in Turtle format, and read this data from Python using RDFLib. However, I'm having trouble, and I'm not sure if it's because my Turtle is malformed or I'm misusing RDFLib.
My test data is:
@PREFIX rdf: <http://www.w3.org/1999/02/22-rdf-syntax-ns#> .
@PREFIX rdfs: <http://www.w3.org/2000/01/rdf-schema#> .
@PREFIX p: <http://www.myplantdomain.com/plant/description> .
p:description a rdfs:Property .
p:name a rdfs:Property .
p:language a rdfs:Property .
p:value a rdfs:Property .
p:gender a rdfs:Property .
p:inforescence a rdfs:Property .
p:color a rdfs:Property .
p:sense a rdfs:Property .
p:type a rdfs:Property .
p:fruit a rdfs:Property .
p:flower a rdfs:Property .
p:dataSource a rdfs:Property .
p:degree a rdfs:Property .
p:date a rdfs:Property .
p:person a rdfs:Property .
p:c2a7b9a3-c54a-41f5-a3b2-155351b3590f
p:description [
p:name [
p:kingdom "Plantae" ;
p:division "Pinophyta" ;
p:class "Pinopsida" ;
p:order "Pinales" ;
p:family "Pinaceae" ;
p:genus "Abies" ;
p:species "A. alba" ;
p:language "latin" ;
p:given_by [
p:person p:source/Philip_Miller ;
p:start_date "1923-1-2"^^<http://www.w3.org/2001/XMLSchema#date>
]
] ;
p:name [
p:language "english" ;
p:value "silver fir"
] ;
p:flower [
p:gender "male"@en ;
p:inflorescence "catkin"@en ;
p:color "brown"@en ;
p:color "yellow"@en ;
p:sense "straight"@en
] ;
p:flower [
p:gender "female"@en ;
p:inflorescence "catkin"@en ;
p:color "pink"@en ;
p:color "yellow"@en ;
p:sense "straight"@en
] ;
p:fruit [
p:type "cone"@en ;
p:color "brown"@en
]
] .
And my Python is:
import rdflib
g = rdflib.Graph()
#result = g.parse('trees.ttl')
#result = g.parse('trees.ttl', format='ttl')
result = g.parse('trees.ttl', format='n3')
print len(g)
for stmt in g:
print stmt
Which gives me the errors:
ValueError: Found @PREFIX when expecting a http://www.w3.org/2000/10/swap/grammar/n3#document . todoStack=[['http://www.w3.org/2000/10/swap/grammar/n3#document', []]]
I've tried varying the parse() parameters, but everything gives me an error. I've found little to no examples on how to parse Turtle. What am I doing wrong?
| [
"I think the first problem is w/the uppercase PREFIX-- if you lowercase those it gets past that point. Not sure if it's a bug in rdflib or in the Turtle .ttl, but the Turtle Validator online demo seems to agree it's a problem with the .ttl (says Validation failed: The @PREFIX directive is not supported, line 1 co... | [
10
] | [] | [] | [
"debugging",
"python",
"rdflib",
"semantic_web",
"turtle_rdf"
] | stackoverflow_0003557561_debugging_python_rdflib_semantic_web_turtle_rdf.txt |
Q:
Dealing with simultaneous button presses and changing shift states
I am currently working on a (Python2.5) application which handles input from a game controller. We've designated a button as a shift button to change the mapping (inputtype,value->function) of the other buttons on the fly. The mapping also depends on the mode our application is running in. We are running into lots of hairy edge cases (e.g. how to handle press shift, press button x, release shift, release button x) and I was wondering if there are any known good structures/architectures/patterns for dealing with this kind of input?
A:
Satemachines are a good pattern to handle complex inputs.
Here is a machine that handle the above sequence.
You can implement statemachines with switch or state pattern (see Python state-machine design )
| Dealing with simultaneous button presses and changing shift states | I am currently working on a (Python2.5) application which handles input from a game controller. We've designated a button as a shift button to change the mapping (inputtype,value->function) of the other buttons on the fly. The mapping also depends on the mode our application is running in. We are running into lots of hairy edge cases (e.g. how to handle press shift, press button x, release shift, release button x) and I was wondering if there are any known good structures/architectures/patterns for dealing with this kind of input?
| [
"Satemachines are a good pattern to handle complex inputs.\nHere is a machine that handle the above sequence.\n\nYou can implement statemachines with switch or state pattern (see Python state-machine design )\n"
] | [
2
] | [] | [] | [
"controls",
"input",
"joystick",
"python",
"user_input"
] | stackoverflow_0003557219_controls_input_joystick_python_user_input.txt |
Q:
How to measure Python import latencies
My django application takes forever to load so I'd like to find a way to measure the import latencies so I can find the offending module and make it load lazily.
Is there an obvious way to do this? I was considering tweaking the import statement itself to produce the latencies but I'm not sure exactly how to do that. I guess that it would be ideal to have the import tree (or DAG?) along with the latencies but just a list of latencies and import statements would be enough.
A:
You can redefine the __import__ built-in function to log the start and end times (delegating everything else to the original built-in __import__). That's exactly the way to "tweak the import statement" in Python: redefine __import__!
Edit: here's a simple example...:
import sys
import __builtin__
_orgimp = __builtin__.__import__
import logging
FORMAT = "%(asctime)-15s %(message)s"
logging.basicConfig(format=FORMAT, level=logging.INFO)
def __import__(name, *a):
r = sys.modules.get(name)
if r is not None: return r
logging.info('import bgn %s', name)
r = _orgimp(name, *a)
logging.info('import end %s', name)
return r
__builtin__.__import__ = __import__
import pyparsing
This shows, on my system:
2010-08-24 08:36:39,649 import bgn pyparsing
2010-08-24 08:36:39,652 import bgn weakref
2010-08-24 08:36:39,652 import bgn _weakref
2010-08-24 08:36:39,653 import end _weakref
2010-08-24 08:36:39,653 import end weakref
2010-08-24 08:36:39,654 import bgn copy
2010-08-24 08:36:39,655 import bgn org.python.core
2010-08-24 08:36:39,656 import end copy
2010-08-24 08:36:39,675 import end pyparsing
Of course you can parse this log to show the nesting (what module first-imported what other modules) and "attempted imports" that failed (here, that of org.python.core from copy, no doubt in a try/except statement) as well as the time at which each import begins and concludes (the latter only if it does conclude, of course, not if it fails -- easy to tweak with try/finally or whatever to get the exact behavior you prefer!-).
| How to measure Python import latencies | My django application takes forever to load so I'd like to find a way to measure the import latencies so I can find the offending module and make it load lazily.
Is there an obvious way to do this? I was considering tweaking the import statement itself to produce the latencies but I'm not sure exactly how to do that. I guess that it would be ideal to have the import tree (or DAG?) along with the latencies but just a list of latencies and import statements would be enough.
| [
"You can redefine the __import__ built-in function to log the start and end times (delegating everything else to the original built-in __import__). That's exactly the way to \"tweak the import statement\" in Python: redefine __import__!\nEdit: here's a simple example...:\nimport sys\n\nimport __builtin__\n_orgimp ... | [
7
] | [] | [] | [
"import",
"python"
] | stackoverflow_0003558073_import_python.txt |
Q:
add Python path to PATH system variable automatically under Windows
I'm creating one-click python installer (integrated with my application). Is there any way to force Python MSI installer to add python's path to SYSTEM PATH variable?
I'm using MSI installer because it is very easy to specify (using command line) how it should interact with the user.
A:
There has to be a way, but what some people do is provide batch files that set up the environment before invoking Python. That's what BZR does, anyway. If you can write that batch file somewhere that's already normally in the path, so much the better.
If you're just worried about invoking Python, the normal Python installer does file associations, so you can work it that way.
A:
User variables are stored in the Windows Registry under HKEY_CURRENT_USER\Environment
I would use winreg in a post install script to set or add to the PATH there.
http://docs.python.org/library/_winreg.html
| add Python path to PATH system variable automatically under Windows | I'm creating one-click python installer (integrated with my application). Is there any way to force Python MSI installer to add python's path to SYSTEM PATH variable?
I'm using MSI installer because it is very easy to specify (using command line) how it should interact with the user.
| [
"There has to be a way, but what some people do is provide batch files that set up the environment before invoking Python. That's what BZR does, anyway. If you can write that batch file somewhere that's already normally in the path, so much the better.\nIf you're just worried about invoking Python, the normal Pytho... | [
0,
0
] | [] | [] | [
"python",
"python_install"
] | stackoverflow_0003557949_python_python_install.txt |
Q:
How to apply __str__ function when printing a list of objects in Python
Well this interactive python console snippet will tell everything:
>>> class Test:
... def __str__(self):
... return 'asd'
...
>>> t = Test()
>>> print(t)
asd
>>> l = [Test(), Test(), Test()]
>>> print(l)
[__main__.Test instance at 0x00CBC1E8, __main__.Test instance at 0x00CBC260,
__main__.Test instance at 0x00CBC238]
Basically I would like to get three asd string printed when I print the list. I have also tried pprint but it gives the same results.
A:
Try:
class Test:
def __repr__(self):
return 'asd'
And read this documentation link:
A:
The suggestion in other answers to implement __repr__ is definitely one possibility. If that's unfeasible for whatever reason (existing type, __repr__ needed for reasons other than aesthetic, etc), then just do
print [str(x) for x in l]
or, as some are sure to suggest, map(str, l) (just a bit more compact).
A:
You need to make a __repr__ method:
>>> class Test:
def __str__(self):
return 'asd'
def __repr__(self):
return 'zxcv'
>>> [Test(), Test()]
[zxcv, zxcv]
>>> print _
[zxcv, zxcv]
Refer to the docs:
object.__repr__(self)
Called by the repr() built-in function and by string conversions (reverse quotes) to compute the “official” string representation of an object. If at all possible, this should look like a valid Python expression that could be used to recreate an object with the same value (given an appropriate environment). If this is not possible, a string of the form <...some useful description...> should be returned. The return value must be a string object. If a class defines __repr__() but not __str__(), then __repr__() is also used when an “informal” string representation of instances of that class is required.
This is typically used for debugging, so it is important that the representation is information-rich and unambiguous.
| How to apply __str__ function when printing a list of objects in Python | Well this interactive python console snippet will tell everything:
>>> class Test:
... def __str__(self):
... return 'asd'
...
>>> t = Test()
>>> print(t)
asd
>>> l = [Test(), Test(), Test()]
>>> print(l)
[__main__.Test instance at 0x00CBC1E8, __main__.Test instance at 0x00CBC260,
__main__.Test instance at 0x00CBC238]
Basically I would like to get three asd string printed when I print the list. I have also tried pprint but it gives the same results.
| [
"Try:\nclass Test:\n def __repr__(self):\n return 'asd'\n\nAnd read this documentation link:\n",
"The suggestion in other answers to implement __repr__ is definitely one possibility. If that's unfeasible for whatever reason (existing type, __repr__ needed for reasons other than aesthetic, etc), then just... | [
54,
10,
3
] | [] | [] | [
"list",
"object",
"printing",
"python",
"string"
] | stackoverflow_0003558474_list_object_printing_python_string.txt |
Q:
Pass each element of a list to a function that takes multiple arguments in Python?
For example, if I have
a=[['a','b','c'],[1,2,3],['d','e','f'],[4,5,6]]
How can I get each element of a to be an argument of say, zip without having to type
zip(a[0],a[1],a[2],a[3])?
A:
Using sequence unpacking (thanks to delnan for the name):
zip(*a)
| Pass each element of a list to a function that takes multiple arguments in Python? | For example, if I have
a=[['a','b','c'],[1,2,3],['d','e','f'],[4,5,6]]
How can I get each element of a to be an argument of say, zip without having to type
zip(a[0],a[1],a[2],a[3])?
| [
"Using sequence unpacking (thanks to delnan for the name):\nzip(*a)\n\n"
] | [
25
] | [
"Chain()?\nhttp://docs.python.org/library/itertools.html#itertools.chain\nnm, read it wrong. That won't work.\n"
] | [
-1
] | [
"arguments",
"function",
"python"
] | stackoverflow_0003558593_arguments_function_python.txt |
Q:
How do I pickle an object?
Here is the code I have:
import pickle
alist = ['here', 'there']
c = open('config.pck', 'w')
pickle.dump(alist, c)
and this is the error I receive:
Traceback (most recent call last):
File "C:\pickle.py", line 1, in ?
import pickle
File "C:\pickle.py", line 6, in ?
pickle.dump(alist, c)
AttributeError: 'module' object has no attribute 'dump'
whats going on? I am using python 2.4 on windows xp
A:
Don't call your file pickle.py. It conflicts with the python standard libary module of the same name. So your import pickle is not picking up the python module.
A:
The code you have works fine for me.
Python 2.5.4 (r254:67916, Dec 23 2008, 15:10:54) [MSC v.1310 32 bit (Intel)] on
win32
Type "help", "copyright", "credits" or "license" for more information.
>>> import pickle
>>>
>>> alist = ['here', 'there']
>>> c = open('config.pck', 'w')
>>>
>>> pickle.dump(alist, c)
>>>
The issue is that your filename "pickle.py" is making the import pickle statement try to import from your own file instead of the main library. Rename your code file.
A:
Your script is called pickle and therefore shadows the module picke from the standard library. It imports itself and tries to call its dump function (and of course it doesn't have one).
Note that you're "lucky" that you don't get kicked into an infinite import loop (because importing the same module twice just creates another reference to the same module object in memory).
| How do I pickle an object? | Here is the code I have:
import pickle
alist = ['here', 'there']
c = open('config.pck', 'w')
pickle.dump(alist, c)
and this is the error I receive:
Traceback (most recent call last):
File "C:\pickle.py", line 1, in ?
import pickle
File "C:\pickle.py", line 6, in ?
pickle.dump(alist, c)
AttributeError: 'module' object has no attribute 'dump'
whats going on? I am using python 2.4 on windows xp
| [
"Don't call your file pickle.py. It conflicts with the python standard libary module of the same name. So your import pickle is not picking up the python module.\n",
"The code you have works fine for me.\nPython 2.5.4 (r254:67916, Dec 23 2008, 15:10:54) [MSC v.1310 32 bit (Intel)] on\nwin32\nType \"help\", \"copy... | [
21,
3,
1
] | [] | [] | [
"debugging",
"pickle",
"python"
] | stackoverflow_0003558718_debugging_pickle_python.txt |
Q:
Why is my variable empty in post?
This is what I'm trying to do. Have one main form with all the data and have several dialogs, from which the data will be added to the main form.
After all the data is in the main form I will submit the form. But the problem is it won't save the values of the data in the dialogs when I copy the html to the main form. It won't put the values in the post string, the post string will show the name but containing an empty value.
This is my html:
<div class="form">
<form method="post" enctype="multipart/form-data" action="/admin/home/create/" class="niceform">
<fieldset>
<dl>
<dt><label>Name:</label></dt>
<dd><input class="NFText" name="name" id="" size="54" type="text"></dd>
</dl>
<dl>
<dt><label>StaffPicks:</label></dt>
<dd >
<a onClick="openStaffPickDialog()" class="bt_green"><span class="bt_green_lft"></span><strong>Manage Staffpicks</strong><span class="bt_green_r"></span></a></dd>
</dl>
<dl>
<dt><label>Reviews:</label></dt>
<dd><a onClick="openReviewDialog()" class="bt_green"><span class="bt_green_lft"></span><strong>Manage Reviews</strong><span class="bt_green_r"></span></a></dd>
</dl>
<dl>
<dt><label>Carousel(Add Slide to Carousel):</label></dt>
<dd><a onClick="openCarouselDialog()" class="bt_green"><span class="bt_green_lft"></span><strong>Add Carousel</strong><span class="bt_green_r"></span></a></dd>
</dl>
<dl>
<dt><label>Theme:</label></dt>
<dd><input class="NFText" name="theme" id="" size="54" type="text"></dd>
</dl>
<div id="appendform"></div>
<input type="hidden" id="slidecount" name="slidecount" value="1"/>
<dl class="submit">
<img class="NFButtonLeft" src="/admin/img/0.png"><input type="submit" value="Save" id="submit" name="submit" class="NFButton"><img src="/admin/img/0.png" class="NFButtonRight">
</dl>
</fieldset>
<div id="hiddeninform" style="visibility:hidden; height:1px;"></div>
</form>
</div>
<div style="visibility:hidden; height:1px;">
<div id="carouseldialog">
<form id="carouselform">
<div id="carouselslides">
<div id="slide1"><label>LinkURL:</label><input name="linkurl1" type="text" /><br/>
<label>Upload Image</label><input name="slideimage1" type="file" /><br/></div>
</div>
<a onClick="addSlide()" class="bt_green"><span class="bt_green_lft"></span><strong>Add Slide</strong><span class="bt_green_r"></span></a>
<a onClick="removeSlide()" class="bt_red"><span class="bt_red_lft"></span><strong>Remove Slide</strong><span class="bt_red_r"></span></a>
</form>
</div>
<div id="carouselslide">
<div id="slidenonumber">
<br/>
<label>LinkURL:</label><input name="linkurl" id="linkurl" type="text" /><br/>
<label>Upload Image</label><input name="slideimage" id="slideimage" type="file" /><br/>
</div>
</div>
<div id="staffpickdialog">
<div id="staffpicksaddto">
<select id="staffpicks" name="staffpicks" size="1">
{% for program in programs %}
<option value="{{program.key.name}}">{{program.name}}</option>
{% endfor %}
</select>
</div>
<a onClick="addStaffpick()" class="bt_green"><span class="bt_green_lft"></span><strong>Add Staffpick</strong><span class="bt_green_r"></span></a></dd>
<a onClick="removeStaffPick()" class="bt_red"><span class="bt_red_lft"></span><strong>Remove Staffpick</strong><span class="bt_red_r"></span></a>
</div>
<div id="staffpickhidden">
<br/>
<select id="staffpicks" name="staffpicks" >
{% for program in programs %}
<option value="{{program.key.name}}">{{program.name}}</option>
{% endfor %}
</select>
</div>
<div id="reviewdialog">
<div id="reviewsaddto">
<textarea cols="60" rows="5" id="reviews" name="reviews"></textarea>
</div>
<a onClick="addReview()" class="bt_green"><span class="bt_green_lft"></span><strong>Add Staffpick</strong><span class="bt_green_r"></span></a></dd>
<a onClick="removeReview()" class="bt_red"><span class="bt_red_lft"></span><strong>Remove Staffpick</strong><span class="bt_red_r"></span></a>
</div>
<div id="reviewhidden">
<br/>
<textarea cols="60" rows="5" id="reviews" name="reviews"></textarea>
</div>
</div>
This is my javascript:
function openReviewDialog(){
$('#reviewdialog').dialog({
width: 480,
modal: true,
buttons: {
'Save': function() {
$('#hiddeninform').append($('#reviewsaddto').html())
$(this).dialog('close');
},
Cancel: function() {
$(this).dialog('close');
}
}
})
}
A:
I'm pretty sure values aren't passed when you call .html on a form input element. Try looping through all of the elements in your dialog and adding them as hidden elements to the form.
$("select, textarea, input", $("#dialog")).each(function (i) {
$("#hiddeninform").append($("<input/>").attr("name", $(this).attr("name")).val($(this).val()));
});
A:
Best way to do it is actually like this. Using the above answer will get you in trouble if you're using file fields or other special kind of fields I guess. But credits to him for the solution!
function openCarouselDialog(){
$('#carouseldialog').dialog({
width: 450,
modal: true,
buttons: {
'Save': function() {
$("#carouseldialog input[type=text]").each(function (i) {
$("#hiddeninform").append($(this));
});
$("#carouseldialog input[type=file]").each(function (i) {
$("#hiddeninform").append($(this));
});
$(this).dialog('close');
},
Cancel: function() {
$(this).dialog('close');
}
}
})
}
| Why is my variable empty in post? | This is what I'm trying to do. Have one main form with all the data and have several dialogs, from which the data will be added to the main form.
After all the data is in the main form I will submit the form. But the problem is it won't save the values of the data in the dialogs when I copy the html to the main form. It won't put the values in the post string, the post string will show the name but containing an empty value.
This is my html:
<div class="form">
<form method="post" enctype="multipart/form-data" action="/admin/home/create/" class="niceform">
<fieldset>
<dl>
<dt><label>Name:</label></dt>
<dd><input class="NFText" name="name" id="" size="54" type="text"></dd>
</dl>
<dl>
<dt><label>StaffPicks:</label></dt>
<dd >
<a onClick="openStaffPickDialog()" class="bt_green"><span class="bt_green_lft"></span><strong>Manage Staffpicks</strong><span class="bt_green_r"></span></a></dd>
</dl>
<dl>
<dt><label>Reviews:</label></dt>
<dd><a onClick="openReviewDialog()" class="bt_green"><span class="bt_green_lft"></span><strong>Manage Reviews</strong><span class="bt_green_r"></span></a></dd>
</dl>
<dl>
<dt><label>Carousel(Add Slide to Carousel):</label></dt>
<dd><a onClick="openCarouselDialog()" class="bt_green"><span class="bt_green_lft"></span><strong>Add Carousel</strong><span class="bt_green_r"></span></a></dd>
</dl>
<dl>
<dt><label>Theme:</label></dt>
<dd><input class="NFText" name="theme" id="" size="54" type="text"></dd>
</dl>
<div id="appendform"></div>
<input type="hidden" id="slidecount" name="slidecount" value="1"/>
<dl class="submit">
<img class="NFButtonLeft" src="/admin/img/0.png"><input type="submit" value="Save" id="submit" name="submit" class="NFButton"><img src="/admin/img/0.png" class="NFButtonRight">
</dl>
</fieldset>
<div id="hiddeninform" style="visibility:hidden; height:1px;"></div>
</form>
</div>
<div style="visibility:hidden; height:1px;">
<div id="carouseldialog">
<form id="carouselform">
<div id="carouselslides">
<div id="slide1"><label>LinkURL:</label><input name="linkurl1" type="text" /><br/>
<label>Upload Image</label><input name="slideimage1" type="file" /><br/></div>
</div>
<a onClick="addSlide()" class="bt_green"><span class="bt_green_lft"></span><strong>Add Slide</strong><span class="bt_green_r"></span></a>
<a onClick="removeSlide()" class="bt_red"><span class="bt_red_lft"></span><strong>Remove Slide</strong><span class="bt_red_r"></span></a>
</form>
</div>
<div id="carouselslide">
<div id="slidenonumber">
<br/>
<label>LinkURL:</label><input name="linkurl" id="linkurl" type="text" /><br/>
<label>Upload Image</label><input name="slideimage" id="slideimage" type="file" /><br/>
</div>
</div>
<div id="staffpickdialog">
<div id="staffpicksaddto">
<select id="staffpicks" name="staffpicks" size="1">
{% for program in programs %}
<option value="{{program.key.name}}">{{program.name}}</option>
{% endfor %}
</select>
</div>
<a onClick="addStaffpick()" class="bt_green"><span class="bt_green_lft"></span><strong>Add Staffpick</strong><span class="bt_green_r"></span></a></dd>
<a onClick="removeStaffPick()" class="bt_red"><span class="bt_red_lft"></span><strong>Remove Staffpick</strong><span class="bt_red_r"></span></a>
</div>
<div id="staffpickhidden">
<br/>
<select id="staffpicks" name="staffpicks" >
{% for program in programs %}
<option value="{{program.key.name}}">{{program.name}}</option>
{% endfor %}
</select>
</div>
<div id="reviewdialog">
<div id="reviewsaddto">
<textarea cols="60" rows="5" id="reviews" name="reviews"></textarea>
</div>
<a onClick="addReview()" class="bt_green"><span class="bt_green_lft"></span><strong>Add Staffpick</strong><span class="bt_green_r"></span></a></dd>
<a onClick="removeReview()" class="bt_red"><span class="bt_red_lft"></span><strong>Remove Staffpick</strong><span class="bt_red_r"></span></a>
</div>
<div id="reviewhidden">
<br/>
<textarea cols="60" rows="5" id="reviews" name="reviews"></textarea>
</div>
</div>
This is my javascript:
function openReviewDialog(){
$('#reviewdialog').dialog({
width: 480,
modal: true,
buttons: {
'Save': function() {
$('#hiddeninform').append($('#reviewsaddto').html())
$(this).dialog('close');
},
Cancel: function() {
$(this).dialog('close');
}
}
})
}
| [
"I'm pretty sure values aren't passed when you call .html on a form input element. Try looping through all of the elements in your dialog and adding them as hidden elements to the form. \n$(\"select, textarea, input\", $(\"#dialog\")).each(function (i) {\n $(\"#hiddeninform\").append($(\"<input/>\").attr(\"name\... | [
2,
0
] | [] | [] | [
"google_app_engine",
"jquery",
"jquery_ui",
"python"
] | stackoverflow_0003514857_google_app_engine_jquery_jquery_ui_python.txt |
Q:
Python: how many similar words in string?
I have some ugly strings similar to these:
string1 = 'Fantini, Rauch, C.Straus, Priuli, Bertali: 'Festival Mass at the Imperial Court of Vienna, 1648' (Yorkshire Bach Choir & Baroque Soloists + Baroque Brass of London/Seymour)'
string2 = 'Vinci, Leonardo {c.1690-1730}: Arias from Semiramide Riconosciuta, Didone Abbandonata, La Caduta dei Decemviri, Lo Cecato Fauzo, La Festa de Bacco, Catone in Utica. (Maria Angeles Peters sop. w.M.Carraro conducting)'
I would like a library or algorithm that will give me a percentage of how many words they have in common, while excluding special characters such as ',' and ':' and ''' and '{' etc.
I know of the Levenshtein algorithm. However, this compares numbers of similar CHARACTERS, whereas I would like to compare how many WORDS they have in common
A:
Regex could easily give you all the words:
import re
s1 = "Fantini, Rauch, C.Straus, Priuli, Bertali: 'Festival Mass at the Imperial Court of Vienna, 1648' (Yorkshire Bach Choir & Baroque Soloists + Baroque Brass of London/Seymour)"
s2 = "Vinci, Leonardo {c.1690-1730}: Arias from Semiramide Riconosciuta, Didone Abbandonata, La Caduta dei Decemviri, Lo Cecato Fauzo, La Festa de Bacco, Catone in Utica. (Maria Angeles Peters sop. w.M.Carraro conducting)"
s1w = re.findall('\w+', s1.lower())
s2w = re.findall('\w+', s2.lower())
collections.Counter (Python 2.7+) can quickly count up the number of times a word occurs.
from collections import Counter
s1cnt = Counter(s1w)
s2cnt = Counter(s2w)
A very crude comparison could be done through set.intersection or difflib.SequenceMatcher, but it sounds like you would want to implement a Levenshtein algorithm that deals with words, where you could use those two lists.
common = set(s1w).intersection(s2w)
# returns set(['c'])
import difflib
common_ratio = difflib.SequenceMatcher(None, s1w, s2w).ratio()
print '%.1f%% of words common.' % (100*common_ratio)
Prints: 3.4% of words similar.
A:
n = 0
words1 = set(sentence1.split())
for word in sentence2.split():
# strip some chars here, e.g. as in [1]
if word in words1:
n += 1
(1: How to remove symbols from a string with Python?)
Edit: Note that this considers a word to be common to both sentences if it appears anywhere in both - to compare the position, you can omit the set conversion (just call split() on both), use something like:
n = 0
for word_from_1, word_from_2 in zip(sentence1.split(), sentence2.split()):
# strip some chars here, e.g. as in [1]
if word_from_1 == word_from_2:
n += 1
A:
The Lenvenshtein algorithm itself isn't restricted to comparing characters, it could compare any arbitrary objects. The fact that the classical form uses characters is an implementation detail, they could be any symbols or constructs that can be compared for equality.
In Python, convert the strings into lists of words then apply the algorithm to the lists. Maybe someone else can help you with cleaning up unwanted characters, presumably using some regular expression magic.
| Python: how many similar words in string? | I have some ugly strings similar to these:
string1 = 'Fantini, Rauch, C.Straus, Priuli, Bertali: 'Festival Mass at the Imperial Court of Vienna, 1648' (Yorkshire Bach Choir & Baroque Soloists + Baroque Brass of London/Seymour)'
string2 = 'Vinci, Leonardo {c.1690-1730}: Arias from Semiramide Riconosciuta, Didone Abbandonata, La Caduta dei Decemviri, Lo Cecato Fauzo, La Festa de Bacco, Catone in Utica. (Maria Angeles Peters sop. w.M.Carraro conducting)'
I would like a library or algorithm that will give me a percentage of how many words they have in common, while excluding special characters such as ',' and ':' and ''' and '{' etc.
I know of the Levenshtein algorithm. However, this compares numbers of similar CHARACTERS, whereas I would like to compare how many WORDS they have in common
| [
"Regex could easily give you all the words:\nimport re\ns1 = \"Fantini, Rauch, C.Straus, Priuli, Bertali: 'Festival Mass at the Imperial Court of Vienna, 1648' (Yorkshire Bach Choir & Baroque Soloists + Baroque Brass of London/Seymour)\"\ns2 = \"Vinci, Leonardo {c.1690-1730}: Arias from Semiramide Riconosciuta, Did... | [
7,
2,
2
] | [] | [] | [
"python",
"string"
] | stackoverflow_0003558787_python_string.txt |
Q:
regex to eliminate field in bibtex file
I am trying to slim down the bib text files I get from my reference manager because it leaves extra fields that end up getting mangled when I put it into LaTeX.
A characteristic entry that I want to clean up is:
@Article{Kholmurodov:2001p113,
author = {K Kholmurodov and I Puzynin and W Smith and K Yasuoka and T Ebisuzaki},
journal = {Computer Physics Communications},
title = {MD simulation of cluster-surface impacts for metallic phases: soft landing, droplet spreading and implantation},
abstract = {Lots of text here. Even more text.},
affiliation = {RIKEN, Inst Phys {\&} Chem Res, Computat Sci Div, Adv Comp Ctr, Wako, Saitama 3510198, Japan},
number = {1},
pages = {1--16},
volume = {141},
year = {2001},
month = {Dec},
language = {English},
keywords = {Ethane, molecular dynamics, Clusters, Dl_Poly Code, solid surface, metal, Hydrocarbon Thin-Films, Adsorption, impact, Impact Processes, solid surface, Molecular Dynamics Simulation, Large Systems, DL_POLY, Beam Deposition, Package, Collision-Induced Desorption, Diamond Films, Vapor-Deposition, Transition-Metals, Molecular-Dynamics Simulation},
date-added = {2008-06-27 08:58:25 -0500},
date-modified = {2009-03-24 15:40:27 -0500},
pmid = {000172275000001},
local-url = {file://localhost/User/user/Papers/2001/Kholmurodov/Kholmurodov-MD%20simulation%20of%20cluster-surface%20impacts-2001.pdf},
uri = {papers://B08E511A-2FA9-45A0-8612-FA821DF82090/Paper/p113},
read = {Yes},
rating = {0}
}
I would like to eliminate fields like month, abstract, keywords, etc. some of which are single lines and some of which are multiple lines.
I have given it a try in Python and like this:
fOpen = open(f,'r')
start_text = fOpen.read()
fOpen.close()
# regex
out_text = re.sub(r'^(month).*,\n','',start_text)
out_text = re.sub(r'^(annote)((.|\n)*?)\},\n','',out_text)
out_text = re.sub(r'^(note)((.|\n)*?)\},\n','',out_text)
out_text = re.sub(r'^(abstract)((.|\n)*?)\},\n','',out_text)
fNew = open(f,'w')
fNew.write(out_text)
fNew.close()
I have tried to run these regexes in TextMate to see if they work before giving them a try in Python and they appear to be ok.
Any suggestions?
Thanks.
A:
What about this regex (apply with multi-line and dotall flags):
^(?:month|annote|note|abstract)\s*=\s*\{(?:(?!\},$).)*\},[\r\n]+
Explanation:
^ # start-of-line
(?: # non-capturing group 1
month|annote|note|abstract # one of these terms
) # end non-capturing group 1
\s*=\s* # whitespace, an equals sign, whitespace
\{ # a literal curly brace
(?: # non-capturing group 2
(?! # negative look-ahead (if not followed by...)
\},$ # a curly brace, a comma and the end-of-line
) # end negative look-ahead
. # ...then match next character, whatever it is
)* # end non-capturing group 2, repeat
\}, # a literal curly brace and a comma
[\r\n]+ # at least one end-of-line character
This single expression sorts out all affected lines in one step.
EDIT / WARNING: Note that this will fail as soon as the following occurs:
affiliation = {RIKEN, Inst Phys {\&},
Computat Sci Div, Adv Comp Ctr, Wako, Saitama 3510198, Japan},
Nested structures cannot be handled by regular expressions. No pure regex solution can be correct in all cases in this context, the best you can get is a good approximation.
The question is if you if you are 100% sure that the situation above cannot occur (and I don't think you can be) - or if you are willing to take the risk. If you are not entirely sure that this will not a problem - use or write a parser.
| regex to eliminate field in bibtex file | I am trying to slim down the bib text files I get from my reference manager because it leaves extra fields that end up getting mangled when I put it into LaTeX.
A characteristic entry that I want to clean up is:
@Article{Kholmurodov:2001p113,
author = {K Kholmurodov and I Puzynin and W Smith and K Yasuoka and T Ebisuzaki},
journal = {Computer Physics Communications},
title = {MD simulation of cluster-surface impacts for metallic phases: soft landing, droplet spreading and implantation},
abstract = {Lots of text here. Even more text.},
affiliation = {RIKEN, Inst Phys {\&} Chem Res, Computat Sci Div, Adv Comp Ctr, Wako, Saitama 3510198, Japan},
number = {1},
pages = {1--16},
volume = {141},
year = {2001},
month = {Dec},
language = {English},
keywords = {Ethane, molecular dynamics, Clusters, Dl_Poly Code, solid surface, metal, Hydrocarbon Thin-Films, Adsorption, impact, Impact Processes, solid surface, Molecular Dynamics Simulation, Large Systems, DL_POLY, Beam Deposition, Package, Collision-Induced Desorption, Diamond Films, Vapor-Deposition, Transition-Metals, Molecular-Dynamics Simulation},
date-added = {2008-06-27 08:58:25 -0500},
date-modified = {2009-03-24 15:40:27 -0500},
pmid = {000172275000001},
local-url = {file://localhost/User/user/Papers/2001/Kholmurodov/Kholmurodov-MD%20simulation%20of%20cluster-surface%20impacts-2001.pdf},
uri = {papers://B08E511A-2FA9-45A0-8612-FA821DF82090/Paper/p113},
read = {Yes},
rating = {0}
}
I would like to eliminate fields like month, abstract, keywords, etc. some of which are single lines and some of which are multiple lines.
I have given it a try in Python and like this:
fOpen = open(f,'r')
start_text = fOpen.read()
fOpen.close()
# regex
out_text = re.sub(r'^(month).*,\n','',start_text)
out_text = re.sub(r'^(annote)((.|\n)*?)\},\n','',out_text)
out_text = re.sub(r'^(note)((.|\n)*?)\},\n','',out_text)
out_text = re.sub(r'^(abstract)((.|\n)*?)\},\n','',out_text)
fNew = open(f,'w')
fNew.write(out_text)
fNew.close()
I have tried to run these regexes in TextMate to see if they work before giving them a try in Python and they appear to be ok.
Any suggestions?
Thanks.
| [
"What about this regex (apply with multi-line and dotall flags):\n\n^(?:month|annote|note|abstract)\\s*=\\s*\\{(?:(?!\\},$).)*\\},[\\r\\n]+\n\nExplanation:\n\n^ # start-of-line\n(?: # non-capturing group 1\n month|annote|note|abstract # one of these terms\n)... | [
2
] | [] | [] | [
"bibtex",
"parsing",
"python",
"regex"
] | stackoverflow_0003558691_bibtex_parsing_python_regex.txt |
Q:
Python - TypeError: unbound method
So this Python problem has been giving me problems since I've tried refactoring the code into different files. I have a file called object.py and in it, the related code is:
class Object:
#this is a generic object: the player, a monster, an item, the stairs...
#it's always represented by a character on screen.
def __init__(self, x, y, char, color):
self.x = x
self.y = y
self.char = char
self.color = color
def move(self, dx, dy):
#move by the given amount, if the destination is not blocked
#if not map[self.x + dx][self.y + dy].blocked:
self.x += dx
self.y += dy
Now, when I try to compile this file specifically I get this error:
TypeError: unbound method __init__() must be called with Object instance as first argument (got int instance instead)
The code that is attempting to call this is:
player = object_info.Object.__init__(BurglaryConstants.SCREEN_WIDTH/2, BurglaryConstants.SCREEN_HEIGHT/2, '@', libtcod.white)
Which causes this error when compiling:
AttributeError: 'module' object has no attribute 'Object'
So what the heck is going on with all this and how should I be refactoring this? Also I assume having a class called Object isn't a very good coding practice, correct?
Thanks for your help!
A:
Update
You are defining Object in a file called object.py. And yet the client refers to object_info.Object. Is this a typo?
Also I assume having a class called Object isn't a very good coding practice, correct?
Correct. Rename your class to something else, say GenericObject or GenericBase. Also don't use the module name object.py. Change it appropriately.
Also
You are constructing an instance of Object but the way you are doing it is wrong. Try this:
player = object_info.Object(BurglaryConstants.SCREEN_WIDTH/2, BurglaryConstants.SCREEN_HEIGHT/2, '@', libtcod.white)
This chapter from Dive Into Python should prove useful.
A:
First, always use new-style classes, i.e. inherit from object. (This is not needed if you are running Python 3, which has only new-style classes)
Second, calling __init__ is very likely wrong here - if you want to instanciate a new Object, just write Object(x, y, char, color).
| Python - TypeError: unbound method | So this Python problem has been giving me problems since I've tried refactoring the code into different files. I have a file called object.py and in it, the related code is:
class Object:
#this is a generic object: the player, a monster, an item, the stairs...
#it's always represented by a character on screen.
def __init__(self, x, y, char, color):
self.x = x
self.y = y
self.char = char
self.color = color
def move(self, dx, dy):
#move by the given amount, if the destination is not blocked
#if not map[self.x + dx][self.y + dy].blocked:
self.x += dx
self.y += dy
Now, when I try to compile this file specifically I get this error:
TypeError: unbound method __init__() must be called with Object instance as first argument (got int instance instead)
The code that is attempting to call this is:
player = object_info.Object.__init__(BurglaryConstants.SCREEN_WIDTH/2, BurglaryConstants.SCREEN_HEIGHT/2, '@', libtcod.white)
Which causes this error when compiling:
AttributeError: 'module' object has no attribute 'Object'
So what the heck is going on with all this and how should I be refactoring this? Also I assume having a class called Object isn't a very good coding practice, correct?
Thanks for your help!
| [
"Update\nYou are defining Object in a file called object.py. And yet the client refers to object_info.Object. Is this a typo?\n\nAlso I assume having a class called Object isn't a very good coding practice, correct?\n\nCorrect. Rename your class to something else, say GenericObject or GenericBase. Also don't use th... | [
4,
1
] | [] | [] | [
"attributeerror",
"initialization",
"python"
] | stackoverflow_0003558937_attributeerror_initialization_python.txt |
Q:
how do python module variables work?
I used to think that once a module was loaded, no re-importing would be done if other files imported that same module, or if it were imported in different ways. For example, I have mdir/__init__.py, which is empty, and mdir/mymod.py, which is:
thenum = None
def setNum(n):
global thenum
if thenum is not None:
raise ValueError("Num already set")
thenum = n
def getNum():
if thenum is None:
raise ValueError("Num hasn't been set")
return thenum
First few use cases from the same file go according to expectation. This file is ./usage.py, the same folder mdir is in:
import mdir.mymod
mdir.mymod.setNum(4)
print mdir.mymod.getNum()
from mdir import mymod
print mymod.getNum()
from mdir.mymod import *
print getNum()
try:
setNum(10)
except ValueError:
print "YHep, exception"
The output is as expected:
4
4
4
YHep, exception
However, if I muck with the system path, then it looks like the module is imported anew:
#BEHOLD
import sys
sys.path.append("mdir")
import mymod
try:
mymod.getNum()
except ValueError:
print "Should not have gotten exception"
mymod.setNum(10)
print mymod.getNum()
print mdir.mymod.getNum()
That code, running after the previous code, yields:
Should not have gotten exception
10
4
What gives?
A:
mymod and mdir.mymod are considered different modules - here's somewhat related discussion: http://code.djangoproject.com/ticket/3951
Explanation:
It's best to play with python interactive interpreter and see for yourself. I created directory (package) mydir under some directory and inside it two files (modules) - __init__.py and mymod.py, both empty. I started python inside of directory containing mydir. Now see what happens:
>>> import mydir.mymod
>>> from mydir import mymod
>>> mymod == mydir.mymod
True
Why are mymod and mydir.mymod considered the same thing? Well, both names refer to the same module object - modules equality is determined by their paths comparison:
>>> mymod
<module 'mydir.mymod' from 'mydir\mymod.py'>
>>> mydir.mymod
<module 'mydir.mymod' from 'mydir\mymod.py'>
Now, if I alter sys.path to contain mydir and import mymod in such a way that path of imported module will seem to be different:
>>> import sys
>>> sys.path.append( "d:/zrodla/stack/mydir" )
# note that importing mymod (and not mydir.mymod) prior to appending mydir to
# path would cause an error
>>> mymod2
<module 'mymod' from 'd:/zrodla/stack/mydir\mymod.pyc'>
>>> mymod2 == mydir.mymod
False
then resulting module objects will not compare equal. This way one module will be imported twice - it's normal and that's the way python works. Just remember that imported modules are identified by their paths - more specifically by 'dotted paths' I think - look at sys.modules keys:
>>> [x for x in sys.modules.keys() if "my" in x]
['mydir', 'mymod', 'mydir.mymod']
I hope it's clear now.
| how do python module variables work? | I used to think that once a module was loaded, no re-importing would be done if other files imported that same module, or if it were imported in different ways. For example, I have mdir/__init__.py, which is empty, and mdir/mymod.py, which is:
thenum = None
def setNum(n):
global thenum
if thenum is not None:
raise ValueError("Num already set")
thenum = n
def getNum():
if thenum is None:
raise ValueError("Num hasn't been set")
return thenum
First few use cases from the same file go according to expectation. This file is ./usage.py, the same folder mdir is in:
import mdir.mymod
mdir.mymod.setNum(4)
print mdir.mymod.getNum()
from mdir import mymod
print mymod.getNum()
from mdir.mymod import *
print getNum()
try:
setNum(10)
except ValueError:
print "YHep, exception"
The output is as expected:
4
4
4
YHep, exception
However, if I muck with the system path, then it looks like the module is imported anew:
#BEHOLD
import sys
sys.path.append("mdir")
import mymod
try:
mymod.getNum()
except ValueError:
print "Should not have gotten exception"
mymod.setNum(10)
print mymod.getNum()
print mdir.mymod.getNum()
That code, running after the previous code, yields:
Should not have gotten exception
10
4
What gives?
| [
"mymod and mdir.mymod are considered different modules - here's somewhat related discussion: http://code.djangoproject.com/ticket/3951\nExplanation:\nIt's best to play with python interactive interpreter and see for yourself. I created directory (package) mydir under some directory and inside it two files (modules)... | [
4
] | [] | [] | [
"import",
"module",
"python"
] | stackoverflow_0003558979_import_module_python.txt |
Q:
Handling arbitrary number of command line arguments in python
I am trying to have my script be able to take in an arbitrary number of file names as command line arguments. In Unix, it is possible to use the '*' key to represent any character. For example,
ls blah*.txt
will list every file with blah at the beginning and txt at the end.
I need something like this for my python script.
python myscript.py blah*.txt
Is this possible? and if it is, how can it be done?
A:
import sys
for arg in sys.argv[1:]:
print arg
In Unix-land, the shell does the job of glob-expanding the commandline arguments, so you don't need to do it yourself. If you're processing a bunch of files in sequence, you might also look at the fileinput module, which works like Perl's "magic ARGV" handle and the -n and -i flags. It lets you loop over every line of every file named on the commandline, optionally moving the file to a backup name and opening stdout to the original name of the file, which lets you do something simple like:
import fileinput
for line in fileinput.input(inplace = True, backup = '.bak'):
print fileinput.filelineno() + ": " + line
to add the line number to the beginning of every line of every file on the commandline, while saving the originals as filename.bak.
A:
Thats why you have sys.argv (and dont forget to import sys) It will return all your blah*.txt as a list of filenames
A:
I think you want to use glob.
A:
There is also fnmatch for when you don't want to have to worry about the path.
A:
import sys, glob
files = reduce(lambda x, y: x + y, (glob.glob(x) for x in sys.argv[1:]))
| Handling arbitrary number of command line arguments in python | I am trying to have my script be able to take in an arbitrary number of file names as command line arguments. In Unix, it is possible to use the '*' key to represent any character. For example,
ls blah*.txt
will list every file with blah at the beginning and txt at the end.
I need something like this for my python script.
python myscript.py blah*.txt
Is this possible? and if it is, how can it be done?
| [
"import sys\n\nfor arg in sys.argv[1:]:\n print arg\n\nIn Unix-land, the shell does the job of glob-expanding the commandline arguments, so you don't need to do it yourself. If you're processing a bunch of files in sequence, you might also look at the fileinput module, which works like Perl's \"magic ARGV\" handle... | [
3,
1,
0,
0,
0
] | [] | [] | [
"python"
] | stackoverflow_0003559477_python.txt |
Q:
Is there a way of using breakpoints in python?
I am just wondering if there is a way to add breakpoints in IDLE so that I can stop at a point in my script and write other lines in the idle shell for testing. If not, is there other software that can do this?
A:
you can add the line
import pdb; pdb.set_trace()
anywhere in your code, when reached it will drop you into a debug shell. so useful i have an emacs shortcut to add the snippet.
you may also want to look at ipdb, and use
import ipdb; ipdb.set_trace()
instead
A:
http://docs.python.org/library/pdb.html
A:
If you are running Windows, you might look at PyScripter if you want a development environment with more features than IDLE.
| Is there a way of using breakpoints in python? | I am just wondering if there is a way to add breakpoints in IDLE so that I can stop at a point in my script and write other lines in the idle shell for testing. If not, is there other software that can do this?
| [
"you can add the line\nimport pdb; pdb.set_trace()\n\nanywhere in your code, when reached it will drop you into a debug shell. so useful i have an emacs shortcut to add the snippet.\nyou may also want to look at ipdb, and use\nimport ipdb; ipdb.set_trace()\n\ninstead\n",
"http://docs.python.org/library/pdb.html\... | [
6,
3,
1
] | [] | [] | [
"breakpoints",
"debugging",
"python"
] | stackoverflow_0003555945_breakpoints_debugging_python.txt |
Q:
How to check that a path is an existing regular file and not a directory?
One script is used to exchange file information amongst teams. It is used as:
$ share.py -p /path/to/file.txt
The argument checking ensures that /path/to/file.txt exists and has the correct permissions:
#[...]
# ensure that file exists and is readable
if not os.access(options.path, os.F_OK):
raise MyError('the file does not exist')
# ensure that path is absolute
if not os.path.isabs(options.path):
raise MyError('I need absolute path')
# ensure that file has read permissions for others
info = os.stat(options.path)
last_bit = oct(info.st_mode)[-1]
if not last_bit in ['4', '5', '6', '7']:
raise MyError('others cannot read the file: change permission')
The problem is that one user sent:
$ share.py -p /path/to/
and the program did not fail as it should have. In retrospective I should have seen this coming, but I did not.
How can I add a test to ensure that path is a regular file which may or may not have an extension (I cannot simply process the name string)?
A:
import os.path
os.path.isfile(filename)
A:
os.path.exists(path) and not os.path.isdir(path)
| How to check that a path is an existing regular file and not a directory? | One script is used to exchange file information amongst teams. It is used as:
$ share.py -p /path/to/file.txt
The argument checking ensures that /path/to/file.txt exists and has the correct permissions:
#[...]
# ensure that file exists and is readable
if not os.access(options.path, os.F_OK):
raise MyError('the file does not exist')
# ensure that path is absolute
if not os.path.isabs(options.path):
raise MyError('I need absolute path')
# ensure that file has read permissions for others
info = os.stat(options.path)
last_bit = oct(info.st_mode)[-1]
if not last_bit in ['4', '5', '6', '7']:
raise MyError('others cannot read the file: change permission')
The problem is that one user sent:
$ share.py -p /path/to/
and the program did not fail as it should have. In retrospective I should have seen this coming, but I did not.
How can I add a test to ensure that path is a regular file which may or may not have an extension (I cannot simply process the name string)?
| [
"import os.path\nos.path.isfile(filename)\n\n",
"os.path.exists(path) and not os.path.isdir(path)\n\n"
] | [
9,
4
] | [] | [] | [
"file",
"python"
] | stackoverflow_0003559617_file_python.txt |
Q:
If you import yourself in Python, why don't you get an infinite loop?
This question is a response to the following SO post:
How do I pickle an object?
In that thread, the OP accidentally imports his own module at the top of the same module. Why doesn't this cause an infinite loop?
A:
Modules are imported only once. Python realizes it already has been imported, so does not do it again.
See: http://docs.python.org/tutorial/modules.html#more-on-modules
A:
When Python encounters an import statement, it checks sys.modules for the presence of the module first before doing anything
A:
import module does not reload the module if it has already been imported
A:
I believe python tracks which modules have already been imported so that time is not wasted redundantly importing. Each module can only be imported once.
A:
An import in Python causes the namespace bindings for the imported module to be put in the current namespace if they are not present already. If you import a module twice, it will actually be imported (and hence executed) only once. That is why when you import the module into itself, nothing actually happens as the namespace bindings are already present in the current namespace.
| If you import yourself in Python, why don't you get an infinite loop? | This question is a response to the following SO post:
How do I pickle an object?
In that thread, the OP accidentally imports his own module at the top of the same module. Why doesn't this cause an infinite loop?
| [
"Modules are imported only once. Python realizes it already has been imported, so does not do it again.\nSee: http://docs.python.org/tutorial/modules.html#more-on-modules\n",
"When Python encounters an import statement, it checks sys.modules for the presence of the module first before doing anything\n",
"import... | [
12,
5,
2,
2,
2
] | [] | [] | [
"import",
"infinite_loop",
"python"
] | stackoverflow_0003558842_import_infinite_loop_python.txt |
Q:
modifying list elements
How can I modify the list below:
[('AAA', '1-1', 1, (1.11, (2.22, 3.33))), ('BBB', '2-2', 2, (4.44, (5.55, 6.66))), ('CCC', '3-3', 3, (7, (8, 9)))]
into something like this:
[('AAA', '1-1', 1, 1.11, 2.22, 3.33), ('BBB', '2-2', 2, 4.44, 5.55, 6.66), ('CCC', '3-3', 3, 7, 8, 9)]
Many thanks in advance.
A:
It looks like you want to flatten the tuples that are members of the outer list?
Try this:
>>> def flatten(lst):
return sum( ([x] if not isinstance(x, (list, tuple)) else flatten(x)
for x in lst), [] )
>>> def modify(lst):
return [tuple(flatten(x)) for x in lst]
>>> x = [('AAA', '1-1', 1, (1.11, (2.22, 3.33))), ('BBB', '2-2', 2, (4.44, (5.55, 6.66))), ('CCC', '3-3', 3, (7, (8, 9)))]
>>> modify(x)
[('AAA', '1-1', 1, 1.11, 2.22, 3.33), ('BBB', '2-2', 2, 4.44, 5.55, 6.66), ('CCC', '3-3', 3, 7, 8, 9)]
>>>
Hope it helps :-)
A:
Not a specific solution, but there are a lot of great recipes in the itertools library:
http://docs.python.org/library/itertools.html
| modifying list elements | How can I modify the list below:
[('AAA', '1-1', 1, (1.11, (2.22, 3.33))), ('BBB', '2-2', 2, (4.44, (5.55, 6.66))), ('CCC', '3-3', 3, (7, (8, 9)))]
into something like this:
[('AAA', '1-1', 1, 1.11, 2.22, 3.33), ('BBB', '2-2', 2, 4.44, 5.55, 6.66), ('CCC', '3-3', 3, 7, 8, 9)]
Many thanks in advance.
| [
"It looks like you want to flatten the tuples that are members of the outer list?\nTry this:\n>>> def flatten(lst):\n return sum( ([x] if not isinstance(x, (list, tuple)) else flatten(x)\n for x in lst), [] )\n\n>>> def modify(lst):\n return [tuple(flatten(x)) for x in lst]\n\n>>> x = [('AAA', '1-... | [
1,
0
] | [] | [] | [
"python"
] | stackoverflow_0003559729_python.txt |
Q:
Need to delete part of text lines in python
I have the following problem. I have a list of different text lines that all has a comma in it. I want to keep the text to the left of the comma and delete everything that occurs after the comma for all the lines in the file.
Here is a sample line from the file:
1780375 "004956 , down , 943794 , 22634 , ET , 2115 ,
I'd like to delete the characters after the first comma:
I tried to make the program yet am having some trouble. Here is what i have so far:
datafile = open('C:\\middlelist3.txt', 'r')
smallerdataset = open('C:\\nocommas.txt', 'w')
counter = 1
for line in datafile:
print counter
counter +=1
datafile.rstrip(s[,])
smallerdataset.write(line)
A:
You can use split for this. It splits the string on a given substring. As you only need the first part, I set 1 as the second parameter to make it only split on the first one.
Instead of using a counter, you could use enumerate, like this:
datafile = open('C:\\middlelist3.txt', 'r')
smallerdataset = open('C:\\nocommas.txt', 'w')
for counter, line in enumerate(datafile):
print counter
smallerdataset.write(line.split(',', 1)[0])
smallerdataset.close()
This is how you could improve your script using the with statement and generator expressions:
with open('C:\\middlelist3.txt') as datafile:
list = (line.split(',', 1)[0] for line in datafile)
with open('C:\\nocommas.txt', 'w') as smallfile:
smallfile.writelines(list)
| Need to delete part of text lines in python | I have the following problem. I have a list of different text lines that all has a comma in it. I want to keep the text to the left of the comma and delete everything that occurs after the comma for all the lines in the file.
Here is a sample line from the file:
1780375 "004956 , down , 943794 , 22634 , ET , 2115 ,
I'd like to delete the characters after the first comma:
I tried to make the program yet am having some trouble. Here is what i have so far:
datafile = open('C:\\middlelist3.txt', 'r')
smallerdataset = open('C:\\nocommas.txt', 'w')
counter = 1
for line in datafile:
print counter
counter +=1
datafile.rstrip(s[,])
smallerdataset.write(line)
| [
"You can use split for this. It splits the string on a given substring. As you only need the first part, I set 1 as the second parameter to make it only split on the first one.\nInstead of using a counter, you could use enumerate, like this:\ndatafile = open('C:\\\\middlelist3.txt', 'r')\n\nsmallerdataset = open('C... | [
4
] | [] | [] | [
"python"
] | stackoverflow_0003559939_python.txt |
Q:
merge sort in python
basically I have a bunch of files containing domains. I've sorted each individual file based on its TLD using .sort(key=func_that_returns_tld)
now that I've done that I want to merge all the files and end up wtih one massive sorted file. I assume I need something like this:
open all files
read one line from each file into a list
sort list with .sort(key=func_that_returns_tld)
output that list to file
loop by reading next line
am I thinking about this right? any advice on how to accomplish this would be appreciated.
A:
If your files are not very large, then simply read them all into memory (as S. Lott suggests). That would definitely be simplest.
However, you mention collation creates one "massive" file. If it's too massive to fit in memory, then perhaps use heapq.merge. It may be a little harder to set up, but it has the advantage of not requiring that all the iterables be pulled into memory at once.
import heapq
import contextlib
class Domain(object):
def __init__(self,domain):
self.domain=domain
@property
def tld(self):
# Put your function for calculating TLD here
return self.domain.split('.',1)[0]
def __lt__(self,other):
return self.tld<=other.tld
def __str__(self):
return self.domain
class DomFile(file):
def next(self):
return Domain(file.next(self).strip())
filenames=('data1.txt','data2.txt')
with contextlib.nested(*(DomFile(filename,'r') for filename in filenames)) as fhs:
for elt in heapq.merge(*fhs):
print(elt)
with data1.txt:
google.com
stackoverflow.com
yahoo.com
and data2.txt:
standards.freedesktop.org
www.imagemagick.org
yields:
google.com
stackoverflow.com
standards.freedesktop.org
www.imagemagick.org
yahoo.com
A:
Unless your file is incomprehensibly huge, it will fit into memory.
Your pseudo-code is hard to read. Please indent your pseudo-code correctly. The final "loop by reading next line" makes no sense.
Basically, it's this.
all_data= []
for f in list_of_files:
with open(f,'r') as source:
all_data.extend( source.readlines() )
all_data.sort(... whatever your keys are... )
You're done. You can write all_data to a file, or process it further or whatever you want to do with it.
A:
Another option (again, only if all your data won't fit into memory) is to create a SQLite3 database and do the sorting there and write it to file after.
| merge sort in python | basically I have a bunch of files containing domains. I've sorted each individual file based on its TLD using .sort(key=func_that_returns_tld)
now that I've done that I want to merge all the files and end up wtih one massive sorted file. I assume I need something like this:
open all files
read one line from each file into a list
sort list with .sort(key=func_that_returns_tld)
output that list to file
loop by reading next line
am I thinking about this right? any advice on how to accomplish this would be appreciated.
| [
"If your files are not very large, then simply read them all into memory (as S. Lott suggests). That would definitely be simplest. \nHowever, you mention collation creates one \"massive\" file. If it's too massive to fit in memory, then perhaps use heapq.merge. It may be a little harder to set up, but it has the ad... | [
8,
0,
0
] | [] | [] | [
"merge",
"python",
"sorting"
] | stackoverflow_0003559807_merge_python_sorting.txt |
Q:
How to scroll an inactive Tkinter ListBox?
I'm writing a Tkinter GUI in Python. It has an Entry for searching with a results ListBox below it. The ListBox also has a Scrollbar. How can I get scrolling with the mouse and arrow keys to work in the ListBox without switching focus away from the search field? IE I want the user to be able to type a search, scroll around, and keep typing without having to tab back and forth between widgets. Thanks
A:
Add bindings to the entry widget that call the listbox yview and/or see commands when the user presses up and down or uses the up/down scrollwheel.
For example, you can do something like this for the arrow keys:
class App(Tkinter.Tk):
def __init__(self):
Tkinter.Tk.__init__(self)
self.entry = Tkinter.Entry()
self.listbox = Tkinter.Listbox()
self.entry.pack(side="top", fill="x")
self.listbox.pack(side="top", fill="both", expand=True)
for i in range(100):
self.listbox.insert("end", "item %s" % i)
self.entry.bind("<Down>", self.OnEntryDown)
self.entry.bind("<Up>", self.OnEntryUp)
def OnEntryDown(self, event):
self.listbox.yview_scroll(1,"units")
def OnEntryUp(self, event):
self.listbox.yview_scroll(-1,"units")
| How to scroll an inactive Tkinter ListBox? | I'm writing a Tkinter GUI in Python. It has an Entry for searching with a results ListBox below it. The ListBox also has a Scrollbar. How can I get scrolling with the mouse and arrow keys to work in the ListBox without switching focus away from the search field? IE I want the user to be able to type a search, scroll around, and keep typing without having to tab back and forth between widgets. Thanks
| [
"Add bindings to the entry widget that call the listbox yview and/or see commands when the user presses up and down or uses the up/down scrollwheel.\nFor example, you can do something like this for the arrow keys:\nclass App(Tkinter.Tk):\n def __init__(self):\n Tkinter.Tk.__init__(self)\n self.entr... | [
6
] | [] | [] | [
"events",
"listbox",
"python",
"scroll",
"tkinter"
] | stackoverflow_0003559673_events_listbox_python_scroll_tkinter.txt |
Q:
blank space in the top of the plot matplotlib django
I've a question about matplotlib bars.
I've already made some bar charts but I don't know why, this one left a huge blank space in the top.
the code is similar to other graphics I've made and they don't have this problem.
If anyone has any idea, I appreciate the help.
x = matplotlib.numpy.arange(0, max(total))
ind = matplotlib.numpy.arange(len(age_list))
ax.barh(ind, total)
ax.set_yticks(ind)
ax.set_yticklabels(age_list)
A:
By "blank space in the top" do you mean that the y-limits are set too large?
By default, matplotlib will choose the x and y axis limits so that they're rounded to the closest "even" number (e.g. 1, 2, 12, 5, 50, -0.5 etc...).
If you want the axis limits to be set so that they're "tight" around the plot (i.e. the min and max of the data) use ax.axis('tight') (or equivalently, plt.axis('tight') which will use the current axis).
Another very useful method is plt.margins(...)/ax.margins(). It will act similar to axis('tight'), but will leave a bit of padding around the limits.
As an example of your problem:
import numpy as np
import matplotlib.pyplot as plt
# Make some data...
age_list = range(10,31)
total = np.random.random(len(age_list))
ind = np.arange(len(age_list))
plt.barh(ind, total)
# Set the y-ticks centered on each bar
# The default height (thickness) of each bar is 0.8
# Therefore, adding 0.4 to the tick positions will
# center the ticks on the bars...
plt.yticks(ind + 0.4, age_list)
plt.show()
If I wanted the limits to be tighter, I could call plt.axis('tight') after the call to plt.barh, which would give:
However, you might not want things to be too tight, so you could use plt.margins(0.02) to add 2% padding in all directions. You can then set the left-hand limit back to 0 with plt.xlim(xmin=0):
import numpy as np
import matplotlib.pyplot as plt
# Make some data...
age_list = range(10,31)
total = np.random.random(len(age_list))
ind = np.arange(len(age_list))
height = 0.8
plt.barh(ind, total, height=height)
plt.yticks(ind + height / 2.0, age_list)
plt.margins(0.05)
plt.xlim(xmin=0)
plt.show()
Which produces a bit nicer of a plot:
Hopefully that points you in the right direction, at any rate!
| blank space in the top of the plot matplotlib django | I've a question about matplotlib bars.
I've already made some bar charts but I don't know why, this one left a huge blank space in the top.
the code is similar to other graphics I've made and they don't have this problem.
If anyone has any idea, I appreciate the help.
x = matplotlib.numpy.arange(0, max(total))
ind = matplotlib.numpy.arange(len(age_list))
ax.barh(ind, total)
ax.set_yticks(ind)
ax.set_yticklabels(age_list)
| [
"By \"blank space in the top\" do you mean that the y-limits are set too large?\nBy default, matplotlib will choose the x and y axis limits so that they're rounded to the closest \"even\" number (e.g. 1, 2, 12, 5, 50, -0.5 etc...).\nIf you want the axis limits to be set so that they're \"tight\" around the plot (i.... | [
7
] | [] | [] | [
"django",
"matplotlib",
"python"
] | stackoverflow_0003558950_django_matplotlib_python.txt |
Q:
Problems defining install-platlib in pydistutils.cfg --
According to the docs I should be able to simply define this in my ~/.pydistutils.cfg and be off and running.
[install]
install-base=$HOME
install-purelib=python/lib
install-platlib=python/lib.$PLAT
install-scripts=python/scripts
install-data=python/data
But - when I do this I simply get this error...
error: install-base or
install-platbase supplied, but
installation scheme is incomplete
But I followed the docs explicitly. Can anyone shed any light on why this is occurring; and how to fix it??
A:
You MUST include this..
install-headers=python/??
So the final looks like this..
[install]
install-base=$HOME
install-purelib=python/lib
install-platlib=python/lib.$PLAT
install-scripts=python/scripts
install-headers=python/include
install-data=python/data
| Problems defining install-platlib in pydistutils.cfg -- | According to the docs I should be able to simply define this in my ~/.pydistutils.cfg and be off and running.
[install]
install-base=$HOME
install-purelib=python/lib
install-platlib=python/lib.$PLAT
install-scripts=python/scripts
install-data=python/data
But - when I do this I simply get this error...
error: install-base or
install-platbase supplied, but
installation scheme is incomplete
But I followed the docs explicitly. Can anyone shed any light on why this is occurring; and how to fix it??
| [
"You MUST include this..\ninstall-headers=python/??\n\nSo the final looks like this..\n[install]\ninstall-base=$HOME\ninstall-purelib=python/lib\ninstall-platlib=python/lib.$PLAT\ninstall-scripts=python/scripts\ninstall-headers=python/include\ninstall-data=python/data\n\n"
] | [
7
] | [] | [] | [
"python"
] | stackoverflow_0003560865_python.txt |
Q:
i need to do object cleanup when instance is deleted, but not on exit. can an instance delete itself?
i'd like to do some cleanup whenever an instance is deleted at runtime, but not during garbage collection that happens on exit.
in the example below, when c is deleted, a file is removed, and this is what i want;
however, that file is also removed when the program exits, and this is NOT what i want.
class C:
def __del__(self):
os.remove(self.filename)
c=C()
del c
can i tie runtime instance deletion with a block of statements, but not execute that same block when python exits?
thanks.
A:
CPython uses reference counting and only runs a fully-fledged GC (that removes cyclic references) once in a while, c = C(); del c would trigger the new C to be gc'd right away, yeah. As for __del__ and interpreter exit, the docs say:
It is not guaranteed that __del__() methods are called for objects that still exist when the interpreter exits.
But it seems impossible to be sure. Plus (admittedly, this has little relevance in practive), other implementations like Jython and IronPython don't use reference counting = object destruction/finalization is less predictable (or - in theory - may not occur at all, at least in .NET).
Anyway: this requirement (only executing __del__ when gc'd normally, not on interpreter exit) really smells. Could you elaborate on why you need to care about this?
You might want a context manager.
A:
What you want to do is not so pythonic (and I don't think it's possible). Deleting instances at runtime should usally not be needed.
You could use your own function instead of del at runtime:
def rem(object):
object.__remove()
class C:
def __remove(self):
os.remove(self.filename)
c=C()
rem(c)
Or you could implent deletion as instance method (more pythonic!):
class C:
def remove(self):
os.remove(self.filename)
c=C()
c.remove()
Or you could destroy the deletion handler at programs end:
class C:
instances = []
def __init__(self):
C.instances.append(self)
def __del__(self):
C.instances.remove(self)
os.remove(self.filename)
c = C()
del c
# ... do something ...
for c in C.instances:
del c.__del__
| i need to do object cleanup when instance is deleted, but not on exit. can an instance delete itself? | i'd like to do some cleanup whenever an instance is deleted at runtime, but not during garbage collection that happens on exit.
in the example below, when c is deleted, a file is removed, and this is what i want;
however, that file is also removed when the program exits, and this is NOT what i want.
class C:
def __del__(self):
os.remove(self.filename)
c=C()
del c
can i tie runtime instance deletion with a block of statements, but not execute that same block when python exits?
thanks.
| [
"CPython uses reference counting and only runs a fully-fledged GC (that removes cyclic references) once in a while, c = C(); del c would trigger the new C to be gc'd right away, yeah. As for __del__ and interpreter exit, the docs say:\n\nIt is not guaranteed that __del__() methods are called for objects that still ... | [
4,
1
] | [] | [] | [
"oop",
"python"
] | stackoverflow_0003560804_oop_python.txt |
Q:
Problem with dragging mouse cursor with Python
Could someone tell me why this doesn't work?
def selectAndCopy(x,y,z,w):
ctypes.windll.user32.SetCursorPos(x,y)
time.sleep(1)
win32api.mouse_event(win32con.MOUSEEVENTF_LEFTDOWN, 0, 0, 0)
time.sleep(1)
ctypes.windll.user32.SetCursorPos(z,w)
time.sleep(1)
win32api.mouse_event(win32con.MOUSEEVENTF_LEFTUP, 0, 0, 0)
time.sleep(1)
shell.SendKeys('^c')
the code isn't dragging to the first location to the second, it's only moving it.
A:
Don't reinvent the wheel! There's the package pywinauto that has a ready-to-use function for this:
pywinauto.controls.HwndWrapper.DragMouse(button='left', pressed='',
press_coords=(0, 0),
release_coords=(0, 0))
| Problem with dragging mouse cursor with Python | Could someone tell me why this doesn't work?
def selectAndCopy(x,y,z,w):
ctypes.windll.user32.SetCursorPos(x,y)
time.sleep(1)
win32api.mouse_event(win32con.MOUSEEVENTF_LEFTDOWN, 0, 0, 0)
time.sleep(1)
ctypes.windll.user32.SetCursorPos(z,w)
time.sleep(1)
win32api.mouse_event(win32con.MOUSEEVENTF_LEFTUP, 0, 0, 0)
time.sleep(1)
shell.SendKeys('^c')
the code isn't dragging to the first location to the second, it's only moving it.
| [
"Don't reinvent the wheel! There's the package pywinauto that has a ready-to-use function for this:\npywinauto.controls.HwndWrapper.DragMouse(button='left', pressed='', \n press_coords=(0, 0), \n release_coords=(0, 0))\n\n"
] | [
0
] | [] | [] | [
"python"
] | stackoverflow_0003560901_python.txt |
Q:
URL is appended to WSGI script's path, why?
I have a development server set up running Apache 2.2 with mod_wsgi. I have a test project and a webapp in development setup, and they half work. When I attempt to access something other than the project's landing page, Apache appends the rest of the URL onto the path of the WSGI script and won't load the page.
In httpd.conf:
WSGIScriptAplias /dubserv/ /home/sli/www/dubserv.wsgi
<Directory /home/sli/www/dubserv>
Order deny,allow
Allow from all
</Directory>
When accessing something other than the landing page for the app, this is the result (in this case, /login/):
[Tue Aug 24 12:38:44 2010] [error] [client 192.168.1.100] Target WSGI script not found or unable to stat: /home/sli/www/dubserv.wsgilogin
The result is the same if I put the WSGI script in anywhere under the project's root.
A:
Use /dubserv and not /dubserv/ with WSGIScriptAlias. The instructions shouldn't show a trailing slash and so one should not be included.
| URL is appended to WSGI script's path, why? | I have a development server set up running Apache 2.2 with mod_wsgi. I have a test project and a webapp in development setup, and they half work. When I attempt to access something other than the project's landing page, Apache appends the rest of the URL onto the path of the WSGI script and won't load the page.
In httpd.conf:
WSGIScriptAplias /dubserv/ /home/sli/www/dubserv.wsgi
<Directory /home/sli/www/dubserv>
Order deny,allow
Allow from all
</Directory>
When accessing something other than the landing page for the app, this is the result (in this case, /login/):
[Tue Aug 24 12:38:44 2010] [error] [client 192.168.1.100] Target WSGI script not found or unable to stat: /home/sli/www/dubserv.wsgilogin
The result is the same if I put the WSGI script in anywhere under the project's root.
| [
"Use /dubserv and not /dubserv/ with WSGIScriptAlias. The instructions shouldn't show a trailing slash and so one should not be included.\n"
] | [
0
] | [] | [] | [
"apache2",
"django",
"mod_wsgi",
"python"
] | stackoverflow_0003558795_apache2_django_mod_wsgi_python.txt |
Q:
python, datetime.date: difference between two days
I'm playing around with 2 objects {@link http://docs.python.org/library/datetime.html#datetime.date}
I would like to calculate all the days between them, assuming that date 1 >= date 2, and print them out. Here is an example what I would like to achieve. But I don't think this is efficient at all. Is there a better way to do this?
# i think +2 because this calc gives only days between the two days,
# i would like to include them
daysDiff = (dateTo - dateFrom).days + 2
while (daysDiff > 0):
rptDate = dateFrom.today() - timedelta(days=daysDiff)
print rptDate.strftime('%Y-%m-%d')
daysDiff -= 1
A:
I don't see this as particularly inefficient, but you could make it slightly cleaner without the while loop:
delta = dateTo - dateFrom
for delta_day in range(0, delta.days+1): # Or use xrange in Python 2.x
print dateFrom + datetime.timedelta(delta_day)
(Also, notice how printing or using str on a date produces that '%Y-%m-%d' format for you for free)
It might be inefficient, however, to do it this way if you were creating a long list of days in one go instead of just printing, for example:
[dateFrom + datetime.timedelta(delta_day) for delta_day in range(0, delta.days+1)]
This could easily be rectified by creating a generator instead of a list. Either replace [...] with (...) in the above example, or:
def gen_days_inclusive(start_date, end_date):
delta_days = (end_date - start_date).days
for day in xrange(delta_days + 1):
yield start_date + datetime.timedelta(day)
Whichever suits your syntax palate better.
| python, datetime.date: difference between two days | I'm playing around with 2 objects {@link http://docs.python.org/library/datetime.html#datetime.date}
I would like to calculate all the days between them, assuming that date 1 >= date 2, and print them out. Here is an example what I would like to achieve. But I don't think this is efficient at all. Is there a better way to do this?
# i think +2 because this calc gives only days between the two days,
# i would like to include them
daysDiff = (dateTo - dateFrom).days + 2
while (daysDiff > 0):
rptDate = dateFrom.today() - timedelta(days=daysDiff)
print rptDate.strftime('%Y-%m-%d')
daysDiff -= 1
| [
"I don't see this as particularly inefficient, but you could make it slightly cleaner without the while loop:\ndelta = dateTo - dateFrom\n\nfor delta_day in range(0, delta.days+1): # Or use xrange in Python 2.x\n print dateFrom + datetime.timedelta(delta_day)\n\n(Also, notice how printing or using str on a date ... | [
6
] | [] | [] | [
"python"
] | stackoverflow_0003561183_python.txt |
Q:
Django many-to-many problem in admin
I am essentially creating a blog application in django as a way of learning the ropes and boosting my skill level in django. I basically have a many-to-many relationship that I am having problems with in the admin site. I have two main types, Article and ArticleTag. Many Articles can belong to many ArticleTags, and the relationship should be bidirectional so as to be able to "follow" the relationship from either side.
The problem I am having is that in the admin panel, when I go to create a new Article, it will not allow me to create a new Article without creating a new ArticleTag, which can't be created without creating a new Article, etc. How can I make these work properly and be optional? Also, is there a fairly easy way to create a control to facilitate tagging as per stack overflow or delicious.com? I am fairly new to the admin system :)
A:
You forgot to specify blank=True in your ManyToManyField declaration:
class Article(models.Model):
tags = models.ManyToManyField(ArticleTag, blank=True,
related_name="articles")
Also, is there a fairly easy way to create a control to facilitate tagging as per stack overflow or delicious.com?
There's nothing built-in, but there are several add-on libraries for Django that do tagging. One of them might fit your needs.
| Django many-to-many problem in admin | I am essentially creating a blog application in django as a way of learning the ropes and boosting my skill level in django. I basically have a many-to-many relationship that I am having problems with in the admin site. I have two main types, Article and ArticleTag. Many Articles can belong to many ArticleTags, and the relationship should be bidirectional so as to be able to "follow" the relationship from either side.
The problem I am having is that in the admin panel, when I go to create a new Article, it will not allow me to create a new Article without creating a new ArticleTag, which can't be created without creating a new Article, etc. How can I make these work properly and be optional? Also, is there a fairly easy way to create a control to facilitate tagging as per stack overflow or delicious.com? I am fairly new to the admin system :)
| [
"You forgot to specify blank=True in your ManyToManyField declaration:\nclass Article(models.Model):\n tags = models.ManyToManyField(ArticleTag, blank=True, \n related_name=\"articles\")\n\n\nAlso, is there a fairly easy way to create a control to facilitate tagging as per stack overflow or delicious.com?... | [
3
] | [] | [] | [
"django",
"django_admin",
"django_models",
"python"
] | stackoverflow_0003561508_django_django_admin_django_models_python.txt |
Q:
Confusing loop problem (python)
this is similar to the question in merge sort in python
I'm restating because I don't think I explained the problem very well over there.
basically I have a series of about 1000 files all containing domain names. altogether the data is > 1gig so I'm trying to avoid loading all the data into ram. each individual file has been sorted using .sort(get_tld) which has sorted the data according to its TLD (not according to its domain name. sorted all the .com's together, .orgs together, etc)
a typical file might look like
something.ca
somethingelse.ca
somethingnew.com
another.net
whatever.org
etc.org
but obviosuly longer.
I now want to merge all the files into one, maintaining the sort so that in the end the one large file will still have all the .coms together, .orgs together, etc.
What I want to do basically is
open all the files
loop:
read 1 line from each open file
put them all in a list and sort with .sort(get_tld)
write each item from the list to a new file
the problem I'm having is that I can't figure out how to loop over the files
I can't use with open() as because I don't have 1 file open to loop over, I have many. Also they're all of variable length so I have to make sure to get all the way through the longest one.
any advice is much appreciated.
A:
Whether you're able to keep 1000 files at once is a separate issue and depends on your OS and its configuration; if not, you'll have to proceed in two steps -- merge groups of N files into temporary ones, then merge the temporary ones into the final-result file (two steps should suffice, as they let you merge a total of N squared files; as long as N is at least 32, merging 1000 files should therefore be possible). In any case, this is a separate issue from the "merge N input files into one output file" task (it's only an issue of whether you call that function once, or repeatedly).
The general idea for the function is to keep a priority queue (module heapq is good at that;-) with small lists containing the "sorting key" (the current TLD, in your case) followed by the last line read from the file, and finally the open file ready for reading the next line (and something distinct in between to ensure that the normal lexicographical order won't accidentally end up trying to compare two open files, which would fail). I think some code is probably the best way to explain the general idea, so next I'll edit this answer to supply the code (however I have no time to test it, so take it as pseudocode intended to communicate the idea;-).
import heapq
def merge(inputfiles, outputfile, key):
"""inputfiles: list of input, sorted files open for reading.
outputfile: output file open for writing.
key: callable supplying the "key" to use for each line.
"""
# prepare the heap: items are lists with [thekey, k, theline, thefile]
# where k is an arbitrary int guaranteed to be different for all items,
# theline is the last line read from thefile and not yet written out,
# (guaranteed to be a non-empty string), thekey is key(theline), and
# thefile is the open file
h = [(k, i.readline(), i) for k, i in enumerate(inputfiles)]
h = [[key(s), k, s, i] for k, s, i in h if s]
heapq.heapify(h)
while h:
# get and output the lowest available item (==available item w/lowest key)
item = heapq.heappop(h)
outputfile.write(item[2])
# replenish the item with the _next_ line from its file (if any)
item[2] = item[3].readline()
if not item[2]: continue # don't reinsert finished files
# compute the key, and re-insert the item appropriately
item[0] = key(item[2])
heapq.heappush(h, item)
Of course, in your case, as the key function you'll want one that extracts the top-level domain given a line that's a domain name (with trailing newline) -- in a previous question you were already pointed to the urlparse module as preferable to string manipulation for this purpose. If you do insist on string manipulation,
def tld(domain):
return domain.rsplit('.', 1)[-1].strip()
or something along these lines is probably a reasonable approach under this constraint.
If you use Python 2.6 or better, heapq.merge is the obvious alternative, but in that case you need to prepare the iterators yourself (including ensuring that "open file objects" never end up being compared by accident...) with a similar "decorate / undecorate" approach from that I use in the more portable code above.
A:
You want to use merge sort, e.g. heapq.merge. I'm not sure if your OS allows you to open 1000 files simultaneously. If not you may have to do it in 2 or more passes.
A:
Why don't you divide the domains by first letter, so you would just split the source files into 26 or more files which could be named something like: domains-a.dat, domains-b.dat. Then you can load these entirely into RAM and sort them and write them out to a common file.
So:
3 input files split into 26+ source files
26+ source files could be loaded individually, sorted in RAM and then written to the combined file.
If 26 files are not enough, I'm sure you could split into even more files... domains-ab.dat. The point is that files are cheap and easy to work with (in Python and many other languages), and you should use them to your advantage.
A:
Your algorithm for merging sorted files is incorrect. What you do is read one line from each file, find the lowest-ranked item among all the lines read, and write it to the output file. Repeat this process (ignoring any files that are at EOF) until the end of all files has been reached.
A:
#! /usr/bin/env python
"""Usage: unconfuse.py file1 file2 ... fileN
Reads a list of domain names from each file, and writes them to standard output grouped by TLD.
"""
import sys, os
spools = {}
for name in sys.argv[1:]:
for line in file(name):
if (line == "\n"): continue
tld = line[line.rindex(".")+1:-1]
spool = spools.get(tld, None)
if (spool == None):
spool = file(tld + ".spool", "w+")
spools[tld] = spool
spool.write(line)
for tld in sorted(spools.iterkeys()):
spool = spools[tld]
spool.seek(0)
for line in spool:
sys.stdout.write(line)
spool.close()
os.remove(spool.name)
| Confusing loop problem (python) | this is similar to the question in merge sort in python
I'm restating because I don't think I explained the problem very well over there.
basically I have a series of about 1000 files all containing domain names. altogether the data is > 1gig so I'm trying to avoid loading all the data into ram. each individual file has been sorted using .sort(get_tld) which has sorted the data according to its TLD (not according to its domain name. sorted all the .com's together, .orgs together, etc)
a typical file might look like
something.ca
somethingelse.ca
somethingnew.com
another.net
whatever.org
etc.org
but obviosuly longer.
I now want to merge all the files into one, maintaining the sort so that in the end the one large file will still have all the .coms together, .orgs together, etc.
What I want to do basically is
open all the files
loop:
read 1 line from each open file
put them all in a list and sort with .sort(get_tld)
write each item from the list to a new file
the problem I'm having is that I can't figure out how to loop over the files
I can't use with open() as because I don't have 1 file open to loop over, I have many. Also they're all of variable length so I have to make sure to get all the way through the longest one.
any advice is much appreciated.
| [
"Whether you're able to keep 1000 files at once is a separate issue and depends on your OS and its configuration; if not, you'll have to proceed in two steps -- merge groups of N files into temporary ones, then merge the temporary ones into the final-result file (two steps should suffice, as they let you merge a to... | [
6,
3,
2,
1,
0
] | [] | [] | [
"loops",
"python",
"sorting"
] | stackoverflow_0003561221_loops_python_sorting.txt |
Q:
Decimal to hex in python
So I have kind of a ignorant (maybe?) question. I'm working with writing to a serial device for the first time. I have a frame [12, 0, 0, 0, 0, 0, 0, 0, 7, 0, X, Y] that I need to send. X and Y are checksum values. My understanding in using the pyserial module is that I need to convert this frame into a string representation. Ok that's fine, but I'm confused on what format things are supposed to be in. I tried doing
a = [12, 0, 0, 0, 0, 0, 0, 0, 7, 0, X, Y]
send = "".join(chr(t) for t in a)
But my confusion comes from the fact that X and Y, when using chr, transform into weird strings (assuming their ascii representation). For example if X is 36, chr(x) is '$' instead of '\x24'. Is there a way I can get a string representing the '\xnn' value instead of the ascii code? What's confusing me is that 12 and 7 convert to '\x0b' and '\x07' correctly. Am I missing something?
Update:
So it might be that I'm not quite understanding how serial writes are being done or what my device is expecting of me. This is a portion of my C code that is working:
fd=open("/dev/ttyS2",O_RDWR|O_NDELAY);
char buff_out[20]
//Next line is psuedo
for i in buff_out print("%x ",buff_out[i]); // prints b 0 0 0 0 0 0 0 9 b3 36
write(fd,buff_out,11);
sleep()
read(fd,buff_in,size);
for i in buff_in print("%x ",buff_in[i]); // prints the correct frame that I'm expecting
Python:
frame = [11, 0, 0, 0, 0, 0, 0, 0, 9] + [crc1, crc1]
senddata = "".join(chr(x) for x in frame)
IEC = serial.Serial(port='/dev/ttyS2', baudrate=1200, timeout=0)
IEC.send(senddata)
IEC.read(18) # number of bytes to read doesn't matter, it's always 0
Am I going about this the right way? Obviously you can't tell exactly since it's device specific and I can't really give too many specifics out. But is that the correct format that serial.send() expects data in?
A:
It's perfectly normal for ASCII bytes to be represented by single characters if they can be printed, and by the \x?? notation otherwise. In both cases they represent a single byte, and you can write strings in either fashion:
>>> '\x68\x65\x6c\x6c\x6f'
'hello'
However if you're using Python 2.6 or later then you might find it easier and more natural to use the built-in bytearray rather than messing around with ord or struct.
>>> vals = [12, 0, 0, 0, 0, 0, 0, 0, 7, 0, 36, 100]
>>> b = bytearray(vals)
>>> b
bytearray(b'\x0c\x00\x00\x00\x00\x00\x00\x00\x07\x00$d')
You can convert to a str (or bytes in Python 3) just by casting, and can index the bytearray to get the integers back.
>>> str(b)
'\x0c\x00\x00\x00\x00\x00\x00\x00\x07\x00$d'
>>> b[0]
12
>>> b[-1]
100
As to your serial Python code, it looks fine to me - I'm not sure why you think there is a problem...
A:
The character with the ASCII-code 36 is '$'. Look it up in any ASCII table. Python only displays the hex escapes if the character is not printable (control characters etc).
At the lowest level, it's the same bit pattern anyway - no matter whether Python prints it as a hex escape or as the char with that ASCII value.
But you might want to use the struct module, it takes care of such conversions for you.
A:
I would guess you want struct.
>>> import struct
>>> struct.pack('>B', 12)
'\x0c'
>>> vals = [12, 0, 0, 0, 0, 0, 0, 0, 7, 0, 0xa, 0xb]
>>> ''.join(struct.pack('>B', x) for x in vals)
'\x0c\x00\x00\x00\x00\x00\x00\x00\x07\x00\n\x0b'
A:
What you do is perfectly fine: your send is what you want: a sequence of bytes with the values you want (a).
If you want to see what are the hexadecimal codes of the characters in send, you can do:
import binascii
print binascii.hexlify(send)
or
print ''.join(r'\x%02x' % ord(char) for char in send)
(if you want \x prefixes).
What you see when directly printing repr(send) is a representation of send, which uses ASCII: 65 represents 'A', but character 12 is '\x0c'. This is merely a convention used by Python, which is convenient when the string contains words, for instance: it is better to display 'Hello' than \x48\x65\x6c\x6c\x6f!
| Decimal to hex in python | So I have kind of a ignorant (maybe?) question. I'm working with writing to a serial device for the first time. I have a frame [12, 0, 0, 0, 0, 0, 0, 0, 7, 0, X, Y] that I need to send. X and Y are checksum values. My understanding in using the pyserial module is that I need to convert this frame into a string representation. Ok that's fine, but I'm confused on what format things are supposed to be in. I tried doing
a = [12, 0, 0, 0, 0, 0, 0, 0, 7, 0, X, Y]
send = "".join(chr(t) for t in a)
But my confusion comes from the fact that X and Y, when using chr, transform into weird strings (assuming their ascii representation). For example if X is 36, chr(x) is '$' instead of '\x24'. Is there a way I can get a string representing the '\xnn' value instead of the ascii code? What's confusing me is that 12 and 7 convert to '\x0b' and '\x07' correctly. Am I missing something?
Update:
So it might be that I'm not quite understanding how serial writes are being done or what my device is expecting of me. This is a portion of my C code that is working:
fd=open("/dev/ttyS2",O_RDWR|O_NDELAY);
char buff_out[20]
//Next line is psuedo
for i in buff_out print("%x ",buff_out[i]); // prints b 0 0 0 0 0 0 0 9 b3 36
write(fd,buff_out,11);
sleep()
read(fd,buff_in,size);
for i in buff_in print("%x ",buff_in[i]); // prints the correct frame that I'm expecting
Python:
frame = [11, 0, 0, 0, 0, 0, 0, 0, 9] + [crc1, crc1]
senddata = "".join(chr(x) for x in frame)
IEC = serial.Serial(port='/dev/ttyS2', baudrate=1200, timeout=0)
IEC.send(senddata)
IEC.read(18) # number of bytes to read doesn't matter, it's always 0
Am I going about this the right way? Obviously you can't tell exactly since it's device specific and I can't really give too many specifics out. But is that the correct format that serial.send() expects data in?
| [
"It's perfectly normal for ASCII bytes to be represented by single characters if they can be printed, and by the \\x?? notation otherwise. In both cases they represent a single byte, and you can write strings in either fashion:\n>>> '\\x68\\x65\\x6c\\x6c\\x6f'\n'hello'\n\nHowever if you're using Python 2.6 or later... | [
3,
1,
0,
0
] | [] | [] | [
"hex",
"python",
"serial_port"
] | stackoverflow_0003561117_hex_python_serial_port.txt |
Q:
Dissecting a line of (obfuscated?) Python
I was reading another question on Stack Overflow (Zen of Python), and I came across this line in Jaime Soriano's answer:
import this
"".join([c in this.d and this.d[c] or c for c in this.s])
Entering the above in a Python shell prints:
"The Zen of Python, by Tim Peters\n\nBeautiful is better than ugly.\nExplicit is
better than implicit.\nSimple is better than complex.\nComplex is better than
complicated.\nFlat is better than nested.\nSparse is better than dense.
\nReadability counts.\nSpecial cases aren't special enough to break the rules.
\nAlthough practicality beats purity.\nErrors should never pass silently.
\nUnless explicitly silenced.\nIn the face of ambiguity, refuse the temptation to
guess.\nThere should be one-- and preferably only one --obvious way to do it.
\nAlthough that way may not be obvious at first unless you're Dutch.\nNow is
better than never.\nAlthough never is often better than *right* now.\nIf the
implementation is hard to explain, it's a bad idea.\nIf the implementation is
easy to explain, it may be a good idea.\nNamespaces are one honking great idea
-- let's do more of those!"
And so of course I was compelled to spend my entire morning trying to understand the above list... comprehension... thing. I hesitate to flatly declare it obfuscated, but only because I've been programming for just a month and a half and so am unsure as to whether or not such constructions are commonplace in python.
this.s contains an encoded version of the above printout:
"Gur Mra bs Clguba, ol Gvz Crgref\n\nOrnhgvshy vf orggre guna htyl.\nRkcyvpvg vf orggre guna vzcyvpvg.\nFvzcyr vf orggre guna pbzcyrk.\nPbzcyrk vf orggre guna pbzcyvpngrq.\nSyng vf orggre guna arfgrq.\nFcnefr vf orggre guna qrafr.\nErnqnovyvgl pbhagf.\nFcrpvny pnfrf nera'g fcrpvny rabhtu gb oernx gur ehyrf.\nNygubhtu cenpgvpnyvgl orngf chevgl.\nReebef fubhyq arire cnff fvyragyl.\nHayrff rkcyvpvgyl fvyraprq.\nVa gur snpr bs nzovthvgl, ershfr gur grzcgngvba gb thrff.\nGurer fubhyq or bar-- naq cersrenoyl bayl bar --boivbhf jnl gb qb vg.\nNygubhtu gung jnl znl abg or boivbhf ng svefg hayrff lbh'er Qhgpu.\nAbj vf orggre guna arire.\nNygubhtu arire vf bsgra orggre guna *evtug* abj.\nVs gur vzcyrzragngvba vf uneq gb rkcynva, vg'f n onq vqrn.\nVs gur vzcyrzragngvba vf rnfl gb rkcynva, vg znl or n tbbq vqrn.\nAnzrfcnprf ner bar ubaxvat terng vqrn -- yrg'f qb zber bs gubfr!"
And this.d contains a dictionary with the cypher that decodes this.s:
{'A': 'N', 'C': 'P', 'B': 'O', 'E': 'R', 'D': 'Q', 'G': 'T', 'F': 'S', 'I': 'V', 'H': 'U', 'K': 'X', 'J': 'W', 'M': 'Z', 'L': 'Y', 'O': 'B', 'N': 'A', 'Q': 'D', 'P': 'C', 'S': 'F', 'R': 'E', 'U': 'H', 'T': 'G', 'W': 'J', 'V': 'I', 'Y': 'L', 'X': 'K', 'Z': 'M', 'a': 'n', 'c': 'p', 'b': 'o', 'e': 'r', 'd': 'q', 'g': 't', 'f': 's', 'i': 'v', 'h': 'u', 'k': 'x', 'j': 'w', 'm': 'z', 'l': 'y', 'o': 'b', 'n': 'a', 'q': 'd', 'p': 'c', 's': 'f', 'r': 'e', 'u': 'h', 't': 'g', 'w': 'j', 'v': 'i', 'y': 'l', 'x': 'k', 'z': 'm'}
As far as I can tell, the flow of execution in Jaime's code is like this:
1. the loop c for c in this.s assigns a value to c
2. if the statement c in this.d evaluates to True, the "and" statement executes whatever happens to be to its immediate right, in this case this.d[c].
3. if the statement c in this.d evaluates to False (which never happens in Jaime's code), the "or" statement executes whatever happens to be to its immediate right, in this case the loop c for c in this.s.
Am I correct about that flow?
Even if I am correct about the order of execution, this still leaves me with a ton of questions. Why is <1> the first thing to execute, even though the code for it comes last on the line after several conditional statements? In other words, why does the for loop begin to execute and assign value, but then only actually return a value at a later point in the code execution, if at all?
Also, for bonus points, what's with the weird line in the Zen file about the Dutch?
Edit: Though it shames me to say it now, until three seconds ago I assumed Guido van Rossum was Italian. After reading his Wikipedia article, I at least grasp, if not fully understand, why that line is in there.
A:
The operators in the list comprehension line associate like this:
"".join([(((c in this.d) and this.d[c]) or c) for c in this.s])
Removing the list comprehension:
result = []
for c in this.s:
result.append(((c in this.d) and this.d[c]) or c)
print "".join(result)
Removing the and/or boolean trickery, which is used to emulate a if-else statement:
result = []
for c in this.s:
if c in this.d:
result.append(this.d[c])
else:
result.append(c)
print "".join(result)
A:
You are correct about the flow.
The loop is of kind [dosomething(c) for c in this.s] It's a list comprehension and should be read as dosomething for all c in this.s.
The Dutch part is about Guido Van Rossum creator of python is Dutch.
A:
Your analysis is close. It is a list comprehension. (btw, the same output would result if the outer square brackets were eliminated, which would be called a generator comprehension)
There is some documentation here.
The basic form of a list comprehension is
[expression for var in enumerable if condition]
They are evaluated in this order:
enumerable is evaluated
Each value in turn is assigned to var
condition is checked
expression is evaluated
The result is the list of expression values for each element in the enumerable for which the condition was true.
This example doesn't use a condtion, so what is left, after adding some parentheses is:
[(c in this.d and this.d[c] or c) for c in (this.s)]
this.s is the enumerable. c is the iterating variable. c in this.d and this.d[c] or c is the expression.
c in this.d and this.d[c] or c uses the short-circuiting nature of python's logical operators to achieve the same thing as this.d[c] if c in this.d else c.
All in all, I would not call this obfuscated at all. Once you understand the power of list comprehensions, it will look quite natural.
A:
Generally, list comprehensions are of the following form:
[ expression for var in iterator ]
When I write down a list comprehension, I often start by writing
[ for var in iterator ]
because many years of procedural programming has inculcated the for-loop aspect into my mind as the part that comes first.
And, as you've rightly noted, the for-loop is the part that seems to "execute" first.
For each pass through the loop, the expression is evaluated.
(A minor point: expressions are evaluated, statements are executed.)
So in this case, we have
[ expression for c in this.s ]
this.s is a string. In Python, strings are iterators! When you write
for c in some_string:
the loop iterates over the characters in the string. So c takes on each of the characters in this.s in order.
Now the expression is
c in this.d and this.d[c] or c
This is what's known as a ternary operation. That link explains the logic, but the basic idea is
if c in this.d:
the expression evaluates to this.d[c]
else:
the expression evaluates c
The condition c in this.d is thus simply to check that the dict this.d has a key with value c. If it does, return this.d[c], and if it doesn't, return c itself.
Another way to write it would be
[this.d.get(c,c) for c in this.s]
(the second argument to the get method is the default value returned when the first argument is not in the dict).
PS. The ternary form
condition and value1 or value2
is error prone. (Consider what happens if condition is True, but value1 is None. Since condition is True, you might expect the ternary form to evaluate to value1, that is, None. But since None has boolean value False, the ternary form evaluates to value2 instead. Thus, if you are not careful and aware of this pitfall, the ternary form can introduce errors.)
For modern versions of Python a better way to write this would be
value1 if condition else value2
It is not susceptible to the pitfall mentioned above. If condition is True, the expression always evaluates to value1.
But in the particular case above, I'd prefer this.d.get(c,c).
A:
"".join([c in this.d and this.d[c] or c for c in this.s]) is certainly obfuscated. Here's a Zen version:
this.s.decode('rot13')
A:
My version with modern if else and generator:
import this ## prints zenofpython
print '-'*70
whatiszenofpython = "".join(this.d[c] if c in this.d else c for c in this.s)
zen = ''
for c in this.s:
zen += this.d[c] if c in this.d else c
print zen
Verbal version:
import this, the main program of it descrambles and print the message this.s
To descramble the message replace those letters which are found in dict this.d with their decoded counter parts (upper/lowercase different). The other letters do not need to change but print as they are.
| Dissecting a line of (obfuscated?) Python | I was reading another question on Stack Overflow (Zen of Python), and I came across this line in Jaime Soriano's answer:
import this
"".join([c in this.d and this.d[c] or c for c in this.s])
Entering the above in a Python shell prints:
"The Zen of Python, by Tim Peters\n\nBeautiful is better than ugly.\nExplicit is
better than implicit.\nSimple is better than complex.\nComplex is better than
complicated.\nFlat is better than nested.\nSparse is better than dense.
\nReadability counts.\nSpecial cases aren't special enough to break the rules.
\nAlthough practicality beats purity.\nErrors should never pass silently.
\nUnless explicitly silenced.\nIn the face of ambiguity, refuse the temptation to
guess.\nThere should be one-- and preferably only one --obvious way to do it.
\nAlthough that way may not be obvious at first unless you're Dutch.\nNow is
better than never.\nAlthough never is often better than *right* now.\nIf the
implementation is hard to explain, it's a bad idea.\nIf the implementation is
easy to explain, it may be a good idea.\nNamespaces are one honking great idea
-- let's do more of those!"
And so of course I was compelled to spend my entire morning trying to understand the above list... comprehension... thing. I hesitate to flatly declare it obfuscated, but only because I've been programming for just a month and a half and so am unsure as to whether or not such constructions are commonplace in python.
this.s contains an encoded version of the above printout:
"Gur Mra bs Clguba, ol Gvz Crgref\n\nOrnhgvshy vf orggre guna htyl.\nRkcyvpvg vf orggre guna vzcyvpvg.\nFvzcyr vf orggre guna pbzcyrk.\nPbzcyrk vf orggre guna pbzcyvpngrq.\nSyng vf orggre guna arfgrq.\nFcnefr vf orggre guna qrafr.\nErnqnovyvgl pbhagf.\nFcrpvny pnfrf nera'g fcrpvny rabhtu gb oernx gur ehyrf.\nNygubhtu cenpgvpnyvgl orngf chevgl.\nReebef fubhyq arire cnff fvyragyl.\nHayrff rkcyvpvgyl fvyraprq.\nVa gur snpr bs nzovthvgl, ershfr gur grzcgngvba gb thrff.\nGurer fubhyq or bar-- naq cersrenoyl bayl bar --boivbhf jnl gb qb vg.\nNygubhtu gung jnl znl abg or boivbhf ng svefg hayrff lbh'er Qhgpu.\nAbj vf orggre guna arire.\nNygubhtu arire vf bsgra orggre guna *evtug* abj.\nVs gur vzcyrzragngvba vf uneq gb rkcynva, vg'f n onq vqrn.\nVs gur vzcyrzragngvba vf rnfl gb rkcynva, vg znl or n tbbq vqrn.\nAnzrfcnprf ner bar ubaxvat terng vqrn -- yrg'f qb zber bs gubfr!"
And this.d contains a dictionary with the cypher that decodes this.s:
{'A': 'N', 'C': 'P', 'B': 'O', 'E': 'R', 'D': 'Q', 'G': 'T', 'F': 'S', 'I': 'V', 'H': 'U', 'K': 'X', 'J': 'W', 'M': 'Z', 'L': 'Y', 'O': 'B', 'N': 'A', 'Q': 'D', 'P': 'C', 'S': 'F', 'R': 'E', 'U': 'H', 'T': 'G', 'W': 'J', 'V': 'I', 'Y': 'L', 'X': 'K', 'Z': 'M', 'a': 'n', 'c': 'p', 'b': 'o', 'e': 'r', 'd': 'q', 'g': 't', 'f': 's', 'i': 'v', 'h': 'u', 'k': 'x', 'j': 'w', 'm': 'z', 'l': 'y', 'o': 'b', 'n': 'a', 'q': 'd', 'p': 'c', 's': 'f', 'r': 'e', 'u': 'h', 't': 'g', 'w': 'j', 'v': 'i', 'y': 'l', 'x': 'k', 'z': 'm'}
As far as I can tell, the flow of execution in Jaime's code is like this:
1. the loop c for c in this.s assigns a value to c
2. if the statement c in this.d evaluates to True, the "and" statement executes whatever happens to be to its immediate right, in this case this.d[c].
3. if the statement c in this.d evaluates to False (which never happens in Jaime's code), the "or" statement executes whatever happens to be to its immediate right, in this case the loop c for c in this.s.
Am I correct about that flow?
Even if I am correct about the order of execution, this still leaves me with a ton of questions. Why is <1> the first thing to execute, even though the code for it comes last on the line after several conditional statements? In other words, why does the for loop begin to execute and assign value, but then only actually return a value at a later point in the code execution, if at all?
Also, for bonus points, what's with the weird line in the Zen file about the Dutch?
Edit: Though it shames me to say it now, until three seconds ago I assumed Guido van Rossum was Italian. After reading his Wikipedia article, I at least grasp, if not fully understand, why that line is in there.
| [
"The operators in the list comprehension line associate like this:\n\"\".join([(((c in this.d) and this.d[c]) or c) for c in this.s])\n\nRemoving the list comprehension:\nresult = []\nfor c in this.s:\n result.append(((c in this.d) and this.d[c]) or c)\nprint \"\".join(result)\n\nRemoving the and/or boolean trick... | [
11,
2,
2,
2,
2,
0
] | [] | [] | [
"control_flow",
"execution",
"obfuscation",
"python"
] | stackoverflow_0003559124_control_flow_execution_obfuscation_python.txt |
Q:
Where are Python dylibs installed on the Mac?
On Mac OSX 10.6.4 where do you install dynamic libraries (dylib) so Python 2.6.1 can import them? I've tried placing them in /usr/local/lib and usr/localbin and /Library/Python/2.6/site-packages but none of these locations have worked. The library I'm trying to install is libevecache.dylib a library to access cache files for Eve-Online.
A:
Anywhere in your $DYLD_LIBRARY_PATH should work for compiled library files; you can also try setting $PYTHONPATH / sys.path.
A:
Run the included setup.py file. You should never try to copy things into place manually; it'll lead to disaster, especially in situations involving pip or easy_install.
| Where are Python dylibs installed on the Mac? | On Mac OSX 10.6.4 where do you install dynamic libraries (dylib) so Python 2.6.1 can import them? I've tried placing them in /usr/local/lib and usr/localbin and /Library/Python/2.6/site-packages but none of these locations have worked. The library I'm trying to install is libevecache.dylib a library to access cache files for Eve-Online.
| [
"Anywhere in your $DYLD_LIBRARY_PATH should work for compiled library files; you can also try setting $PYTHONPATH / sys.path.\n",
"Run the included setup.py file. You should never try to copy things into place manually; it'll lead to disaster, especially in situations involving pip or easy_install.\n"
] | [
0,
0
] | [] | [] | [
"dylib",
"macos",
"python"
] | stackoverflow_0003561209_dylib_macos_python.txt |
Q:
Django utf-8 and django-mailer strangeness
Latest django mailer from trunk http://github.com/jtauber/django-mailer/tree/master/docs/
Tested with Postgresql 8.4, sqlite3
template
{{ title }}
forms.py
#-*- coding: utf-8 -*-
if "mailer" in settings.INSTALLED_APPS:
from mailer import send_mail
else:
from django.core.mail import send_mail
...
body_txt = render_to_string(
'mails/share_deal/email_body.txt',
{
'title':u"éééààà",
}
)
send_mail( "", body_txt , "foo@ff.ff", ["bar@kl.fd"], fail_silently=True)
Error
Environment:
Request Method: POST
Request URL: http://localhost:8000/deals/share/
Django Version: 1.2 SVN-13596
Python Version: 2.6.5
Installed Applications:
['django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.sites',
'django.contrib.messages',
'django.contrib.admin',
'django_extensions',
'django.contrib.markup',
'django.contrib.comments',
'ajaxcomments',
'mailer',
'profiles',
'tagging',
'wmd',
'core',
'deals']
Installed Middleware:
('django.middleware.common.CommonMiddleware',
'django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware')
Traceback:
File "/home/gregory/.virtualenvs/alpha/src/django/django/core/handlers/base.py" in get_response
100. response = callback(request, *callback_args, **callback_kwargs)
File "/home/gregory/projects/casadeal/casadeal/core/decorators.py" in wrap
12. return f(request, *args, **kwargs)
File "/home/gregory/.virtualenvs/alpha/src/django/django/views/decorators/http.py" in inner
37. return func(request, *args, **kwargs)
File "/home/gregory/projects/casadeal/casadeal/deals/views.py" in share_deal
22. form.send_mail()
File "/home/gregory/projects/casadeal/casadeal/deals/forms.py" in send_mail
89. fail_silently=True)
File "/home/gregory/.virtualenvs/casadeal/src/django-mailer/mailer/__init__.py" in send_mail
45. priority=priority).save()
File "/home/gregory/.virtualenvs/alpha/src/django/django/db/models/base.py" in save
435. self.save_base(using=using, force_insert=force_insert, force_update=force_update)
File "/home/gregory/.virtualenvs/alpha/src/django/django/db/models/base.py" in save_base
528. result = manager._insert(values, return_id=update_pk, using=using)
File "/home/gregory/.virtualenvs/alpha/src/django/django/db/models/manager.py" in _insert
195. return insert_query(self.model, values, **kwargs)
File "/home/gregory/.virtualenvs/alpha/src/django/django/db/models/query.py" in insert_query
1479. return query.get_compiler(using=using).execute_sql(return_id)
File "/home/gregory/.virtualenvs/alpha/src/django/django/db/models/sql/compiler.py" in execute_sql
783. cursor = super(SQLInsertCompiler, self).execute_sql(None)
File "/home/gregory/.virtualenvs/alpha/src/django/django/db/models/sql/compiler.py" in execute_sql
727. cursor.execute(sql, params)
File "/home/gregory/.virtualenvs/alpha/src/django/django/db/backends/util.py" in execute
15. return self.cursor.execute(sql, params)
File "/home/gregory/.virtualenvs/alpha/src/django/django/db/backends/postgresql_psycopg2/base.py" in execute
44. return self.cursor.execute(query, args)
Exception Type: DatabaseError at /deals/share/
Exception Value: ERREUR: séquence d'octets invalide pour l'encodage « UTF8 » : 0xe9e9e9
HINT: Cette erreur peut aussi survenir si la séquence d'octets ne correspond pas
au jeu de caractères attendu par le serveur, le jeu étant contrôlé par
« client_encoding ».
Basically it says that the encoding was not valid for UTF8 and contained 0xe9e9e9
This seems quite strange,
Any hints on where it could come from ?
A:
U+00E9 is LATIN SMALL LETTER E WITH ACUTE.
This MAY be the source (not necessarily the cause) of the problem: 'title':u"éééààà",.
Cause may be something like your_title.encode('latin1').decode('utf8') (not in one step, of course).
| Django utf-8 and django-mailer strangeness | Latest django mailer from trunk http://github.com/jtauber/django-mailer/tree/master/docs/
Tested with Postgresql 8.4, sqlite3
template
{{ title }}
forms.py
#-*- coding: utf-8 -*-
if "mailer" in settings.INSTALLED_APPS:
from mailer import send_mail
else:
from django.core.mail import send_mail
...
body_txt = render_to_string(
'mails/share_deal/email_body.txt',
{
'title':u"éééààà",
}
)
send_mail( "", body_txt , "foo@ff.ff", ["bar@kl.fd"], fail_silently=True)
Error
Environment:
Request Method: POST
Request URL: http://localhost:8000/deals/share/
Django Version: 1.2 SVN-13596
Python Version: 2.6.5
Installed Applications:
['django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.sites',
'django.contrib.messages',
'django.contrib.admin',
'django_extensions',
'django.contrib.markup',
'django.contrib.comments',
'ajaxcomments',
'mailer',
'profiles',
'tagging',
'wmd',
'core',
'deals']
Installed Middleware:
('django.middleware.common.CommonMiddleware',
'django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware')
Traceback:
File "/home/gregory/.virtualenvs/alpha/src/django/django/core/handlers/base.py" in get_response
100. response = callback(request, *callback_args, **callback_kwargs)
File "/home/gregory/projects/casadeal/casadeal/core/decorators.py" in wrap
12. return f(request, *args, **kwargs)
File "/home/gregory/.virtualenvs/alpha/src/django/django/views/decorators/http.py" in inner
37. return func(request, *args, **kwargs)
File "/home/gregory/projects/casadeal/casadeal/deals/views.py" in share_deal
22. form.send_mail()
File "/home/gregory/projects/casadeal/casadeal/deals/forms.py" in send_mail
89. fail_silently=True)
File "/home/gregory/.virtualenvs/casadeal/src/django-mailer/mailer/__init__.py" in send_mail
45. priority=priority).save()
File "/home/gregory/.virtualenvs/alpha/src/django/django/db/models/base.py" in save
435. self.save_base(using=using, force_insert=force_insert, force_update=force_update)
File "/home/gregory/.virtualenvs/alpha/src/django/django/db/models/base.py" in save_base
528. result = manager._insert(values, return_id=update_pk, using=using)
File "/home/gregory/.virtualenvs/alpha/src/django/django/db/models/manager.py" in _insert
195. return insert_query(self.model, values, **kwargs)
File "/home/gregory/.virtualenvs/alpha/src/django/django/db/models/query.py" in insert_query
1479. return query.get_compiler(using=using).execute_sql(return_id)
File "/home/gregory/.virtualenvs/alpha/src/django/django/db/models/sql/compiler.py" in execute_sql
783. cursor = super(SQLInsertCompiler, self).execute_sql(None)
File "/home/gregory/.virtualenvs/alpha/src/django/django/db/models/sql/compiler.py" in execute_sql
727. cursor.execute(sql, params)
File "/home/gregory/.virtualenvs/alpha/src/django/django/db/backends/util.py" in execute
15. return self.cursor.execute(sql, params)
File "/home/gregory/.virtualenvs/alpha/src/django/django/db/backends/postgresql_psycopg2/base.py" in execute
44. return self.cursor.execute(query, args)
Exception Type: DatabaseError at /deals/share/
Exception Value: ERREUR: séquence d'octets invalide pour l'encodage « UTF8 » : 0xe9e9e9
HINT: Cette erreur peut aussi survenir si la séquence d'octets ne correspond pas
au jeu de caractères attendu par le serveur, le jeu étant contrôlé par
« client_encoding ».
Basically it says that the encoding was not valid for UTF8 and contained 0xe9e9e9
This seems quite strange,
Any hints on where it could come from ?
| [
"U+00E9 is LATIN SMALL LETTER E WITH ACUTE.\nThis MAY be the source (not necessarily the cause) of the problem: 'title':u\"éééààà\",.\nCause may be something like your_title.encode('latin1').decode('utf8') (not in one step, of course).\n"
] | [
0
] | [] | [] | [
"django",
"encoding",
"mailer",
"python",
"utf_8"
] | stackoverflow_0003559855_django_encoding_mailer_python_utf_8.txt |
Q:
how remove special characters from the end of every word in a string?
i want it match only the end of every word
example:
"i am test-ing., i am test.ing-, i am_, test_ing,"
output should be:
"i am test-ing i am test.ing i am test_ing"
A:
>>> import re
>>> test = "i am test-ing., i am test.ing-, i am_, test_ing,"
>>> re.sub(r'([^\w\s]|_)+(?=\s|$)', '', test)
'i am test-ing i am test.ing i am test_ing'
Matches one or more non-alphanumeric characters ([^\w\s]|_) followed by either a space (\s) or the end of the string ($). The (?= ) construct is a lookahead assertion: it makes sure that a matching space is not included in the match, so it doesn't get replaced; only the [\W_]+ gets replaced.
Okay, but why [^\w\s]|_, you ask? The first part matches anything that's not alphanumeric or an underscore ([^\w]) or whitespace ([^\s]), i.e. punctuation characters. Except we do want to eliminate underscores, so we then include those with |_.
| how remove special characters from the end of every word in a string? | i want it match only the end of every word
example:
"i am test-ing., i am test.ing-, i am_, test_ing,"
output should be:
"i am test-ing i am test.ing i am test_ing"
| [
">>> import re\n>>> test = \"i am test-ing., i am test.ing-, i am_, test_ing,\"\n>>> re.sub(r'([^\\w\\s]|_)+(?=\\s|$)', '', test)\n'i am test-ing i am test.ing i am test_ing'\n\nMatches one or more non-alphanumeric characters ([^\\w\\s]|_) followed by either a space (\\s) or the end of the string ($). The (?= ) con... | [
6
] | [] | [] | [
"python",
"regex"
] | stackoverflow_0003561999_python_regex.txt |
Q:
Need help with basic function - Python
want to count the number of times a letter appears in a string, having issues here. any help
def countLetters(string, character):
count = 0
for character in string:
if character == character:
count = count + 1
print count
A:
The others have covered the errors of your function. Here's an alternative way of doing what you want. Python's built-in string method count() returns the number of occurrences of a string.
x = "Don't reinvent the wheel."
x.count("e")
Gives:
5
A:
if character == character:
character will always equal character because they're the same variable. Just change the names of those variables. Maybe search_character?
I also wouldn't use string as a variable name since it's the name of a built-in module.
A:
You have the same variable name for those characters (which means they'll always be equal). Try:
def countLetters(string, character):
count = 0
for char in string:
if char == character:
count = count + 1
print count
Of course this is the same as str.count()
| Need help with basic function - Python | want to count the number of times a letter appears in a string, having issues here. any help
def countLetters(string, character):
count = 0
for character in string:
if character == character:
count = count + 1
print count
| [
"The others have covered the errors of your function. Here's an alternative way of doing what you want. Python's built-in string method count() returns the number of occurrences of a string.\nx = \"Don't reinvent the wheel.\"\nx.count(\"e\")\n\nGives:\n5\n\n",
"if character == character:\n\ncharacter will always ... | [
10,
3,
1
] | [] | [] | [
"python"
] | stackoverflow_0003562057_python.txt |
Q:
Pre-configured Python web framework with Authentication, Profiles, etc
I want port some my Python scripts into web apps so that others can use it and I'll use some sort of web framework. I've been playing around with Django lately but it doesn't have the basic user registration, email verification stuff built in and one would probably end up using django-registration.
Almost all web applications require you to create an account, verify your account by clicking that verification link in your account and so on. One would save a lot of time if he could just skip past the part of setting up authentication, verification, the usual log-in and log-out pages and get to part of doing the "core" part.
Has anyone come across a pre-configured Python web-framework (Django would be nice) that does the all usual basic stuff? Django has that contrib.auth bit you can add django-registration
(I hope this question sounds reasonable.)
Thanks.
A:
Take a look at Pinax ( http://pinaxproject.com/ ), which consists of a set of Django apps that take care of some of the most common tasks. Including the user registration one you outlined.
However, this is actually not very difficult to build. You are right, most sides need it, but implementing it even from scratch is pretty easy.
A:
web2py take a look at Access Control Chapter in http://web2py.com/book
| Pre-configured Python web framework with Authentication, Profiles, etc | I want port some my Python scripts into web apps so that others can use it and I'll use some sort of web framework. I've been playing around with Django lately but it doesn't have the basic user registration, email verification stuff built in and one would probably end up using django-registration.
Almost all web applications require you to create an account, verify your account by clicking that verification link in your account and so on. One would save a lot of time if he could just skip past the part of setting up authentication, verification, the usual log-in and log-out pages and get to part of doing the "core" part.
Has anyone come across a pre-configured Python web-framework (Django would be nice) that does the all usual basic stuff? Django has that contrib.auth bit you can add django-registration
(I hope this question sounds reasonable.)
Thanks.
| [
"Take a look at Pinax ( http://pinaxproject.com/ ), which consists of a set of Django apps that take care of some of the most common tasks. Including the user registration one you outlined.\nHowever, this is actually not very difficult to build. You are right, most sides need it, but implementing it even from scrat... | [
2,
0
] | [] | [] | [
"python"
] | stackoverflow_0003557832_python.txt |
Q:
How do I determine the appropriate check interval?
I'm just starting to work on a tornado application that is having some CPU issues. The CPU time will monotonically grow as time goes by, maxing out the CPU at 100%. The system is currently designed to not block the main thread. If it needs to do something that blocks and asynchronous drivers aren't available, it will spawn another thread to do the blocking operation.
Thus we have the main thread being almost totally CPU-bound and a bunch of other threads that are almost totally IO-bound. From what I've read, this seems to be the perfect way to run into problems with the GIL. Plus, my profiling shows that we're spending a lot of time waiting on signals (which I'm assuming is what __semwait_signal is doing), which is consistent with the effects the GIL would have in my limited understanding.
If I use sys.setcheckinterval to set the check interval to 300, the CPU growth slows down significantly. What I'm trying to determine is whether I should increase the check interval, leave it at 300, or be scared with upping it. After all, I notice that CPU performance gets better, but I'm a bit concerned that this will negatively impact the system's responsiveness.
Of course, the correct answer is probably that we need to rethink our architecture to take the GIL into account. But that isn't something that can be done immediately. So how do I determine the appropriate course of action to take in the short-term?
A:
The first thing I would check for would be to ensure that you're properly exiting threads. It's very hard to figure out what's going on with just your description to go from, but you use the word "monotonically," which implies that CPU use is tied to time rather than to load.
You may very well be running into threading limits of Python, but it should vary up and down with load (number of active threads,) and CPU usage (context switching costs) should reduce as those threads exit. Is there some reason for a thread, once created, to live forever? If that's the case, prioritize that rearchitecture. Otherwise, short term would be to figure out why CPU usage is tied to time and not load. It implies that each new thread has a permanent, irreversible cost in your system - meaning it never exits.
| How do I determine the appropriate check interval? | I'm just starting to work on a tornado application that is having some CPU issues. The CPU time will monotonically grow as time goes by, maxing out the CPU at 100%. The system is currently designed to not block the main thread. If it needs to do something that blocks and asynchronous drivers aren't available, it will spawn another thread to do the blocking operation.
Thus we have the main thread being almost totally CPU-bound and a bunch of other threads that are almost totally IO-bound. From what I've read, this seems to be the perfect way to run into problems with the GIL. Plus, my profiling shows that we're spending a lot of time waiting on signals (which I'm assuming is what __semwait_signal is doing), which is consistent with the effects the GIL would have in my limited understanding.
If I use sys.setcheckinterval to set the check interval to 300, the CPU growth slows down significantly. What I'm trying to determine is whether I should increase the check interval, leave it at 300, or be scared with upping it. After all, I notice that CPU performance gets better, but I'm a bit concerned that this will negatively impact the system's responsiveness.
Of course, the correct answer is probably that we need to rethink our architecture to take the GIL into account. But that isn't something that can be done immediately. So how do I determine the appropriate course of action to take in the short-term?
| [
"The first thing I would check for would be to ensure that you're properly exiting threads. It's very hard to figure out what's going on with just your description to go from, but you use the word \"monotonically,\" which implies that CPU use is tied to time rather than to load.\nYou may very well be running into t... | [
1
] | [] | [] | [
"gil",
"multithreading",
"python",
"tornado"
] | stackoverflow_0003559457_gil_multithreading_python_tornado.txt |
Q:
Should I make a copy of the instance of a class to achieve this? If yes, how do I do it?
Sorry if the title is not very clear. I was not sure about the appropriate title. Let me explain what I need.
I am doing multiple runs of a simulation, where each run corresponds to a different seed. However, I want the starting characteristics of the instances of a class to remain the same across the different runs. For example, consider the class of people in a city. In the code below the command city = people() creates person objects each of whom has some wealth chosen randomly from a distribution. Let F(.) be the realized initial distribution of wealth in the population. As one particular run of a simulation is made, things change in the population and various attributes of the person objects get updated. For example, a person's income changes. The final values of these attributes depend on some random realizations that occur during the simulation run. Now I want to again run the simulation with a different random seed, where before the run begins all attributes are reset to their initial values (including the wealth distribution that was randomly determined). Should I make a shallowCopy or a deepCopy? Is there a third way that is better?
Thanks a ton.
city = people()
for seedValue in ListOfSeeds:
cityThisInstance = city.copy()
cityThisInstance.someAttribute = xxxxx
cityThisInstance.anotherAttribute = yyyyy
Rest of the code
A:
From what I understand, you always want your initial conditions (e.g. the state of city before you even get to your loop) to be the same. If that's the case, I would prefer to just reinitialize the class whenever you run through the loop, as it's much clearer.
initargs = 21, 50000
initkwargs = {car: 'blue', make: 'mazda'}
for loop:
cityThisInstance = people(*initargs, **initkwargs)
If whenever you initialize the class some significant amount of code runs, it may be better to simply copy it's state. Deepcopy would be preferred, so that way all the variables it uses will be copied, especially mutables, rather than point to where the originals are.
import copy
for loop:
cityThisInstance = copy.deepcopy(city)
| Should I make a copy of the instance of a class to achieve this? If yes, how do I do it? | Sorry if the title is not very clear. I was not sure about the appropriate title. Let me explain what I need.
I am doing multiple runs of a simulation, where each run corresponds to a different seed. However, I want the starting characteristics of the instances of a class to remain the same across the different runs. For example, consider the class of people in a city. In the code below the command city = people() creates person objects each of whom has some wealth chosen randomly from a distribution. Let F(.) be the realized initial distribution of wealth in the population. As one particular run of a simulation is made, things change in the population and various attributes of the person objects get updated. For example, a person's income changes. The final values of these attributes depend on some random realizations that occur during the simulation run. Now I want to again run the simulation with a different random seed, where before the run begins all attributes are reset to their initial values (including the wealth distribution that was randomly determined). Should I make a shallowCopy or a deepCopy? Is there a third way that is better?
Thanks a ton.
city = people()
for seedValue in ListOfSeeds:
cityThisInstance = city.copy()
cityThisInstance.someAttribute = xxxxx
cityThisInstance.anotherAttribute = yyyyy
Rest of the code
| [
"From what I understand, you always want your initial conditions (e.g. the state of city before you even get to your loop) to be the same. If that's the case, I would prefer to just reinitialize the class whenever you run through the loop, as it's much clearer.\ninitargs = 21, 50000\ninitkwargs = {car: 'blue', mak... | [
2
] | [] | [] | [
"class",
"copy",
"python"
] | stackoverflow_0003562034_class_copy_python.txt |
Q:
Python, string (consisting of variable and strings, concatenated) used as new variable name?
I've been searching on this but am coming up a little short on exactly how to do specifically what i am trying to do.. I want to concatentate a string (I guess it would be a string in this case as it has a variable and string) such as below, where I need to use a variable consisting of a string to call a listname that has an index (from another variable).. I simplified my code below to just show the relevant parts its part of a macro that is replacing values:
toreplacetype = 'type'
toreplace_indx = 5
replacement_string = 'list'+toreplacetype[toreplace_indx]
so... I am trying to make the string on the last line equal to the actual variable name:
replacement_string = listtype[5]
Any advice on how to do this is appreciated
EDIT:
To explain further, this is for a macro that is sort of a template system where I am indicating things in a python script that I want to replace with specific values so I am using regex to do this. So, when I match something, I want to be able to replace it from a specific value within a list, but, for example, in the template I have {{type}}, so I extract this, but then I need to manipulate it as above so that I can use the extracted value "type" to call a specific value from within a list (such as from a list called "listtype") (there is more than 1 list so I need to find the one called "listtype" so I just want to concatenate as above to get this, based on the value I extracted using regex
A:
This is not recommended. Use a dict instead.
vars['list%s' % toreplacetype][5] = ...
A:
Hrm...
globals()['list%s'% toreplacetype][toreplace_indx]
A:
replacement_string = 'list'+toreplacetype+'['+str(toreplace_indx)+']'
will yield listtype[5] when you print it.
You need to basically break it into 5 parts: 1 string variable, 3 strings and an int casted to a string.
I think this is what you are asking?
| Python, string (consisting of variable and strings, concatenated) used as new variable name? | I've been searching on this but am coming up a little short on exactly how to do specifically what i am trying to do.. I want to concatentate a string (I guess it would be a string in this case as it has a variable and string) such as below, where I need to use a variable consisting of a string to call a listname that has an index (from another variable).. I simplified my code below to just show the relevant parts its part of a macro that is replacing values:
toreplacetype = 'type'
toreplace_indx = 5
replacement_string = 'list'+toreplacetype[toreplace_indx]
so... I am trying to make the string on the last line equal to the actual variable name:
replacement_string = listtype[5]
Any advice on how to do this is appreciated
EDIT:
To explain further, this is for a macro that is sort of a template system where I am indicating things in a python script that I want to replace with specific values so I am using regex to do this. So, when I match something, I want to be able to replace it from a specific value within a list, but, for example, in the template I have {{type}}, so I extract this, but then I need to manipulate it as above so that I can use the extracted value "type" to call a specific value from within a list (such as from a list called "listtype") (there is more than 1 list so I need to find the one called "listtype" so I just want to concatenate as above to get this, based on the value I extracted using regex
| [
"This is not recommended. Use a dict instead.\nvars['list%s' % toreplacetype][5] = ...\n\n",
"Hrm...\nglobals()['list%s'% toreplacetype][toreplace_indx]\n\n",
"replacement_string = 'list'+toreplacetype+'['+str(toreplace_indx)+']'\n\nwill yield listtype[5] when you print it.\nYou need to basically break it into ... | [
1,
1,
0
] | [] | [] | [
"concatenation",
"python",
"variables"
] | stackoverflow_0003562386_concatenation_python_variables.txt |
Q:
Basic Financial Library for Python
I am looking for a financial library for Python that will enable me to do a discounted cash flow analysis. I have looked around and found the QuantLib, which is overkill for what I want to do. I just need a small library that I can use to input a series of cash flows and have it output a net present value and internal rate of return. Anyone have something like this or know where I can find it?
A:
Just for completeness, since I'm late:
numpy has some functions for (very) basic financial calculations. numpy, scipy could also be used, to do the calculations from the basic formulas as in R.
net present value of cashflow
>>> cashflow = 2*np.ones(6)
>>> cashflow[-1] +=100
>>> cashflow
array([ 2., 2., 2., 2., 2., 102.])
>>> np.npv(0.01, cashflow)
105.79547647457932
get internal rate or return
>>> n = np.npv(0.01, cashflow)
>>> np.irr(np.r_[-n, cashflow])
0.010000000000000231
just the basics:
>>> [f for f in dir(np.lib.financial) if not f[0] == '_']
['fv', 'ipmt', 'irr', 'mirr', 'np', 'nper', 'npv', 'pmt', 'ppmt', 'pv', 'rate']
and it's necessary to watch out what the timing is.
A:
If you really only want to compute net present value (== an inner product of vectors for cashflows and discount factors) and internal rate of return (== a simple iterative root search for one variable) then you can just code it up.
I use R much more than Python so here is an R solution:
R> data <- data.frame(CF=c(rep(2,5), 102), df=1.01^(-(1:6)))
R> data
CF df
1 2 0.9901
2 2 0.9803
3 2 0.9706
4 2 0.9610
5 2 0.9515
6 102 0.9420
R> NPV <- sum(data[,1] * data[,2])
R> print(NPV)
[1] 105.8
R>
This sets up two-column data structure of cash flows and discount factors and computes NPV as the sum of the products. So a (simplistic) six-year bond with a 2% coupon in 1% flat yield curve would be worth 105.80.
For IRR, we do just about the same but make the NPV a function of the rate:
R> irrSearch <- function(rate) { data <- data.frame(CF=c(rep(2,5), 102),
df=(1+rate/100)^(-(1:6)));
100 - sum(data[,1] * data[,2]) }
R> uniroot( irrSearch, c(0.01,5) )
R> irr <- uniroot( irrSearch, c(0.01,5) )
R> irr$root
[1] 2
R>
So the 'root' to the search for the internal rate of return of 2% bond in a flat-curve world is ... unsurprisingly 2%.
| Basic Financial Library for Python | I am looking for a financial library for Python that will enable me to do a discounted cash flow analysis. I have looked around and found the QuantLib, which is overkill for what I want to do. I just need a small library that I can use to input a series of cash flows and have it output a net present value and internal rate of return. Anyone have something like this or know where I can find it?
| [
"Just for completeness, since I'm late: \nnumpy has some functions for (very) basic financial calculations. numpy, scipy could also be used, to do the calculations from the basic formulas as in R.\nnet present value of cashflow\n>>> cashflow = 2*np.ones(6)\n>>> cashflow[-1] +=100\n>>> cashflow\narray([ 2., 2.,... | [
12,
3
] | [] | [] | [
"finance",
"python"
] | stackoverflow_0002259379_finance_python.txt |
Q:
Monitor Multiple Pylons Application
Are there any tools that I can run on my server to monitor multiple Pylons applications?
I need to monitor the number of requests each application receives, how much memory each application is using, how much of the cpu is being used and other stats similar to those. I need to see the stats for each individual Pylons application.
All information needs to be stored in a database for me to retrieve later (preferably SQLite, PostgreSQL, or MySQL).
Thanks
*UPDATE*
It is a Unix server and it is running Ubuntu. It's using Nginx.
Each application must store its data in its own database for just the application.
A:
You probably want to use something like Zenoss.
There is some specific nginx integration graphs here: http://community.zenoss.org/docs/DOC-7441
A:
If your server is unix-like, you have a lot of tools that helps with processes monitoring such as ps, top, lsof etc.
To monitor the requests to the server, depending on the server you are using, look for webserver logs analyzers (ex. apachetop). I also recommend the performance testing (ApacheBench).
Here's some links:
Top:
http://www.linuxforums.org/articles/using-top-more-efficiently_89.html
Netstat:
http://www.simplehelp.net/2009/01/19/monitor-your-linux-machine-with-netstat/
Apachetop:
http://www.howtogeek.com/howto/ubuntu/monitor-your-website-in-real-time-with-apachetop/
ApacheBench:
http://www.cyberciti.biz/tips/howto-performance-benchmarks-a-web-server.html
| Monitor Multiple Pylons Application | Are there any tools that I can run on my server to monitor multiple Pylons applications?
I need to monitor the number of requests each application receives, how much memory each application is using, how much of the cpu is being used and other stats similar to those. I need to see the stats for each individual Pylons application.
All information needs to be stored in a database for me to retrieve later (preferably SQLite, PostgreSQL, or MySQL).
Thanks
*UPDATE*
It is a Unix server and it is running Ubuntu. It's using Nginx.
Each application must store its data in its own database for just the application.
| [
"You probably want to use something like Zenoss.\nThere is some specific nginx integration graphs here: http://community.zenoss.org/docs/DOC-7441\n",
"If your server is unix-like, you have a lot of tools that helps with processes monitoring such as ps, top, lsof etc.\nTo monitor the requests to the server, depend... | [
2,
1
] | [] | [] | [
"monitoring",
"nginx",
"pylons",
"python"
] | stackoverflow_0003518149_monitoring_nginx_pylons_python.txt |
Q:
Is it possible in numpy to use advanced list slicing and still get a view?
In other words, I want to do something like
A[[-1, 0, 1], [2, 3, 4]] += np.ones((3, 3))
instead of
A[-1:3, 2:5] += np.ones((1, 3))
A[0:2, 2:5] += np.ones((2, 3))
A:
If I understand correctly, you can do what you want to do with the following:
A[[[-1],[0],[1]],[2,3,4]] += np.ones((3, 3))
However, the numpy folks made a function, ix_, to make it a little bit easier:
A[np.ix_([-1,0,1],[2,3,4])] += np.ones((3, 3))
I hope that helps.
| Is it possible in numpy to use advanced list slicing and still get a view? | In other words, I want to do something like
A[[-1, 0, 1], [2, 3, 4]] += np.ones((3, 3))
instead of
A[-1:3, 2:5] += np.ones((1, 3))
A[0:2, 2:5] += np.ones((2, 3))
| [
"If I understand correctly, you can do what you want to do with the following:\nA[[[-1],[0],[1]],[2,3,4]] += np.ones((3, 3))\n\nHowever, the numpy folks made a function, ix_, to make it a little bit easier:\nA[np.ix_([-1,0,1],[2,3,4])] += np.ones((3, 3))\n\nI hope that helps. \n"
] | [
3
] | [] | [] | [
"numpy",
"python"
] | stackoverflow_0003562387_numpy_python.txt |
Q:
How to access Gmail's "Send" button using Selenium RC for Java or C# or Python
I have tried this probably 6 or 7 different ways, such as using various attribute values, XPath, id pattern matching (it always matches ":\w\w"), etc. as locators, and nothing has worked. If anyone can give me a tested, confirmed-working locator string for this button, I'd be much obliged.
A:
If you want to emulate a click on the button, just go to #compose.
A:
If you're using Python, use the mechanize library and access Gmail's HTML version. The Send button is simply a form submit button.
import re
import mechanize
br = mechanize.Browser()
br.open("http://htmlversionofgmail.com/composewindow")
br.select_form(nr=0) # select the first form
# Do some stuff, fill out the subject, whatever.
response = br.submit()
| How to access Gmail's "Send" button using Selenium RC for Java or C# or Python | I have tried this probably 6 or 7 different ways, such as using various attribute values, XPath, id pattern matching (it always matches ":\w\w"), etc. as locators, and nothing has worked. If anyone can give me a tested, confirmed-working locator string for this button, I'd be much obliged.
| [
"If you want to emulate a click on the button, just go to #compose.\n",
"If you're using Python, use the mechanize library and access Gmail's HTML version. The Send button is simply a form submit button.\nimport re\nimport mechanize\n\nbr = mechanize.Browser()\nbr.open(\"http://htmlversionofgmail.com/composewind... | [
0,
0
] | [] | [] | [
"c#",
"gmail",
"java",
"python",
"selenium_rc"
] | stackoverflow_0003561993_c#_gmail_java_python_selenium_rc.txt |
Q:
How to check if DataStore Indexes are being served on AppEngine?
How can I check if datastore Indexes as defined in index.yaml are serving in the python code?
I am using Python 1.3.6 AppEngine SDK.
A:
Attempt to perform a query that requires that index. If it raises a NeedIndexError, it's not uploaded or not yet serving.
A:
I don't think there's a way to check without adding some logging to the SDK code. If you're using the SQLite stub, __FindIndexForQuery, lines 1114-1140, is the part that looks for applicable indices to a query, and (at line 1140), returns, and I quote:
An entity_pb.CompositeIndex PB, if a
suitable index exists; otherwise None
A little logging at that point (and when it's about to fall off the end having exhausted the loop -- that's how it returns None) will give you a trace of all your indices that are actually used, as part of the logs of course. The protocol buffer it returns is an instance of the class defined in this file, starting at line 2576.
If you can explain why you want to know this, it would, I think, be quite reasonable to open a feature request on the App Engine tracker, asking Google to add the logging that I'm suggesting, so you don't have to keep maintaining your edited version of the file!
(If you use the file stub, the relevant file is here, and the part to instrument is around line 824 and following; of course, this part will be used only if you're running the SDK in "require indices" mode, AKA "strict mode", otherwise, indices are created in, not used by, the SDK;-)
| How to check if DataStore Indexes are being served on AppEngine? | How can I check if datastore Indexes as defined in index.yaml are serving in the python code?
I am using Python 1.3.6 AppEngine SDK.
| [
"Attempt to perform a query that requires that index. If it raises a NeedIndexError, it's not uploaded or not yet serving.\n",
"I don't think there's a way to check without adding some logging to the SDK code. If you're using the SQLite stub, __FindIndexForQuery, lines 1114-1140, is the part that looks for appli... | [
2,
0
] | [] | [] | [
"google_app_engine",
"python"
] | stackoverflow_0003562466_google_app_engine_python.txt |
Q:
Polymorphism or Inheritance or any other suggestion?
I trying my hands on python. I am trying to implement a crypto class which does enc/dec . In my crypto class i require user to pass 3 args to do the enc dec operations. Till now i was reading key from file and doing the operations. Now i want to provide a generate key function also. But problem is that to call generate keys i dont want user to provide any arguments while initiating the class.
So what essentially i am trying to achieve is that when the crypto class is instantiated without giving any arguments, i just want to expose generate_key function. and when all the 3 args are provided while instantiating class, I want to expose all other enc/dec functions but not key gen function.
I am not able to understand is it a polymorphism situation, or inheritance or should i just use 2 different classes one having generate keys and other for enc dec functions..
Please give me some suggestion about how can i handle this situation efficiently?
Example:
class crypto:
def __init__(self,id, val1):
self._id = id
self._val1 = val1
def encrypt(self):
""" encryption here """
def save(self):
""" save to file """
def load(self):
""" load from file"""
def decrypt(self):
""" decryption here"""
def gen_keys(self):
""" gen key here"""
So Now, when this crypto class is instantiate with no arguments, i just want to expose gen keys function. and if it is instantiated with the id and val1, then i want to expose all functions but not gen keys.
I hope this will provide some clarification about my question. Please suggest me how can i achieve this.
Thanks,
Jon
A:
You want a factory with either inherited or duck-typed objects. For example:
class CryptoBasic(object):
def __init__(self, *args):
"""Do what you need to do."""
def basic_method(self, *args):
"""Do some basic method."""
class CryptoExtended(CryptoBasic):
def __init__(self, *args):
"""Do what you need to do."""
def extended_method(self, *args):
"""Do more."""
# This is the factory method
def create_crypto(req_arg, opt_arg=None):
if opt_arg:
return CryptoExtended(req_arg, opt_arg)
else:
return CryptoBasic(req_arg)
| Polymorphism or Inheritance or any other suggestion? | I trying my hands on python. I am trying to implement a crypto class which does enc/dec . In my crypto class i require user to pass 3 args to do the enc dec operations. Till now i was reading key from file and doing the operations. Now i want to provide a generate key function also. But problem is that to call generate keys i dont want user to provide any arguments while initiating the class.
So what essentially i am trying to achieve is that when the crypto class is instantiated without giving any arguments, i just want to expose generate_key function. and when all the 3 args are provided while instantiating class, I want to expose all other enc/dec functions but not key gen function.
I am not able to understand is it a polymorphism situation, or inheritance or should i just use 2 different classes one having generate keys and other for enc dec functions..
Please give me some suggestion about how can i handle this situation efficiently?
Example:
class crypto:
def __init__(self,id, val1):
self._id = id
self._val1 = val1
def encrypt(self):
""" encryption here """
def save(self):
""" save to file """
def load(self):
""" load from file"""
def decrypt(self):
""" decryption here"""
def gen_keys(self):
""" gen key here"""
So Now, when this crypto class is instantiate with no arguments, i just want to expose gen keys function. and if it is instantiated with the id and val1, then i want to expose all functions but not gen keys.
I hope this will provide some clarification about my question. Please suggest me how can i achieve this.
Thanks,
Jon
| [
"You want a factory with either inherited or duck-typed objects. For example:\nclass CryptoBasic(object):\n\n def __init__(self, *args):\n \"\"\"Do what you need to do.\"\"\"\n\n def basic_method(self, *args):\n \"\"\"Do some basic method.\"\"\"\n\nclass CryptoExtended(CryptoBasic):\n\n def _... | [
1
] | [] | [] | [
"oop",
"python"
] | stackoverflow_0003562972_oop_python.txt |
Q:
How to decode the pixels in a JPG in App Engine (using pure python)?
Using python App Engine I need to convert a JPG image that is one 9 MB file (of Pakistan's floods) into many PNG tiles.
For the PNG part, I already know how to use PyPNG, which is great. Note: PIL cant be used with App Engine.
So how do I decode the JPG into pixel data?
A:
Using Image class and crop and execute_transforms to encode as png?
Note: You should provide relevant part of your code
A:
You can use the efforts here to get a pure python JPEG Parser. Why the absolute need to use App Engine ? If you want more flexible library usage try EC2.
| How to decode the pixels in a JPG in App Engine (using pure python)? | Using python App Engine I need to convert a JPG image that is one 9 MB file (of Pakistan's floods) into many PNG tiles.
For the PNG part, I already know how to use PyPNG, which is great. Note: PIL cant be used with App Engine.
So how do I decode the JPG into pixel data?
| [
"Using Image class and crop and execute_transforms to encode as png? \nNote: You should provide relevant part of your code\n",
"You can use the efforts here to get a pure python JPEG Parser. Why the absolute need to use App Engine ? If you want more flexible library usage try EC2.\n"
] | [
2,
1
] | [] | [] | [
"google_app_engine",
"jpeg",
"python"
] | stackoverflow_0003562958_google_app_engine_jpeg_python.txt |
Q:
Can search(r'(ab)+', "ababababab") match all the characters in python
I found that findall(r'(ab)+', "ababababab") can only match the ["ab"]
>>> re.findall(r'(ab)+', "ababababab")
['ab']
i just know that using r'(?:ab)+' can match all the characters
>>> re.findall(r'(?:ab)+', "ababababab")
['ababababab']
Why does this happen?
Sorry,i may not speak my question clearly
(?:ab) takes 'ab' as a whole ,let's make c=ab,so c+=ababab....
so this is clearly
>>> re.findall(r'(?:ab)+', "ababababab") <br>
['ababababab']
my question is that why does this happen:
>>> match=re.search(r'(ab)+', "ababababab") <br>
>>> match.group()<br>
'ababababab'
A:
I think the question you are asking here is why does it return this:
>>> re.findall(r'(ab)+', "ababababab")
['ab']
The answer is that if you have one or more groups in the pattern then findall will return a list with all the matched groups. However your regex has one group that is matched multiple times within the regex, so it takes the last value of the match.
I think what you want is either this:
>>> re.findall(r'(ab)', "ababababab")
['ab', 'ab', 'ab', 'ab', 'ab']
or the version you posted:
>>> re.findall(r'(?:ab)+', "ababababab")
['ababababab']
A:
If the pattern contains a group, findall returns the group rather than the entire match. Here (ab)+ matches the entire string, but only the group (ab) is returned.
| Can search(r'(ab)+', "ababababab") match all the characters in python | I found that findall(r'(ab)+', "ababababab") can only match the ["ab"]
>>> re.findall(r'(ab)+', "ababababab")
['ab']
i just know that using r'(?:ab)+' can match all the characters
>>> re.findall(r'(?:ab)+', "ababababab")
['ababababab']
Why does this happen?
Sorry,i may not speak my question clearly
(?:ab) takes 'ab' as a whole ,let's make c=ab,so c+=ababab....
so this is clearly
>>> re.findall(r'(?:ab)+', "ababababab") <br>
['ababababab']
my question is that why does this happen:
>>> match=re.search(r'(ab)+', "ababababab") <br>
>>> match.group()<br>
'ababababab'
| [
"I think the question you are asking here is why does it return this:\n>>> re.findall(r'(ab)+', \"ababababab\")\n['ab']\n\nThe answer is that if you have one or more groups in the pattern then findall will return a list with all the matched groups. However your regex has one group that is matched multiple times wi... | [
6,
1
] | [] | [] | [
"python",
"regex"
] | stackoverflow_0003563318_python_regex.txt |
Q:
Django: output aggregation of aggregation ordered by counts
I'm trying to output the following data in my django templates.
Countries would be ordered descending by # of stories.
Cities would be ordered descending by # of stories (under that country)
Country A(# of stories)
City A (# of stories)
City B (# of stories)
Country B(# of stories)
City A (# of stories)
City B (# of stories)
My models are the following:
# Create your models here.
class Country(models.Model):
name = models.CharField(max_length=50)
class City(models.Model):
name = models.CharField(max_length=50)
country = models.ForeignKey(Country)
class Story(models.Model):
city = models.ForeignKey(City)
country = models.ForeignKey(Country)
name = models.CharField(max_length=255)
What's the easiest way to do this?
A:
This solution worked for me. You will need to tweak it to pass it to a template though.
from django.db.models import Count
all_countries = Country.objects.annotate(Count('story')).order_by('-story__count')
for country in all_countries:
print "Country %s (%s)" % (country.name, country.story__count)
all_cities = City.objects.filter(country = country).annotate(Count('story')).order_by('-story__count')
for city in all_cities:
print "\tCity %s (%s)" % (city.name, city.story__count)
Update
Here is one way of sending this information to the template. This one involves the use of a custom filter.
@register.filter
def get_cities_and_counts(country):
all_cities = City.objects.filter(country = country).annotate(Count('story')).order_by('-story__count')
return all_cities
View:
def story_counts(request, *args, **kwargs):
all_countries = Country.objects.annotate(Count('story')).order_by('-story__count')
context = dict(all_countries = all_countries)
return render_to_response(..., context)
And in your template:
{% for country in all_countries %}
<h3>{{ country.name }} ({{ country.story__count }})</h3>
{% for city in country|get_cities_and_counts %}
<p>{{ city.name }} ({{ city.story__count }})</p>
{% endfor %}
{% endfor %}
Update 2
Variant with a custom method in model.
class Country(models.Model):
name = models.CharField(max_length=50)
def _get_cities_and_story_counts(self):
retrun City.objects.filter(country = self).annotate(Count('story')).order_by('-story__count')
city_story_counts = property(_get_cities_and_story_counts)
This lets you avoid defining a filter. The template code changes to:
{% for country in all_countries %}
<h3>{{ country.name }} ({{ country.story__count }})</h3>
{% for city in country.city_story_counts %}
<p>{{ city.name }} ({{ city.story__count }})</p>
{% endfor %}
{% endfor %}
| Django: output aggregation of aggregation ordered by counts | I'm trying to output the following data in my django templates.
Countries would be ordered descending by # of stories.
Cities would be ordered descending by # of stories (under that country)
Country A(# of stories)
City A (# of stories)
City B (# of stories)
Country B(# of stories)
City A (# of stories)
City B (# of stories)
My models are the following:
# Create your models here.
class Country(models.Model):
name = models.CharField(max_length=50)
class City(models.Model):
name = models.CharField(max_length=50)
country = models.ForeignKey(Country)
class Story(models.Model):
city = models.ForeignKey(City)
country = models.ForeignKey(Country)
name = models.CharField(max_length=255)
What's the easiest way to do this?
| [
"This solution worked for me. You will need to tweak it to pass it to a template though.\nfrom django.db.models import Count\nall_countries = Country.objects.annotate(Count('story')).order_by('-story__count')\n\nfor country in all_countries:\n print \"Country %s (%s)\" % (country.name, country.story__count)\n ... | [
0
] | [] | [] | [
"aggregate",
"django",
"python"
] | stackoverflow_0003562036_aggregate_django_python.txt |
Q:
How do I set a Jabber status with python-xmpp?
How do I set a GChat or jabber status via python? Right now I've got this:
import xmpp
new_status = "blah blah blah"
login = 'email'
pwd = 'password'
cnx = xmpp.Client('gmail.com')
cnx.connect( server=('talk.google.com',5223) )
cnx.auth(login, pwd, 'botty')
pres = xmpp.Presence()
pres.setStatus(new_status)
cnx.send(pres)
It executes, but the status is not updated. I know I'm connecting to the server successfully, as I can send chat messages to others. What am I doing wrong here?
A:
You might want to take a look at this file:
http://steliosm.net/projects/picaxejabber/picaxe_xmpp.py
Edit:
My bad, first answer was out of context, I've misread your code.
cnx.sendInitPresence()
You haven't send your initial state I guess ...
A:
NOTE: wanted to mention this to those who want to do what's mentioned in this thread. If one is not familiar with XMPP protocol and stanzas, one might miss some needed info to set proper status. The xmpppy module docs don't seem to explicitly clarify the steps to set presence.
Setting initial presence is easiest, as shown in previous posts in this thread. It sets a default presence (type) of user being available. Not sure what the default "status" and "show" states are, assume blank or "available" also.
However, when setting new status by defining a new presence object to send status, if you initialize the object with defaults (no arguments) as in the original post here, the presence object (or stanza) to be sent is incomplete because it doesn't define a proper presence "type". So depending on the XMPP server you are working with it may or may not take the setting correctly.
The proper way to initialize new presence status object would be like this:
offPres = xmpp.Presence(typ='unavailable',show='unavailable',status='unavailable')
or simply just the following, if toggling between "available/online" and "unavailable/offline" w/o logging on and off XMPP IM session, where we don't care what is shown for status/show state (i.e. the label you see associated with status, like "Offline - away" vs just "offline").
offPres = xmpp.Presence(typ='unavailable')
For custom status like DND, Away, Out to Lunch, etc., that gets a little trickier. I'm not really familiar with XMPP myself but assume you would specify the status and show state value as such (e.g. DND, Away) while setting presence type as "available" or "unavailable" depending on whether you want to appear that way or not.
And based on the xmpppy docs, you can only specify presence type at initialization of the object, can't change it afterwards. But you can change the status and show states for the presence object after initialization. That is done as shown in original post here. For show state, there is a matching setShow method just like setStatus.
Sending the presence is same as in original post.
| How do I set a Jabber status with python-xmpp? | How do I set a GChat or jabber status via python? Right now I've got this:
import xmpp
new_status = "blah blah blah"
login = 'email'
pwd = 'password'
cnx = xmpp.Client('gmail.com')
cnx.connect( server=('talk.google.com',5223) )
cnx.auth(login, pwd, 'botty')
pres = xmpp.Presence()
pres.setStatus(new_status)
cnx.send(pres)
It executes, but the status is not updated. I know I'm connecting to the server successfully, as I can send chat messages to others. What am I doing wrong here?
| [
"You might want to take a look at this file:\nhttp://steliosm.net/projects/picaxejabber/picaxe_xmpp.py\nEdit:\nMy bad, first answer was out of context, I've misread your code.\ncnx.sendInitPresence()\n\nYou haven't send your initial state I guess ...\n",
"NOTE: wanted to mention this to those who want to do what'... | [
1,
1
] | [] | [] | [
"chat",
"python",
"status",
"xmpp"
] | stackoverflow_0002473487_chat_python_status_xmpp.txt |
Q:
Google map plotting
I was wondering if anyone has any ideas/tutorials on how to plot various points on a google map, and save the points in a database with custom marker titles.
I want something similar to http://www.mapmyrun.com/create_new , where i can actually draw on a map and mark out paths and such.
A:
Plotting the points is done in Javascript, I managed to learn everything I needed from the maps API docs:
http://code.google.com/apis/maps/documentation/javascript/basics.html
I scraped the code below off a site I made which moves a single point to where the mouse is clicked. You should be able to store a set of points in a JS array, or better, get them from the map when submitting your form then update a hidden form field with the values which can be inserted in your database with a php/python script on the server.
<html>
<head>
<script type="text/javascript" src="http://maps.google.com/maps/api/js?sensor=false"></script>
</head>
<body onload="initialize()">
<div id="map_canvas" style="width:400px; height:600px; display:block; float:left">
</div>
</body>
</html>
<script type="text/javascript">
var map;
var marker = null;
function initialize() {
var myLatlng = new google.maps.LatLng(54, -2.0);
var myOptions = {
zoom: 6,
center: myLatlng,
mapTypeId: google.maps.MapTypeId.ROADMAP
}
map = new google.maps.Map(document.getElementById("map_canvas"), myOptions);
google.maps.event.addListener(map, 'click', function(event) {
placeMarker(event.latLng);
});
}
function placeMarker(location) {
var clickedLocation = new google.maps.LatLng(location);
if(marker == null){
marker = new google.maps.Marker({
position: location,
map: map
});
}else{
marker.setPosition(location);
}
map.setCenter(location);
}
</script>
Edit:
Here is a demo from docs site, which creates a list of points and draws a lines between them:
http://code.google.com/apis/maps/documentation/javascript/examples/polyline-simple.html
There are other examples there too. Just load them and press ctrl+u in firefox to view the source.
| Google map plotting | I was wondering if anyone has any ideas/tutorials on how to plot various points on a google map, and save the points in a database with custom marker titles.
I want something similar to http://www.mapmyrun.com/create_new , where i can actually draw on a map and mark out paths and such.
| [
"Plotting the points is done in Javascript, I managed to learn everything I needed from the maps API docs:\nhttp://code.google.com/apis/maps/documentation/javascript/basics.html\nI scraped the code below off a site I made which moves a single point to where the mouse is clicked. You should be able to store a set of... | [
1
] | [] | [] | [
"google_maps",
"path",
"php",
"python"
] | stackoverflow_0003563885_google_maps_path_php_python.txt |
Q:
__del__ at program end
Suppose there is a program with a couple of objects living in it at runtime.
Is the __del__ method of each object called when the programs ends?
If yes I could for example do something like this:
class Client:
__del__( self ):
disconnect_from_server()
A:
There are many potential difficulties associated with using __del__.
Usually, it is not necessary, or the best idea to define it yourself.
Instead, if you want an object that cleans up after itself upon exit or an exception, use a context manager:
per Carl's comment:
class Client:
def __exit__(self,ext_type,exc_value,traceback):
self.disconnect_from_server()
with Client() as c:
...
original answer:
import contextlib
class Client:
...
@contextlib.contextmanager
def make_client():
c=Client()
yield c
c.disconnect_from_server()
with make_client() as c:
...
A:
I second the general idea of using context managers and the with statement instead of relying on __del__ (for much the same reasons one prefers try/finally to finalizer methods in Java, plus one: in Python, the presence of __del__ methods can make cyclic garbage uncollectable).
However, given that the goal is to have "an object that cleans up after itself upon exit or an exception", the implementation by @~unutbu is not correct:
@contextlib.contextmanager
def make_client():
c=Client()
yield c
c.disconnect_from_server()
with make_client() as c:
...
If an exception is raised in the ... part, disconnect_from_server_ does not get called (since the exception propagates through make_client, being uncaught there, and therefore terminates it while it's waiting at the yield).
The fix is simple:
@contextlib.contextmanager
def make_client():
c=Client()
try: yield c
finally: c.disconnect_from_server()
Essentially, the with statement lets you almost forget about the good old try/finally statement... except when you're writing context managers with contextlib, and then it's really important to remember it!-)
A:
Consider using with-statement to make cleanup explicit.
With circular references __del__ is not called:
class Foo:
def __del__(self):
self.p = None
print "deleting foo"
a = Foo()
b = Foo()
a.p = b
b.p = a
prints nothing.
A:
Yes, the Python interpreter tidies up at shutdown, including calling the __del__ method of every object (except objects that are part of a reference cycle).
Although, as others have pointed out, __del__ methods are very fragile and should be used with caution.
| __del__ at program end | Suppose there is a program with a couple of objects living in it at runtime.
Is the __del__ method of each object called when the programs ends?
If yes I could for example do something like this:
class Client:
__del__( self ):
disconnect_from_server()
| [
"There are many potential difficulties associated with using __del__.\nUsually, it is not necessary, or the best idea to define it yourself.\nInstead, if you want an object that cleans up after itself upon exit or an exception, use a context manager:\nper Carl's comment:\nclass Client:\n def __exit__(self,ext_ty... | [
7,
5,
2,
1
] | [] | [] | [
"python"
] | stackoverflow_0003554952_python.txt |
Q:
Decorator changing function status from method to function
[Updated]: Answer inline below question
I have an inspecting program and one objective is for logic in a decorator to know whether the function it is decorating is a class method or regular function. This is failing in a strange way. Below is code run in Python 2.6:
def decorate(f):
print 'decorator thinks function is', f
return f
class Test(object):
@decorate
def test_call(self):
pass
if __name__ == '__main__':
Test().test_call()
print 'main thinks function is', Test().test_call
Then on execution:
decorator thinks function is <function test_call at 0x10041cd70>
main thinks function is <bound method Test.test_call of <__main__.Test object at 0x100425a90>>
Any clue on what's going wrong, and if it is possible for @decorate to correctly infer that test_call is a method?
[Answer]
carl's answer below is nearly perfect. I had a problem when using the decorator on a method that subclasses call. I adapted his code to include a im_func comparison on superclass members:
ismethod = False
for item in inspect.getmro(type(args[0])):
for x in inspect.getmembers(item):
if 'im_func' in dir(x[1]):
ismethod = x[1].im_func == newf
if ismethod:
break
else:
continue
break
A:
As others have said, a function is decorated before it is bound, so you cannot directly determine whether it's a 'method' or 'function'.
A reasonable way to determine if a function is a method or not is to check whether 'self' is the first parameter. While not foolproof, most Python code adheres to this convention:
import inspect
ismethod = inspect.getargspec(method).args[0] == 'self'
Here's a convoluted way that seems to automatically figure out whether the method is a bound or not. Works for a few simple cases on CPython 2.6, but no promises. It decides a function is a method if the first argument to is an object with the decorated function bound to it.
import inspect
def decorate(f):
def detect(*args, **kwargs):
try:
members = inspect.getmembers(args[0])
members = (x[1].im_func for x in members if 'im_func' in dir(x[1]))
ismethod = detect in members
except:
ismethod = False
print ismethod
return f(*args, **kwargs)
return detect
@decorate
def foo():
pass
class bar(object):
@decorate
def baz(self):
pass
foo() # prints False
bar().baz() # prints True
A:
No, this is not possible as you have requested, because there is no inherent difference between bound methods and functions. A method is simply a function wrapped up to get the calling instance as the first argument (using Python descriptors).
A call like:
Test.test_call
which returns an unbound method, translates to
Test.__dict__[ 'test_call' ].__get__( None, spam )
which is an unbound method, even though
Test.__dict__[ 'test_call' ]
is a function. This is because functions are descriptors whose __get__ methods return methods; when Python sees one of these in the lookup chain it calls the __get__ method instead of continuing up the chain.
In effect, the 'bound-methodiness' of a function is determined at runtime, not at define-time!
The decorator simply sees the function as it is defined, without looking it up in a __dict__, so cannot tell whether it is looking at a bound method.
It might be possible to do this with a class decorator that modifies __getattribute__, but that's a particularly nasty hack. Why must you have this functionality? Surely, since you have to place the decorator on the function yourself, you could pass it an argument that says whether said function is defined within a class?
class Test:
@decorate( method = True )
def test_call:
...
@decorate( method = False )
def test_call:
...
A:
Your decorator is run before the function becomes a method. def keyword inside a class defines a function line in any other place, then the functions defined in the body of a class are added to the class as methods. Decorator operates on the function before it is processed by the class that is why your code 'fails'.
There is no way for the @decorate to see the function is actually a method. A workaround for that would be to decorate the function whatever it is (e.g. adding an attribute do_something_about_me_if_I_am_a_method ;-)) and then process it again after the class is computed (iterating over the class members and doing whatever you want with those decorated).
A:
I tried a slightly different example, with one decorated method and one undecorated method.
def decorate(f):
print 'decorator thinks function is', f
return f
class Test(object):
@decorate
def test_call(self):
pass
def test_call_2(self):
pass
if __name__ == '__main__':
print 'main thinks function is', Test.test_call
print 'main thinks function 2 is', Test.test_call_2
Then the output is:
decorator thinks function is <function test_call at 0x100426b18>
main thinks function is <unbound method Test.test_call>
main thinks function 2 is <unbound method Test.test_call_2>
Thus, the decorator saw a different type than the main function did, but the decorator did not change the function's type, or it would be different from the undecorated function.
| Decorator changing function status from method to function | [Updated]: Answer inline below question
I have an inspecting program and one objective is for logic in a decorator to know whether the function it is decorating is a class method or regular function. This is failing in a strange way. Below is code run in Python 2.6:
def decorate(f):
print 'decorator thinks function is', f
return f
class Test(object):
@decorate
def test_call(self):
pass
if __name__ == '__main__':
Test().test_call()
print 'main thinks function is', Test().test_call
Then on execution:
decorator thinks function is <function test_call at 0x10041cd70>
main thinks function is <bound method Test.test_call of <__main__.Test object at 0x100425a90>>
Any clue on what's going wrong, and if it is possible for @decorate to correctly infer that test_call is a method?
[Answer]
carl's answer below is nearly perfect. I had a problem when using the decorator on a method that subclasses call. I adapted his code to include a im_func comparison on superclass members:
ismethod = False
for item in inspect.getmro(type(args[0])):
for x in inspect.getmembers(item):
if 'im_func' in dir(x[1]):
ismethod = x[1].im_func == newf
if ismethod:
break
else:
continue
break
| [
"As others have said, a function is decorated before it is bound, so you cannot directly determine whether it's a 'method' or 'function'.\nA reasonable way to determine if a function is a method or not is to check whether 'self' is the first parameter. While not foolproof, most Python code adheres to this conventio... | [
5,
3,
1,
0
] | [] | [] | [
"decorator",
"inspection",
"python"
] | stackoverflow_0003564049_decorator_inspection_python.txt |
Q:
Python, mechanize, proper syntax for setting multiple headers?
I can't seem to find how to do this anywere, I am trying to set multiple headers with python's mechanize module, such as:
br.addheaders = [('user-agent', ' Mozilla/5.0 (X11; U; Linux i686; en-US; rv:1.9.2.3) Gecko/20100423 Ubuntu/10.04 (lucid) Firefox/3.6.3')]
br.addheaders = [('accept', 'text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8')]
But it seems that it only takes the last br.addheaders.. so it only shows the 'accept' header, not the 'user-agent' header, which leads me to believe that each call to 'br.addheaders' overwrites any previous calls to this.. I can't figure the syntax to include 2 or more headers so I would greatly appreciate any help..
I am using this website to test headers output:
http://www.ericgiguere.com/tools/http-header-viewer.html
A:
According to http://wwwsearch.sourceforge.net/mechanize/doc.html#adding-headers, the syntax would be
br.addheaders = [('user-agent', ' Mozilla/5.0 (X11; U; Linux i686; en-US; rv:1.9.2.3) Gecko/20100423 Ubuntu/10.04 (lucid) Firefox/3.6.3'),
('accept', 'text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8')]
That is, make a list of header tuples.
| Python, mechanize, proper syntax for setting multiple headers? | I can't seem to find how to do this anywere, I am trying to set multiple headers with python's mechanize module, such as:
br.addheaders = [('user-agent', ' Mozilla/5.0 (X11; U; Linux i686; en-US; rv:1.9.2.3) Gecko/20100423 Ubuntu/10.04 (lucid) Firefox/3.6.3')]
br.addheaders = [('accept', 'text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8')]
But it seems that it only takes the last br.addheaders.. so it only shows the 'accept' header, not the 'user-agent' header, which leads me to believe that each call to 'br.addheaders' overwrites any previous calls to this.. I can't figure the syntax to include 2 or more headers so I would greatly appreciate any help..
I am using this website to test headers output:
http://www.ericgiguere.com/tools/http-header-viewer.html
| [
"According to http://wwwsearch.sourceforge.net/mechanize/doc.html#adding-headers, the syntax would be \nbr.addheaders = [('user-agent', ' Mozilla/5.0 (X11; U; Linux i686; en-US; rv:1.9.2.3) Gecko/20100423 Ubuntu/10.04 (lucid) Firefox/3.6.3'),\n('accept', 'text/html,application/xhtml+xml,application/xml;q=0.9,*/*;... | [
10
] | [] | [] | [
"http_headers",
"mechanize",
"python",
"webautomation"
] | stackoverflow_0003564509_http_headers_mechanize_python_webautomation.txt |
Q:
Create and retrieve object list in Python
I would like to keep a reference of the objects I've created in one script to use them in another script (without using shelve).
I would like something close to :
script 1
class Porsche(Car):
""" class representing a Porsche """
def __init__(self, color):
self.color = color
class Porsche_Container:
# objects here
return objects
my_Porsche = Porsche(blue)
my_Porsche2 = Porsche(red)
script2
for object in Porsche_Container:
print object.color
rgds,
A:
The best way to do this is explicitly to construct the set of objects that you want to access. It is possible to list e.g. all global variables defined in the other script, but not a good idea.
script1
...
porsche_container = { myPorsche1, myPorsche2 }
script 2
import script1
for porsche in script1.porsche_container:
...
A:
Are these scripts going to be run in different processes? If not the solution is pretty straight forward (see katriealex's answer).
If they are going to run in different processes then you'll need more complex solutions involving inter process communication.
A:
I'm assuming you want only one process.
Use import, treat one 'script' as the main module and the other 'script' as a library module that you import. In my modified example script2.py is the main module and script1.py is the library.
script1.py
# -*- coding: utf-8 -*-
class Porsche(object):
""" class representing a Porsche """
def __init__(self, color):
self.color = color
BLUE = 1
RED = 2
def make_porsche_list():
return [Porsche(BLUE), Porsche(RED)]
script2.py
# -*- coding: utf-8 -*-
import script1
porsche_container = script1.make_porsche_list()
for object in porsche_container:
print object.color
Output:
eike@lixie:~/Desktop/test> python script2.py
1
2
eike@lixie:~/Desktop/test> ls
script1.py script1.py~ script1.pyc script2.py script2.py~
| Create and retrieve object list in Python | I would like to keep a reference of the objects I've created in one script to use them in another script (without using shelve).
I would like something close to :
script 1
class Porsche(Car):
""" class representing a Porsche """
def __init__(self, color):
self.color = color
class Porsche_Container:
# objects here
return objects
my_Porsche = Porsche(blue)
my_Porsche2 = Porsche(red)
script2
for object in Porsche_Container:
print object.color
rgds,
| [
"The best way to do this is explicitly to construct the set of objects that you want to access. It is possible to list e.g. all global variables defined in the other script, but not a good idea.\n\nscript1\n...\nporsche_container = { myPorsche1, myPorsche2 }\n\nscript 2\nimport script1\nfor porsche in script1.porsc... | [
0,
0,
0
] | [] | [] | [
"python"
] | stackoverflow_0003564749_python.txt |
Q:
How do i render a template inside another template?
I'm new in Django and Python and I'm stuck! It's complicated to explain but I will give it a try... I have my index.html template with an include tag:
{% include 'menu.inc.html' %}
The menu is a dynamic (http://code.google.com/p/django-treemenus/). The menu-app holds a view that renders menu.inc.html:
from django.http import HttpResponse
from django.template import Context, loader
from treemenus.models import Menu
def mymenu(request):
mainmenu = Menu.objects.get(id = 1)
template = loader.get_template('menu.inc.html')
context = Context({
'mainmenu':mainmenu,
})
return HttpResponse(template.render(context))
So when I access index.html the server will serve it to me and django will load and serve menu.inc.html! But not the content! My question is:
How do I reverse link the menu.inc.html to the view?! or
How do I tell django that a template needs a rendered template by a specific view?!
I don't want put mainmenu = Menu.objects.get(id = 1) in my index's view because the menu will be on other pages too ... I was thinking iframes + rule in the urls.py, but that's an ugly workaround ...
Do I make any sense?!
A:
At first blush this seems to be a case for adding an inclusion tag. You might want to write a custom tag that renders the tree menu. From the main view you can then pass the necessary context variables for this tag to work.
From the documentation:
Another common type of template tag is the type that displays some data by rendering another template.
| How do i render a template inside another template? | I'm new in Django and Python and I'm stuck! It's complicated to explain but I will give it a try... I have my index.html template with an include tag:
{% include 'menu.inc.html' %}
The menu is a dynamic (http://code.google.com/p/django-treemenus/). The menu-app holds a view that renders menu.inc.html:
from django.http import HttpResponse
from django.template import Context, loader
from treemenus.models import Menu
def mymenu(request):
mainmenu = Menu.objects.get(id = 1)
template = loader.get_template('menu.inc.html')
context = Context({
'mainmenu':mainmenu,
})
return HttpResponse(template.render(context))
So when I access index.html the server will serve it to me and django will load and serve menu.inc.html! But not the content! My question is:
How do I reverse link the menu.inc.html to the view?! or
How do I tell django that a template needs a rendered template by a specific view?!
I don't want put mainmenu = Menu.objects.get(id = 1) in my index's view because the menu will be on other pages too ... I was thinking iframes + rule in the urls.py, but that's an ugly workaround ...
Do I make any sense?!
| [
"At first blush this seems to be a case for adding an inclusion tag. You might want to write a custom tag that renders the tree menu. From the main view you can then pass the necessary context variables for this tag to work.\nFrom the documentation:\n\nAnother common type of template tag is the type that displays s... | [
2
] | [] | [] | [
"django",
"python",
"templates",
"url"
] | stackoverflow_0003565245_django_python_templates_url.txt |
Q:
Django - dreaded 'iteration over non-sequence'
Hi I'm looking to populate a list of members, based on where their club comes from.
This is my code:
members = []
if userprofile.countries.count() > 0:
for c in userprofile.countries.all():
clubs = Club.objects.filter(location__country = c)
for club in clubs:
members_list = Member.objects.get_members(club)
for m in members_list:
members.append(m)
However, when evaluating for m in members_list: it throws an 'iteration over non-sequence'
I'm not entirely sure why? Can anyone give me any ideas?!
EDIT:
Solved using the following:
members = []
if userprofile.countries.count() > 0:
members_list = member.objects.filter(memberstoentities__club__location__country__in = userprofile.countries.all())
for m in members_list:
members.append(m)
A:
Can't comment unless looking at Member model. But
Can't we use .filter with back navigation, instead of get_members
Do we need those many loops, and db access inside loop? ex:
clubs = Club.objects.filter(location__country__in = list_of_user_countries)
If your final list is list of members, you can do that as I mentioned above (at least in optimized way)
| Django - dreaded 'iteration over non-sequence' | Hi I'm looking to populate a list of members, based on where their club comes from.
This is my code:
members = []
if userprofile.countries.count() > 0:
for c in userprofile.countries.all():
clubs = Club.objects.filter(location__country = c)
for club in clubs:
members_list = Member.objects.get_members(club)
for m in members_list:
members.append(m)
However, when evaluating for m in members_list: it throws an 'iteration over non-sequence'
I'm not entirely sure why? Can anyone give me any ideas?!
EDIT:
Solved using the following:
members = []
if userprofile.countries.count() > 0:
members_list = member.objects.filter(memberstoentities__club__location__country__in = userprofile.countries.all())
for m in members_list:
members.append(m)
| [
"Can't comment unless looking at Member model. But\n\nCan't we use .filter with back navigation, instead of get_members\nDo we need those many loops, and db access inside loop? ex:\n\nclubs = Club.objects.filter(location__country__in = list_of_user_countries)\nIf your final list is list of members, you can do that ... | [
2
] | [] | [] | [
"django",
"django_models",
"django_queryset",
"python"
] | stackoverflow_0003565166_django_django_models_django_queryset_python.txt |
Q:
Problem requiring lists
The current issue im facing is comes from the following scenario. I have a script that runs a commandline program to find all files of a certain extension within an specific folder, lets call these files File A. Another section of the script runs a grep command through each file for filenames within File A. What would be the best method to store what filenames are in File A and only File A, and how could I achieve it? Thanks
A:
EDIT: I see you were the one who asked the previous question! Why open a new one?
There was a recent question on this exact problem -- the structure you are modelling is a directed graph. See my answer to that question, using Python's networkx package. Using this package is a good idea if you are going to do some post-processing of the data. However, for simple situations, you could make your own data structure. Here is a sample using an adjacency list representation of a graph; it is not difficult to use an adjacency matrix instead.
from collections import defaultdict
adj_list = defaultdict( set )
for filename in os.listdir( <dir> ):
with open( filename ) as theFile:
for line in theFile:
# parse line into filename, say 'target'
adj_list[ filename ].add( target )
This will give you a dictionary of filename -> files linked by that file.
| Problem requiring lists | The current issue im facing is comes from the following scenario. I have a script that runs a commandline program to find all files of a certain extension within an specific folder, lets call these files File A. Another section of the script runs a grep command through each file for filenames within File A. What would be the best method to store what filenames are in File A and only File A, and how could I achieve it? Thanks
| [
"EDIT: I see you were the one who asked the previous question! Why open a new one?\n\nThere was a recent question on this exact problem -- the structure you are modelling is a directed graph. See my answer to that question, using Python's networkx package. Using this package is a good idea if you are going to do so... | [
2
] | [] | [] | [
"dictionary",
"nested_lists",
"python"
] | stackoverflow_0003565543_dictionary_nested_lists_python.txt |
Q:
Create and retrieve object list in Python enhanced
This post is the follow-up of my previous post (Create and retrieve object list in Python).
I had to modify my code in the following way :
script1
#!/usr/bin/python
class Porsche:
""" class representing a Porsche """
def __init__(self, color):
self.color = color
def create_porsche(parameter_1, parameter_2):
myPorsche = Porsche(color = parameter_1)
myPorsche2 = Porsche(color = parameter_2)
create_porsche(parameter_1 = 'blue', parameter_2 = 'red')
porsche_container = (myPorsche, myPorsche2)
and I'd like to have porsche_container = (myPorsche, myPorsche2) working the same way as in my previous script :
old script 1
#!/usr/bin/python
class Porsche:
""" class representing a Porsche """
def __init__(self, color):
self.color = color
myPorsche = Porsche(color = 'blue')
myPorsche2 = Porsche(color = 'red')
porsche_container = (myPorsche, myPorsche2)
How can I do that please ?
rgds,
A:
create_porsche doesn't return anything, so you don't know what it's created. Make it return a list of the cars that it creates, which you can then store in your global variable.
def create_porsche(parameter_1, parameter_2):
myPorsche = Porsche(color = parameter_1)
myPorsche2 = Porsche(color = parameter_2)
return [ myPorsche, myPorsche2 ]
porsche_container = create_porsche(parameter_1 = 'blue', parameter_2 = 'red')
The reason the code you posted above doesn't work is that the variables myPorsche and myPorsche2 are defined within the function create_porsche, so they are scoped to that function. That means that you can't see or access them outside of that block of code. If you want to know about them, make create_porsche return them. (Note: it is possible to tell Python that they should be global variables i.e., not scoped within the function -- you use the global keyword -- but you shouldn't do that unless you must.)
I don't mean to be rude here, but have you read any Python tutorials? Something like Dive Into Python might help you a lot in understanding things like this (function scopes and return values).
A:
Here is my take on how to go about creating Porsche objects and add them to a container.
class Porsche(object):
def __init__(self, color):
self.color = color
class PorscheCreator(object):
def __init__(self):
self._cars = []
def create(self, *args, **kwargs):
porsche = Porsche(*args, **kwargs)
self._cars.append(porsche)
return porsche
def _get_cars(self):
for each in self._cars:
yield each
cars = property(_get_cars)
creator = PorscheCreator()
myPorsche = creator.create('blue')
myPorsche2 = creator.create('red')
And in script 2:
from script1 import creator
for each in creator.cars:
print car.color
| Create and retrieve object list in Python enhanced | This post is the follow-up of my previous post (Create and retrieve object list in Python).
I had to modify my code in the following way :
script1
#!/usr/bin/python
class Porsche:
""" class representing a Porsche """
def __init__(self, color):
self.color = color
def create_porsche(parameter_1, parameter_2):
myPorsche = Porsche(color = parameter_1)
myPorsche2 = Porsche(color = parameter_2)
create_porsche(parameter_1 = 'blue', parameter_2 = 'red')
porsche_container = (myPorsche, myPorsche2)
and I'd like to have porsche_container = (myPorsche, myPorsche2) working the same way as in my previous script :
old script 1
#!/usr/bin/python
class Porsche:
""" class representing a Porsche """
def __init__(self, color):
self.color = color
myPorsche = Porsche(color = 'blue')
myPorsche2 = Porsche(color = 'red')
porsche_container = (myPorsche, myPorsche2)
How can I do that please ?
rgds,
| [
"create_porsche doesn't return anything, so you don't know what it's created. Make it return a list of the cars that it creates, which you can then store in your global variable.\ndef create_porsche(parameter_1, parameter_2):\n myPorsche = Porsche(color = parameter_1)\n myPorsche2 = Porsche(color = parameter_... | [
1,
0
] | [] | [] | [
"python"
] | stackoverflow_0003565930_python.txt |
Q:
How to maintain mail conversion (reply / forward / reply to all like gmail) of email using Python pop/imap lib?
I've develop webmail client for any mail server.
I want to implement message conversion for it — for example same emails fwd/reply/reply2all should be shown together like gmail does...
My question is: what's the key to find those emails which are either reply/fwd or related to the original mail....
A:
The In-Reply-To header of the child should have the value of the Message-Id header of the parent(s).
A:
Google just seems to chain messages based on the subject line (so does Apple Mail by the way.)
| How to maintain mail conversion (reply / forward / reply to all like gmail) of email using Python pop/imap lib? | I've develop webmail client for any mail server.
I want to implement message conversion for it — for example same emails fwd/reply/reply2all should be shown together like gmail does...
My question is: what's the key to find those emails which are either reply/fwd or related to the original mail....
| [
"The In-Reply-To header of the child should have the value of the Message-Id header of the parent(s).\n",
"Google just seems to chain messages based on the subject line (so does Apple Mail by the way.)\n"
] | [
4,
3
] | [] | [] | [
"imap",
"imaplib",
"pop3",
"poplib",
"python"
] | stackoverflow_0003530851_imap_imaplib_pop3_poplib_python.txt |
Q:
Reportlab 'LayoutError' handling and debugging
I have been working with some complex PDF outputs with reportlab. These are generally fine but there are some cases still where I get LayoutErrors - these are usually because Flowables are too big at some point.
It's proving o be pretty hard to debug these as I don't often have more information than something like this;
Flowable <Table@0x104C32290 4 rows x 6 cols> with cell(0,0) containing
'<Paragraph at 0x104df2ea8>Authors'(789.0 x 1176) too large on page 5 in frame 'normal'(801.543307087 x 526.582677165*) of template 'Later'
It's really not that helpful. What I would ideally like to know is the best debugging and testing strategies for this kinda thing.
Is there a way I can view a broken PDF? i.e. rendered with the layout errors so I can see whats going on more easily.
Is there a way I can add a hook to reportlab to better handle these errors? Rather than just failing the whole PDF?
Any other suggestions about generally improving, testing and handling problems like these.
I don't have a particular example so its more general advice, the exception above I have resolved but its kinda through trial and error (read; guessing and seeing what happens).
A:
Make sure you are not re-using any of your flowable objects (as in, rendering multiple versions of a document using common template parts). This is not supported by ReportLab, and can cause this error.
The reason seems to be that ReportLab will set an attribute on these objects when performing the layout to indicate that it was needed to move them to a separate page. If it has to be moved twice, it will throw that exception. These attributes are not reset when you render a document, so it can appear that an object was moved to a separate page twice when it really wasn't.
I've hacked around this before by resetting the attribute manually (I can't remember the name right now; it was '_deferred' or something), but the correct approach is to toss out any objects you used to render a document after it's rendered.
A:
We had a problem when using Reportlab to format some content that was originally html and sometimes the html was too complex. The solution (and I take no credit here, this was from the guys at Reportlab) was to catch the error when it occurred and output it directly into the PDF.
That means you get to see the cause of the problem in the right context. You could expand on this to output details of the exception, but in our case since our problem was converting html to rml we just had to display our input:
Tthe preppy template contains this:
{{script}}
#This section contains python functions used within the rml.
#we can import any helper code we need within the template,
#to save passing in hundreds of helper functions at the top
from rml_helpers import blocks
{{endscript}}
and then later bits of template like:
{{if equip.specification}}
<condPageBreak height="1in"/>
<para style="h2">Item specification</para>
{{blocks(equip.specification)}}
{{endif}}
In rml_helpers.py we have:
from xml.sax.saxutils import escape
from rlextra.radxml.html_cleaner import cleanBlocks
from rlextra.radxml.xhtml2rml import xhtml2rml
def q(stuff):
"""Quoting function which works with unicode strings.
The data from Zope is Unicode objects. We need to explicitly
convert to UTF8; then escape any ampersands. So
u"Black & Decker drill"
becomes
"Black & Decker drill"
and any special characters (Euro, curly quote etc) end up
suitable for XML. For completeness we'll accept 'None'
objects as well and output an empty string.
"""
if stuff is None:
return ''
elif isinstance(stuff,unicode):
stuff = escape(stuff.encode('utf8'))
else:
stuff = escape(str(stuff))
return stuff.replace('"','"').replace("'", ''')
def blocks(txt):
try:
txt2 = cleanBlocks(txt)
rml = xhtml2rml(txt2)
return rml
except:
return '<para style="big_warning">Could not process markup</para><para style="normal">%s</para>' % q(txt)
So anything which is too complex for xhtml2rml to handle throws an exception and is replaced in the output by a big warning 'Could not process markup' followed by the markup that caused the error, escaped so it appears as literal.
Then all we have to do is to remember to search the output PDF for the error message and fix up the input accordingly.
| Reportlab 'LayoutError' handling and debugging | I have been working with some complex PDF outputs with reportlab. These are generally fine but there are some cases still where I get LayoutErrors - these are usually because Flowables are too big at some point.
It's proving o be pretty hard to debug these as I don't often have more information than something like this;
Flowable <Table@0x104C32290 4 rows x 6 cols> with cell(0,0) containing
'<Paragraph at 0x104df2ea8>Authors'(789.0 x 1176) too large on page 5 in frame 'normal'(801.543307087 x 526.582677165*) of template 'Later'
It's really not that helpful. What I would ideally like to know is the best debugging and testing strategies for this kinda thing.
Is there a way I can view a broken PDF? i.e. rendered with the layout errors so I can see whats going on more easily.
Is there a way I can add a hook to reportlab to better handle these errors? Rather than just failing the whole PDF?
Any other suggestions about generally improving, testing and handling problems like these.
I don't have a particular example so its more general advice, the exception above I have resolved but its kinda through trial and error (read; guessing and seeing what happens).
| [
"Make sure you are not re-using any of your flowable objects (as in, rendering multiple versions of a document using common template parts). This is not supported by ReportLab, and can cause this error.\nThe reason seems to be that ReportLab will set an attribute on these objects when performing the layout to indic... | [
4,
2
] | [] | [] | [
"debugging",
"python",
"reportlab",
"testing"
] | stackoverflow_0003069288_debugging_python_reportlab_testing.txt |
Q:
How do I make wx.TextCtrl multi-line text update smoothly?
I'm working on an GUI program, and I use AppendText to update status in a multi-line text box(made of wx.TextCtrl). I noticed each time there's a new line written in this box, instead of smoothly adding this line to the end, the whole texts in the box just disappear(not in real, just visually) and I have to click the scroll button to check the newly updated/written status line. Why this happening? Should I add some styles? Hopefully you guys can help me out.
Here's my sample code:
import wx
import thread
import time
class TestFrame(wx.Frame):
def __init__(self):
wx.Frame.__init__(self, parent = None, id = -1, title = "Testing", pos=(350, 110), size=(490,530), style=wx.SYSTEM_MENU | wx.CAPTION | wx.CLOSE_BOX | wx.MINIMIZE_BOX)
panel = wx.Panel(self)
self.StartButton = wx.Button(parent = panel, id = -1, label = "Start", pos = (110, 17), size = (50, 20))
self.MultiLine = wx.TextCtrl(parent = panel, id = -1, pos = (38, 70), size = (410, 90), style = wx.TE_MULTILINE|wx.TE_READONLY|wx.TE_AUTO_URL)
self.Bind(wx.EVT_BUTTON, self.OnStart, self.StartButton)
def OnStart(self, event):
self.StartButton.Disable()
thread.start_new_thread(self.LongRunning, ())
def LongRunning(self):
Counter = 1
while True:
self.MultiLine.AppendText("Hi," + str(Counter) + "\n")
Counter = Counter + 1
time.sleep(2)
class TestApp(wx.App):
def OnInit(self):
self.TestFrame = TestFrame()
self.TestFrame.Show()
self.SetTopWindow(self.TestFrame)
return True
def main():
App = TestApp(redirect = False)
App.MainLoop()
if __name__ == "__main__":
main()
A:
try this:
self.logs = wx.TextCtrl(self, id=-1, value='', pos=wx.DefaultPosition,
size=(-1,300),
style= wx.TE_MULTILINE | wx.SUNKEN_BORDER)
self.logs.AppendText(text + "\n")
A:
Try calling the Refresh() method on the textCtrl
Update:
A question has already been asked regarding this problem, here is the answer which pretty much solves it, -its not perfect but maybe you can improve on it...
Here is a thread from the wxpython mailing list regarding the problem which may also be of interest to you.
| How do I make wx.TextCtrl multi-line text update smoothly? | I'm working on an GUI program, and I use AppendText to update status in a multi-line text box(made of wx.TextCtrl). I noticed each time there's a new line written in this box, instead of smoothly adding this line to the end, the whole texts in the box just disappear(not in real, just visually) and I have to click the scroll button to check the newly updated/written status line. Why this happening? Should I add some styles? Hopefully you guys can help me out.
Here's my sample code:
import wx
import thread
import time
class TestFrame(wx.Frame):
def __init__(self):
wx.Frame.__init__(self, parent = None, id = -1, title = "Testing", pos=(350, 110), size=(490,530), style=wx.SYSTEM_MENU | wx.CAPTION | wx.CLOSE_BOX | wx.MINIMIZE_BOX)
panel = wx.Panel(self)
self.StartButton = wx.Button(parent = panel, id = -1, label = "Start", pos = (110, 17), size = (50, 20))
self.MultiLine = wx.TextCtrl(parent = panel, id = -1, pos = (38, 70), size = (410, 90), style = wx.TE_MULTILINE|wx.TE_READONLY|wx.TE_AUTO_URL)
self.Bind(wx.EVT_BUTTON, self.OnStart, self.StartButton)
def OnStart(self, event):
self.StartButton.Disable()
thread.start_new_thread(self.LongRunning, ())
def LongRunning(self):
Counter = 1
while True:
self.MultiLine.AppendText("Hi," + str(Counter) + "\n")
Counter = Counter + 1
time.sleep(2)
class TestApp(wx.App):
def OnInit(self):
self.TestFrame = TestFrame()
self.TestFrame.Show()
self.SetTopWindow(self.TestFrame)
return True
def main():
App = TestApp(redirect = False)
App.MainLoop()
if __name__ == "__main__":
main()
| [
"try this:\nself.logs = wx.TextCtrl(self, id=-1, value='', pos=wx.DefaultPosition,\n size=(-1,300),\n style= wx.TE_MULTILINE | wx.SUNKEN_BORDER)\nself.logs.AppendText(text + \"\\n\")\n\n",
"Try calling the Refresh() method on the textCtrl\nUpdate:\nA question ... | [
4,
2
] | [] | [] | [
"python",
"wx.textctrl",
"wxpython"
] | stackoverflow_0003566603_python_wx.textctrl_wxpython.txt |
Q:
Python: shape of a matrix and imshow()
I have a 3-D array ar.
print shape(ar) # --> (81, 81, 256)
I want to plot this array.
fig = plt.figure()
ax1 = fig.add_subplot(111)
for i in arange(256):
im1 = ax1.imshow(ar[:][:][i])
plt.draw()
print i
I get this error-message:
im1 = ax1.imshow(ar[:][:][i])
IndexError: list index out of range
Why do I get this strange message? The graph has the size 81 x 256 and not like expected 81 x 81. But why?
A:
Do:
ar[:,:,i]
The syntax ar[:] makes a copy of ar (slices all its elements), so ar[:][:][i] is semantically equivalent to ar[i]. This is an 81*256 matrix, since ndarrays are nested lists.
| Python: shape of a matrix and imshow() | I have a 3-D array ar.
print shape(ar) # --> (81, 81, 256)
I want to plot this array.
fig = plt.figure()
ax1 = fig.add_subplot(111)
for i in arange(256):
im1 = ax1.imshow(ar[:][:][i])
plt.draw()
print i
I get this error-message:
im1 = ax1.imshow(ar[:][:][i])
IndexError: list index out of range
Why do I get this strange message? The graph has the size 81 x 256 and not like expected 81 x 81. But why?
| [
"Do:\nar[:,:,i]\n\nThe syntax ar[:] makes a copy of ar (slices all its elements), so ar[:][:][i] is semantically equivalent to ar[i]. This is an 81*256 matrix, since ndarrays are nested lists.\n"
] | [
2
] | [] | [] | [
"arrays",
"matplotlib",
"multidimensional_array",
"numpy",
"python"
] | stackoverflow_0003566782_arrays_matplotlib_multidimensional_array_numpy_python.txt |
Q:
Google App Engine : Cursor Versus Offset
Do you know which is the best approach for fetching chunks of result from a query?
1.Cursor
q = Person.all()
last_cursor = memcache.get('person_cursor')
if last_cursor:
q.with_cursor(last_cursor)
people = q.fetch(100)
cursor = q.cursor()
memcache.set('person_cursor', cursor)
2.Offset
q = Person.all()
offset = memcache.get('offset')
if not offset:
offset = 0
people = q.fetch(100, offset = offset)
memcache.set('offset', offset + 100)
Reading the Google documentation, it seems that Cursor does not add the overhead of a query offset.
A:
While it's hard to measure precise and reliably, I'd be astonished if the cursor didn't run rings around the offset approach at soon as a sufficiently large set of Person entities are getting returned. As the docs say very clearly and explicitly,
The datastore fetches offset + limit
results to the application. The first
offset results are not skipped by the
datastore itself.
The fetch() method skips the first
offset results, then returns the rest
(limit results).
The query has performance
characteristics that correspond
linearly with the offset amount plus
the limit.
I'm not sure how it could be any more explicit: O(offset + limit) is the big-O performance of fetching with an offset. If overall (say over multiple scheduled tasks) you're fetching a million items, 1000 at a time, when you fetch the last 1000 (with offset 999000) the datastore does not skip the first 999000 (even though fetch does not return them), so the performance impact will be staggering.
No such caveat applies to using cursors: fetching resumes exactly where it left off, without having to repeatedly fetch all the (possibly many) items already fetched along that cursor in previous queries. Therefore, with performance O(limit), elapsed time should be arbitrarily better than that you can obtain with an offset, as long as that offset gets sufficiently large.
| Google App Engine : Cursor Versus Offset | Do you know which is the best approach for fetching chunks of result from a query?
1.Cursor
q = Person.all()
last_cursor = memcache.get('person_cursor')
if last_cursor:
q.with_cursor(last_cursor)
people = q.fetch(100)
cursor = q.cursor()
memcache.set('person_cursor', cursor)
2.Offset
q = Person.all()
offset = memcache.get('offset')
if not offset:
offset = 0
people = q.fetch(100, offset = offset)
memcache.set('offset', offset + 100)
Reading the Google documentation, it seems that Cursor does not add the overhead of a query offset.
| [
"While it's hard to measure precise and reliably, I'd be astonished if the cursor didn't run rings around the offset approach at soon as a sufficiently large set of Person entities are getting returned. As the docs say very clearly and explicitly,\n\nThe datastore fetches offset + limit\n results to the applicati... | [
31
] | [] | [] | [
"google_app_engine",
"python"
] | stackoverflow_0003566462_google_app_engine_python.txt |
Q:
URL encoding/decoding with Python
I am trying to encode and store, and decode arguments in Python and getting lost somewhere along the way. Here are my steps:
1) I use google toolkit's gtm_stringByEscapingForURLArgument to convert an NSString properly for passing into HTTP arguments.
2) On my server (python), I store these string arguments as something like u'1234567890-/:;()$&@".,?!\'[]{}#%^*+=_\\|~<>\u20ac\xa3\xa5\u2022.,?!\'' (note that these are the standard keys on an iphone keypad in the "123" view and the "#+=" view, the \u and \x chars in there being some monetary prefixes like pound, yen, etc)
3) I call urllib.quote(myString,'') on that stored value, presumably to %-escape them for transport to the client so the client can unpercent escape them.
The result is that I am getting an exception when I try to log the result of % escaping. Is there some crucial step I am overlooking that needs to be applied to the stored value with the \u and \x format in order to properly convert it for sending over http?
Update: The suggestion marked as the answer below worked for me. I am providing some updates to address the comments below to be complete, though.
The exception I received cited an issue with \u20ac. I don't know if it was a problem with that specifically, rather than the fact that it was the first unicode character in the string.
That \u20ac char is the unicode for the 'euro' symbol. I basically found I'd have issues with it unless I used the urllib2 quote method.
A:
url encoding a "raw" unicode doesn't really make sense. What you need to do is .encode("utf8") first so you have a known byte encoding and then .quote() that.
The output isn't very pretty but it should be a correct uri encoding.
>>> s = u'1234567890-/:;()$&@".,?!\'[]{}#%^*+=_\|~<>\u20ac\xa3\xa5\u2022.,?!\''
>>> urllib2.quote(s.encode("utf8"))
'1234567890-/%3A%3B%28%29%24%26%40%22.%2C%3F%21%27%5B%5D%7B%7D%23%25%5E%2A%2B%3D_%5C%7C%7E%3C%3E%E2%82%AC%C2%A3%C2%A5%E2%80%A2.%2C%3F%21%27'
Remember that you will need to both unquote() and decode() this to print it out properly if you're debugging or whatever.
>>> print urllib2.unquote(urllib2.quote(s.encode("utf8")))
1234567890-/:;()$&@".,?!'[]{}#%^*+=_\|~<>€£¥•.,?!'
>>> # oops, nasty  means we've got a utf8 byte stream being treated as an ascii stream
>>> print urllib2.unquote(urllib2.quote(s.encode("utf8"))).decode("utf8")
1234567890-/:;()$&@".,?!'[]{}#%^*+=_\|~<>€£¥•.,?!'
This is, in fact, what the django functions mentioned in another answer do.
The functions
django.utils.http.urlquote() and
django.utils.http.urlquote_plus() are
versions of Python’s standard
urllib.quote() and urllib.quote_plus()
that work with non-ASCII characters.
(The data is converted to UTF-8 prior
to encoding.)
Be careful if you are applying any further quotes or encodings not to mangle things.
A:
i want to second pycruft's remark. web protocols have evolved over decades, and dealing with the various sets of conventions can be cumbersome. now URLs happen to be explicitly not defined for characters, but only for bytes (octets). as a historical coincidence, URLs are one of the places where you can only assume, but not enforce or safely expect an encoding to be present. however, there is a convention to prefer latin-1 and utf-8 over other encodings here. for a while, it looked like 'unicode percent escapes' would be the future, but they never caught on.
it is of paramount importance to be pedantically picky in this area about the difference between unicode objects and octet strings (in Python < 3.0; that's, confusingly, str unicode objects and bytes/bytearray objects in Python >= 3.0). unfortunately, in my experience it is for a number of reasons pretty difficult to cleanly separate the two concepts in Python 2.x.
even more OT, when you want to receive third-party HTTP requests, you can not absolutely rely on URLs being sent in percent-escaped, utf-8-encoded octets: there may both be the occasional %uxxxx escape in there, and at least firefox 2.x used to encode URLs as latin-1 where possible, and as utf-8 only where necessary.
A:
You are out of your luck with stdlib, urllib.quote doesn't work with unicode. If you are using django you can use django.utils.http.urlquote which works properly with unicode
| URL encoding/decoding with Python | I am trying to encode and store, and decode arguments in Python and getting lost somewhere along the way. Here are my steps:
1) I use google toolkit's gtm_stringByEscapingForURLArgument to convert an NSString properly for passing into HTTP arguments.
2) On my server (python), I store these string arguments as something like u'1234567890-/:;()$&@".,?!\'[]{}#%^*+=_\\|~<>\u20ac\xa3\xa5\u2022.,?!\'' (note that these are the standard keys on an iphone keypad in the "123" view and the "#+=" view, the \u and \x chars in there being some monetary prefixes like pound, yen, etc)
3) I call urllib.quote(myString,'') on that stored value, presumably to %-escape them for transport to the client so the client can unpercent escape them.
The result is that I am getting an exception when I try to log the result of % escaping. Is there some crucial step I am overlooking that needs to be applied to the stored value with the \u and \x format in order to properly convert it for sending over http?
Update: The suggestion marked as the answer below worked for me. I am providing some updates to address the comments below to be complete, though.
The exception I received cited an issue with \u20ac. I don't know if it was a problem with that specifically, rather than the fact that it was the first unicode character in the string.
That \u20ac char is the unicode for the 'euro' symbol. I basically found I'd have issues with it unless I used the urllib2 quote method.
| [
"url encoding a \"raw\" unicode doesn't really make sense. What you need to do is .encode(\"utf8\") first so you have a known byte encoding and then .quote() that.\nThe output isn't very pretty but it should be a correct uri encoding.\n>>> s = u'1234567890-/:;()$&@\".,?!\\'[]{}#%^*+=_\\|~<>\\u20ac\\xa3\\xa5\\u2022.... | [
71,
4,
2
] | [] | [] | [
"python",
"url_encoding"
] | stackoverflow_0003563126_python_url_encoding.txt |
Q:
Trouble with receiving data from
HTML:
<form enctype="multipart/form-data" action="/convert_upl" method="post">
Name: <input type="text" name="file_name">
File: <input type="file" name="subs_file">
<input type="submit" value="Send">
</form>
Python (Google App Engine):
if self.request.get('file_name'):
file_name = self.request.get('file_name')
My problem is that I receive no data from file_name text input. I am aware that the trouble is because of it's existence within the form enctype="multipart/form-data" but I don't know how to solve it - I mean how to receive a file and the string from the input with one click of the submit button.
Thanks in advance.
A:
You are using the POST method to send the data but then are trying to get it with the GET method.
instead of
self.request.get('file_name')
do something like
self.request.post('file_name')
A:
The uploading example code works fine for me. Have you tried using that code exactly? Does it work for you, or what problems do you see?
As you'll see, that example has a form with the same encoding you're using:
<form action="/sign" enctype="multipart/form-data" method="post">
<div><label>Message:</label></div>
<div><textarea name="content" rows="3" cols="60"></textarea></div>
<div><label>Avatar:</label></div>
<div><input type="file" name="img"/></div>
<div><input type="submit" value="Sign Guestbook"></div>
</form>
it's just a bit more careful in the HTML to properly use label tags to display field labels, but that only affect the form's looks when rendered in the browser.
The Python code is also similar to what you show (for the tiny susbset that you do show):
def post(self):
greeting = Greeting()
if users.get_current_user():
greeting.author = users.get_current_user()
greeting.content = self.request.get("content")
avatar = self.request.get("img")
greeting.avatar = db.Blob(avatar)
greeting.put()
self.redirect('/')
and of course the /sign URL is directed to the class whose do_post method we've just shown.
So, if this code works and yours doesn't, where is the difference? Not in the part you've shown us, so it must be in some parts you haven't shown... can you reproduce the part about this example code from Google working just fine?
| Trouble with receiving data from | HTML:
<form enctype="multipart/form-data" action="/convert_upl" method="post">
Name: <input type="text" name="file_name">
File: <input type="file" name="subs_file">
<input type="submit" value="Send">
</form>
Python (Google App Engine):
if self.request.get('file_name'):
file_name = self.request.get('file_name')
My problem is that I receive no data from file_name text input. I am aware that the trouble is because of it's existence within the form enctype="multipart/form-data" but I don't know how to solve it - I mean how to receive a file and the string from the input with one click of the submit button.
Thanks in advance.
| [
"You are using the POST method to send the data but then are trying to get it with the GET method.\ninstead of \nself.request.get('file_name')\n\ndo something like\nself.request.post('file_name')\n\n",
"The uploading example code works fine for me. Have you tried using that code exactly? Does it work for you, o... | [
0,
0
] | [] | [] | [
"cgi",
"google_app_engine",
"html",
"python"
] | stackoverflow_0003566458_cgi_google_app_engine_html_python.txt |
Q:
How add already captured screenshot to wx.BoxSizer?
My Python code:
self.images = wx.StaticBitmap(self, id=-1, pos=wx.DefaultPosition,
size=(200,150),
style= wx.SUNKEN_BORDER)
self.hbox = wx.BoxSizer(wx.HORIZONTAL)
self.sizer.Add(self.hbox) # my main sizer
#in function dynamically captured images
bmp = wx.BitmapFromImage(image)
self.images.SetBitmap(bmp)
self.hbox.Add(self.images, 1, wx.EXPAND | wx.ALL, 3)
...and after I want to add next image (another - I don't want to replace older) I have information "Adding a window to the same sizer twice?"
How can I resolve this problem?
A:
In your function for dynamically captured images, you need to create a new staticBitmap rather than setting self.images which overwrites and therefore replaces...
So instead of
self.images.SetBitmap(bmp)
you need to do
newImage = wx.StaticBitmap(self, id=-1
size=(200,150),
style= wx.SUNKEN_BORDER
bitmap = bmp)
self.hbox.Add(newImage, 1, wx.EXPAND | wx.ALL, 3)
self.SetSizerAndFit(self.sizer)
self.Refresh()
self.Layout()
| How add already captured screenshot to wx.BoxSizer? | My Python code:
self.images = wx.StaticBitmap(self, id=-1, pos=wx.DefaultPosition,
size=(200,150),
style= wx.SUNKEN_BORDER)
self.hbox = wx.BoxSizer(wx.HORIZONTAL)
self.sizer.Add(self.hbox) # my main sizer
#in function dynamically captured images
bmp = wx.BitmapFromImage(image)
self.images.SetBitmap(bmp)
self.hbox.Add(self.images, 1, wx.EXPAND | wx.ALL, 3)
...and after I want to add next image (another - I don't want to replace older) I have information "Adding a window to the same sizer twice?"
How can I resolve this problem?
| [
"In your function for dynamically captured images, you need to create a new staticBitmap rather than setting self.images which overwrites and therefore replaces...\nSo instead of \nself.images.SetBitmap(bmp)\nyou need to do \nnewImage = wx.StaticBitmap(self, id=-1\n size=(200,150),\n ... | [
3
] | [] | [] | [
"python",
"wxpython",
"wxwidgets"
] | stackoverflow_0003566528_python_wxpython_wxwidgets.txt |
Q:
Python module installed or not installed?
How can I check if my Python module is successfully installed.
I did:
python setup.py install
inside the folder where my module was downloaded.
Now, I can see that this resulted in a folder inside this location:
/usr/lib/python2.4/site-packages (I can see my module folder is inside here)
Now I am using PHP to execute a script from this module:
exec("/usr/bin/python /usr/lib/python2.4/site-packages/MyModule/myModule script.py -v pixfx.xml 2>&1", $output, $return);
This runs the script.py file but does not load modules which this script requires.
This script has code like this:
#! /usr/bin/env python
import sys
import os
import getopt
import re
from myModule.ttLib import TTFont // this is line60 as I have removed comments
I get this error:
Traceback (most recent call last): File "/usr/lib/python2.4/site-packages/MyModule/myModule/script.py", line 60, in ? from myModule.ttLib import TTFont ImportError: No module named myModule.ttLib
Does this mean there could be some problem with the way my module was installed.
or
How do I check if the module is installed correctly....
I also tried to do this in SSH terminal:
help('modules')
This listed a load of modules but my module name was missing.
Any help?
****** EDIT {Solved} ******
Reinstalling the module solved it.
Its funny that what I used online SSH tool provided by Mediatemple, it didnt install the module correctly.
Later when I installed using Terminal from my Mac computer, everything worked.
Just thought I will add this for other who might face similar problem.
Thanks
A:
You can check that the Python interpreter that you are calling sees your module by doing:
/usr/bin/python -c "import MyModule"
This command should simply import MyModule/__init__.py and not complain about MyModule not being found.
Since there are many modules in your code, you actually want to create a package, not a module.
To do so, you can simply add an empty __init__.py file in MyModule/ and all its subpackages, so as to indicate that you have a package (i.e. is a folder that contains many modules).
If your ttLib is in MyModule/myModule/ttLib/, you can do the same and add an empty __init__.py file in MyModule/ and MyModule/myModule/, so as to declare that MyModule and MyModule/myModule are packages; you can then simply do:
from MyModule.myModule.ttLib import …
Hope this helps! The full documentation for packages can be found on the official site.
A:
I am not an expert in Python, but one way to debug this is to launch the python prompt, and do import myModule then, some simple command that uses that module's constructs. If this works then your module installation is not the issue. If not your module wasnt installed.
A:
You should see more than just the directory creation /usr/lib/python2.4/site-packages.
A:
Did you tell python to look under /usr/lib/python2.4/site-packages/MyModule/ for your module(s)? (You need to put a *.pth file in /usr/lib/python2.4/site-packages/ for that, or maybe you should not put them into an extra directory.)
Try the following in a python shell:
>>> import sys
>>> sys.path
What does that print? Does it include '/usr/lib/python2.4/site-packages/MyModule'?
A:
I reinstalled the module and everything works fine.
It seems the module was not installed correctly.
| Python module installed or not installed? | How can I check if my Python module is successfully installed.
I did:
python setup.py install
inside the folder where my module was downloaded.
Now, I can see that this resulted in a folder inside this location:
/usr/lib/python2.4/site-packages (I can see my module folder is inside here)
Now I am using PHP to execute a script from this module:
exec("/usr/bin/python /usr/lib/python2.4/site-packages/MyModule/myModule script.py -v pixfx.xml 2>&1", $output, $return);
This runs the script.py file but does not load modules which this script requires.
This script has code like this:
#! /usr/bin/env python
import sys
import os
import getopt
import re
from myModule.ttLib import TTFont // this is line60 as I have removed comments
I get this error:
Traceback (most recent call last): File "/usr/lib/python2.4/site-packages/MyModule/myModule/script.py", line 60, in ? from myModule.ttLib import TTFont ImportError: No module named myModule.ttLib
Does this mean there could be some problem with the way my module was installed.
or
How do I check if the module is installed correctly....
I also tried to do this in SSH terminal:
help('modules')
This listed a load of modules but my module name was missing.
Any help?
****** EDIT {Solved} ******
Reinstalling the module solved it.
Its funny that what I used online SSH tool provided by Mediatemple, it didnt install the module correctly.
Later when I installed using Terminal from my Mac computer, everything worked.
Just thought I will add this for other who might face similar problem.
Thanks
| [
"You can check that the Python interpreter that you are calling sees your module by doing:\n/usr/bin/python -c \"import MyModule\"\n\nThis command should simply import MyModule/__init__.py and not complain about MyModule not being found.\nSince there are many modules in your code, you actually want to create a pack... | [
1,
0,
0,
0,
0
] | [] | [] | [
"php",
"python"
] | stackoverflow_0003563205_php_python.txt |
Q:
Python unix timestamp conversion and timezone
Hey all! Ive got timezone troubles.
I have a time stamp of 2010-07-26 23:35:03
What I really want to do is subtract 15 minutes from that time.
My method was going to be a simple conversion to unix time, subtract the seconds and convert back. Simple right?
My problem is that python adjusts the returned unix time using my local timezone, currently eastern daylight savings time which I believe is GMT -4.
So when I do this:
# packet[20] holds the time stamp
unix_time_value = (mktime(packet[20].timetuple()))
I get 1280201703 which is Tue, 27 Jul 2010 03:35:03. I can do this:
unix_time_value = (mktime(packet[20].timetuple())) - (4 * 3600)
but now I have to check for eastern standard time which is -5 GMT and adjust the (4 * 3600) to (5 * 3600). Is there any way to tell python to not use my local timezone and just convert the darn timestamp OR is there an easy way to take packet[20] and subtract 15 minutes?
A:
Subtract datetime.timedelta(seconds=15*60).
A:
The online docs have a handy table (what you call "unix time" is more properly called "UTC", for "Universal Time Coordinate", and "seconds since the epoch" is a "timestamp" as a float...):
Use the following functions to convert
between time representations:
From To Use
seconds since the epoch struct_time in UTC gmtime()
seconds since the epoch struct_time in local time localtime()
struct_time in UTC seconds since the epoch calendar.timegm()
struct_time in local time seconds since the epoch mktime()
where the unqualified function names come from the time module (since that's where the docs are;-). So, since you apparently start with a struct_time in UTC, use calendar.timegm() to get the timestamp (AKA "seconds since the epoch"), subtract 15 * 60 = 900 (since the units of measure are seconds), and put the resulting "seconds since the epoch" back into a struct_time in UTC with time.gmtime. Or, use time.mktime and time.localtime if you prefer to work in local times (but that might give problem if the 15 minutes can straddle the instant in which it switches to DST or back -- always working in UTC is much sounder).
Of course, to use calendar.timegm, you'll need an import calendar in your code (imports are usually best placed at the top of the script or module).
A:
Scroll down and read about subtracting from a date: http://pleac.sourceforge.net/pleac_python/datesandtimes.html
| Python unix timestamp conversion and timezone | Hey all! Ive got timezone troubles.
I have a time stamp of 2010-07-26 23:35:03
What I really want to do is subtract 15 minutes from that time.
My method was going to be a simple conversion to unix time, subtract the seconds and convert back. Simple right?
My problem is that python adjusts the returned unix time using my local timezone, currently eastern daylight savings time which I believe is GMT -4.
So when I do this:
# packet[20] holds the time stamp
unix_time_value = (mktime(packet[20].timetuple()))
I get 1280201703 which is Tue, 27 Jul 2010 03:35:03. I can do this:
unix_time_value = (mktime(packet[20].timetuple())) - (4 * 3600)
but now I have to check for eastern standard time which is -5 GMT and adjust the (4 * 3600) to (5 * 3600). Is there any way to tell python to not use my local timezone and just convert the darn timestamp OR is there an easy way to take packet[20] and subtract 15 minutes?
| [
"Subtract datetime.timedelta(seconds=15*60).\n",
"The online docs have a handy table (what you call \"unix time\" is more properly called \"UTC\", for \"Universal Time Coordinate\", and \"seconds since the epoch\" is a \"timestamp\" as a float...):\n\nUse the following functions to convert\n between time represe... | [
6,
6,
1
] | [] | [] | [
"python"
] | stackoverflow_0003567425_python.txt |
Q:
Combine SimpleXMLRPCServer and BaseHTTPRequestHandler in Python
Because cross-domain xmlrpc requests are not possible in JavaScript
I need to create a Python app which exposes both some HTML through HTTP and an XML-RPC service on the same domain.
Creating an HTTP request handler and SimpleXMLRPCServer in python is quite easy,
but they both have to listen on a different port, which means a different domain.
Is there a way to create something that will listen on a single port on the localhost
and expose both the HTTPRequestHandler and XMLRPCRequest handler?
Right now I have two different services:
httpServer = HTTPServer(('localhost',8001), HttpHandler);
xmlRpcServer = SimpleXMLRPCServer(('localhost',8000),requestHandler=RequestHandler)
Update
I cannot install Apache on the device
The hosted page will be a single html page
The only client will be the device on witch the python service runs itself
A:
Both of them subclass of SocketServer.TCPServer. There must be someway to refactor them so that once server instance can dispatch to both.
An easier alternative may be to keep the HTTPServer in front and proxy XML RPC to the SimpleXMLRPCServer instance.
A:
The solution was actually quite simple, based on Wai Yip Tung's reply:
All I had to do was keep using the SimpleXMLRPCServer instance,
but modify the handler:
class RequestHandler(SimpleXMLRPCRequestHandler):
rpc_paths = ('/RPC2',)
def do_GET(self):
#implementation here
This will cause the handler to respond to GET requests as well as the original POST (XML-RPC) requests.
A:
Using HTTPServer for providing contents is not a good idea. You should use a webserver like Apache and use Python as CGI (or a more advanced interface like mod_wsgi).
Then, the webserver is running on one port and you can server HTML directly over the webserver and write as many CGI scripts as you like in Python, as example one for XMLRPC requests using CGIXMLRPCRequestHandler.
class MyFuncs:
def div(self, x, y) : return x // y
handler = CGIXMLRPCRequestHandler()
handler.register_function(pow)
handler.register_function(lambda x,y: x+y, 'add')
handler.register_introspection_functions()
handler.register_instance(MyFuncs())
handler.handle_request()
| Combine SimpleXMLRPCServer and BaseHTTPRequestHandler in Python | Because cross-domain xmlrpc requests are not possible in JavaScript
I need to create a Python app which exposes both some HTML through HTTP and an XML-RPC service on the same domain.
Creating an HTTP request handler and SimpleXMLRPCServer in python is quite easy,
but they both have to listen on a different port, which means a different domain.
Is there a way to create something that will listen on a single port on the localhost
and expose both the HTTPRequestHandler and XMLRPCRequest handler?
Right now I have two different services:
httpServer = HTTPServer(('localhost',8001), HttpHandler);
xmlRpcServer = SimpleXMLRPCServer(('localhost',8000),requestHandler=RequestHandler)
Update
I cannot install Apache on the device
The hosted page will be a single html page
The only client will be the device on witch the python service runs itself
| [
"Both of them subclass of SocketServer.TCPServer. There must be someway to refactor them so that once server instance can dispatch to both.\nAn easier alternative may be to keep the HTTPServer in front and proxy XML RPC to the SimpleXMLRPCServer instance.\n",
"The solution was actually quite simple, based on Wai... | [
2,
2,
0
] | [] | [] | [
"httpserver",
"python",
"simplexmlrpcserver"
] | stackoverflow_0003561140_httpserver_python_simplexmlrpcserver.txt |
Q:
How to use named parameters in Python methods that are defaulting to a class level value?
Usage scenario:
# case #1 - for classes
a = MyClass() # default logger is None
a = MyClass(logger="a") # set the default logger to be "a"
a.test(logger="b") # this means that logger will be "b" only inside this method
a.test(logger=None) # this means that logger will be None but only inside this method
a.test() # here logger should defaults to the value specified when object was initialized ("a")
How can I implement MyClass in order to be able to use it as above?
Let's assume that I have several methods inside MyClass that can accept the logger named parameter so I would appreciate a solution that does not require to add a lot of duplicate code at the beginning of each test...() method.
I read about the sentinel example, but this does not work for classes and I would not like to add a global variable to keep the sentinel object inside.
A:
_sentinel = object()
class MyClass(object):
def __init__(self, logger=None):
self.logger = logger
def test(self, logger=_sentinel):
if logger is _sentinel: logger = self.logger
# in case you want to use this inside a function from your module use:
_sentinel = object()
logger = None
def test(logger=_sentinel)
if logger is _sentinel: logger = globals().get('logger')
two core ideas: capturing the set of named values that may be (or may not be) locally overridden into a keywords-parameters dict; using a sentinel object as the default value to uniquely identify whether a certain named argument has been explicitly passed or not (None is often used for this purpose, but when, as here, you want None as a "first class value" for the parameter, a unique sentinel object will do just as well).
A:
class MyClass(object):
def __init__(self, logger=None):
self.logger = logger
def test(self, **kwargs):
logger = kwargs.get("logger", self.logger)
# use logger, which is sourced as given in OP
Notes
The use of **kwargs is necessary as you're allowing None values for the logger named variable in MyClass.test. You could do away with this if you picked some other sentinel value (but None is most common).
It was unclear in the original question if you wanted a class or instance default. The one given above is an instance default, that is the default logger across all MyClass instances is None, set in the MyClass constructor.
A:
class MyClass(object):
def __init__(self, logger = None):
self.logger = logger
def test(self, **kwargs):
logger = self.logger
if kwargs.has_key("logger"):
logger = kwargs.get(logger)
print "logger is %s" logger.name
Brief explanation: test starts off by assuming that it is going to use the instance logger. However if an explicit logger is passed in as command line argument it will be used instead. If logger = None is passed as a key word argument then no logger is used.
| How to use named parameters in Python methods that are defaulting to a class level value? | Usage scenario:
# case #1 - for classes
a = MyClass() # default logger is None
a = MyClass(logger="a") # set the default logger to be "a"
a.test(logger="b") # this means that logger will be "b" only inside this method
a.test(logger=None) # this means that logger will be None but only inside this method
a.test() # here logger should defaults to the value specified when object was initialized ("a")
How can I implement MyClass in order to be able to use it as above?
Let's assume that I have several methods inside MyClass that can accept the logger named parameter so I would appreciate a solution that does not require to add a lot of duplicate code at the beginning of each test...() method.
I read about the sentinel example, but this does not work for classes and I would not like to add a global variable to keep the sentinel object inside.
| [
"_sentinel = object()\n\nclass MyClass(object):\n def __init__(self, logger=None):\n self.logger = logger\n def test(self, logger=_sentinel):\n if logger is _sentinel: logger = self.logger\n\n# in case you want to use this inside a function from your module use:\n_sentinel = object()\nlogger = None\ndef tes... | [
9,
3,
1
] | [] | [] | [
"named_parameters",
"python"
] | stackoverflow_0003567618_named_parameters_python.txt |
Q:
how do I get variables from one wx notebook page to a different wx notebook page?
I am wondering how one would get a variable from one page to another from a wx notebook. I am thinking there should be some way to reference a variable if I know the variable name and page id. For example if I had the following code, how would I reference variable x from panel y and vice versa
import wx
class PanelX(wx.Panel):
def __init__(self, parent):
wx.Panel.__init__(self, parent)
x = 3
class PanelY(wx.Panel):
def __init__(self, parent):
wx.Panel.__init__(self, parent)
y=4
class MainFrame(wx.Frame):
def __init__(self):
wx.Frame.__init__(self, None, title="Main Frame", size = (500,450))
p = wx.Panel(self)
nb = wx.Notebook(p)
nb.AddPage(PanelX(nb), "Panel X")
nb.AddPage(PanelY(nb), "Panel Y")
sizer = wx.BoxSizer()
sizer.Add(nb, 1, wx.EXPAND)
p.SetSizer(sizer)
if __name__ == "__main__":
app = wx.App()
MainFrame().Show()
app.MainLoop()
A:
The variables you're creating in your panels aren't "saved" in the class - they're a local variable used in the constructor, and discarded from memory as soon as that method's executed.
You'll have to create your variables with "self" in front of them -- self.x = 3
This will create "instance variables" - variables that have different values depending on the class instance they belong to.
You can get a page from a Notebook by using its GetPage method. Here's your example modified:
import wx
class PanelX(wx.Panel):
def __init__(self, parent):
wx.Panel.__init__(self, parent)
self.x = 3
class PanelY(wx.Panel):
def __init__(self, parent):
wx.Panel.__init__(self, parent)
self.y = 4
class MainFrame(wx.Frame):
def __init__(self):
wx.Frame.__init__(self, None, title="Main Frame", size = (500,450))
p = wx.Panel(self)
nb = wx.Notebook(p)
nb.AddPage(PanelX(nb), "Panel X")
nb.AddPage(PanelY(nb), "Panel Y")
sizer = wx.BoxSizer()
sizer.Add(nb, 1, wx.EXPAND)
p.SetSizer(sizer)
page = nb.GetPage(0)
print "PanelX's X value is %s" % page.x
page = nb.GetPage(1)
print "PanelY's Y value is %s" % page.y
if __name__ == "__main__":
app = wx.App()
MainFrame().Show()
app.MainLoop()
| how do I get variables from one wx notebook page to a different wx notebook page? | I am wondering how one would get a variable from one page to another from a wx notebook. I am thinking there should be some way to reference a variable if I know the variable name and page id. For example if I had the following code, how would I reference variable x from panel y and vice versa
import wx
class PanelX(wx.Panel):
def __init__(self, parent):
wx.Panel.__init__(self, parent)
x = 3
class PanelY(wx.Panel):
def __init__(self, parent):
wx.Panel.__init__(self, parent)
y=4
class MainFrame(wx.Frame):
def __init__(self):
wx.Frame.__init__(self, None, title="Main Frame", size = (500,450))
p = wx.Panel(self)
nb = wx.Notebook(p)
nb.AddPage(PanelX(nb), "Panel X")
nb.AddPage(PanelY(nb), "Panel Y")
sizer = wx.BoxSizer()
sizer.Add(nb, 1, wx.EXPAND)
p.SetSizer(sizer)
if __name__ == "__main__":
app = wx.App()
MainFrame().Show()
app.MainLoop()
| [
"The variables you're creating in your panels aren't \"saved\" in the class - they're a local variable used in the constructor, and discarded from memory as soon as that method's executed.\nYou'll have to create your variables with \"self\" in front of them -- self.x = 3\nThis will create \"instance variables\" - v... | [
5
] | [] | [] | [
"python",
"wxpython"
] | stackoverflow_0003567225_python_wxpython.txt |
Q:
Using python ctypes to call io_submit in Linux
I'm trying to call io_submit using python ctypes.
The code I'm writing is supposed to work on both 32 and 64-bit Intel/AMD architectures, but here I'll focus on 64 bits.
I have defined the following:
def PADDED64(type, name1, name2):
return [(name1, type), (name2, type)]
def PADDEDptr64(type, name1, name2):
return [(name1, type)]
def PADDEDul64(name1, name2):
return [(name1, ctypes.c_ulong)]
class IOVec(ctypes.Structure):
_fields_ = [("iov_base", ctypes.c_void_p), ("iov_len", ctypes.c_size_t)]
class IOCBDataCommon64(ctypes.Structure):
_fields_ = PADDEDptr64(ctypes.c_void_p, "buf", "__pad1") + \
PADDEDul64("nbytes", "__pad2") + \
[("offset", ctypes.c_longlong), ("__pad3", ctypes.c_longlong), ("flags", ctypes.c_uint), ("resfd", ctypes.c_uint)]
class IOCBDataVector(ctypes.Structure):
_fields_ = [("vec", ctypes.POINTER(IOVec)), ("nr", ctypes.c_int), ("offset", ctypes.c_longlong)]
class IOCBDataPoll64(ctypes.Structure):
_fields_ = PADDED64(ctypes.c_int, "events", "__pad1")
class SockAddr(ctypes.Structure):
_fields_ = [("sa_family", ctypes.c_ushort), ("sa_data", ctypes.c_char * 14)]
class IOCBDataSockAddr(ctypes.Structure):
_fields_ = [("addr", ctypes.POINTER(SockAddr)), ("len", ctypes.c_int)]
class IOCBDataUnion64(ctypes.Union):
_fields_ = [("c", IOCBDataCommon64), ("v", IOCBDataVector), ("poll", IOCBDataPoll64), ("saddr", IOCBDataSockAddr)]
class IOCB64(ctypes.Structure):
_fields_ = PADDEDptr64(ctypes.c_void_p, "data" , "__pad1") + \
PADDED64(ctypes.c_uint, "key", "__pad2") + \
[("aio_lio_opcode", ctypes.c_short), ("aio_reqprio", ctypes.c_short), ("aio_fildes", ctypes.c_int), ("u", IOCBDataUnion64)]
class Timespec(ctypes.Structure):
_fields_ = [("tv_sec", ctypes.c_long), ("tv_nsec", ctypes.c_long)]
class IOEvent64(ctypes.Structure):
_fields_ = PADDEDptr64(ctypes.c_void_p, "data", "__pad1") + \
PADDEDptr64(ctypes.POINTER(IOCB64), "obj", "__pad2") + \
PADDEDul64("res", "__pad3") + \
PADDEDul64("res2", "__pad4")
I have a wrapper class called AIOCommands:
class AIOCommands:
def __init__(self, aioCommandList):
self.__commandList = aioCommandList
self.__iocbs = (IOCB64 * len(self.__commandList))()
for i in range(len(self.__commandList)):
self.__commandList[i].initialize(self.__iocbs[i])
def size(self):
return len(self.__iocbs)
def getIOCBArray(self):
return self.__iocbs
I have defined the arguments and the return value of io_submit:
class Executor:
def __init__(self, aioLibraryPath):
self.__aio = ctypes.CDLL(aioLibraryPath)
self.__aio.io_submit.argtypes = [self.aio_context_t, ctypes.c_long, ctypes.POINTER(ctypes.POINTER(IOCB64))]
self.__aio.io_submit.restype = ctypes.c_long
Now, what should Executor.io_submit body look like? I tried:
def io_submit(self, aioContext, aioCommands):
iocbPtr = ctypes.cast(aioCommands.getIOCBArray(), ctypes.POINTER(self.iocb_t))
return self.__aio.io_submit(aioContext, aioCommands.size(), ctypes.byref(iocbPtr))
But I get a segmentation fault whenever the length of aioCommandList is greater than 1.
When the list contains just 1 command, the code works as expected.
Could this be a problem with my structure definitions? I've tried to imitate the definitions in libaio.h (assuming only little-endian architectures will be supported):
#if defined(__i386__) /* little endian, 32 bits */
#define PADDED(x, y) x; unsigned y
#define PADDEDptr(x, y) x; unsigned y
#define PADDEDul(x, y) unsigned long x; unsigned y
#elif defined(__ia64__) || defined(__x86_64__) || defined(__alpha__)
#define PADDED(x, y) x, y
#define PADDEDptr(x, y) x
#define PADDEDul(x, y) unsigned long x
#elif defined(__powerpc64__) /* big endian, 64 bits */
#define PADDED(x, y) unsigned y; x
#define PADDEDptr(x,y) x
#define PADDEDul(x, y) unsigned long x
#elif defined(__PPC__) /* big endian, 32 bits */
#define PADDED(x, y) unsigned y; x
#define PADDEDptr(x, y) unsigned y; x
#define PADDEDul(x, y) unsigned y; unsigned long x
#elif defined(__s390x__) /* big endian, 64 bits */
#define PADDED(x, y) unsigned y; x
#define PADDEDptr(x,y) x
#define PADDEDul(x, y) unsigned long x
#elif defined(__s390__) /* big endian, 32 bits */
#define PADDED(x, y) unsigned y; x
#define PADDEDptr(x, y) unsigned y; x
#define PADDEDul(x, y) unsigned y; unsigned long x
#else
#error endian?
#endif
struct io_iocb_poll {
PADDED(int events, __pad1);
}; /* result code is the set of result flags or -'ve errno */
struct io_iocb_sockaddr {
struct sockaddr *addr;
int len;
}; /* result code is the length of the sockaddr, or -'ve errno */
struct io_iocb_common {
PADDEDptr(void *buf, __pad1);
PADDEDul(nbytes, __pad2);
long long offset;
long long __pad3;
unsigned flags;
unsigned resfd;
}; /* result code is the amount read or -'ve errno */
struct io_iocb_vector {
const struct iovec *vec;
int nr;
long long offset;
}; /* result code is the amount read or -'ve errno */
struct iocb {
PADDEDptr(void *data, __pad1); /* Return in the io completion event */
PADDED(unsigned key, __pad2); /* For use in identifying io requests */
short aio_lio_opcode;
short aio_reqprio;
int aio_fildes;
union {
struct io_iocb_common c;
struct io_iocb_vector v;
struct io_iocb_poll poll;
struct io_iocb_sockaddr saddr;
} u;
};
Any help would be appreciated, I've been stuck on this for several hours.
A:
The way I understand it is that the iocbpp argument to io_submit() is an array of pointers to struct iocb.
This seems to be reinforced with the Linux-specific example here: http://voinici.ceata.org/~sana/blog/?p=248 and by the EINVAL error documentation here: http://linux.die.net/man/2/io_submit (array subscripting takes precedence over dereferencing)
What you have provided to io_submit() is a reference to an array of struct iocb. You will surely get a segfault as io_submit dereferences bogus memory addresses as it iterates through the iocbpp array. The first element (index 0) will work fine since there is no memory offset to access it.
edit
Another example here: http://www.xmailserver.org/eventfd-aio-test.c
| Using python ctypes to call io_submit in Linux | I'm trying to call io_submit using python ctypes.
The code I'm writing is supposed to work on both 32 and 64-bit Intel/AMD architectures, but here I'll focus on 64 bits.
I have defined the following:
def PADDED64(type, name1, name2):
return [(name1, type), (name2, type)]
def PADDEDptr64(type, name1, name2):
return [(name1, type)]
def PADDEDul64(name1, name2):
return [(name1, ctypes.c_ulong)]
class IOVec(ctypes.Structure):
_fields_ = [("iov_base", ctypes.c_void_p), ("iov_len", ctypes.c_size_t)]
class IOCBDataCommon64(ctypes.Structure):
_fields_ = PADDEDptr64(ctypes.c_void_p, "buf", "__pad1") + \
PADDEDul64("nbytes", "__pad2") + \
[("offset", ctypes.c_longlong), ("__pad3", ctypes.c_longlong), ("flags", ctypes.c_uint), ("resfd", ctypes.c_uint)]
class IOCBDataVector(ctypes.Structure):
_fields_ = [("vec", ctypes.POINTER(IOVec)), ("nr", ctypes.c_int), ("offset", ctypes.c_longlong)]
class IOCBDataPoll64(ctypes.Structure):
_fields_ = PADDED64(ctypes.c_int, "events", "__pad1")
class SockAddr(ctypes.Structure):
_fields_ = [("sa_family", ctypes.c_ushort), ("sa_data", ctypes.c_char * 14)]
class IOCBDataSockAddr(ctypes.Structure):
_fields_ = [("addr", ctypes.POINTER(SockAddr)), ("len", ctypes.c_int)]
class IOCBDataUnion64(ctypes.Union):
_fields_ = [("c", IOCBDataCommon64), ("v", IOCBDataVector), ("poll", IOCBDataPoll64), ("saddr", IOCBDataSockAddr)]
class IOCB64(ctypes.Structure):
_fields_ = PADDEDptr64(ctypes.c_void_p, "data" , "__pad1") + \
PADDED64(ctypes.c_uint, "key", "__pad2") + \
[("aio_lio_opcode", ctypes.c_short), ("aio_reqprio", ctypes.c_short), ("aio_fildes", ctypes.c_int), ("u", IOCBDataUnion64)]
class Timespec(ctypes.Structure):
_fields_ = [("tv_sec", ctypes.c_long), ("tv_nsec", ctypes.c_long)]
class IOEvent64(ctypes.Structure):
_fields_ = PADDEDptr64(ctypes.c_void_p, "data", "__pad1") + \
PADDEDptr64(ctypes.POINTER(IOCB64), "obj", "__pad2") + \
PADDEDul64("res", "__pad3") + \
PADDEDul64("res2", "__pad4")
I have a wrapper class called AIOCommands:
class AIOCommands:
def __init__(self, aioCommandList):
self.__commandList = aioCommandList
self.__iocbs = (IOCB64 * len(self.__commandList))()
for i in range(len(self.__commandList)):
self.__commandList[i].initialize(self.__iocbs[i])
def size(self):
return len(self.__iocbs)
def getIOCBArray(self):
return self.__iocbs
I have defined the arguments and the return value of io_submit:
class Executor:
def __init__(self, aioLibraryPath):
self.__aio = ctypes.CDLL(aioLibraryPath)
self.__aio.io_submit.argtypes = [self.aio_context_t, ctypes.c_long, ctypes.POINTER(ctypes.POINTER(IOCB64))]
self.__aio.io_submit.restype = ctypes.c_long
Now, what should Executor.io_submit body look like? I tried:
def io_submit(self, aioContext, aioCommands):
iocbPtr = ctypes.cast(aioCommands.getIOCBArray(), ctypes.POINTER(self.iocb_t))
return self.__aio.io_submit(aioContext, aioCommands.size(), ctypes.byref(iocbPtr))
But I get a segmentation fault whenever the length of aioCommandList is greater than 1.
When the list contains just 1 command, the code works as expected.
Could this be a problem with my structure definitions? I've tried to imitate the definitions in libaio.h (assuming only little-endian architectures will be supported):
#if defined(__i386__) /* little endian, 32 bits */
#define PADDED(x, y) x; unsigned y
#define PADDEDptr(x, y) x; unsigned y
#define PADDEDul(x, y) unsigned long x; unsigned y
#elif defined(__ia64__) || defined(__x86_64__) || defined(__alpha__)
#define PADDED(x, y) x, y
#define PADDEDptr(x, y) x
#define PADDEDul(x, y) unsigned long x
#elif defined(__powerpc64__) /* big endian, 64 bits */
#define PADDED(x, y) unsigned y; x
#define PADDEDptr(x,y) x
#define PADDEDul(x, y) unsigned long x
#elif defined(__PPC__) /* big endian, 32 bits */
#define PADDED(x, y) unsigned y; x
#define PADDEDptr(x, y) unsigned y; x
#define PADDEDul(x, y) unsigned y; unsigned long x
#elif defined(__s390x__) /* big endian, 64 bits */
#define PADDED(x, y) unsigned y; x
#define PADDEDptr(x,y) x
#define PADDEDul(x, y) unsigned long x
#elif defined(__s390__) /* big endian, 32 bits */
#define PADDED(x, y) unsigned y; x
#define PADDEDptr(x, y) unsigned y; x
#define PADDEDul(x, y) unsigned y; unsigned long x
#else
#error endian?
#endif
struct io_iocb_poll {
PADDED(int events, __pad1);
}; /* result code is the set of result flags or -'ve errno */
struct io_iocb_sockaddr {
struct sockaddr *addr;
int len;
}; /* result code is the length of the sockaddr, or -'ve errno */
struct io_iocb_common {
PADDEDptr(void *buf, __pad1);
PADDEDul(nbytes, __pad2);
long long offset;
long long __pad3;
unsigned flags;
unsigned resfd;
}; /* result code is the amount read or -'ve errno */
struct io_iocb_vector {
const struct iovec *vec;
int nr;
long long offset;
}; /* result code is the amount read or -'ve errno */
struct iocb {
PADDEDptr(void *data, __pad1); /* Return in the io completion event */
PADDED(unsigned key, __pad2); /* For use in identifying io requests */
short aio_lio_opcode;
short aio_reqprio;
int aio_fildes;
union {
struct io_iocb_common c;
struct io_iocb_vector v;
struct io_iocb_poll poll;
struct io_iocb_sockaddr saddr;
} u;
};
Any help would be appreciated, I've been stuck on this for several hours.
| [
"The way I understand it is that the iocbpp argument to io_submit() is an array of pointers to struct iocb. \nThis seems to be reinforced with the Linux-specific example here: http://voinici.ceata.org/~sana/blog/?p=248 and by the EINVAL error documentation here: http://linux.die.net/man/2/io_submit (array subscrip... | [
1
] | [] | [] | [
"c",
"ctypes",
"linux",
"python",
"stack"
] | stackoverflow_0003565417_c_ctypes_linux_python_stack.txt |
Q:
PyQt: How to catch mouse-over-event of QTableWidget-headers?
what I want to do is to change the text of a QLable, everytime I hover with the mouse over the horizontalHeaders of my QTableWidget. How can I do that? Everytime I'm over a new header I need a signal and the index of the header. Hope someone of you has an idea. There must be a function, because if you hover over the headers, the background of the header changes.
A:
Install an event filter that on the horizontalHeader() by using QObject.installEventFilter():
class HeaderViewFilter(QObject):
# ...
def eventFilter(self, object, event):
if event.type() == QEvent.HoverEvent:
pass # do something useful
# you could emit a signal here if you wanted
self. filter = HeaderViewFilter()
horizontalHeader().installEventFilter(self.filter)
With self.filter in place, you'll be notified of the necessary events and can respond accordingly.
UPDATE: it looks like HoverEvent isn't quite what we need. In order to get hover events, you need to setAttribute needs to be called with Qt::WA_Hover. From the documentation on this attribute:
Forces Qt to generate paint events when the mouse enters or leaves the widget. This feature is typically used when implementing custom styles; see the Styles example for details.
So yes, it generates events only when you enter or leave the widget.
Since the same header is used for all rows or all columns, we'll actually want to know about where the mouse is within the widget. Here's some new code which should handle mouse moves:
class HeaderViewFilter(QObject):
def __init__(self, parent, header, *args):
super(HeaderViewFilter, self).__init__(parent, *args)
self.header = header
def eventFilter(self, object, event):
if event.type() == QEvent.MouseMove:
logicalIndex = self.header.logicalIndexAt(event.pos())
# you could emit a signal here if you wanted
self.filter = HeaderViewFilter()
self.horizontalHeader = yourView.horizontalHeader()
self.horizontalHeader.setMouseTracking(1)
self.horizontalHeader.installEventFilter(self.filter)
As you can see above, the main concept still applies. We either need an event filter so that we can watch for events or we need to subclass QHeaderView so that it will provide us with the necessary information.
| PyQt: How to catch mouse-over-event of QTableWidget-headers? | what I want to do is to change the text of a QLable, everytime I hover with the mouse over the horizontalHeaders of my QTableWidget. How can I do that? Everytime I'm over a new header I need a signal and the index of the header. Hope someone of you has an idea. There must be a function, because if you hover over the headers, the background of the header changes.
| [
"Install an event filter that on the horizontalHeader() by using QObject.installEventFilter():\nclass HeaderViewFilter(QObject):\n # ...\n def eventFilter(self, object, event):\n if event.type() == QEvent.HoverEvent:\n pass # do something useful\n # you could emit a signal here if... | [
2
] | [] | [] | [
"header",
"mousehover",
"pyqt",
"python",
"qtablewidget"
] | stackoverflow_0003562447_header_mousehover_pyqt_python_qtablewidget.txt |
Q:
How do you directly write to a request body in Python
I am currently implementing code to call out to an API where the post request body needs to contain several columns of data in csv format.
e.g.
Col1, Col2, Col3
1, 2, 3
4, 5, 6
etc, with the content type header is set to 'text/csv'
How do I directly write to the request body?
I have a coworker who is doing the same thing as I am in Java and the Apache httpclient lib simply has a setRequestBody method.
Is there something similar in httplib, urllib (1,2) or pyCurl? Thanks.
A:
Any HTTP client will give you some way to set the request body. For example, httplib.HTTPConnection.request takes an optional body parameter that allows you to pass request data. Same with urllib2.urlopen (there it's called data). I've never used PycURL myself but it definitely provides some way to include a body in the request.
| How do you directly write to a request body in Python | I am currently implementing code to call out to an API where the post request body needs to contain several columns of data in csv format.
e.g.
Col1, Col2, Col3
1, 2, 3
4, 5, 6
etc, with the content type header is set to 'text/csv'
How do I directly write to the request body?
I have a coworker who is doing the same thing as I am in Java and the Apache httpclient lib simply has a setRequestBody method.
Is there something similar in httplib, urllib (1,2) or pyCurl? Thanks.
| [
"Any HTTP client will give you some way to set the request body. For example, httplib.HTTPConnection.request takes an optional body parameter that allows you to pass request data. Same with urllib2.urlopen (there it's called data). I've never used PycURL myself but it definitely provides some way to include a body ... | [
2
] | [] | [] | [
"csv",
"httplib",
"pycurl",
"python",
"request"
] | stackoverflow_0003568530_csv_httplib_pycurl_python_request.txt |
Q:
Which cross platform scripting language should we adopt for a group of DBAs?
I wanted to get the community's feedback on a language choice our team is looking to make in the near future. We are a software developer, and I work in a team of Oracle and SQL Server DBAs supporting a cross platform Java application which runs on Oracle Application Server. We have SQL Server and Oracle code bases, and support customers on Windows, Solaris and Linux servers.
Many of the tasks we do on a frequent basis are insufficiently automated, and where they are, tend to be much more automated via shell scripts, with little equivalent functionality on Windows. Unfortunately, we now have this problem of redeveloping scripts and so on, on two platforms. So, I wish for us to choose a cross platform language to script in, instead of using Bash and awkwardly translating to Cygwin or Batch files where necessary.
It would need to be:
Dynamic (so don't suggest Java or C!)
Easily available on each platform (Windows, Solaris, Linux, perhaps AIX)
Require very little in the way of setup (root access not always available!)
Be easy for shell scripters, i.e. DBAs, to adopt, who are not hardcore developers.
Be easy to understand other people's code
Friendly with SQL Server and Oracle, without messing around.
A few nice XML features wouldn't go amiss.
It would be preferable if it would run on the JVM, since this will almost always be installed on every server (certainly on all application servers) and we have many Java developers in our company, so sticking to the JVM makes sense. This isn't exclusive though, since I know Python is a very viable language here.
I have created a list of options, but there may be more: Groovy, Scala, Jython, Python, Ruby, Perl.
No one has much experience of any, except I have quite a lot of Java and Groovy experience myself. We are looking for something dynamic, easy to pick up, will work with both SQL server and Oracle effortlessly, has some XML simplifying features, and that won't be a turnoff for DBAs. Many of us are very Bash orientated - what could move us away from this addiction?
What are people's opinions on this?
thanks!
Chris
A:
You can opt for Python. Its dynamic(interpreted) , is available on Windows/Linux/Solaris, has easy to read syntax so that your code maintenance is easy. There modules/libraries for Oracle interaction and various other database servers as well. there are also library support for XML. All 7 points are covered.
A:
I think your best three options are Groovy, Python, and Scala. All three let you write code at a high level (compared to C/Java). Python has its own perfectly adequate DB bindings, and Groovy and Scala can use ones made for Java.
The advantages of Python are that it is widely used already, so there are tons of tools, libraries, expertise, etc. available around it. It has a particularly clean syntax, which makes working with it aesthetically pleasing. The disadvantages are that it is slow (which may not be an issue for you), untyped (so you have runtime errors instead of compile-time errors), and you can't really switch back and forth between Jython and Python, so you have to pick whether you want the large amount of Python stuff, or the huge amount of Java stuff, minus a lot of the nice Python stuff.
The advantages of Groovy are that you know it already and it interoperates well with Java libraries. Its disadvantages are also slowness and lack of static typing. (So in contrast to Python, the choice is: do you value Python's clean syntax and wide adoption more, or do you value the vast set of Java libraries more in a language made to work well in that environment?)
The advantages of Scala are that it is statically typed (i.e. if the code gets past the compiler, it has a greater chance of working), is fast (as fast as Java if you care to work hard enough), and interoperates well with Java libraries. The disadvantages are that it imposes a bit more work on you to make the static typing work (though far, far less than Java while simultaneously being more safe), and that the canonical style for Scala is a hybrid object/functional blend that feels more different than the other two (and thus requires more training to use at full effectiveness IMO). In contrast to Groovy, the question would be whether familiarity and ease of getting started is more important than speed and correctness.
Personally, I now do almost all of my work in Scala because my work requires speed and because the compiler catches those sort of errors in coding that I commonly make (so it is the only language I've used where I am not surprised when large blocks of code run correctly once I get them to compile). But I've had good experiences with Python in other contexts--interfacing with large databases seems like a good use-case.
(I'd rule out Perl as being harder to maintain with no significant benefits over e.g. Python, and I'd rule out Ruby as being not enough more powerful than Python to warrant the less-intuitive syntax and lower rate of adoption/tool availability.)
A:
The XML thing almost calls for Scala. Now, I love Scala, but I suggest Python here.
A:
If you want a dynamic language and there already a lot of Java developers in your company, then Groovy seems an obvious choice, as it's very easy for Java developers to pick up (also, you said you have some Groovy experience yourself).
Groovy runs on the JVM and has excellent support for working with XML. It also has provides a very straightforward syntax for working with relational databases.
It comes with a console and a shell (though I never use the shell) which make it really easy to test/run scripts or snippets of Groovy code.
A:
Although I prefer working on the JVM, one thing that turns me off is having to spin up a JVM to run a script. If you can work in a REPL this is not such a big deal, but it really slows you down when doing edit-run-debug scripting.
Now of course Oracle has a lot of Java stuff where interaction moght be needed, but that is something only you can estimate how important it is. For plain Oracle DB work I have seen very little Java and lots fo PLSQL/SQL.
If your dba now do their work in bash, then they will very likely pickup perl in a short time as there is a nice, logical progression path.
Since ruby was designed to be an improved version of perl, it might fit in that category too. Actually python also.
Scala is statically typed like Java, albeit with much better type inference.
My recommendation would be to go the Perl route. The CPAN is its ace in the hole, you do not have to deal with the OO stuff which might turn off some DBA's (although it is there for the power users).
A:
I've been in a similar situation, though on a small scale. The previous situation was that any automation on the SQL Server DBs was done with VBScript, which I did start out using. As I wanted something cross-platform (and less annoying than VBScript) I went with Python.
What I learnt is:
Obviously you want a language that comes with libraries to access your databases comfortably. I wasn't too concerned with abstracting the differences away (ie, I still wrote SQL queries in the relevant dialect, with parameters). However, I'd be a bit less happy with PHP, for example, which has only very vendor-specific libraries and functions for certain databases. I see it's not on your list.
THE major obstacle was authentication. If your SQL Server uses Windows domain authentication, you'll have to work to get in. Another system also had specific needs as it required RSA tokens to be supported.
For the second point, Python is quite versatile enough to work around the difficulties, but it was getting into "badly supported" territory, especially on Windows. It was easy to work around the first problem from a Windows host, and for a Unix host it is possible though not easy. If you're using SQL Server authentication, it becomes a lot easier.
From your other choices, I'd expect various ways of authenticating and DB drivers to exist for Perl, which philosophically would be easier for DBAs used to shell scripting. Ruby - no experience, but it tends to have spotty support for some of the odder authentication methods and connectors. Scala I'd expect to be a bit too much of a "programmer's programming language" -- OOO and FP? It's a very interesting language, but maybe not the one I'd chose at first. As for the rest of the Java-based options, I don't have an opinion, but do check that all the connection types you want to make are solidly supported.
| Which cross platform scripting language should we adopt for a group of DBAs? | I wanted to get the community's feedback on a language choice our team is looking to make in the near future. We are a software developer, and I work in a team of Oracle and SQL Server DBAs supporting a cross platform Java application which runs on Oracle Application Server. We have SQL Server and Oracle code bases, and support customers on Windows, Solaris and Linux servers.
Many of the tasks we do on a frequent basis are insufficiently automated, and where they are, tend to be much more automated via shell scripts, with little equivalent functionality on Windows. Unfortunately, we now have this problem of redeveloping scripts and so on, on two platforms. So, I wish for us to choose a cross platform language to script in, instead of using Bash and awkwardly translating to Cygwin or Batch files where necessary.
It would need to be:
Dynamic (so don't suggest Java or C!)
Easily available on each platform (Windows, Solaris, Linux, perhaps AIX)
Require very little in the way of setup (root access not always available!)
Be easy for shell scripters, i.e. DBAs, to adopt, who are not hardcore developers.
Be easy to understand other people's code
Friendly with SQL Server and Oracle, without messing around.
A few nice XML features wouldn't go amiss.
It would be preferable if it would run on the JVM, since this will almost always be installed on every server (certainly on all application servers) and we have many Java developers in our company, so sticking to the JVM makes sense. This isn't exclusive though, since I know Python is a very viable language here.
I have created a list of options, but there may be more: Groovy, Scala, Jython, Python, Ruby, Perl.
No one has much experience of any, except I have quite a lot of Java and Groovy experience myself. We are looking for something dynamic, easy to pick up, will work with both SQL server and Oracle effortlessly, has some XML simplifying features, and that won't be a turnoff for DBAs. Many of us are very Bash orientated - what could move us away from this addiction?
What are people's opinions on this?
thanks!
Chris
| [
"You can opt for Python. Its dynamic(interpreted) , is available on Windows/Linux/Solaris, has easy to read syntax so that your code maintenance is easy. There modules/libraries for Oracle interaction and various other database servers as well. there are also library support for XML. All 7 points are covered.\n",
... | [
6,
5,
4,
3,
1,
0
] | [] | [] | [
"groovy",
"jython",
"python",
"scala",
"shell"
] | stackoverflow_0003564177_groovy_jython_python_scala_shell.txt |
Q:
Displaying QComboBox text rather than index value in QStyledItemDelegate
So I have a model and one of the columns contains a country. However because I want to display a combo box to choose the country from a list of options, I don't store the country name in the model directly. Instead I store an index value into a list of allowable countries. This allows me to use a QComboBox in my form view as recommended in the Qt docs. The problem is I also have a table view, and the table view displays the index integer, not the country name. I have set up a QStyledItemDelegate and implemented createEditor so if you click in the world cell it does pop up the ComboBox, but when you're not editing the country you see the index value.
I'm part way to a solution. I have implemented a paint method to do the work, but it's displaying the value offset to it's proper position and I can't figure out how to get it to display correctly. I think option.rect.topLeft() in the render method is wrong, but I can't figure out how to set the drawing correctly.
def paint(self, painter, option, index):
if index.column() == COUNTRY:
painter.save()
countryRef, ok = inex.data().toInt()
countryStr = country_list[countryRef]
widget = QLineEdit()
widget.setGeometry(option.rect)
widget.setText(countryStr)
widget.render(painter, option.rect.topLeft())
painter.store()
else:
QStylyedItemDelegate.paint(self, painter, option, index)
A:
Models have different item data roles for different data. There's a Qt::DisplayRole, Qt::EditRole, and a Qt::UserRole among others. In this case, you want to display something different than your actual data, so add a new role, let's say Qt::UserRole+1 that's used for your index.
Then you want your delegate to set the appropriate data in setModelData:
def setModelData(self, editor, model, index):
cbIndex = editor.currentIndex()
model.setData(index, cbIndex, Qt.UserRole+1)
# we want a nice displayable though
model.setData(index, countryIndexToDisplayable(cbIndex), Qt.DisplayRole)
Of course, you'll retrieve the data to set in the editor in a similar fashion:
def setEditorData(self, widget, index):
widget.setCurrentIndex(index.data(Qt.UserRole+1))
Depending on your model and view, you might be able to use Qt::EditRole which is pretty much intended for that purpose. If you then use a native type for the display role, you shouldn't need to do any custom painting, although you can if you like.
| Displaying QComboBox text rather than index value in QStyledItemDelegate | So I have a model and one of the columns contains a country. However because I want to display a combo box to choose the country from a list of options, I don't store the country name in the model directly. Instead I store an index value into a list of allowable countries. This allows me to use a QComboBox in my form view as recommended in the Qt docs. The problem is I also have a table view, and the table view displays the index integer, not the country name. I have set up a QStyledItemDelegate and implemented createEditor so if you click in the world cell it does pop up the ComboBox, but when you're not editing the country you see the index value.
I'm part way to a solution. I have implemented a paint method to do the work, but it's displaying the value offset to it's proper position and I can't figure out how to get it to display correctly. I think option.rect.topLeft() in the render method is wrong, but I can't figure out how to set the drawing correctly.
def paint(self, painter, option, index):
if index.column() == COUNTRY:
painter.save()
countryRef, ok = inex.data().toInt()
countryStr = country_list[countryRef]
widget = QLineEdit()
widget.setGeometry(option.rect)
widget.setText(countryStr)
widget.render(painter, option.rect.topLeft())
painter.store()
else:
QStylyedItemDelegate.paint(self, painter, option, index)
| [
"Models have different item data roles for different data. There's a Qt::DisplayRole, Qt::EditRole, and a Qt::UserRole among others. In this case, you want to display something different than your actual data, so add a new role, let's say Qt::UserRole+1 that's used for your index.\nThen you want your delegate to ... | [
4
] | [] | [] | [
"pyqt",
"pyqt4",
"python"
] | stackoverflow_0003568422_pyqt_pyqt4_python.txt |
Q:
using DES/3DES with python
what is the best module /package in python to use des /3des for encryption /decryption.
could someone provide example to encrypt data with des/3des on python.
A:
pyDes can be used for both, DES and 3DES. Sample usage:
from pyDes import *
data = "Please encrypt my data"
k = des("DESCRYPT", CBC, "\0\0\0\0\0\0\0\0", pad=None, padmode=PAD_PKCS5)
d = k.encrypt(data)
print "Encrypted: %r" % d
print "Decrypted: %r" % k.decrypt(d)
assert k.decrypt(d, padmode=PAD_PKCS5) == data
An alternative is the Chillkat Python Encryption Library which supports a lot of encryption algorithms (including DES & 3DES), but it is not free. Sample usage:
crypt.put_CryptAlgorithm("des")
crypt.put_CipherMode("cbc")
crypt.put_KeyLength(64)
crypt.put_PaddingScheme(0)
crypt.put_EncodingMode("hex")
ivHex = "0001020304050607"
crypt.SetEncodedIV(ivHex,"hex")
keyHex = "0001020304050607"
crypt.SetEncodedKey(keyHex,"hex")
encStr = crypt.encryptStringENC("The quick brown fox jumps over the lazy dog.")
print encStr
decStr = crypt.decryptStringENC(encStr)
print decStr
Anyway, I hope that you are aware that neither DES nor 3DES are considered paritcularly safe nowadays, there are many better alternatives (AES in the first place if you want to stick to standards, or Twofish, Blowfish, etc...)
A:
You can use the M2Crypto Python wrapper for OpenSSL. It has the advantage of being fast (as fast as OpenSSL), but the disadvantage of the documentation being limited.
Here is the example from my answer to "How to 3DES encrypt in Python using the M2Crypto wrapper?"
with open(keyfile, 'rb') as f:
key = f.read()
encrypt = 1
cipher = Cipher(alg='des_ede3_ecb', key=key, op=encrypt, iv='\0'*16)
ciphertext = cipher.update(plaintext)
ciphertext += cipher.final()
| using DES/3DES with python | what is the best module /package in python to use des /3des for encryption /decryption.
could someone provide example to encrypt data with des/3des on python.
| [
"pyDes can be used for both, DES and 3DES. Sample usage:\nfrom pyDes import *\n\ndata = \"Please encrypt my data\"\nk = des(\"DESCRYPT\", CBC, \"\\0\\0\\0\\0\\0\\0\\0\\0\", pad=None, padmode=PAD_PKCS5)\nd = k.encrypt(data)\nprint \"Encrypted: %r\" % d\nprint \"Decrypted: %r\" % k.decrypt(d)\nassert k.decrypt(d, pad... | [
21,
7
] | [] | [] | [
"3des",
"cryptography",
"python"
] | stackoverflow_0002435283_3des_cryptography_python.txt |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.