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:
urllib.urlopen isn't working. Is there a workaround?
I'm getting a getaddress error and after doing some sleuthing, it looks like it might be my corporate intranet not allowing the connection (I'm assuming due to security, although it is strange that IE works but won't allow Python to open a url). Is there a safe way to get around this?
Here's the exact error:
Traceback (most recent call last):
File "<pyshell#1>", line 1, in <module>
b = urllib.urlopen('http://www.google.com')
File "C:\Python26\lib\urllib.py", line 87, in urlopen
return opener.open(url)
File "C:\Python26\lib\urllib.py", line 203, in open
return getattr(self, name)(url)
File "C:\Python26\lib\urllib.py", line 342, in open_http
h.endheaders()
File "C:\Python26\lib\httplib.py", line 868, in endheaders
self._send_output()
File "C:\Python26\lib\httplib.py", line 740, in _send_output
self.send(msg)
File "C:\Python26\lib\httplib.py", line 699, in send
self.connect()
File "C:\Python26\lib\httplib.py", line 683, in connect
self.timeout)
File "C:\Python26\lib\socket.py", line 498, in create_connection
for res in getaddrinfo(host, port, 0, SOCK_STREAM):
IOError: [Errno socket error] [Errno 11001] getaddrinfo failed
More info: I also get this error with urllib2.urlopen
A:
You probably need to fill in proxy information.
import urllib2
proxy_handler = urllib2.ProxyHandler({'http': 'http://yourcorporateproxy:12345/'})
proxy_auth_handler = urllib2.HTTPBasicAuthHandler()
proxy_auth_handler.add_password('realm', 'host', 'username', 'password')
opener = urllib2.build_opener(proxy_handler, proxy_auth_handler)
opener.open('http://www.stackoverflow.com')
A:
Check you are using the correct proxy.
You can get the proxy information by using urllib.getproxies (note: getproxies does not work with dynamic proxy configuration, like when using PAC).
Update As per information about empty proxy list, I would suggest using an urlopener, with the proxy name and information.
Some good information about how use proxies urlopeners:
Urllib manual
Michael Foord's introduction to urllib
A:
Possibly this is a DNS issue, try urlopen with the IP address of the web server you're accessing, i.e.
import urllib
URL="http://66.102.11.99" # www.google.com
f = urllib.urlopen(URL)
f.read()
If this succeeds, then it's probably a DNS issue rather than a proxy issue (but you should also check your proxy setup).
A:
Looks like a DNS problem.
Since you are using Windows, you can try run this command
nslookup www.google.com
To check if the web address can be resolved successfully.
If not, it is a network setting issue
If OK, then we have to look at possible alternative causes
A:
I was facing the same issue.
In my system the proxy configuration is through a .PAC file.
So i opended that file, took out the default proxy url, for me it was http://168.219.61.250:8080/
Following test code worked for me :
import urllib2
proxy_support = urllib2.ProxyHandler({'http': 'http://168.219.61.250:8080/'})
opener = urllib2.build_opener(proxy_support)
urllib2.install_opener(opener)
response = urllib2.urlopen('http://python.org/')
html = response.read()
print html
You might need to add some more code, if your proxy requires authentication
Hope this helps!!
|
urllib.urlopen isn't working. Is there a workaround?
|
I'm getting a getaddress error and after doing some sleuthing, it looks like it might be my corporate intranet not allowing the connection (I'm assuming due to security, although it is strange that IE works but won't allow Python to open a url). Is there a safe way to get around this?
Here's the exact error:
Traceback (most recent call last):
File "<pyshell#1>", line 1, in <module>
b = urllib.urlopen('http://www.google.com')
File "C:\Python26\lib\urllib.py", line 87, in urlopen
return opener.open(url)
File "C:\Python26\lib\urllib.py", line 203, in open
return getattr(self, name)(url)
File "C:\Python26\lib\urllib.py", line 342, in open_http
h.endheaders()
File "C:\Python26\lib\httplib.py", line 868, in endheaders
self._send_output()
File "C:\Python26\lib\httplib.py", line 740, in _send_output
self.send(msg)
File "C:\Python26\lib\httplib.py", line 699, in send
self.connect()
File "C:\Python26\lib\httplib.py", line 683, in connect
self.timeout)
File "C:\Python26\lib\socket.py", line 498, in create_connection
for res in getaddrinfo(host, port, 0, SOCK_STREAM):
IOError: [Errno socket error] [Errno 11001] getaddrinfo failed
More info: I also get this error with urllib2.urlopen
|
[
"You probably need to fill in proxy information.\nimport urllib2\nproxy_handler = urllib2.ProxyHandler({'http': 'http://yourcorporateproxy:12345/'})\nproxy_auth_handler = urllib2.HTTPBasicAuthHandler()\nproxy_auth_handler.add_password('realm', 'host', 'username', 'password')\n\nopener = urllib2.build_opener(proxy_handler, proxy_auth_handler)\nopener.open('http://www.stackoverflow.com')\n\n",
"Check you are using the correct proxy.\nYou can get the proxy information by using urllib.getproxies (note: getproxies does not work with dynamic proxy configuration, like when using PAC).\nUpdate As per information about empty proxy list, I would suggest using an urlopener, with the proxy name and information.\nSome good information about how use proxies urlopeners:\n\nUrllib manual\nMichael Foord's introduction to urllib\n\n",
"Possibly this is a DNS issue, try urlopen with the IP address of the web server you're accessing, i.e.\nimport urllib\nURL=\"http://66.102.11.99\" # www.google.com\nf = urllib.urlopen(URL)\nf.read()\n\nIf this succeeds, then it's probably a DNS issue rather than a proxy issue (but you should also check your proxy setup).\n",
"Looks like a DNS problem. \nSince you are using Windows, you can try run this command\nnslookup www.google.com\n\nTo check if the web address can be resolved successfully.\nIf not, it is a network setting issue\nIf OK, then we have to look at possible alternative causes\n",
"I was facing the same issue.\nIn my system the proxy configuration is through a .PAC file.\nSo i opended that file, took out the default proxy url, for me it was http://168.219.61.250:8080/\nFollowing test code worked for me :\nimport urllib2\n\nproxy_support = urllib2.ProxyHandler({'http': 'http://168.219.61.250:8080/'})\nopener = urllib2.build_opener(proxy_support)\nurllib2.install_opener(opener)\nresponse = urllib2.urlopen('http://python.org/')\nhtml = response.read()\nprint html\n\nYou might need to add some more code, if your proxy requires authentication\nHope this helps!!\n"
] |
[
7,
4,
2,
2,
2
] |
[] |
[] |
[
"python",
"url"
] |
stackoverflow_0001076958_python_url.txt
|
Q:
Is it possible to fetch a https page via an authenticating proxy with urllib2 in Python 2.5?
I'm trying to add authenticating proxy support to an existing script, as it is the script connects to a https url (with urllib2.Request and urllib2.urlopen), scrapes the page and performs some actions based on what it has found. Initially I had hoped this would be as easy as simply adding a urllib2.ProxyHandler({"http": MY_PROXY}) as an arg to urllib2.build_opener which in turn is passed to urllib2.install_opener. Unfortunately this doesn't seem to work when attempting to do a urllib2.Request(ANY_HTTPS_PAGE). Googling around lends me to believe that the proxy support in urllib2 in python 2.5 does not support https urls. This surprised me to say the least.
There appear to be solutions floating around the web, for example http://bugs.python.org/issue1424152 contains a patch for urllib2 and httplib which purports to solve the issue (when I tried it the issue I began to get the following error instead: urllib2.URLError: <urlopen error (1, 'error:140770FC:SSL routines:SSL23_GET_SERVER_HELLO:unknown protocol')>). There is a cookbook recipe here http://code.activestate.com/recipes/456195 which I am planning to try next. All in all though I'm surprised this isn't supported "out of the box", which makes me wonder if I'm simply missing out on an obvious solutions, so in short — has anyone got a simple method for fetching https pages using an authenticating proxy with urllib2 in Python 2.5? Ideally this would work:
import urllib2
#perhaps the dictionary below needs a corresponding "https" entry?
#That doesn't seem to work out of the box.
proxy_handler = urllib2.ProxyHandler({"http": "http://user:pass@myproxy:port"})
urllib2.install_opener( urllib2.build_opener( urllib2.HTTPHandler,
urllib2.HTTPSHandler,
proxy_handler ))
request = urllib2.Request(A_HTTPS_URL)
response = urllib2.urlopen( request)
print response.read()
Many Thanks
A:
You may want to look into httplib2. One of the examples claims support for SOCKS proxies if the socks module is installed.
|
Is it possible to fetch a https page via an authenticating proxy with urllib2 in Python 2.5?
|
I'm trying to add authenticating proxy support to an existing script, as it is the script connects to a https url (with urllib2.Request and urllib2.urlopen), scrapes the page and performs some actions based on what it has found. Initially I had hoped this would be as easy as simply adding a urllib2.ProxyHandler({"http": MY_PROXY}) as an arg to urllib2.build_opener which in turn is passed to urllib2.install_opener. Unfortunately this doesn't seem to work when attempting to do a urllib2.Request(ANY_HTTPS_PAGE). Googling around lends me to believe that the proxy support in urllib2 in python 2.5 does not support https urls. This surprised me to say the least.
There appear to be solutions floating around the web, for example http://bugs.python.org/issue1424152 contains a patch for urllib2 and httplib which purports to solve the issue (when I tried it the issue I began to get the following error instead: urllib2.URLError: <urlopen error (1, 'error:140770FC:SSL routines:SSL23_GET_SERVER_HELLO:unknown protocol')>). There is a cookbook recipe here http://code.activestate.com/recipes/456195 which I am planning to try next. All in all though I'm surprised this isn't supported "out of the box", which makes me wonder if I'm simply missing out on an obvious solutions, so in short — has anyone got a simple method for fetching https pages using an authenticating proxy with urllib2 in Python 2.5? Ideally this would work:
import urllib2
#perhaps the dictionary below needs a corresponding "https" entry?
#That doesn't seem to work out of the box.
proxy_handler = urllib2.ProxyHandler({"http": "http://user:pass@myproxy:port"})
urllib2.install_opener( urllib2.build_opener( urllib2.HTTPHandler,
urllib2.HTTPSHandler,
proxy_handler ))
request = urllib2.Request(A_HTTPS_URL)
response = urllib2.urlopen( request)
print response.read()
Many Thanks
|
[
"You may want to look into httplib2. One of the examples claims support for SOCKS proxies if the socks module is installed.\n"
] |
[
1
] |
[] |
[] |
[
"https",
"proxy",
"python",
"urllib2"
] |
stackoverflow_0001152980_https_proxy_python_urllib2.txt
|
Q:
Stopping a Long-Running Subprocess
I create a subprocess using subprocess.Popen() that runs for a long time. It is called from its own thread, and the thread is blocked until the subprocess completes/returns.
I want to be able to interrupt the subprocess so the process terminates when I want.
Any ideas?
A:
I think you're looking for Popen.terminate or .kill function. They were added in python 2.6.
|
Stopping a Long-Running Subprocess
|
I create a subprocess using subprocess.Popen() that runs for a long time. It is called from its own thread, and the thread is blocked until the subprocess completes/returns.
I want to be able to interrupt the subprocess so the process terminates when I want.
Any ideas?
|
[
"I think you're looking for Popen.terminate or .kill function. They were added in python 2.6.\n"
] |
[
4
] |
[] |
[] |
[
"python",
"subprocess"
] |
stackoverflow_0001153407_python_subprocess.txt
|
Q:
Simple python / Beautiful Soup type question
I'm trying to do some simple string manipulation with the href attribute of a hyperlink extracted using Beautiful Soup:
from BeautifulSoup import BeautifulSoup
soup = BeautifulSoup('<a href="http://www.some-site.com/">Some Hyperlink</a>')
href = soup.find("a")["href"]
print href
print href[href.indexOf('/'):]
All I get is:
Traceback (most recent call last):
File "test.py", line 5, in <module>
print href[href.indexOf('/'):]
AttributeError: 'unicode' object has no attribute 'indexOf'
How should I convert whatever href is into a normal string?
A:
Python strings do not have an indexOf method.
Use href.index('/')
href.find('/') is similar. But find returns -1 if the string is not found, while index raises a ValueError.
So the correct thing is to use index (since '...'[-1] will return the last character of the string).
A:
href is a unicode string. If you need the regular string, then use
regular_string = str(href)
A:
You mean find(), not indexOf().
Python docs on strings.
|
Simple python / Beautiful Soup type question
|
I'm trying to do some simple string manipulation with the href attribute of a hyperlink extracted using Beautiful Soup:
from BeautifulSoup import BeautifulSoup
soup = BeautifulSoup('<a href="http://www.some-site.com/">Some Hyperlink</a>')
href = soup.find("a")["href"]
print href
print href[href.indexOf('/'):]
All I get is:
Traceback (most recent call last):
File "test.py", line 5, in <module>
print href[href.indexOf('/'):]
AttributeError: 'unicode' object has no attribute 'indexOf'
How should I convert whatever href is into a normal string?
|
[
"Python strings do not have an indexOf method.\nUse href.index('/')\nhref.find('/') is similar. But find returns -1 if the string is not found, while index raises a ValueError.\nSo the correct thing is to use index (since '...'[-1] will return the last character of the string).\n",
"href is a unicode string. If you need the regular string, then use \nregular_string = str(href)\n\n",
"You mean find(), not indexOf().\nPython docs on strings.\n"
] |
[
10,
0,
0
] |
[] |
[] |
[
"beautifulsoup",
"python",
"string"
] |
stackoverflow_0001153167_beautifulsoup_python_string.txt
|
Q:
Listing builtin functions and methods (Python)
I have came up with this:
[a for a in dir(__builtins__) if str(type(getattr(__builtins__,a))) == "<type 'builtin_function_or_method'>"]
I know its ugly. Can you show me a better/more pythonic way of doing this?
A:
There is the inspect module:
import inspect
filter(inspect.isbuiltin, (member for name, member in inspect.getmembers(__builtins__)))
Edit: reading the documentation a little more closely, I came up with this variant that doesn't use __getattr__
import inspect
members = (member for name, member in inspect.getmembers(__builtins__))
filter(inspect.isbuiltin, members)
A:
Here's a variation without getattr:
import inspect
[n.__name__ for n in __builtins__.__dict__.values() if inspect.isbuiltin(n)]
And if you want the actual function pointers:
import inspect
[n for n in __builtins__.__dict__.values() if inspect.isbuiltin(n)]
|
Listing builtin functions and methods (Python)
|
I have came up with this:
[a for a in dir(__builtins__) if str(type(getattr(__builtins__,a))) == "<type 'builtin_function_or_method'>"]
I know its ugly. Can you show me a better/more pythonic way of doing this?
|
[
"There is the inspect module:\nimport inspect\n\nfilter(inspect.isbuiltin, (member for name, member in inspect.getmembers(__builtins__)))\n\nEdit: reading the documentation a little more closely, I came up with this variant that doesn't use __getattr__\nimport inspect\n\nmembers = (member for name, member in inspect.getmembers(__builtins__))\nfilter(inspect.isbuiltin, members)\n\n",
"Here's a variation without getattr:\nimport inspect\n[n.__name__ for n in __builtins__.__dict__.values() if inspect.isbuiltin(n)]\n\nAnd if you want the actual function pointers:\nimport inspect\n[n for n in __builtins__.__dict__.values() if inspect.isbuiltin(n)]\n\n"
] |
[
6,
2
] |
[] |
[] |
[
"inspect",
"introspection",
"module",
"python"
] |
stackoverflow_0001153690_inspect_introspection_module_python.txt
|
Q:
How would you inherit from and override the django model classes to create a listOfStringsField?
I want to create a new type of field for django models that is basically a ListOfStrings. So in your model code you would have the following:
models.py:
from django.db import models
class ListOfStringsField(???):
???
class myDjangoModelClass():
myName = models.CharField(max_length=64)
myFriends = ListOfStringsField() #
other.py:
myclass = myDjangoModelClass()
myclass.myName = "bob"
myclass.myFriends = ["me", "myself", "and I"]
myclass.save()
id = myclass.id
loadedmyclass = myDjangoModelClass.objects.filter(id__exact=id)
myFriendsList = loadedclass.myFriends
# myFriendsList is a list and should equal ["me", "myself", "and I"]
How would you go about writing this field type, with the following stipulations?
We don't want to do create a field which just crams all the strings together and separates them with a token in one field like this. It is a good solution in some cases, but we want to keep the string data normalized so tools other than django can query the data.
The field should automatically create any secondary tables needed to store the string data.
The secondary table should ideally have only one copy of each unique string. This is optional, but would be nice to have.
Looking in the Django code it looks like I would want to do something similar to what ForeignKey is doing, but the documentation is sparse.
This leads to the following questions:
Can this be done?
Has it been done (and if so where)?
Is there any documentation on Django about how to extend and override their model classes, specifically their relationship classes? I have not seen a lot of documentation on that aspect of their code, but there is this.
This is comes from this question.
A:
There's some very good documentation on creating custom fields here.
However, I think you're overthinking this. It sounds like you actually just want a standard foreign key, but with the additional ability to retrieve all the elements as a single list. So the easiest thing would be to just use a ForeignKey, and define a get_myfield_as_list method on the model:
class Friends(model.Model):
name = models.CharField(max_length=100)
my_items = models.ForeignKey(MyModel)
class MyModel(models.Model):
...
def get_my_friends_as_list(self):
return ', '.join(self.friends_set.values_list('name', flat=True))
Now calling get_my_friends_as_list() on an instance of MyModel will return you a list of strings, as required.
A:
I also think you're going about this the wrong way. Trying to make a Django field create an ancillary database table is almost certainly the wrong approach. It would be very difficult to do, and would likely confuse third party developers if you are trying to make your solution generally useful.
If you're trying to store a denormalized blob of data in a single column, I'd take an approach similar to the one you linked to, serializing the Python data structure and storing it in a TextField. If you want tools other than Django to be able to operate on the data then you can serialize to JSON (or some other format that has wide language support):
from django.db import models
from django.utils import simplejson
class JSONDataField(models.TextField):
__metaclass__ = models.SubfieldBase
def to_python(self, value):
if value is None:
return None
if not isinstance(value, basestring):
return value
return simplejson.loads(value)
def get_db_prep_save(self, value):
if value is None:
return None
return simplejson.dumps(value)
If you just want a django Manager-like descriptor that lets you operate on a list of strings associated with a model then you can manually create a join table and use a descriptor to manage the relationship. It's not exactly what you need, but this code should get you started.
A:
What you have described sounds to me really similar to the tags.
So, why not using django tagging?
It works like a charm, you can install it independently from your application and its API is quite easy to use.
A:
Thanks for all those that answered. Even if I didn't use your answer directly the examples and links got me going in the right direction.
I am not sure if this is production ready, but it appears to be working in all my tests so far.
class ListValueDescriptor(object):
def __init__(self, lvd_parent, lvd_model_name, lvd_value_type, lvd_unique, **kwargs):
"""
This descriptor object acts like a django field, but it will accept
a list of values, instead a single value.
For example:
# define our model
class Person(models.Model):
name = models.CharField(max_length=120)
friends = ListValueDescriptor("Person", "Friend", "CharField", True, max_length=120)
# Later in the code we can do this
p = Person("John")
p.save() # we have to have an id
p.friends = ["Jerry", "Jimmy", "Jamail"]
...
p = Person.objects.get(name="John")
friends = p.friends
# and now friends is a list.
lvd_parent - The name of our parent class
lvd_model_name - The name of our new model
lvd_value_type - The value type of the value in our new model
This has to be the name of one of the valid django
model field types such as 'CharField', 'FloatField',
or a valid custom field name.
lvd_unique - Set this to true if you want the values in the list to
be unique in the table they are stored in. For
example if you are storing a list of strings and
the strings are always "foo", "bar", and "baz", your
data table would only have those three strings listed in
it in the database.
kwargs - These are passed to the value field.
"""
self.related_set_name = lvd_model_name.lower() + "_set"
self.model_name = lvd_model_name
self.parent = lvd_parent
self.unique = lvd_unique
# only set this to true if they have not already set it.
# this helps speed up the searchs when unique is true.
kwargs['db_index'] = kwargs.get('db_index', True)
filter = ["lvd_parent", "lvd_model_name", "lvd_value_type", "lvd_unique"]
evalStr = """class %s (models.Model):\n""" % (self.model_name)
evalStr += """ value = models.%s(""" % (lvd_value_type)
evalStr += self._params_from_kwargs(filter, **kwargs)
evalStr += ")\n"
if self.unique:
evalStr += """ parent = models.ManyToManyField('%s')\n""" % (self.parent)
else:
evalStr += """ parent = models.ForeignKey('%s')\n""" % (self.parent)
evalStr += "\n"
evalStr += """self.innerClass = %s\n""" % (self.model_name)
print evalStr
exec (evalStr) # build the inner class
def __get__(self, instance, owner):
value_set = instance.__getattribute__(self.related_set_name)
l = []
for x in value_set.all():
l.append(x.value)
return l
def __set__(self, instance, values):
value_set = instance.__getattribute__(self.related_set_name)
for x in values:
value_set.add(self._get_or_create_value(x))
def __delete__(self, instance):
pass # I should probably try and do something here.
def _get_or_create_value(self, x):
if self.unique:
# Try and find an existing value
try:
return self.innerClass.objects.get(value=x)
except django.core.exceptions.ObjectDoesNotExist:
pass
v = self.innerClass(value=x)
v.save() # we have to save to create the id.
return v
def _params_from_kwargs(self, filter, **kwargs):
"""Given a dictionary of arguments, build a string which
represents it as a parameter list, and filter out any
keywords in filter."""
params = ""
for key in kwargs:
if key not in filter:
value = kwargs[key]
params += "%s=%s, " % (key, value.__repr__())
return params[:-2] # chop off the last ', '
class Person(models.Model):
name = models.CharField(max_length=120)
friends = ListValueDescriptor("Person", "Friend", "CharField", True, max_length=120)
Ultimately I think this would still be better if it were pushed deeper into the django code and worked more like the ManyToManyField or the ForeignKey.
|
How would you inherit from and override the django model classes to create a listOfStringsField?
|
I want to create a new type of field for django models that is basically a ListOfStrings. So in your model code you would have the following:
models.py:
from django.db import models
class ListOfStringsField(???):
???
class myDjangoModelClass():
myName = models.CharField(max_length=64)
myFriends = ListOfStringsField() #
other.py:
myclass = myDjangoModelClass()
myclass.myName = "bob"
myclass.myFriends = ["me", "myself", "and I"]
myclass.save()
id = myclass.id
loadedmyclass = myDjangoModelClass.objects.filter(id__exact=id)
myFriendsList = loadedclass.myFriends
# myFriendsList is a list and should equal ["me", "myself", "and I"]
How would you go about writing this field type, with the following stipulations?
We don't want to do create a field which just crams all the strings together and separates them with a token in one field like this. It is a good solution in some cases, but we want to keep the string data normalized so tools other than django can query the data.
The field should automatically create any secondary tables needed to store the string data.
The secondary table should ideally have only one copy of each unique string. This is optional, but would be nice to have.
Looking in the Django code it looks like I would want to do something similar to what ForeignKey is doing, but the documentation is sparse.
This leads to the following questions:
Can this be done?
Has it been done (and if so where)?
Is there any documentation on Django about how to extend and override their model classes, specifically their relationship classes? I have not seen a lot of documentation on that aspect of their code, but there is this.
This is comes from this question.
|
[
"There's some very good documentation on creating custom fields here. \nHowever, I think you're overthinking this. It sounds like you actually just want a standard foreign key, but with the additional ability to retrieve all the elements as a single list. So the easiest thing would be to just use a ForeignKey, and define a get_myfield_as_list method on the model:\nclass Friends(model.Model):\n name = models.CharField(max_length=100)\n my_items = models.ForeignKey(MyModel)\n\nclass MyModel(models.Model):\n ...\n\n def get_my_friends_as_list(self):\n return ', '.join(self.friends_set.values_list('name', flat=True))\n\nNow calling get_my_friends_as_list() on an instance of MyModel will return you a list of strings, as required.\n",
"I also think you're going about this the wrong way. Trying to make a Django field create an ancillary database table is almost certainly the wrong approach. It would be very difficult to do, and would likely confuse third party developers if you are trying to make your solution generally useful.\nIf you're trying to store a denormalized blob of data in a single column, I'd take an approach similar to the one you linked to, serializing the Python data structure and storing it in a TextField. If you want tools other than Django to be able to operate on the data then you can serialize to JSON (or some other format that has wide language support):\nfrom django.db import models\nfrom django.utils import simplejson\n\nclass JSONDataField(models.TextField):\n __metaclass__ = models.SubfieldBase\n\n def to_python(self, value):\n if value is None: \n return None\n if not isinstance(value, basestring): \n return value\n return simplejson.loads(value)\n\n def get_db_prep_save(self, value):\n if value is None: \n return None\n return simplejson.dumps(value)\n\nIf you just want a django Manager-like descriptor that lets you operate on a list of strings associated with a model then you can manually create a join table and use a descriptor to manage the relationship. It's not exactly what you need, but this code should get you started.\n",
"What you have described sounds to me really similar to the tags.\nSo, why not using django tagging?\nIt works like a charm, you can install it independently from your application and its API is quite easy to use.\n",
"Thanks for all those that answered. Even if I didn't use your answer directly the examples and links got me going in the right direction.\nI am not sure if this is production ready, but it appears to be working in all my tests so far. \nclass ListValueDescriptor(object):\n\n def __init__(self, lvd_parent, lvd_model_name, lvd_value_type, lvd_unique, **kwargs):\n \"\"\"\n This descriptor object acts like a django field, but it will accept\n a list of values, instead a single value.\n For example:\n # define our model\n class Person(models.Model):\n name = models.CharField(max_length=120)\n friends = ListValueDescriptor(\"Person\", \"Friend\", \"CharField\", True, max_length=120)\n\n # Later in the code we can do this\n p = Person(\"John\")\n p.save() # we have to have an id\n p.friends = [\"Jerry\", \"Jimmy\", \"Jamail\"]\n ...\n p = Person.objects.get(name=\"John\")\n friends = p.friends\n # and now friends is a list.\n lvd_parent - The name of our parent class\n lvd_model_name - The name of our new model\n lvd_value_type - The value type of the value in our new model\n This has to be the name of one of the valid django\n model field types such as 'CharField', 'FloatField',\n or a valid custom field name.\n lvd_unique - Set this to true if you want the values in the list to\n be unique in the table they are stored in. For\n example if you are storing a list of strings and\n the strings are always \"foo\", \"bar\", and \"baz\", your\n data table would only have those three strings listed in\n it in the database.\n kwargs - These are passed to the value field.\n \"\"\"\n self.related_set_name = lvd_model_name.lower() + \"_set\"\n self.model_name = lvd_model_name\n self.parent = lvd_parent\n self.unique = lvd_unique\n\n # only set this to true if they have not already set it.\n # this helps speed up the searchs when unique is true.\n kwargs['db_index'] = kwargs.get('db_index', True)\n\n filter = [\"lvd_parent\", \"lvd_model_name\", \"lvd_value_type\", \"lvd_unique\"]\n\n evalStr = \"\"\"class %s (models.Model):\\n\"\"\" % (self.model_name)\n evalStr += \"\"\" value = models.%s(\"\"\" % (lvd_value_type)\n evalStr += self._params_from_kwargs(filter, **kwargs) \n evalStr += \")\\n\"\n if self.unique:\n evalStr += \"\"\" parent = models.ManyToManyField('%s')\\n\"\"\" % (self.parent)\n else:\n evalStr += \"\"\" parent = models.ForeignKey('%s')\\n\"\"\" % (self.parent)\n evalStr += \"\\n\"\n evalStr += \"\"\"self.innerClass = %s\\n\"\"\" % (self.model_name)\n\n print evalStr\n\n exec (evalStr) # build the inner class\n\n def __get__(self, instance, owner):\n value_set = instance.__getattribute__(self.related_set_name)\n l = []\n for x in value_set.all():\n l.append(x.value)\n\n return l\n\n def __set__(self, instance, values):\n value_set = instance.__getattribute__(self.related_set_name)\n for x in values:\n value_set.add(self._get_or_create_value(x))\n\n def __delete__(self, instance):\n pass # I should probably try and do something here.\n\n\n def _get_or_create_value(self, x):\n if self.unique:\n # Try and find an existing value\n try:\n return self.innerClass.objects.get(value=x)\n except django.core.exceptions.ObjectDoesNotExist:\n pass\n\n v = self.innerClass(value=x)\n v.save() # we have to save to create the id.\n return v\n\n def _params_from_kwargs(self, filter, **kwargs):\n \"\"\"Given a dictionary of arguments, build a string which \n represents it as a parameter list, and filter out any\n keywords in filter.\"\"\"\n params = \"\"\n for key in kwargs:\n if key not in filter:\n value = kwargs[key]\n params += \"%s=%s, \" % (key, value.__repr__())\n\n return params[:-2] # chop off the last ', '\n\nclass Person(models.Model):\n name = models.CharField(max_length=120)\n friends = ListValueDescriptor(\"Person\", \"Friend\", \"CharField\", True, max_length=120)\n\nUltimately I think this would still be better if it were pushed deeper into the django code and worked more like the ManyToManyField or the ForeignKey.\n"
] |
[
7,
5,
5,
2
] |
[
"I think what you want is a custom model field.\n"
] |
[
-1
] |
[
"django",
"django_models",
"inheritance",
"python"
] |
stackoverflow_0001126642_django_django_models_inheritance_python.txt
|
Q:
Change python file in place
I have a large xml file (40 Gb) that I need to split into smaller chunks. I am working with limited space, so is there a way to delete lines from the original file as I write them to new files?
Thanks!
A:
Say you want to split the file into N pieces, then simply start reading from the back of the file (more or less) and repeatedly call truncate:
Truncate the file's size. If the optional size argument is present, the file is truncated to (at most) that size. The size defaults to the current position. The current file position is not changed. ...
import os
import stat
BUF_SIZE = 4096
size = os.stat("large_file")[stat.ST_SIZE]
chunk_size = size // N
# or simply set a fixed chunk size based on your free disk space
c = 0
in_ = open("large_file", "r+")
while size > 0:
in_.seek(-min(size, chunk_size), 2)
# now you have to find a safe place to split the file at somehow
# just read forward until you found one
...
old_pos = in_.tell()
with open("small_chunk%2d" % (c, ), "w") as out:
b = in_.read(BUF_SIZE)
while len(b) > 0:
out.write(b)
b = in_.read(BUF_SIZE)
in_.truncate(old_pos)
size = old_pos
c += 1
Be careful, as I didn't test any of this. It might be needed to call flush after the truncate call, and I don't know how fast the file system is going to actually free up the space.
A:
If you're on Linux/Unix, why not use the split command like this guy does?
split --bytes=100m /input/file /output/dir/prefix
EDIT: then use csplit.
A:
I'm pretty sure there is, as I've even been able to edit/read from the source files of scripts I've run, but the biggest problem would probably be all the shifting that would be done if you started at the beginning of the file. On the other hand, if you go through the file and record all the starting positions of the lines, you could then go in reverse order of position to copy the lines out; once that's done, you could go back, take the new files, one at a time, and (if they're small enough), use readlines() to generate a list, reverse the order of the list, then seek to the beginning of the file and overwrite the lines in their old order with the lines in their new one.
(You would truncate the file after reading the first block of lines from the end by using the truncate() method, which truncates all data past the current file position if used without any arguments besides that of the file object, assuming you're using one of the classes or a subclass of one of the classes from the io package to read your file. You'd just have to make sure that the current file position ends up at the beginning of the last line to be written to a new file.)
EDIT: Based on your comment about having to make the separations at the proper closing tags, you'll probably also have to develop an algorithm to detect such tags (perhaps using the peek method), possibly using a regular expression.
A:
If time is not a major factor (or wear and tear on your disk drive):
Open handle to file
Read up to the size of your partition / logical break point (due to the xml)
Save the rest of your file to disk (not sure how python handles this as far as directly overwriting file or memory usage)
Write the partition to disk
goto 1
If Python does not give you this level of control, you may need to dive into C.
A:
You could always parse the XML file and write out say every 10000 elements to there own file. Look at the Incremental Parsing section of this link.
http://effbot.org/zone/element-iterparse.htm
A:
Here is my script...
import string
import os
from ftplib import FTP
# make ftp connection
ftp = FTP('server')
ftp.login('user', 'pwd')
ftp.cwd('/dir')
f1 = open('large_file.xml', 'r')
size = 0
split = False
count = 0
for line in f1:
if not split:
file = 'split_'+str(count)+'.xml'
f2 = open(file, 'w')
if count > 0:
f2.write('<?xml version="1.0"?>\n')
f2.write('<StartTag xmlns="http://www.blah/1.2.0">\n')
size = 0
count += 1
split = True
if size < 1073741824:
f2.write(line)
size += len(line)
elif str(line) == '</EndTag>\n':
f2.write(line)
f2.write('</EndEndTag>\n')
print('completed file %s' %str(count))
f2.close()
f2 = open(file, 'r')
print("ftp'ing file...")
ftp.storbinary('STOR ' + file, f2)
print('ftp done.')
split = False
f2.close()
os.remove(file)
else:
f2.write(line)
size += len(line)
|
Change python file in place
|
I have a large xml file (40 Gb) that I need to split into smaller chunks. I am working with limited space, so is there a way to delete lines from the original file as I write them to new files?
Thanks!
|
[
"Say you want to split the file into N pieces, then simply start reading from the back of the file (more or less) and repeatedly call truncate:\n\nTruncate the file's size. If the optional size argument is present, the file is truncated to (at most) that size. The size defaults to the current position. The current file position is not changed. ...\n\nimport os\nimport stat\n\nBUF_SIZE = 4096\nsize = os.stat(\"large_file\")[stat.ST_SIZE]\nchunk_size = size // N \n# or simply set a fixed chunk size based on your free disk space\nc = 0\n\nin_ = open(\"large_file\", \"r+\")\n\nwhile size > 0:\n in_.seek(-min(size, chunk_size), 2)\n # now you have to find a safe place to split the file at somehow\n # just read forward until you found one\n ...\n old_pos = in_.tell()\n with open(\"small_chunk%2d\" % (c, ), \"w\") as out:\n b = in_.read(BUF_SIZE)\n while len(b) > 0:\n out.write(b)\n b = in_.read(BUF_SIZE)\n in_.truncate(old_pos)\n size = old_pos\n c += 1\n\nBe careful, as I didn't test any of this. It might be needed to call flush after the truncate call, and I don't know how fast the file system is going to actually free up the space. \n",
"If you're on Linux/Unix, why not use the split command like this guy does?\nsplit --bytes=100m /input/file /output/dir/prefix\n\nEDIT: then use csplit.\n",
"I'm pretty sure there is, as I've even been able to edit/read from the source files of scripts I've run, but the biggest problem would probably be all the shifting that would be done if you started at the beginning of the file. On the other hand, if you go through the file and record all the starting positions of the lines, you could then go in reverse order of position to copy the lines out; once that's done, you could go back, take the new files, one at a time, and (if they're small enough), use readlines() to generate a list, reverse the order of the list, then seek to the beginning of the file and overwrite the lines in their old order with the lines in their new one.\n(You would truncate the file after reading the first block of lines from the end by using the truncate() method, which truncates all data past the current file position if used without any arguments besides that of the file object, assuming you're using one of the classes or a subclass of one of the classes from the io package to read your file. You'd just have to make sure that the current file position ends up at the beginning of the last line to be written to a new file.)\nEDIT: Based on your comment about having to make the separations at the proper closing tags, you'll probably also have to develop an algorithm to detect such tags (perhaps using the peek method), possibly using a regular expression.\n",
"If time is not a major factor (or wear and tear on your disk drive):\n\nOpen handle to file\nRead up to the size of your partition / logical break point (due to the xml)\nSave the rest of your file to disk (not sure how python handles this as far as directly overwriting file or memory usage)\nWrite the partition to disk\ngoto 1\n\nIf Python does not give you this level of control, you may need to dive into C.\n",
"You could always parse the XML file and write out say every 10000 elements to there own file. Look at the Incremental Parsing section of this link.\nhttp://effbot.org/zone/element-iterparse.htm\n",
"Here is my script...\nimport string\nimport os\nfrom ftplib import FTP\n\n# make ftp connection\nftp = FTP('server')\nftp.login('user', 'pwd')\nftp.cwd('/dir')\n\nf1 = open('large_file.xml', 'r')\n\nsize = 0\nsplit = False\ncount = 0\n\nfor line in f1:\n if not split:\n file = 'split_'+str(count)+'.xml'\n f2 = open(file, 'w')\n if count > 0:\n f2.write('<?xml version=\"1.0\"?>\\n')\n f2.write('<StartTag xmlns=\"http://www.blah/1.2.0\">\\n')\n size = 0\n count += 1 \n split = True \n if size < 1073741824:\n f2.write(line)\n size += len(line)\n elif str(line) == '</EndTag>\\n':\n f2.write(line)\n f2.write('</EndEndTag>\\n')\n print('completed file %s' %str(count))\n f2.close()\n f2 = open(file, 'r')\n print(\"ftp'ing file...\")\n ftp.storbinary('STOR ' + file, f2)\n print('ftp done.')\n split = False\n f2.close()\n os.remove(file)\n else:\n f2.write(line)\n size += len(line)\n\n"
] |
[
7,
2,
1,
0,
0,
0
] |
[
"Its a time to buy a new hard drive!\nYou can make backup before trying all other answers and don't get data lost :)\n"
] |
[
-1
] |
[
"file",
"python"
] |
stackoverflow_0001145286_file_python.txt
|
Q:
Python write to line flow
Part of my script is taking values and putting them to a text file delimited by tabs. So I have this:
for linesplit in fileList:
for i in range (0, len(linesplit)):
t.write (linesplit[i]+'\t')
I get as an output in the file what I expect in the first line but in the following lines they all start with a \t in them, like is:
value1 value2 value3
value1 value2 value3
value1 value2 value3
Also, why don't I need to add a t.write('\n') after the second FOR loop to create the newlines? I would expect the code above to produce one long line of tab separated values but it doesn't. If I include the t.write('\n') then the tabs issue is resolved but I get double '\n'...
A:
it doesn't produce what you want because original lines (linesplit) contain end of line character (\n) that you're not stripping. insert the following before your second for loop:
linesplit = linesplit.strip('\n')
That should do the job.
A:
I'm sorry... After I hit submit it dawned on me. My last value already has a \n in it which causes the newline.
A:
Your last value must have a "\n" which causes both problems: The first problem because it outputs '\t' after the newline, the second problem should be obvious - the mystery newlines are coming from your last value.
A:
you linesplit variable could have newlines. just use strip() to remove it.
A:
Your "value3" strings are really "value3\n", which explains the magical newlines and the extraneous tabs on all but the first line.
A:
The inner loop isn't required. Perhaps you meant to use:
t.write('\t'.join(linesplit))
|
Python write to line flow
|
Part of my script is taking values and putting them to a text file delimited by tabs. So I have this:
for linesplit in fileList:
for i in range (0, len(linesplit)):
t.write (linesplit[i]+'\t')
I get as an output in the file what I expect in the first line but in the following lines they all start with a \t in them, like is:
value1 value2 value3
value1 value2 value3
value1 value2 value3
Also, why don't I need to add a t.write('\n') after the second FOR loop to create the newlines? I would expect the code above to produce one long line of tab separated values but it doesn't. If I include the t.write('\n') then the tabs issue is resolved but I get double '\n'...
|
[
"it doesn't produce what you want because original lines (linesplit) contain end of line character (\\n) that you're not stripping. insert the following before your second for loop:\nlinesplit = linesplit.strip('\\n')\n\nThat should do the job.\n",
"I'm sorry... After I hit submit it dawned on me. My last value already has a \\n in it which causes the newline.\n",
"Your last value must have a \"\\n\" which causes both problems: The first problem because it outputs '\\t' after the newline, the second problem should be obvious - the mystery newlines are coming from your last value.\n",
"you linesplit variable could have newlines. just use strip() to remove it. \n",
"Your \"value3\" strings are really \"value3\\n\", which explains the magical newlines and the extraneous tabs on all but the first line.\n",
"The inner loop isn't required. Perhaps you meant to use:\nt.write('\\t'.join(linesplit))\n\n"
] |
[
6,
1,
1,
1,
1,
0
] |
[] |
[] |
[
"file_io",
"python"
] |
stackoverflow_0001154373_file_io_python.txt
|
Q:
How do I debug a py2exe 'application failed to initialize properly' error?
I'm very new to Python in general, but I made an app in Python 2.6 / wxPython 2.8 that works perfectly when I run it through Python. But I wanted to go a step further and be able to deploy it as a Windows executable, so I've been trying out py2exe. But I haven't been able to get it to work. It would always compile an exe, but when I actually try to run that it barks some cryptic error message. At first they were simple messages saying it couldn't find certain DLLs, but even after giving it all the DLLs it wanted, it now returns this:
The application failed to initialize properly (0xc0000142).
Click OK to terminate the application.
So I broke things down and just made a very, very simple application utilizing wxPython just to see if that would work, or if some of the more complicated features of my original app were getting in the way. But even my simple test returned the same error. Here's the code for the simple test script:
import wx
class MainWindow(wx.Frame):
def __init__(self, parent, id, title):
wx.Frame.__init__(self, parent, wx.ID_ANY, title, style=wx.DEFAULT_FRAME_STYLE ^ wx.MAXIMIZE_BOX)
panel = wx.Panel(self, -1, style = wx.TAB_TRAVERSAL | wx.CLIP_CHILDREN | wx.FULL_REPAINT_ON_RESIZE)
main_sizer = wx.BoxSizer(wx.VERTICAL)
testtxt = wx.StaticText(panel, -1, label='This is a test!')
main_sizer.Add(testtxt, 0, wx.ALIGN_CENTER)
panel.SetSizerAndFit(main_sizer)
self.Show(1)
return
app = wx.PySimpleApp()
frame = MainWindow(None, -1, 'Test App')
app.MainLoop()
And here's the py2exe setup script I used:
#!/usr/bin/python
from distutils.core import setup
import py2exe
manifest = """
<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<assembly xmlns="urn:schemas-microsoft-com:asm.v1"
manifestVersion="1.0">
<assemblyIdentity
version="0.64.1.0"
processorArchitecture="x86"
name="Controls"
type="win32"
/>
<description>Test Program</description>
<dependency>
<dependentAssembly>
<assemblyIdentity
type="win32"
name="Microsoft.Windows.Common-Controls"
version="6.0.0.0"
processorArchitecture="X86"
publicKeyToken="6595b64144ccf1df"
language="*"
/>
</dependentAssembly>
</dependency>
</assembly>
"""
setup(
windows = [
{
"script": "testme.py",
"icon_resources": [(1, "testme.ico")],
"other_resources": [(24,1, manifest)]
}
],
data_files=["testme.ico"]
)
Then I run python setup.py py2exe, it generates the EXE file, warns about some DLL files (which I subsequently copy into the dist directory), but then when I try to run the EXE, I get the error I quoted above immediately.
A:
Note that there is a later version of the Visual C++ 2008 Redistributable package: SP1. However, both the SP1 and the earlier release don't install the DLLs into the path. As the download page says (my emphasis):
This package installs runtime
components of C Runtime (CRT),
Standard C++, ATL, MFC, OpenMP and
MSDIA libraries. For libraries that
support side-by-side deployment model
(CRT, SCL, ATL, MFC, OpenMP) they are
installed into the native assembly
cache, also called WinSxS folder, on
versions of Windows operating system
that support side-by-side assemblies.
You will probably find these files in the %WINDIR%\WinSxS folder and not in the path.What I think you need to do is incorporate the manifest information for the relevant DLLs (found in %WINDIR%\WinSxS\Manifests) into your setup.py. I
added the following section:
<dependency>
<dependentAssembly>
<assemblyIdentity
type="win32"
name="Microsoft.VC90.CRT"
version="9.0.30729.4918"
processorArchitecture="X86"
publicKeyToken="1fc8b3b9a1e18e3b"
language="*"
/>
</dependentAssembly>
</dependency>
immediately after the existing <dependency> section, and rebuilt the exe: it ran without problems. Note: depending on exactly what version of the Visual C++ files you installed, the above info may not be exactly correct. Look at the manifests on your system and use the correct version, publicKeyToken etc.
Alternatively, look at this answer for how to deploy the DLLs with your application (as opposed to assuming they already exist on the target system). Oh ... I see you asked that original question ;-)
A:
I've used py2exe before and I've never run across a situation like this....
However, it sounds like missing dependencies are your problem.....
Does the packaged program work on your machine but not on others?
If so, run the packaged application within DEPENDS (dependency walker) on both machines and compare to hopefully discern which packages didn't get included.
Good Luck
A:
You are not supposed to copy ALL of the .dlls it complains about! Some of them are Windows system files, and they are present in the correct places on the system. If you copy them into the dist folder, things won't work correctly.
In general, you only want to copy .dlls which are specific to your application. Not system .dlls. In some situations you may need to ship vcredist_xx.exe in your installer to get the MSVC runtime on the system. You should never try to ship those .dlls files "raw" by yourself. Use the redist package, it will save you time and frustration.
Have you tried following the directions here: http://wiki.wxpython.org/SmallApp ?
A:
Are you sure that you give the same dlls that the one used by wxPython.
The vc++ dlls used by wxpython can be downloaded from the wxpython download page. Did you try these one?
|
How do I debug a py2exe 'application failed to initialize properly' error?
|
I'm very new to Python in general, but I made an app in Python 2.6 / wxPython 2.8 that works perfectly when I run it through Python. But I wanted to go a step further and be able to deploy it as a Windows executable, so I've been trying out py2exe. But I haven't been able to get it to work. It would always compile an exe, but when I actually try to run that it barks some cryptic error message. At first they were simple messages saying it couldn't find certain DLLs, but even after giving it all the DLLs it wanted, it now returns this:
The application failed to initialize properly (0xc0000142).
Click OK to terminate the application.
So I broke things down and just made a very, very simple application utilizing wxPython just to see if that would work, or if some of the more complicated features of my original app were getting in the way. But even my simple test returned the same error. Here's the code for the simple test script:
import wx
class MainWindow(wx.Frame):
def __init__(self, parent, id, title):
wx.Frame.__init__(self, parent, wx.ID_ANY, title, style=wx.DEFAULT_FRAME_STYLE ^ wx.MAXIMIZE_BOX)
panel = wx.Panel(self, -1, style = wx.TAB_TRAVERSAL | wx.CLIP_CHILDREN | wx.FULL_REPAINT_ON_RESIZE)
main_sizer = wx.BoxSizer(wx.VERTICAL)
testtxt = wx.StaticText(panel, -1, label='This is a test!')
main_sizer.Add(testtxt, 0, wx.ALIGN_CENTER)
panel.SetSizerAndFit(main_sizer)
self.Show(1)
return
app = wx.PySimpleApp()
frame = MainWindow(None, -1, 'Test App')
app.MainLoop()
And here's the py2exe setup script I used:
#!/usr/bin/python
from distutils.core import setup
import py2exe
manifest = """
<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<assembly xmlns="urn:schemas-microsoft-com:asm.v1"
manifestVersion="1.0">
<assemblyIdentity
version="0.64.1.0"
processorArchitecture="x86"
name="Controls"
type="win32"
/>
<description>Test Program</description>
<dependency>
<dependentAssembly>
<assemblyIdentity
type="win32"
name="Microsoft.Windows.Common-Controls"
version="6.0.0.0"
processorArchitecture="X86"
publicKeyToken="6595b64144ccf1df"
language="*"
/>
</dependentAssembly>
</dependency>
</assembly>
"""
setup(
windows = [
{
"script": "testme.py",
"icon_resources": [(1, "testme.ico")],
"other_resources": [(24,1, manifest)]
}
],
data_files=["testme.ico"]
)
Then I run python setup.py py2exe, it generates the EXE file, warns about some DLL files (which I subsequently copy into the dist directory), but then when I try to run the EXE, I get the error I quoted above immediately.
|
[
"Note that there is a later version of the Visual C++ 2008 Redistributable package: SP1. However, both the SP1 and the earlier release don't install the DLLs into the path. As the download page says (my emphasis):\n\nThis package installs runtime\n components of C Runtime (CRT),\n Standard C++, ATL, MFC, OpenMP and\n MSDIA libraries. For libraries that\n support side-by-side deployment model\n (CRT, SCL, ATL, MFC, OpenMP) they are\n installed into the native assembly\n cache, also called WinSxS folder, on\n versions of Windows operating system\n that support side-by-side assemblies.\n\nYou will probably find these files in the %WINDIR%\\WinSxS folder and not in the path.What I think you need to do is incorporate the manifest information for the relevant DLLs (found in %WINDIR%\\WinSxS\\Manifests) into your setup.py. I \nadded the following section:\n<dependency>\n <dependentAssembly>\n <assemblyIdentity\n type=\"win32\"\n name=\"Microsoft.VC90.CRT\"\n version=\"9.0.30729.4918\"\n processorArchitecture=\"X86\"\n publicKeyToken=\"1fc8b3b9a1e18e3b\"\n language=\"*\"\n />\n </dependentAssembly>\n</dependency>\n\nimmediately after the existing <dependency> section, and rebuilt the exe: it ran without problems. Note: depending on exactly what version of the Visual C++ files you installed, the above info may not be exactly correct. Look at the manifests on your system and use the correct version, publicKeyToken etc.\nAlternatively, look at this answer for how to deploy the DLLs with your application (as opposed to assuming they already exist on the target system). Oh ... I see you asked that original question ;-)\n",
"I've used py2exe before and I've never run across a situation like this....\nHowever, it sounds like missing dependencies are your problem.....\nDoes the packaged program work on your machine but not on others?\nIf so, run the packaged application within DEPENDS (dependency walker) on both machines and compare to hopefully discern which packages didn't get included. \nGood Luck\n",
"You are not supposed to copy ALL of the .dlls it complains about! Some of them are Windows system files, and they are present in the correct places on the system. If you copy them into the dist folder, things won't work correctly.\nIn general, you only want to copy .dlls which are specific to your application. Not system .dlls. In some situations you may need to ship vcredist_xx.exe in your installer to get the MSVC runtime on the system. You should never try to ship those .dlls files \"raw\" by yourself. Use the redist package, it will save you time and frustration.\nHave you tried following the directions here: http://wiki.wxpython.org/SmallApp ?\n",
"Are you sure that you give the same dlls that the one used by wxPython.\nThe vc++ dlls used by wxpython can be downloaded from the wxpython download page. Did you try these one?\n"
] |
[
10,
0,
0,
0
] |
[] |
[] |
[
"py2exe",
"python",
"wxpython"
] |
stackoverflow_0001153643_py2exe_python_wxpython.txt
|
Q:
How to run statistics Cumulative Distribution Function and Probability Density Function using SciPy?
I am new to Python and new to SciPy libraries. I wanted to take some ques from the experts here on the list before dive into SciPy world.
I was wondering if some one could provide a rough guide about how to run two stats functions: Cumulative Distribution Function (CDF) and Probability Distribution Function (PDF).
My use case is the following: I have a sampleSpaceList [] which have 1000 floating point values. When a new floating point value is generated in my program, I would like to run both CDF and PDF on the sampleList for it and get the probability of value less or equal for CDF and probability distribution for PDF.
some more information
Basically, in my program there are events which can either succeed or fail. If they succeed, then I calculate a event-ratio for that event and add to my sampleSpaceList until it reaches a threshold of 1000. Once the threshold is achieved, then for any next event-ratio; I would like to get a probability that whether that event-ratio would succeed or not in my system.
What I basically would like to get is the probability of success for a particular event ratio.
I am not very sure whether CDF or PDF will be relative to my problem so that 's why I wanted to learn how to use both but at any given moment, I will be only using either CDF or PDF to get a probability of event-ratio being successful.
A:
See this article: Probability distributions in SciPy.
|
How to run statistics Cumulative Distribution Function and Probability Density Function using SciPy?
|
I am new to Python and new to SciPy libraries. I wanted to take some ques from the experts here on the list before dive into SciPy world.
I was wondering if some one could provide a rough guide about how to run two stats functions: Cumulative Distribution Function (CDF) and Probability Distribution Function (PDF).
My use case is the following: I have a sampleSpaceList [] which have 1000 floating point values. When a new floating point value is generated in my program, I would like to run both CDF and PDF on the sampleList for it and get the probability of value less or equal for CDF and probability distribution for PDF.
some more information
Basically, in my program there are events which can either succeed or fail. If they succeed, then I calculate a event-ratio for that event and add to my sampleSpaceList until it reaches a threshold of 1000. Once the threshold is achieved, then for any next event-ratio; I would like to get a probability that whether that event-ratio would succeed or not in my system.
What I basically would like to get is the probability of success for a particular event ratio.
I am not very sure whether CDF or PDF will be relative to my problem so that 's why I wanted to learn how to use both but at any given moment, I will be only using either CDF or PDF to get a probability of event-ratio being successful.
|
[
"See this article: Probability distributions in SciPy.\n"
] |
[
8
] |
[] |
[] |
[
"probability",
"python",
"scipy",
"statistics"
] |
stackoverflow_0001154378_probability_python_scipy_statistics.txt
|
Q:
Are there any libraries for generating Python source?
I'd like to write a code generation tool that will allow me to create sourcefiles for dynamically generated classes. I can create the class and use it in code, but it would be nice to have a sourcefile both for documentation and to allow something to import.
Does such a thing exist? I've seen sourcecodegen, but I'd rather avoid messing with the ast trees as they're not portable.
A:
I'm not aware of any off-the-shelf library, but have a look at the Python templating engines Mako and Jinja2. They can both generate Python source behind the scenes (they convert text templates to Python code and then to Python bytecode).
|
Are there any libraries for generating Python source?
|
I'd like to write a code generation tool that will allow me to create sourcefiles for dynamically generated classes. I can create the class and use it in code, but it would be nice to have a sourcefile both for documentation and to allow something to import.
Does such a thing exist? I've seen sourcecodegen, but I'd rather avoid messing with the ast trees as they're not portable.
|
[
"I'm not aware of any off-the-shelf library, but have a look at the Python templating engines Mako and Jinja2. They can both generate Python source behind the scenes (they convert text templates to Python code and then to Python bytecode).\n"
] |
[
2
] |
[] |
[] |
[
"code_generation",
"python"
] |
stackoverflow_0001155186_code_generation_python.txt
|
Q:
Python: List initialization differences
I want a list full of the same thing, where the thing will either be a string or a number. Is there a difference in the way these two list are created? Is there anything hidden that I should probably know about?
list_1 = [0] * 10
list_2 = [0 for i in range(10)]
Are there any better ways to do this same task?
Thanks in advance.
A:
It depends on whether your list elements are mutable, if they are, there'll be a difference:
>>> l = [[]] * 10
>>> l
[[], [], [], [], [], [], [], [], [], []]
>>> l[0].append(1)
>>> l
[[1], [1], [1], [1], [1], [1], [1], [1], [1], [1]]
>>> l = [[] for i in range(10)]
>>> l[0].append(1)
>>> l
[[1], [], [], [], [], [], [], [], [], []]
For immutable elements, the behavior of the two is the same. There might be a performance difference between them, but I'm not sure which one would perform faster.
A:
I personally would advice to use the first method, since it is most likely the best performing one, since the system knows in advance the size of the list and the contents.
In the second form, it must first evaluate the generator and collect all the values. Most likely by building up the list incrementally -- what is costly because of resizing.
The first method should also be the best way at all.
A:
The first one is not only faster, but is also more readable: just by a quick look, you immediately understand what's into that list, while in the second case you have to stop and see the iteration.
Since source code is written once and read many times, for immutable elements I definitely vote for the first option.
|
Python: List initialization differences
|
I want a list full of the same thing, where the thing will either be a string or a number. Is there a difference in the way these two list are created? Is there anything hidden that I should probably know about?
list_1 = [0] * 10
list_2 = [0 for i in range(10)]
Are there any better ways to do this same task?
Thanks in advance.
|
[
"It depends on whether your list elements are mutable, if they are, there'll be a difference:\n>>> l = [[]] * 10\n>>> l\n[[], [], [], [], [], [], [], [], [], []]\n>>> l[0].append(1)\n>>> l\n[[1], [1], [1], [1], [1], [1], [1], [1], [1], [1]]\n>>> l = [[] for i in range(10)]\n>>> l[0].append(1)\n>>> l\n[[1], [], [], [], [], [], [], [], [], []]\n\nFor immutable elements, the behavior of the two is the same. There might be a performance difference between them, but I'm not sure which one would perform faster.\n",
"I personally would advice to use the first method, since it is most likely the best performing one, since the system knows in advance the size of the list and the contents.\nIn the second form, it must first evaluate the generator and collect all the values. Most likely by building up the list incrementally -- what is costly because of resizing.\nThe first method should also be the best way at all.\n",
"The first one is not only faster, but is also more readable: just by a quick look, you immediately understand what's into that list, while in the second case you have to stop and see the iteration. \nSince source code is written once and read many times, for immutable elements I definitely vote for the first option.\n"
] |
[
16,
3,
1
] |
[] |
[] |
[
"list",
"python"
] |
stackoverflow_0001154494_list_python.txt
|
Q:
python distutils / setuptools: how to exclude a module, or honor svn:ignore flag
I have a python project, 'myproject', that contains several packages. one of those packages, 'myproject.settings', contains a module 'myproject.settings.local' that is excluded from version control via 'svn:ignore' property.
I would like setuptools to ignore this file when making a bdist or bdist_egg target.
I have experimented with find_packages(exclude..) to no avail. Ideally I was hoping that only files that are not ignored by svn would be included.
Is there a way to achieve the exclusion of my module?
(I am on a patched (http://bugs.python.org/setuptools/issue64) version of setuptools trunk, with subversion 1.6.)
thanks for any insight you might have
-frank
A:
I don't know if there is a regular way to do that but you you try a workaround like proposed in the How can I make setuptools ignore subversion inventory?
svn export your package to a temporary directory, run the setup.py from there
|
python distutils / setuptools: how to exclude a module, or honor svn:ignore flag
|
I have a python project, 'myproject', that contains several packages. one of those packages, 'myproject.settings', contains a module 'myproject.settings.local' that is excluded from version control via 'svn:ignore' property.
I would like setuptools to ignore this file when making a bdist or bdist_egg target.
I have experimented with find_packages(exclude..) to no avail. Ideally I was hoping that only files that are not ignored by svn would be included.
Is there a way to achieve the exclusion of my module?
(I am on a patched (http://bugs.python.org/setuptools/issue64) version of setuptools trunk, with subversion 1.6.)
thanks for any insight you might have
-frank
|
[
"I don't know if there is a regular way to do that but you you try a workaround like proposed in the How can I make setuptools ignore subversion inventory?\nsvn export your package to a temporary directory, run the setup.py from there\n"
] |
[
2
] |
[] |
[] |
[
"distutils",
"python",
"setuptools"
] |
stackoverflow_0001154586_distutils_python_setuptools.txt
|
Q:
Python: Replace string with prefixStringSuffix keeping original case, but ignoring case when searching for match
So what I'm trying to do is replace a string "keyword" with
"<b>keyword</b>"
in a larger string.
Example:
myString = "HI there. You should higher that person for the job. Hi hi."
keyword = "hi"
result I would want would be:
result = "<b>HI</b> there. You should higher that person for the job.
<b>Hi</b> <b>hi</b>."
I will not know what the keyword until the user types the keyword
and won't know the corpus (myString) until the query is run.
I found a solution that works most of the time, but has some false positives,
namely it would return "<b>hi<b/>gher"which is not what I want. Also note that I
am trying to preserve the case of the original text, and the matching should take
place irrespective of case. so if the keyword is "hi" it should replace
HI with <b>HI</b> and hi with <b>hi</b>.
The closest I have come is using a slightly derived version of this:
http://code.activestate.com/recipes/576715/
but I still could not figure out how to do a second pass of the string to fix all of the false positives mentioned above.
Or using the NLTK's WordPunctTokenizer (which simplifies some things like punctuation)
but I'm not sure how I would put the sentences back together given it does not
have a reverse function and I want to keep the original punctuation of myString. Essential, doing a concatenation of all the tokens does not return the original
string. For example I would not want to replace "7 - 7" with "7-7" when regrouping the tokens into its original text if the original text had "7 - 7".
Hope that was clear enough. Seems like a simple problem, but its a turned out a little more difficult then I thought.
A:
This ok?
>>> import re
>>> myString = "HI there. You should higher that person for the job. Hi hi."
>>> keyword = "hi"
>>> search = re.compile(r'\b(%s)\b' % keyword, re.I)
>>> search.sub('<b>\\1</b>', myString)
'<b>HI</b> there. You should higher that person for the job. <b>Hi</b> <b>hi</b>.'
The key to the whole thing is using word boundaries, groups and the re.I flag.
A:
You should be able to do this very easily with re.sub using the word boundary assertion \b, which only matches at a word boundary:
import re
def SurroundWith(text, keyword, before, after):
regex = re.compile(r'\b%s\b' % keyword, re.IGNORECASE)
return regex.sub(r'%s\0%s' % (before, after), text)
Then you get:
>>> SurroundWith('HI there. You should hire that person for the job. '
... 'Hi hi.', 'hi', '<b>', '</b>')
'<b>HI</b> there. You should hire that person for the job. <b>Hi</b> <b>hi</b>.'
If you have more complicated criteria for what constitutes a "word boundary," you'll have to do something like:
def SurroundWith2(text, keyword, before, after):
regex = re.compile(r'([^a-zA-Z0-9])(%s)([^a-zA-Z0-9])' % keyword,
re.IGNORECASE)
return regex.sub(r'\1%s\2%s\3' % (before, after), text)
You can modify the [^a-zA-Z0-9] groups to match anything you consider a "non-word."
A:
I think the best solution would be regular expression...
import re
def reg(keyword, myString) :
regx = re.compile(r'\b(' + keyword + r')\b', re.IGNORECASE)
return regx.sub(r'<b>\1</b>', myString)
of course, you must first make your keyword "regular expression safe" (quote any regex special characters).
|
Python: Replace string with prefixStringSuffix keeping original case, but ignoring case when searching for match
|
So what I'm trying to do is replace a string "keyword" with
"<b>keyword</b>"
in a larger string.
Example:
myString = "HI there. You should higher that person for the job. Hi hi."
keyword = "hi"
result I would want would be:
result = "<b>HI</b> there. You should higher that person for the job.
<b>Hi</b> <b>hi</b>."
I will not know what the keyword until the user types the keyword
and won't know the corpus (myString) until the query is run.
I found a solution that works most of the time, but has some false positives,
namely it would return "<b>hi<b/>gher"which is not what I want. Also note that I
am trying to preserve the case of the original text, and the matching should take
place irrespective of case. so if the keyword is "hi" it should replace
HI with <b>HI</b> and hi with <b>hi</b>.
The closest I have come is using a slightly derived version of this:
http://code.activestate.com/recipes/576715/
but I still could not figure out how to do a second pass of the string to fix all of the false positives mentioned above.
Or using the NLTK's WordPunctTokenizer (which simplifies some things like punctuation)
but I'm not sure how I would put the sentences back together given it does not
have a reverse function and I want to keep the original punctuation of myString. Essential, doing a concatenation of all the tokens does not return the original
string. For example I would not want to replace "7 - 7" with "7-7" when regrouping the tokens into its original text if the original text had "7 - 7".
Hope that was clear enough. Seems like a simple problem, but its a turned out a little more difficult then I thought.
|
[
"This ok?\n>>> import re\n>>> myString = \"HI there. You should higher that person for the job. Hi hi.\"\n>>> keyword = \"hi\"\n>>> search = re.compile(r'\\b(%s)\\b' % keyword, re.I)\n>>> search.sub('<b>\\\\1</b>', myString)\n'<b>HI</b> there. You should higher that person for the job. <b>Hi</b> <b>hi</b>.'\n\nThe key to the whole thing is using word boundaries, groups and the re.I flag.\n",
"You should be able to do this very easily with re.sub using the word boundary assertion \\b, which only matches at a word boundary:\nimport re\n\ndef SurroundWith(text, keyword, before, after):\n regex = re.compile(r'\\b%s\\b' % keyword, re.IGNORECASE)\n return regex.sub(r'%s\\0%s' % (before, after), text)\n\nThen you get:\n>>> SurroundWith('HI there. You should hire that person for the job. '\n... 'Hi hi.', 'hi', '<b>', '</b>')\n'<b>HI</b> there. You should hire that person for the job. <b>Hi</b> <b>hi</b>.'\n\nIf you have more complicated criteria for what constitutes a \"word boundary,\" you'll have to do something like:\ndef SurroundWith2(text, keyword, before, after):\n regex = re.compile(r'([^a-zA-Z0-9])(%s)([^a-zA-Z0-9])' % keyword,\n re.IGNORECASE)\n return regex.sub(r'\\1%s\\2%s\\3' % (before, after), text)\n\nYou can modify the [^a-zA-Z0-9] groups to match anything you consider a \"non-word.\"\n",
"I think the best solution would be regular expression...\nimport re\ndef reg(keyword, myString) :\n regx = re.compile(r'\\b(' + keyword + r')\\b', re.IGNORECASE)\n return regx.sub(r'<b>\\1</b>', myString)\n\nof course, you must first make your keyword \"regular expression safe\" (quote any regex special characters).\n"
] |
[
3,
0,
0
] |
[
"Here's one suggestion, from the nitpicking committee. :-)\nmyString = \"HI there. You should higher that person for the job. Hi hi.\"\n\nmyString.replace('higher','hire')\n\n"
] |
[
-1
] |
[
"nltk",
"python",
"regex",
"replace",
"search"
] |
stackoverflow_0000818691_nltk_python_regex_replace_search.txt
|
Q:
Prevent opening a second instance
What's the easiest way to check if my program is already running with WxPython under Windows? Ideally, if the user tries to launch the program a second time, the focus should return to the first instance (even if the window is minimized).
This question is similar but the answer is for VB.NET.
A:
You should use wx.SingleInstanceChecker. See here for more information on how to use it, and this post tells about finding the running instance (you have to use pywin32 functions for this, there's nothing built into wxPython AFAIK).
|
Prevent opening a second instance
|
What's the easiest way to check if my program is already running with WxPython under Windows? Ideally, if the user tries to launch the program a second time, the focus should return to the first instance (even if the window is minimized).
This question is similar but the answer is for VB.NET.
|
[
"You should use wx.SingleInstanceChecker. See here for more information on how to use it, and this post tells about finding the running instance (you have to use pywin32 functions for this, there's nothing built into wxPython AFAIK).\n"
] |
[
3
] |
[] |
[] |
[
"python",
"user_interface",
"windows",
"wxpython"
] |
stackoverflow_0001155315_python_user_interface_windows_wxpython.txt
|
Q:
How do I access an inherited class's inner class and modify it?
So I have a class, specifically, this:
class ProductVariantForm_PRE(ModelForm):
class Meta:
model = ProductVariant
exclude = ("productowner","status")
def clean_meta(self):
if len(self.cleaned_data['meta']) == 0:
raise forms.ValidationError(_(u'You have to select at least 1 meta attribute.'))
for m in self.cleaned_data['meta']:
for n in self.cleaned_data['meta']:
if m != n:
if m.name == n.name:
raise forms.ValidationError(_(u'You can only select 1 meta data of each type. IE: You cannot select 2 COLOR DATA (Red and Blue). You can however select 2 different data such as Shape and Size.'))
return self.cleaned_data['meta']
I wish to extend this class (a ModelForm), and so I have a class B.
Class B will look like this:
class B(ProductVariantForm_PRE):
How can I access the inner class "Meta" in class B and modify the exclude field?
Thanks!
A:
Take a look at the Django documentation for model inheritance here. From that page:
When an abstract base class is
created, Django makes any Meta inner
class you declared in the base class
available as an attribute. If a child
class does not declare its own Meta
class, it will inherit the parent's
Meta. If the child wants to extend the
parent's Meta class, it can subclass
it. For example:
class CommonInfo(models.Model):
...
class Meta:
abstract = True
ordering = ['name']
class Student(CommonInfo):
...
class Meta(CommonInfo.Meta):
db_table = 'student_info'
|
How do I access an inherited class's inner class and modify it?
|
So I have a class, specifically, this:
class ProductVariantForm_PRE(ModelForm):
class Meta:
model = ProductVariant
exclude = ("productowner","status")
def clean_meta(self):
if len(self.cleaned_data['meta']) == 0:
raise forms.ValidationError(_(u'You have to select at least 1 meta attribute.'))
for m in self.cleaned_data['meta']:
for n in self.cleaned_data['meta']:
if m != n:
if m.name == n.name:
raise forms.ValidationError(_(u'You can only select 1 meta data of each type. IE: You cannot select 2 COLOR DATA (Red and Blue). You can however select 2 different data such as Shape and Size.'))
return self.cleaned_data['meta']
I wish to extend this class (a ModelForm), and so I have a class B.
Class B will look like this:
class B(ProductVariantForm_PRE):
How can I access the inner class "Meta" in class B and modify the exclude field?
Thanks!
|
[
"Take a look at the Django documentation for model inheritance here. From that page:\n\nWhen an abstract base class is\n created, Django makes any Meta inner\n class you declared in the base class\n available as an attribute. If a child\n class does not declare its own Meta\n class, it will inherit the parent's\n Meta. If the child wants to extend the\n parent's Meta class, it can subclass\n it. For example:\n\nclass CommonInfo(models.Model):\n ...\n class Meta:\n abstract = True\n ordering = ['name']\n\nclass Student(CommonInfo):\n ...\n class Meta(CommonInfo.Meta):\n db_table = 'student_info'\n\n"
] |
[
4
] |
[] |
[] |
[
"django",
"python"
] |
stackoverflow_0001155351_django_python.txt
|
Q:
Python accessing multiple webpages at once
I have a tkinter GUI that downloads data from multiple websites at once. I run a seperate thread for each download (about 28). Is that too much threads for one GUI process? because it's really slow, each individual page should take about 1 to 2 seconds but when all are run at once it takes over 40 seconds. Is there any way I can shorten the time it takes to download all the pages? Any help is appreciated, thanks.
A:
It's probably the GIL (global interpreter lock) that gets in your way. Python has some performance problems with many threads.
You could try twisted.web.getPage (see http://twistedmatrix.com/projects/core/documentation/howto/async.html a bit down the page).
I don't have benchmarks for that.
But taking the example on that page and adding 28 deferreds to see how fast it is will give you a comparable result pretty fast.
Keep in mind, that you'd have to use the gtk reactor and get into twisteds programming style, though.
A:
A process can have hundreds of threads on any modern OS without any problem.
If you're bandwidth-limited, 1 to 2 seconds times 28 means 40 seconds is about right. If you're latency limited, it should be faster, but with no information, all I can suggest is:
add logging to your code to make sure it's actually running in parallel, and that you're not accidentally serializing your threads somehow;
use a network monitor to make sure that network requests are actually going out in parallel.
It's hard to give anything better without more information.
A:
You can try using processes instead of threads. Python has GIL which might cause some delays in your situation.
|
Python accessing multiple webpages at once
|
I have a tkinter GUI that downloads data from multiple websites at once. I run a seperate thread for each download (about 28). Is that too much threads for one GUI process? because it's really slow, each individual page should take about 1 to 2 seconds but when all are run at once it takes over 40 seconds. Is there any way I can shorten the time it takes to download all the pages? Any help is appreciated, thanks.
|
[
"It's probably the GIL (global interpreter lock) that gets in your way. Python has some performance problems with many threads.\nYou could try twisted.web.getPage (see http://twistedmatrix.com/projects/core/documentation/howto/async.html a bit down the page).\nI don't have benchmarks for that.\nBut taking the example on that page and adding 28 deferreds to see how fast it is will give you a comparable result pretty fast.\nKeep in mind, that you'd have to use the gtk reactor and get into twisteds programming style, though.\n",
"A process can have hundreds of threads on any modern OS without any problem.\nIf you're bandwidth-limited, 1 to 2 seconds times 28 means 40 seconds is about right. If you're latency limited, it should be faster, but with no information, all I can suggest is:\n\nadd logging to your code to make sure it's actually running in parallel, and that you're not accidentally serializing your threads somehow;\nuse a network monitor to make sure that network requests are actually going out in parallel.\n\nIt's hard to give anything better without more information.\n",
"You can try using processes instead of threads. Python has GIL which might cause some delays in your situation.\n"
] |
[
2,
1,
0
] |
[] |
[] |
[
"download",
"multithreading",
"python",
"tkinter",
"user_interface"
] |
stackoverflow_0001155404_download_multithreading_python_tkinter_user_interface.txt
|
Q:
Python: Importing pydoc and then using it natively?
I know how to use pydoc from the command line. However, because of complicated environmental setup, it would be preferable to run it within a python script as a native API call. That is, my python runner looks a bit like this:
import pydoc
pydoc.generate_html_docs_for(someFile)
However, it's not clear to me from the pydoc documentation which function calls I need to use to make this behavior work. Any ideas?
A:
Do you mean something like this?
>>> import pydoc
>>> pydoc.writedoc('sys')
wrote sys.html
>>>
|
Python: Importing pydoc and then using it natively?
|
I know how to use pydoc from the command line. However, because of complicated environmental setup, it would be preferable to run it within a python script as a native API call. That is, my python runner looks a bit like this:
import pydoc
pydoc.generate_html_docs_for(someFile)
However, it's not clear to me from the pydoc documentation which function calls I need to use to make this behavior work. Any ideas?
|
[
"Do you mean something like this?\n>>> import pydoc\n>>> pydoc.writedoc('sys')\nwrote sys.html\n>>>\n\n"
] |
[
8
] |
[] |
[] |
[
"pydoc",
"python"
] |
stackoverflow_0001155853_pydoc_python.txt
|
Q:
Getting rows from XML using XPath and Python
I'd like to get some rows (z:row rows) from XML using:
<rs:data>
<z:row Attribute1="1" Attribute2="1" />
<z:row Attribute1="2" Attribute2="2" />
<z:row Attribute1="3" Attribute2="3" />
<z:row Attribute1="4" Attribute2="4" />
<z:row Attribute1="5" Attribute2="5" />
<z:row Attribute1="6" Attribute2="6" />
</rs:data>
I'm having trouble using (Python):
ElementTree.parse('myxmlfile.xml').getroot().findall('//z:row')
I think that two points are invalid in that case.
Anyone knows how can I do that?
A:
If you don't want to figure out setting up namespaces properly, you can ignore them like this:
XPathGet("//*[local-name() = 'row']")
Which selects every node whose name (without namespace) is row.
A:
The "z:" prefixes represent an XML namespace. you'll need to find out what that namespace is, and do the following:
XmlDocument doc = new XmlDocument();
doc.Load(@"File.xml");
XmlNamespaceManager ns = new XmlNamespaceManager(doc.NameTable);
ns.AddNamespace("z", @"http://thenamespace.com");
XmlNodeList nodes = doc.SelectNodes(@"//z:row", ns);
A:
If I define the namespaces like this:
<?xml version="1.0"?>
<rs:data xmlns="http://example.com" xmlns:rs="http://example.com/rs" xmlns:z="http://example.com/z">
<z:row Attribute1="1" Attribute2="1" />
<z:row Attribute1="2" Attribute2="2" />
<z:row Attribute1="3" Attribute2="3" />
<z:row Attribute1="4" Attribute2="4" />
<z:row Attribute1="5" Attribute2="5" />
<z:row Attribute1="6" Attribute2="6" />
</rs:data>
the Python ElementTree-API can be used like this:
ElementTree.parse("r.xml").getroot().findall('{http://example.com/z}row')
# => [<Element {http://example.com/z}row at 551ee0>, <Element {http://example.com/z}row at 551c60>, <Element {http://example.com/z}row at 551f08>, <Element {http://example.com/z}row at 551be8>, <Element {http://example.com/z}row at 551eb8>, <Element {http://example.com/z}row at 551f30>]
See also http://effbot.org/zone/element.htm#xml-namespaces
|
Getting rows from XML using XPath and Python
|
I'd like to get some rows (z:row rows) from XML using:
<rs:data>
<z:row Attribute1="1" Attribute2="1" />
<z:row Attribute1="2" Attribute2="2" />
<z:row Attribute1="3" Attribute2="3" />
<z:row Attribute1="4" Attribute2="4" />
<z:row Attribute1="5" Attribute2="5" />
<z:row Attribute1="6" Attribute2="6" />
</rs:data>
I'm having trouble using (Python):
ElementTree.parse('myxmlfile.xml').getroot().findall('//z:row')
I think that two points are invalid in that case.
Anyone knows how can I do that?
|
[
"If you don't want to figure out setting up namespaces properly, you can ignore them like this:\nXPathGet(\"//*[local-name() = 'row']\")\n\nWhich selects every node whose name (without namespace) is row.\n",
"The \"z:\" prefixes represent an XML namespace. you'll need to find out what that namespace is, and do the following:\nXmlDocument doc = new XmlDocument();\ndoc.Load(@\"File.xml\");\nXmlNamespaceManager ns = new XmlNamespaceManager(doc.NameTable);\nns.AddNamespace(\"z\", @\"http://thenamespace.com\");\nXmlNodeList nodes = doc.SelectNodes(@\"//z:row\", ns);\n\n",
"If I define the namespaces like this: \n<?xml version=\"1.0\"?>\n<rs:data xmlns=\"http://example.com\" xmlns:rs=\"http://example.com/rs\" xmlns:z=\"http://example.com/z\">\n <z:row Attribute1=\"1\" Attribute2=\"1\" />\n <z:row Attribute1=\"2\" Attribute2=\"2\" />\n <z:row Attribute1=\"3\" Attribute2=\"3\" />\n <z:row Attribute1=\"4\" Attribute2=\"4\" />\n <z:row Attribute1=\"5\" Attribute2=\"5\" />\n <z:row Attribute1=\"6\" Attribute2=\"6\" />\n</rs:data>\n\nthe Python ElementTree-API can be used like this:\nElementTree.parse(\"r.xml\").getroot().findall('{http://example.com/z}row')\n# => [<Element {http://example.com/z}row at 551ee0>, <Element {http://example.com/z}row at 551c60>, <Element {http://example.com/z}row at 551f08>, <Element {http://example.com/z}row at 551be8>, <Element {http://example.com/z}row at 551eb8>, <Element {http://example.com/z}row at 551f30>]\n\nSee also http://effbot.org/zone/element.htm#xml-namespaces\n"
] |
[
1,
1,
1
] |
[] |
[] |
[
"python",
"xml",
"xpath"
] |
stackoverflow_0001155566_python_xml_xpath.txt
|
Q:
Algorithm for BFS traveral of an acylic directed graph
I'm looking for an elegant Python program that does a BFS traveral of a DAG:
Node A is connected to B (A->B) if A "depends on" B (think of python package Foo "depending upon" Bar: Foo->Bar).
In a graph of about 7000 such nodes, I want to sort all nodes such that for all possible (i, j) where 1>=i<j<=7000 .. depends(Ni, Nj) is False. depends(A, B) = True if and only if A->B or A "depends on" B .. and Nx is the node occuring in xth position in the sorted list.
Note: A node can have multiple parents. Eg: A->C and B->C. Therefore, according to the above sorting rule, A and B must come before C.
A:
If I am reading the question correctly, it looks like you want a topological sort. The most efficient algorithm (O(V+E)) for doing this was proposed by Tarjan, and a Python implementation can be found here.
Off-topic, but it seems as though your package dependency analogy is reversed; I would think that "A depends on B" would imply "B->A", but of course this will not change the structure of the tree, merely reverse it.
|
Algorithm for BFS traveral of an acylic directed graph
|
I'm looking for an elegant Python program that does a BFS traveral of a DAG:
Node A is connected to B (A->B) if A "depends on" B (think of python package Foo "depending upon" Bar: Foo->Bar).
In a graph of about 7000 such nodes, I want to sort all nodes such that for all possible (i, j) where 1>=i<j<=7000 .. depends(Ni, Nj) is False. depends(A, B) = True if and only if A->B or A "depends on" B .. and Nx is the node occuring in xth position in the sorted list.
Note: A node can have multiple parents. Eg: A->C and B->C. Therefore, according to the above sorting rule, A and B must come before C.
|
[
"If I am reading the question correctly, it looks like you want a topological sort. The most efficient algorithm (O(V+E)) for doing this was proposed by Tarjan, and a Python implementation can be found here.\nOff-topic, but it seems as though your package dependency analogy is reversed; I would think that \"A depends on B\" would imply \"B->A\", but of course this will not change the structure of the tree, merely reverse it.\n"
] |
[
5
] |
[] |
[] |
[
"algorithm",
"dependencies",
"graph",
"python",
"traversal"
] |
stackoverflow_0001156175_algorithm_dependencies_graph_python_traversal.txt
|
Q:
Composable Regexp in Python
Often, I would like to build up complex regexps from simpler ones. The only way I'm currently aware of of doing this is through string operations, e.g.:
Year = r'[12]\d{3}'
Month = r'Jan|Feb|Mar'
Day = r'\d{2}'
HourMins = r'\d{2}:\d{2}'
Date = r'%s %s, %s, %s' % (Month, Day, Year, HourMins)
DateR = re.compile(Date)
Is anybody aware of a different method or a more systematic approach (maybe a module) in Python to have composable regexps? I'd rather compile each regexp individually (e.g. for using individual compile options), but then there doesn't seem to be a way of composing them anymore!?
A:
You can use Python's formatting syntax for this:
types = {
"year": r'[12]\d{3}',
"month": r'(Jan|Feb|Mar)',
"day": r'\d{2}',
"hourmins": r'\d{2}:\d{2}',
}
import re
Date = r'%(month)s %(day)s, %(year)s, %(hourmins)s' % types
DateR = re.compile(Date)
(Note the added grouping around Jan|Feb|Mar.)
A:
You could use Ping's rxb:
year = member("1", "2") + digit*3
month = either("Jan", "Feb", "Mar")
day = digit*2
hour_mins = digit*2 + ":" + digit*2
date = month + " " + day + ", " + year + ", " + hour_mins
You can then match on the resulting date directly, or use
DateR = date.compile()
|
Composable Regexp in Python
|
Often, I would like to build up complex regexps from simpler ones. The only way I'm currently aware of of doing this is through string operations, e.g.:
Year = r'[12]\d{3}'
Month = r'Jan|Feb|Mar'
Day = r'\d{2}'
HourMins = r'\d{2}:\d{2}'
Date = r'%s %s, %s, %s' % (Month, Day, Year, HourMins)
DateR = re.compile(Date)
Is anybody aware of a different method or a more systematic approach (maybe a module) in Python to have composable regexps? I'd rather compile each regexp individually (e.g. for using individual compile options), but then there doesn't seem to be a way of composing them anymore!?
|
[
"You can use Python's formatting syntax for this:\ntypes = {\n \"year\": r'[12]\\d{3}',\n \"month\": r'(Jan|Feb|Mar)',\n \"day\": r'\\d{2}',\n \"hourmins\": r'\\d{2}:\\d{2}',\n}\nimport re\nDate = r'%(month)s %(day)s, %(year)s, %(hourmins)s' % types\nDateR = re.compile(Date)\n\n(Note the added grouping around Jan|Feb|Mar.)\n",
"You could use Ping's rxb:\nyear = member(\"1\", \"2\") + digit*3\nmonth = either(\"Jan\", \"Feb\", \"Mar\")\nday = digit*2\nhour_mins = digit*2 + \":\" + digit*2\n\ndate = month + \" \" + day + \", \" + year + \", \" + hour_mins\n\nYou can then match on the resulting date directly, or use\nDateR = date.compile()\n\n"
] |
[
4,
1
] |
[] |
[] |
[
"python",
"regex"
] |
stackoverflow_0001156030_python_regex.txt
|
Q:
Latin-1 and the unicode factory in Python
I have a Python 2.6 script that is gagging on special characters, encoded in Latin-1, that I am retrieving from a SQL Server database. I would like to print these characters, but I'm somewhat limited because I am using a library that calls the unicode factory, and I don't know how to make Python use a codec other than ascii.
The script is a simple tool to return lookup data from a database without having to execute the SQL directly in a SQL editor. I use the PrettyTable 0.5 library to display the results.
The core of the script is this bit of code. The tuples I get from the cursor contain integer and string data, and no Unicode data. (I'd use adodbapi instead of pyodbc, which would get me Unicode, but adodbapi gives me other problems.)
x = pyodbc.connect(cxnstring)
r = x.cursor()
r.execute(sql)
t = PrettyTable(columns)
for rec in r:
t.add_row(rec)
r.close()
x.close()
t.set_field_align("ID", 'r')
t.set_field_align("Name", 'l')
print t
But the Name column can contain characters that fall outside the ASCII range. I'll sometimes get an error message like this, in line 222 of prettytable.pyc, when it gets to the t.add_row call:
UnicodeDecodeError: 'ascii' codec can't decode byte 0xed in position 12: ordinal not in range(128)
This is line 222 in prettytable.py. It uses unicode, which is the source of my problems, and not just in this script, but in other Python scripts that I have written.
for i in range(0,len(row)):
if len(unicode(row[i])) > self.widths[i]: # This is line 222
self.widths[i] = len(unicode(row[i]))
Please tell me what I'm doing wrong here. How can I make unicode work without hacking prettytable.py or any of the other libraries that I use? Is there even a way to do this?
EDIT: The error occurs not at the print statement, but at the t.add_row call.
EDIT: With Bastien Léonard's help, I came up with the following solution. It's not a panacea, but it works.
x = pyodbc.connect(cxnstring)
r = x.cursor()
r.execute(sql)
t = PrettyTable(columns)
for rec in r:
urec = [s.decode('latin-1') if isinstance(s, str) else s for s in rec]
t.add_row(urec)
r.close()
x.close()
t.set_field_align("ID", 'r')
t.set_field_align("Name", 'l')
print t.get_string().encode('latin-1')
I ended up having to decode on the way in and encode on the way out. All of this makes me hopeful that everybody ports their libraries to Python 3.x sooner than later!
A:
Add this at the beginning of the module:
# coding: latin1
Or decode the string to Unicode yourself.
[Edit]
It's been a while since I played with Unicode, but hopefully this example will show how to convert from Latin1 to Unicode:
>>> s = u'ééé'.encode('latin1') # a string you may get from the database
>>> s.decode('latin1')
u'\xe9\xe9\xe9'
[Edit]
Documentation:
http://docs.python.org/howto/unicode.html
http://docs.python.org/library/codecs.html
A:
Maybe try to decode the latin1-encoded strings into unicode?
t.add_row((value.decode('latin1') for value in rec))
A:
After a quick peek at the source for PrettyTable, it appears that it works on unicode objects internally (see _stringify_row, add_row and add_column, for example). Since it doesn't know what encoding your input strings are using, it uses the default encoding, usually ascii.
Now ascii is a subset of latin-1, which means if you're converting from ascii to latin-1, you shouldn't have any problems. The reverse however, isn't true; not all latin-1 characters map to ascii characters. To demonstrate this:
>>> s = u'\xed\x31\x32\x33'
>>> print s
# FAILS: Python calls "s.decode('ascii')", but ascii codec can't decode '\xed'
>>> print s.decode('ascii')
# FAILS: Same as above
>>> print s.decode('latin-1')
í123
Explicitly converting the strings to unicode (like you eventually did) fixes things, and makes more sense, IMO -- you're more likely to know what charset your data is using, than the author of PrettyTable :). BTW, you can omit the check for strings in your list comprehension by replacing s.decode('latin-1') with unicode(s, 'latin-1') since all objects can be coerced to strings.
One last thing: don't forget to check the character set of your database and tables -- you don't want to assume 'latin-1' in code, when the data is actually being stored as something else ('utf-8'?) in the database. In MySQL, you can use the SHOW CREATE TABLE <table_name> command to find out what character set a table is using, and SHOW CREATE DATABASE <db_name> to do the same for a database.
|
Latin-1 and the unicode factory in Python
|
I have a Python 2.6 script that is gagging on special characters, encoded in Latin-1, that I am retrieving from a SQL Server database. I would like to print these characters, but I'm somewhat limited because I am using a library that calls the unicode factory, and I don't know how to make Python use a codec other than ascii.
The script is a simple tool to return lookup data from a database without having to execute the SQL directly in a SQL editor. I use the PrettyTable 0.5 library to display the results.
The core of the script is this bit of code. The tuples I get from the cursor contain integer and string data, and no Unicode data. (I'd use adodbapi instead of pyodbc, which would get me Unicode, but adodbapi gives me other problems.)
x = pyodbc.connect(cxnstring)
r = x.cursor()
r.execute(sql)
t = PrettyTable(columns)
for rec in r:
t.add_row(rec)
r.close()
x.close()
t.set_field_align("ID", 'r')
t.set_field_align("Name", 'l')
print t
But the Name column can contain characters that fall outside the ASCII range. I'll sometimes get an error message like this, in line 222 of prettytable.pyc, when it gets to the t.add_row call:
UnicodeDecodeError: 'ascii' codec can't decode byte 0xed in position 12: ordinal not in range(128)
This is line 222 in prettytable.py. It uses unicode, which is the source of my problems, and not just in this script, but in other Python scripts that I have written.
for i in range(0,len(row)):
if len(unicode(row[i])) > self.widths[i]: # This is line 222
self.widths[i] = len(unicode(row[i]))
Please tell me what I'm doing wrong here. How can I make unicode work without hacking prettytable.py or any of the other libraries that I use? Is there even a way to do this?
EDIT: The error occurs not at the print statement, but at the t.add_row call.
EDIT: With Bastien Léonard's help, I came up with the following solution. It's not a panacea, but it works.
x = pyodbc.connect(cxnstring)
r = x.cursor()
r.execute(sql)
t = PrettyTable(columns)
for rec in r:
urec = [s.decode('latin-1') if isinstance(s, str) else s for s in rec]
t.add_row(urec)
r.close()
x.close()
t.set_field_align("ID", 'r')
t.set_field_align("Name", 'l')
print t.get_string().encode('latin-1')
I ended up having to decode on the way in and encode on the way out. All of this makes me hopeful that everybody ports their libraries to Python 3.x sooner than later!
|
[
"Add this at the beginning of the module:\n# coding: latin1\n\nOr decode the string to Unicode yourself.\n[Edit]\nIt's been a while since I played with Unicode, but hopefully this example will show how to convert from Latin1 to Unicode:\n>>> s = u'ééé'.encode('latin1') # a string you may get from the database\n>>> s.decode('latin1')\nu'\\xe9\\xe9\\xe9'\n\n[Edit]\nDocumentation:\nhttp://docs.python.org/howto/unicode.html\nhttp://docs.python.org/library/codecs.html\n",
"Maybe try to decode the latin1-encoded strings into unicode?\nt.add_row((value.decode('latin1') for value in rec))\n\n",
"After a quick peek at the source for PrettyTable, it appears that it works on unicode objects internally (see _stringify_row, add_row and add_column, for example). Since it doesn't know what encoding your input strings are using, it uses the default encoding, usually ascii.\nNow ascii is a subset of latin-1, which means if you're converting from ascii to latin-1, you shouldn't have any problems. The reverse however, isn't true; not all latin-1 characters map to ascii characters. To demonstrate this:\n>>> s = u'\\xed\\x31\\x32\\x33'\n>>> print s\n# FAILS: Python calls \"s.decode('ascii')\", but ascii codec can't decode '\\xed'\n>>> print s.decode('ascii')\n# FAILS: Same as above\n>>> print s.decode('latin-1')\ní123\n\nExplicitly converting the strings to unicode (like you eventually did) fixes things, and makes more sense, IMO -- you're more likely to know what charset your data is using, than the author of PrettyTable :). BTW, you can omit the check for strings in your list comprehension by replacing s.decode('latin-1') with unicode(s, 'latin-1') since all objects can be coerced to strings.\nOne last thing: don't forget to check the character set of your database and tables -- you don't want to assume 'latin-1' in code, when the data is actually being stored as something else ('utf-8'?) in the database. In MySQL, you can use the SHOW CREATE TABLE <table_name> command to find out what character set a table is using, and SHOW CREATE DATABASE <db_name> to do the same for a database.\n"
] |
[
7,
2,
0
] |
[] |
[] |
[
"python",
"unicode"
] |
stackoverflow_0001155903_python_unicode.txt
|
Q:
Import Dynamically Created Python Files
I am creating python files through the course of running a python program. I then want to import these files and run functions that were defined within them. The files I am creating are not stored within my path variables and I'd prefer to keep it that way.
Originally I was calling the execFile(<script_path>) function and then calling the function defined by executing the file. This has a side effect of always entering the if __name__ == "__main__" condition, which with my current setup I can't have happen.
I can't change the generated files, because I've already created 100's of them and don't want to have to revise them all. I can only change the file that calls the generated files.
Basically what I have now...
#<c:\File.py>
def func(word):
print word
if __name__ == "__main__":
print "must only be called from command line"
#results in an error when called from CallingFunction.py
input = sys.argv[1]
#<CallingFunction.py>
#results in Main Condition being called
execFile("c:\\File.py")
func("hello world")
A:
Use
m = __import__("File")
This is essentially the same as doing
import File
m = File
A:
If I understand correctly your remarks to man that the file isn't in sys.path and you'd rather keep it that way, this would still work:
import imp
fileobj, pathname, description = imp.find_module('thefile', 'c:/')
moduleobj = imp.load_module('thefile', fileobj, pathname, description)
fileobj.close()
(Of course, given 'c:/thefile.py', you can extract the parts 'c:/' and 'thefile.py' with os.path.spliy, and from 'thefile.py' get 'thefile' with os.path.splitext.)
|
Import Dynamically Created Python Files
|
I am creating python files through the course of running a python program. I then want to import these files and run functions that were defined within them. The files I am creating are not stored within my path variables and I'd prefer to keep it that way.
Originally I was calling the execFile(<script_path>) function and then calling the function defined by executing the file. This has a side effect of always entering the if __name__ == "__main__" condition, which with my current setup I can't have happen.
I can't change the generated files, because I've already created 100's of them and don't want to have to revise them all. I can only change the file that calls the generated files.
Basically what I have now...
#<c:\File.py>
def func(word):
print word
if __name__ == "__main__":
print "must only be called from command line"
#results in an error when called from CallingFunction.py
input = sys.argv[1]
#<CallingFunction.py>
#results in Main Condition being called
execFile("c:\\File.py")
func("hello world")
|
[
"Use\nm = __import__(\"File\")\n\nThis is essentially the same as doing\nimport File\nm = File\n\n",
"If I understand correctly your remarks to man that the file isn't in sys.path and you'd rather keep it that way, this would still work:\nimport imp\n\nfileobj, pathname, description = imp.find_module('thefile', 'c:/')\nmoduleobj = imp.load_module('thefile', fileobj, pathname, description)\nfileobj.close()\n\n(Of course, given 'c:/thefile.py', you can extract the parts 'c:/' and 'thefile.py' with os.path.spliy, and from 'thefile.py' get 'thefile' with os.path.splitext.)\n"
] |
[
5,
3
] |
[] |
[] |
[
"import",
"python"
] |
stackoverflow_0001156356_import_python.txt
|
Q:
Python: re.find longest sequence
I have a string that is randomly generated:
polymer_str = "diol diNCO diamine diNCO diamine diNCO diamine diNCO diol diNCO diamine"
I'd like to find the longest sequence of "diNCO diol" and the longest of "diNCO diamine". So in the case above the longest "diNCO diol" sequence is 1 and the longest "diNCO diamine" is 3.
How would I go about doing this using python's re module?
Thanks in advance.
EDIT:
I mean the longest number of repeats of a given string. So the longest string with "diNCO diamine" is 3:
diol diNCO diamine diNCO diamine diNCO diamine diNCO diol diNCO diamine
A:
Expanding on Ealdwulf's answer:
Documentation on re.findall can be found here.
def getLongestSequenceSize(search_str, polymer_str):
matches = re.findall(r'(?:\b%s\b\s?)+' % search_str, polymer_str)
longest_match = max(matches)
return longest_match.count(search_str)
This could be written as one line, but it becomes less readable in that form.
Alternative:
If polymer_str is huge, it will be more memory efficient to use re.finditer. Here's how you might go about it:
def getLongestSequenceSize(search_str, polymer_str):
longest_match = ''
for match in re.finditer(r'(?:\b%s\b\s?)+' % search_str, polymer_str):
if len(match.group(0)) > len(longest_match):
longest_match = match.group(0)
return longest_match.count(search_str)
The biggest difference between findall and finditer is that the first returns a list object, while the second iterates over Match objects. Also, the finditer approach will be somewhat slower.
A:
I think the op wants the longest contiguous sequence. You can get all contiguous sequences like:
seqs = re.findall("(?:diNCO diamine)+", polymer_str)
and then find the longest.
A:
import re
pat = re.compile("[^|]+")
p = "diol diNCO diamine diNCO diamine diNCO diamine diNCO diol diNCO diamine".replace("diNCO diamine","|").replace(" ","")
print max(map(len,pat.split(p)))
A:
One was is to use findall:
polymer_str = "diol diNCO diamine diNCO diamine diNCO diamine diNCO diol diNCO diamine"
len(re.findall("diNCO diamine", polymer_str)) # returns 4.
A:
Using re:
m = re.search(r"(\bdiNCO diamine\b\s?)+", polymer_str)
len(m.group(0)) / len("bdiNCO diamine")
|
Python: re.find longest sequence
|
I have a string that is randomly generated:
polymer_str = "diol diNCO diamine diNCO diamine diNCO diamine diNCO diol diNCO diamine"
I'd like to find the longest sequence of "diNCO diol" and the longest of "diNCO diamine". So in the case above the longest "diNCO diol" sequence is 1 and the longest "diNCO diamine" is 3.
How would I go about doing this using python's re module?
Thanks in advance.
EDIT:
I mean the longest number of repeats of a given string. So the longest string with "diNCO diamine" is 3:
diol diNCO diamine diNCO diamine diNCO diamine diNCO diol diNCO diamine
|
[
"Expanding on Ealdwulf's answer:\nDocumentation on re.findall can be found here.\ndef getLongestSequenceSize(search_str, polymer_str):\n matches = re.findall(r'(?:\\b%s\\b\\s?)+' % search_str, polymer_str)\n longest_match = max(matches)\n return longest_match.count(search_str)\n\nThis could be written as one line, but it becomes less readable in that form.\nAlternative:\nIf polymer_str is huge, it will be more memory efficient to use re.finditer. Here's how you might go about it:\ndef getLongestSequenceSize(search_str, polymer_str):\n longest_match = ''\n for match in re.finditer(r'(?:\\b%s\\b\\s?)+' % search_str, polymer_str):\n if len(match.group(0)) > len(longest_match):\n longest_match = match.group(0)\n return longest_match.count(search_str)\n\nThe biggest difference between findall and finditer is that the first returns a list object, while the second iterates over Match objects. Also, the finditer approach will be somewhat slower.\n",
"I think the op wants the longest contiguous sequence. You can get all contiguous sequences like:\nseqs = re.findall(\"(?:diNCO diamine)+\", polymer_str) \nand then find the longest.\n",
"import re\npat = re.compile(\"[^|]+\")\np = \"diol diNCO diamine diNCO diamine diNCO diamine diNCO diol diNCO diamine\".replace(\"diNCO diamine\",\"|\").replace(\" \",\"\")\nprint max(map(len,pat.split(p)))\n\n",
"One was is to use findall:\npolymer_str = \"diol diNCO diamine diNCO diamine diNCO diamine diNCO diol diNCO diamine\"\nlen(re.findall(\"diNCO diamine\", polymer_str)) # returns 4.\n\n",
"Using re:\n m = re.search(r\"(\\bdiNCO diamine\\b\\s?)+\", polymer_str)\n len(m.group(0)) / len(\"bdiNCO diamine\")\n\n"
] |
[
10,
3,
3,
0,
0
] |
[] |
[] |
[
"python",
"regex"
] |
stackoverflow_0001155376_python_regex.txt
|
Q:
Read Block Data in Python?
I have a problem reading data file:
///
* ABC Names
A-06,B-18,
* Data
1.727e-01, 1.258e-01, 2.724e-01, 2.599e-01,-3.266e-01,-9.425e-02,-6.213e-02, 1.479e-01,
1.219e-01, 1.174e-01, 2.213e-01, 2.875e-01,-2.306e-01,-3.900e-03,-5.269e-02, 7.420e-02,
2.592e-01, 2.513e-01, 2.242e-01, 2.620e-01,-1.346e-01,-6.844e-02,-4.139e-02, 9.502e-02,
1.981e-01, 1.937e-01, 2.336e-01, 1.617e-01,-4.240e-02, 2.285e-02, 1.878e-02, 1.064e-01,
9.562e-02, 6.727e-02, 1.135e-01, 6.765e-02,-7.850e-02, 6.711e-02, 1.317e-02, 8.367e-02,
* Starting position
-.5000E+01
///
Code run in Python? I tried using readline(), readlines() functions but no result.
A:
Here's a complete guess at some code that might load the type of file this is an example of, but which should be a little robust:
f = open("mdata.txt")
data_dict = {}
section = None
data_for_section = ""
for line in f:
line = line.strip() #remove whitespace at start and end
if section != None and (line[0] == "*" or line == "///"):
# if we've just finished a section, put whatever we got into the data dict
data_dict[section] = [bit for bit in data_for_section.split(",") if bit != ""]
if line[0] == "*":
# "*" denotes the start of a new section, probably, so remember the name
section = line [2:]
data_for_section = ""
continue
data_for_section += line
f.close()
#got the data, now for some output
print "loaded file. Found headings: %s"%(", ".join(data_dict.keys()))
for key in data_dict.keys():
if len(data_dict[key])>5:
print key, ": array of %i entries"%len(data_dict[key])
else:
print key, ": ", data_dict[key]
which outputs for your file:
loaded file. Found headings: ABC Names, Data, Starting position
ABC Names : ['A-06', 'B-18']
Data : array of 40 entries
Starting position : ['-.5000E+01']
of course, you'd probably want to convert the list of data strings to floating point numbers in the case of data and starting position:
startingPosition = float(data_dict["Starting position"][0])
data_list_of_floats = map(float, data_dict["Data"])
But as to the ABC Names and how they combine with the rest of the file, we'd need some more information for that.
A:
This ought to work for files with block names 'a', 'b', and 'c'. It will create a dictionary with keys as block titles like so:
{'a':['line1','line2'],'b':['line1'],'c':['line1','line2','line3']}
code:
block_names = ['b','a','c']
for line in open('file.txt'):
block_dict = {} #dict to populate with lists of lines
block = [] # dummy block in case there is data or lines before first block
ck_nm = [blk_nm for blk_nm in block_names if line.startswith(blk_nm)] #search block names for a match
if ck_nm: # did we find a match?
block_dict[ck_nm[0]] = block = [] # set current block
else:
block.append(line) #..or line.split(',') ..however you want to parse the data
A:
Suppose the file's named "abc.txt" and is in the current directory; then the following Python script:
f = open("abc.txt")
all_lines = f.readlines()
will read all the lines into list of strings all_lines, each with its ending \n and all.
What you want to do after that we can't guess unless you tell us, but the part you're asking about, the reading, should be satisfied.
A:
Assuming you want to get the block from *Data to *Starting Position,
f=0
for line in open("file"):
line=line.strip()
if "Starting" in line:
f=0
if "Data" in line:
f=1
continue
if f:
print line
the idea is to set a flag. if *Data is hit, set flag. the print all lines if flag is set. If *Starting is hit, turn off the flag.
|
Read Block Data in Python?
|
I have a problem reading data file:
///
* ABC Names
A-06,B-18,
* Data
1.727e-01, 1.258e-01, 2.724e-01, 2.599e-01,-3.266e-01,-9.425e-02,-6.213e-02, 1.479e-01,
1.219e-01, 1.174e-01, 2.213e-01, 2.875e-01,-2.306e-01,-3.900e-03,-5.269e-02, 7.420e-02,
2.592e-01, 2.513e-01, 2.242e-01, 2.620e-01,-1.346e-01,-6.844e-02,-4.139e-02, 9.502e-02,
1.981e-01, 1.937e-01, 2.336e-01, 1.617e-01,-4.240e-02, 2.285e-02, 1.878e-02, 1.064e-01,
9.562e-02, 6.727e-02, 1.135e-01, 6.765e-02,-7.850e-02, 6.711e-02, 1.317e-02, 8.367e-02,
* Starting position
-.5000E+01
///
Code run in Python? I tried using readline(), readlines() functions but no result.
|
[
"Here's a complete guess at some code that might load the type of file this is an example of, but which should be a little robust: \nf = open(\"mdata.txt\")\n\ndata_dict = {}\nsection = None\ndata_for_section = \"\"\nfor line in f:\n line = line.strip() #remove whitespace at start and end\n\n if section != None and (line[0] == \"*\" or line == \"///\"):\n # if we've just finished a section, put whatever we got into the data dict\n data_dict[section] = [bit for bit in data_for_section.split(\",\") if bit != \"\"]\n\n if line[0] == \"*\":\n # \"*\" denotes the start of a new section, probably, so remember the name\n section = line [2:]\n data_for_section = \"\"\n continue\n data_for_section += line\n\nf.close()\n#got the data, now for some output\nprint \"loaded file. Found headings: %s\"%(\", \".join(data_dict.keys()))\n\nfor key in data_dict.keys():\n if len(data_dict[key])>5:\n print key, \": array of %i entries\"%len(data_dict[key])\n else:\n print key, \": \", data_dict[key]\n\nwhich outputs for your file:\nloaded file. Found headings: ABC Names, Data, Starting position\nABC Names : ['A-06', 'B-18']\nData : array of 40 entries\nStarting position : ['-.5000E+01']\nof course, you'd probably want to convert the list of data strings to floating point numbers in the case of data and starting position:\nstartingPosition = float(data_dict[\"Starting position\"][0])\ndata_list_of_floats = map(float, data_dict[\"Data\"])\n\nBut as to the ABC Names and how they combine with the rest of the file, we'd need some more information for that.\n",
"This ought to work for files with block names 'a', 'b', and 'c'. It will create a dictionary with keys as block titles like so:\n{'a':['line1','line2'],'b':['line1'],'c':['line1','line2','line3']} \n\ncode:\nblock_names = ['b','a','c']\n\nfor line in open('file.txt'):\n block_dict = {} #dict to populate with lists of lines\n block = [] # dummy block in case there is data or lines before first block\n ck_nm = [blk_nm for blk_nm in block_names if line.startswith(blk_nm)] #search block names for a match\n if ck_nm: # did we find a match?\n block_dict[ck_nm[0]] = block = [] # set current block\n else:\n block.append(line) #..or line.split(',') ..however you want to parse the data\n\n",
"Suppose the file's named \"abc.txt\" and is in the current directory; then the following Python script:\nf = open(\"abc.txt\")\nall_lines = f.readlines()\n\nwill read all the lines into list of strings all_lines, each with its ending \\n and all.\nWhat you want to do after that we can't guess unless you tell us, but the part you're asking about, the reading, should be satisfied.\n",
"Assuming you want to get the block from *Data to *Starting Position, \nf=0\nfor line in open(\"file\"):\n line=line.strip()\n if \"Starting\" in line:\n f=0\n if \"Data\" in line:\n f=1\n continue\n if f:\n print line\n\nthe idea is to set a flag. if *Data is hit, set flag. the print all lines if flag is set. If *Starting is hit, turn off the flag.\n"
] |
[
2,
1,
0,
0
] |
[
"Without any other information...\ndata = [\n1.727e-01, 1.258e-01, 2.724e-01, 2.599e-01,-3.266e-01,-9.425e-02,-6.213e-02, 1.479e-01,\n1.219e-01, 1.174e-01, 2.213e-01, 2.875e-01,-2.306e-01,-3.900e-03,-5.269e-02, 7.420e-02,\n2.592e-01, 2.513e-01, 2.242e-01, 2.620e-01,-1.346e-01,-6.844e-02,-4.139e-02, 9.502e-02,\n1.981e-01, 1.937e-01, 2.336e-01, 1.617e-01,-4.240e-02, 2.285e-02, 1.878e-02, 1.064e-01,\n9.562e-02, 6.727e-02, 1.135e-01, 6.765e-02,-7.850e-02, 6.711e-02, 1.317e-02, 8.367e-02,\n]\n\n"
] |
[
-1
] |
[
"file",
"python"
] |
stackoverflow_0001141101_file_python.txt
|
Q:
How to a query a set of objects and return a set of object specific attribute in SQLachemy/Elixir?
Suppose that I have a table like:
class Ticker(Entity):
ticker = Field(String(7))
tsdata = OneToMany('TimeSeriesData')
staticdata = OneToMany('StaticData')
How would I query it so that it returns a set of Ticker.ticker?
I dig into the doc and seems like select() is the way to go. However I am not too familiar with the sqlalchemy syntax. Any help is appreciated.
ADDED: My ultimate goal is to have a set of current ticker such that, when new ticker is not in the set, it will be inserted into the database. I am just learning how to create a database and sql in general. Any thought is appreciated.
Thanks. :)
A:
Not sure what you're after exactly but to get an array with all 'Ticker.ticker' values you would do this:
[instance.ticker for instance in Ticker.query.all()]
What you really want is probably the Elixir getting started tutorial - it's good so take a look!
UPDATE 1: Since you have a database, the best way to find out if a new potential ticker needs to be inserted or not is to query the database. This will be much faster than reading all tickers into memory and checking. To see if a value is there or not, try this:
Ticker.query.filter_by(ticker=new_ticker_value).first()
If the result is None you don't have it yet. So all together,
if Ticker.query.filter_by(ticker=new_ticker_value).first() is None:
Ticker(ticker=new_ticker_value)
session.commit()
|
How to a query a set of objects and return a set of object specific attribute in SQLachemy/Elixir?
|
Suppose that I have a table like:
class Ticker(Entity):
ticker = Field(String(7))
tsdata = OneToMany('TimeSeriesData')
staticdata = OneToMany('StaticData')
How would I query it so that it returns a set of Ticker.ticker?
I dig into the doc and seems like select() is the way to go. However I am not too familiar with the sqlalchemy syntax. Any help is appreciated.
ADDED: My ultimate goal is to have a set of current ticker such that, when new ticker is not in the set, it will be inserted into the database. I am just learning how to create a database and sql in general. Any thought is appreciated.
Thanks. :)
|
[
"Not sure what you're after exactly but to get an array with all 'Ticker.ticker' values you would do this:\n[instance.ticker for instance in Ticker.query.all()]\n\nWhat you really want is probably the Elixir getting started tutorial - it's good so take a look!\nUPDATE 1: Since you have a database, the best way to find out if a new potential ticker needs to be inserted or not is to query the database. This will be much faster than reading all tickers into memory and checking. To see if a value is there or not, try this:\nTicker.query.filter_by(ticker=new_ticker_value).first()\n\nIf the result is None you don't have it yet. So all together,\nif Ticker.query.filter_by(ticker=new_ticker_value).first() is None:\n Ticker(ticker=new_ticker_value)\n session.commit()\n\n"
] |
[
0
] |
[] |
[] |
[
"python",
"sql",
"sqlalchemy"
] |
stackoverflow_0001156962_python_sql_sqlalchemy.txt
|
Q:
cx_Oracle and the data source paradigm
There is a Java paradigm for database access implemented in the Java DataSource. This object create a useful abstraction around the creation of database connections. The DataSource object keeps database configuration, but will only create database connections on request. This is allows you to keep all database configuration and initialization code in one place, and makes it easy to change database implementation, or use a mock database for testing.
I currently working on a Python project which uses cx_Oracle. In cx_Oracle, one gets a connection directly from the module:
import cx_Oracle as dbapi
connection = dbapi.connect(connection_string)
# At this point I am assuming that a real connection has been made to the database.
# Is this true?
I am trying to find a parallel to the DataSource in cx_Oracle. I can easily create this by creating a new class and wrapping cx_Oracle, but I was wondering if this is the right way to do it in Python.
A:
You'll find relevant information of how to access databases in Python by looking at PEP-249: Python Database API Specification v2.0. cx_Oracle conforms to this specification, as do many database drivers for Python.
In this specification a Connection object represents a database connection, but there is no built-in pooling. Tools such as SQLAlchemy do provide pooling facilities, and although SQLAlchemy is often billed as an ORM, it does not have to be used as such and offers nice abstractions for use on top of SQL engines.
If you do want to do object-relational-mapping, then SQLAlchemy does the business, and you can consider either its own declarative syntax or another layer such as Elixir which sits on top of SQLAlchemy and provides increased ease of use for more common use cases.
A:
I don't think there is a "right" way to do this in Python, except maybe to go one step further and use another layer between yourself and the database.
Depending on the reason for wanting to use the DataSource concept (which I've only ever come across in Java), SQLAlchemy (or something similar) might solve the problems for you, without you having to write something from scratch.
If that doesn't fit the bill, writing your own wrapper sounds like a reasonable solution.
A:
Yes, Python has a similar abstraction.
This is from our local build regression test, where we assure that we can talk to all of our databases whenever we build a new python.
if database == SYBASE:
import Sybase
conn = Sybase.connect('sybasetestdb','mh','secret')
elif database == POSTRESQL:
import pgdb
conn = pgdb.connect('pgtestdb:mh:secret')
elif database == ORACLE:
import cx_Oracle
conn = cx_Oracle.connect("mh/secret@oracletestdb")
curs=conn.cursor()
curs.execute('select a,b from testtable')
for row in curs.fetchall():
print row
(note, this is the simple version, in our multidb-aware code we have a dbconnection class that has this logic inside.)
A:
I just sucked it up and wrote my own. It allowed me to add things like abstracting the database (Oracle/MySQL/Access/etc), adding logging, error handling with transaction rollbacks, etc.
|
cx_Oracle and the data source paradigm
|
There is a Java paradigm for database access implemented in the Java DataSource. This object create a useful abstraction around the creation of database connections. The DataSource object keeps database configuration, but will only create database connections on request. This is allows you to keep all database configuration and initialization code in one place, and makes it easy to change database implementation, or use a mock database for testing.
I currently working on a Python project which uses cx_Oracle. In cx_Oracle, one gets a connection directly from the module:
import cx_Oracle as dbapi
connection = dbapi.connect(connection_string)
# At this point I am assuming that a real connection has been made to the database.
# Is this true?
I am trying to find a parallel to the DataSource in cx_Oracle. I can easily create this by creating a new class and wrapping cx_Oracle, but I was wondering if this is the right way to do it in Python.
|
[
"You'll find relevant information of how to access databases in Python by looking at PEP-249: Python Database API Specification v2.0. cx_Oracle conforms to this specification, as do many database drivers for Python.\nIn this specification a Connection object represents a database connection, but there is no built-in pooling. Tools such as SQLAlchemy do provide pooling facilities, and although SQLAlchemy is often billed as an ORM, it does not have to be used as such and offers nice abstractions for use on top of SQL engines.\nIf you do want to do object-relational-mapping, then SQLAlchemy does the business, and you can consider either its own declarative syntax or another layer such as Elixir which sits on top of SQLAlchemy and provides increased ease of use for more common use cases.\n",
"I don't think there is a \"right\" way to do this in Python, except maybe to go one step further and use another layer between yourself and the database.\nDepending on the reason for wanting to use the DataSource concept (which I've only ever come across in Java), SQLAlchemy (or something similar) might solve the problems for you, without you having to write something from scratch.\nIf that doesn't fit the bill, writing your own wrapper sounds like a reasonable solution.\n",
"Yes, Python has a similar abstraction.\nThis is from our local build regression test, where we assure that we can talk to all of our databases whenever we build a new python.\nif database == SYBASE:\n import Sybase\n conn = Sybase.connect('sybasetestdb','mh','secret')\nelif database == POSTRESQL:\n import pgdb\n conn = pgdb.connect('pgtestdb:mh:secret')\nelif database == ORACLE:\n import cx_Oracle\n conn = cx_Oracle.connect(\"mh/secret@oracletestdb\")\n\ncurs=conn.cursor()\ncurs.execute('select a,b from testtable')\nfor row in curs.fetchall():\n print row\n\n(note, this is the simple version, in our multidb-aware code we have a dbconnection class that has this logic inside.)\n",
"I just sucked it up and wrote my own. It allowed me to add things like abstracting the database (Oracle/MySQL/Access/etc), adding logging, error handling with transaction rollbacks, etc.\n"
] |
[
3,
1,
0,
0
] |
[] |
[] |
[
"cx_oracle",
"database",
"oracle",
"python"
] |
stackoverflow_0001148472_cx_oracle_database_oracle_python.txt
|
Q:
Python: question about parsing human-readable text
I'm parsing human-readable scientific text that is mostly in the field of chemistry. What I'm interested in is breaking the text into a list of words, scientific terms (more on that below), and punctuation marks.
So for example, I expect the text "hello, world." to break into 4 tokens: 1) "hello"; 2) comma; 3) "world" and 4) period. Note that spaces don't require specialized tokens.
The problem is related to the "scientific terms": these are names of chemical formulas such as "1-methyl-4-phenylpyridinium". Anyone who has ever learned chemistry knows these formulas can get quite long and may contain numbers, dashes and commas, and sometimes even parentheses, but I think it's safe to assume these lovely expressions can't contain spaces. Also, I believe these expressions must start with a number. I would like each such expression to come out as a single token.
Today I use manual parsing to find "chunks" of text that begin with a number and end with either a space, a line break, or a punctuation mark followed by either a space or line break.
I wondered if there's a smart solution (regex or other) I can use to tokenize the text according to the above specifications. I'm working in Python but this may be language agnostic.
An example input (obviously disregard the content...):
"Hello. 1-methyl-4-phenylpyridinium is ultra-bad. However, 1-methyl-4-phenyl-1,2,3,6-tetrahydropyridine is worse."
Example output (each token in its own line):
Hello
.
1-methyl-4-phenylpyridinium
is
ultra
-
bad
.
However
,
1-methyl-4-phenyl-1,2,3,6-tetrahydropyridine
is
worse
.
A:
This will solve your current example. It can be tweaked for a larger data set.
import re
splitterForIndexing = re.compile(r"(?:[a-zA-Z0-9\-,]+[a-zA-Z0-9\-])|(?:[,.])")
source = "Hello. 1-methyl-4-phenylpyridinium is ultra-bad. However, 1-methyl-4-phenyl-1,2,3,6-tetrahydropyridine is worse."
print "\n".join( splitterForIndexing.findall(source))
The result is:
"""
Hello
.
1-methyl-4-phenylpyridinium
is
ultra-bad
.
However
,
1-methyl-4-phenyl-1,2,3,6-tetrahydropyridine
is
worse
.
"""
Sorry didn't see ultra-bad. If it's necessary for those words to be split..
import re
splitterForIndexing = re.compile(r"(?:[a-zA-Z]+)|(?:[a-zA-Z0-9][a-zA-Z0-9\-(),]+[a-zA-Z0-9\-()])|(?:[,.-])")
source = "Hello. 1-methyl-4-phenylpyridinium is ultra-bad. However, 1-methyl-4-phenyl-1,(2,3),6-tetrahydropyridine is worse."
print "\n".join( splitterForIndexing.findall(source))
Gives:
"""
Hello
.
1-methyl-4-phenylpyridinium
is
ultra
-
bad
.
However
,
1-methyl-4-phenyl-1,(2,3),6-tetrahydropyridine
is
worse
.
"""
A:
There might be a regex parsing what you want, but I don't think it will be very readable/maintainable. My advice would be to use a parser generator like ANTLR. I think you'll have to throw the notion overboard that you can make the chemical descriptions a single token, much too complex. ANTLR even has a debugger so you can see why it's not parsing something you think it should, I don't think that's possible using regexps.
Regards,
Sebastiaan
A:
I agree with Sebastiaan Megens that a regex solution may be possible, but probably not very readable or maintainable, especially if you are not already good with regular expressions. I would recommend the pyparsing module, if you're sticking with Python (which I think is a good choice).
Extra maintainability will come in very handy if your parsing needs should grow or change. (And I'm sure plenty of folks would say "when" rather than "if"! For example, someone already commented that you may need a more sophisticated notion of what needs to be allowed as a chemical name. Maybe your requirements are already changing before you've even chosen your tool!)
|
Python: question about parsing human-readable text
|
I'm parsing human-readable scientific text that is mostly in the field of chemistry. What I'm interested in is breaking the text into a list of words, scientific terms (more on that below), and punctuation marks.
So for example, I expect the text "hello, world." to break into 4 tokens: 1) "hello"; 2) comma; 3) "world" and 4) period. Note that spaces don't require specialized tokens.
The problem is related to the "scientific terms": these are names of chemical formulas such as "1-methyl-4-phenylpyridinium". Anyone who has ever learned chemistry knows these formulas can get quite long and may contain numbers, dashes and commas, and sometimes even parentheses, but I think it's safe to assume these lovely expressions can't contain spaces. Also, I believe these expressions must start with a number. I would like each such expression to come out as a single token.
Today I use manual parsing to find "chunks" of text that begin with a number and end with either a space, a line break, or a punctuation mark followed by either a space or line break.
I wondered if there's a smart solution (regex or other) I can use to tokenize the text according to the above specifications. I'm working in Python but this may be language agnostic.
An example input (obviously disregard the content...):
"Hello. 1-methyl-4-phenylpyridinium is ultra-bad. However, 1-methyl-4-phenyl-1,2,3,6-tetrahydropyridine is worse."
Example output (each token in its own line):
Hello
.
1-methyl-4-phenylpyridinium
is
ultra
-
bad
.
However
,
1-methyl-4-phenyl-1,2,3,6-tetrahydropyridine
is
worse
.
|
[
"This will solve your current example. It can be tweaked for a larger data set.\nimport re\nsplitterForIndexing = re.compile(r\"(?:[a-zA-Z0-9\\-,]+[a-zA-Z0-9\\-])|(?:[,.])\")\nsource = \"Hello. 1-methyl-4-phenylpyridinium is ultra-bad. However, 1-methyl-4-phenyl-1,2,3,6-tetrahydropyridine is worse.\"\nprint \"\\n\".join( splitterForIndexing.findall(source))\n\nThe result is:\n\"\"\"\nHello\n.\n1-methyl-4-phenylpyridinium\nis\nultra-bad\n.\nHowever\n,\n1-methyl-4-phenyl-1,2,3,6-tetrahydropyridine\nis\nworse\n.\n\"\"\"\n\nSorry didn't see ultra-bad. If it's necessary for those words to be split..\nimport re\nsplitterForIndexing = re.compile(r\"(?:[a-zA-Z]+)|(?:[a-zA-Z0-9][a-zA-Z0-9\\-(),]+[a-zA-Z0-9\\-()])|(?:[,.-])\")\nsource = \"Hello. 1-methyl-4-phenylpyridinium is ultra-bad. However, 1-methyl-4-phenyl-1,(2,3),6-tetrahydropyridine is worse.\"\nprint \"\\n\".join( splitterForIndexing.findall(source))\n\nGives:\n\"\"\"\nHello\n.\n1-methyl-4-phenylpyridinium\nis\nultra\n-\nbad\n.\nHowever\n,\n1-methyl-4-phenyl-1,(2,3),6-tetrahydropyridine\nis\nworse\n.\n\"\"\"\n\n",
"There might be a regex parsing what you want, but I don't think it will be very readable/maintainable. My advice would be to use a parser generator like ANTLR. I think you'll have to throw the notion overboard that you can make the chemical descriptions a single token, much too complex. ANTLR even has a debugger so you can see why it's not parsing something you think it should, I don't think that's possible using regexps.\nRegards,\nSebastiaan\n",
"I agree with Sebastiaan Megens that a regex solution may be possible, but probably not very readable or maintainable, especially if you are not already good with regular expressions. I would recommend the pyparsing module, if you're sticking with Python (which I think is a good choice).\nExtra maintainability will come in very handy if your parsing needs should grow or change. (And I'm sure plenty of folks would say \"when\" rather than \"if\"! For example, someone already commented that you may need a more sophisticated notion of what needs to be allowed as a chemical name. Maybe your requirements are already changing before you've even chosen your tool!)\n"
] |
[
2,
0,
0
] |
[] |
[] |
[
"parsing",
"python"
] |
stackoverflow_0001153183_parsing_python.txt
|
Q:
How to update an older C extension for Python 2.x to Python 3.x
I'm wanting to use an extension for Python that I found here, but I'm using Python 3.1 and when I attempt to compile the C extension included in the package (_wincon), it does not compile due to all the syntax errors. Unfortunately, it was written for 2.x versions of Python and as such includes methods such as PyMember_Get and PyMember_Set, which are no longer part of Python. My problem is that I have not gotten around to learning C and as such have not been able to figure out how to modify the code to use syntax that is still valid in Python 3.1. (There were also a couple macros such as staticforward that need fixing, but I'm assuming those just need to be changed to static.) Therefore: how do I go about fixing this?
(Note that I have indeed looked into various other Windows console interfaces for Python such as the win32con extension in PyWin32), but none of them fit my needs as much as this one appears to.)
A:
I don't believe there is any magic bullet to make the C sources for a Python extension coded for some old-ish version of Python 2, into valid C sources for one coded for Python 3 -- it takes understanding of C and of how the C API has changed, and of what exactly the extension is doing in each part of its code. Believe me, if we had known of some magic bullet way to do it susbtantially without such human knowledge and understanding, we'd have included a "code generator" (like 2to3 for Python sources -- and even that has substantial limitations!) for such C code translation.
In practice, even though Python 3.1 is per se a mature and production-ready language, you should not yet migrate your code (or write a totally new app) in Python 3.1 if you need some Python 2.* extension that you're unable to port -- stick with 2.6 until the extensions you require are available (or you have learned enough C to port them yourself -- or rewrite them in Cython, which DOES smoothly support Python 2.* and 3.*, with, I believe, just a modicum of care on the programmer's part).
|
How to update an older C extension for Python 2.x to Python 3.x
|
I'm wanting to use an extension for Python that I found here, but I'm using Python 3.1 and when I attempt to compile the C extension included in the package (_wincon), it does not compile due to all the syntax errors. Unfortunately, it was written for 2.x versions of Python and as such includes methods such as PyMember_Get and PyMember_Set, which are no longer part of Python. My problem is that I have not gotten around to learning C and as such have not been able to figure out how to modify the code to use syntax that is still valid in Python 3.1. (There were also a couple macros such as staticforward that need fixing, but I'm assuming those just need to be changed to static.) Therefore: how do I go about fixing this?
(Note that I have indeed looked into various other Windows console interfaces for Python such as the win32con extension in PyWin32), but none of them fit my needs as much as this one appears to.)
|
[
"I don't believe there is any magic bullet to make the C sources for a Python extension coded for some old-ish version of Python 2, into valid C sources for one coded for Python 3 -- it takes understanding of C and of how the C API has changed, and of what exactly the extension is doing in each part of its code. Believe me, if we had known of some magic bullet way to do it susbtantially without such human knowledge and understanding, we'd have included a \"code generator\" (like 2to3 for Python sources -- and even that has substantial limitations!) for such C code translation.\nIn practice, even though Python 3.1 is per se a mature and production-ready language, you should not yet migrate your code (or write a totally new app) in Python 3.1 if you need some Python 2.* extension that you're unable to port -- stick with 2.6 until the extensions you require are available (or you have learned enough C to port them yourself -- or rewrite them in Cython, which DOES smoothly support Python 2.* and 3.*, with, I believe, just a modicum of care on the programmer's part).\n"
] |
[
7
] |
[] |
[] |
[
"c",
"console",
"python",
"windows"
] |
stackoverflow_0001157134_c_console_python_windows.txt
|
Q:
Scrolling through a `wx.ScrolledPanel` with the mouse wheel and arrow keys
In my wxPython application I've created a wx.ScrolledPanel, in which there is a big wx.StaticBitmap that needs to be scrolled.
The scroll bars do appear and I can scroll with them, but I'd also like to be able to scroll with the mouse wheel and the arrow keys on the keyboard. It would be nice if the "Home", "Page Up", and those other keys would also function as expected.
How do I do this?
UPDATE:
I see the problem. The ScrolledPanel is able to scroll, but only when it is under focus. Problem is, how do I get to be under focus? Even clicking on it doesn't do it. Only if I put a text control inside of it I can focus on it and thus scroll with the wheel. But I don't want to have a text control in it. So how do I make it focus?
UPDATE 2:
Here is a code sample that shows this phenomena. Uncomment to see how a text control makes the mouse wheel work.
import wx, wx.lib.scrolledpanel
class MyFrame(wx.Frame):
def __init__(self, *args, **kwargs):
wx.Frame.__init__(self, *args, **kwargs)
scrolled_panel = \
wx.lib.scrolledpanel.ScrolledPanel(parent=self, id=-1)
scrolled_panel.SetupScrolling()
text = "Ooga booga\n" * 50
static_text=wx.StaticText(scrolled_panel, -1, text)
sizer=wx.BoxSizer(wx.VERTICAL)
sizer.Add(static_text, wx.EXPAND, 0)
# Uncomment the following 2 lines to see how adding
# a text control to the scrolled panel makes the
# mouse wheel work.
#
#text_control=wx.TextCtrl(scrolled_panel, -1)
#sizer.Add(text_control, wx.EXPAND, 0)
scrolled_panel.SetSizer(sizer)
self.Show()
if __name__=="__main__":
app = wx.PySimpleApp()
my_frame=MyFrame(None, -1)
#import cProfile; cProfile.run("app.MainLoop()")
app.MainLoop()
A:
Problem is on window Frame gets the focus and child panel is not getting the Focus (on ubuntu linux it is working fine). Workaround can be as simple as to redirect Frame focus event to set focus to panel e.g.
import wx, wx.lib.scrolledpanel
class MyFrame(wx.Frame):
def __init__(self, *args, **kwargs):
wx.Frame.__init__(self, *args, **kwargs)
self.panel = scrolled_panel = \
wx.lib.scrolledpanel.ScrolledPanel(parent=self, id=-1)
scrolled_panel.SetupScrolling()
text = "Ooga booga\n" * 50
static_text=wx.StaticText(scrolled_panel, -1, text)
sizer=wx.BoxSizer(wx.VERTICAL)
sizer.Add(static_text, wx.EXPAND, 0)
scrolled_panel.SetSizer(sizer)
self.Show()
self.panel.SetFocus()
scrolled_panel.Bind(wx.EVT_SET_FOCUS, self.onFocus)
def onFocus(self, event):
self.panel.SetFocus()
if __name__=="__main__":
app = wx.PySimpleApp()
my_frame=MyFrame(None, -1)
app.MainLoop()
or onmouse move over panel, set focus to it, and all keys + mousewheeel will start working e.g.
import wx, wx.lib.scrolledpanel
class MyFrame(wx.Frame):
def __init__(self, *args, **kwargs):
wx.Frame.__init__(self, *args, **kwargs)
self.panel = scrolled_panel = \
wx.lib.scrolledpanel.ScrolledPanel(parent=self, id=-1)
scrolled_panel.SetupScrolling()
scrolled_panel.Bind(wx.EVT_MOTION, self.onMouseMove)
text = "Ooga booga\n" * 50
static_text=wx.StaticText(scrolled_panel, -1, text)
sizer=wx.BoxSizer(wx.VERTICAL)
sizer.Add(static_text, wx.EXPAND, 0)
scrolled_panel.SetSizer(sizer)
self.Show()
def onMouseMove(self, event):
self.panel.SetFocus()
if __name__=="__main__":
app = wx.PySimpleApp()
my_frame=MyFrame(None, -1)
app.MainLoop()
A:
Here's an example that should do what you want, I hope. (Edit: In retrospect, this doesnt' quite work, for example, when there are two scrolled panels... I'll leave it up here though so peole can downvote it or whatever.) Basically I put everything in a panel inside the frame (generally a good idea), and then set the focus to this main panel.
import wx
import wx, wx.lib.scrolledpanel
class MyFrame(wx.Frame):
def __init__(self, *args, **kwargs):
wx.Frame.__init__(self, *args, **kwargs)
main_panel = wx.Panel(self, -1)
main_panel.SetBackgroundColour((150, 100, 100))
self.main_panel = main_panel
scrolled_panel = \
wx.lib.scrolledpanel.ScrolledPanel(parent=main_panel, id=-1)
scrolled_panel.SetupScrolling()
self.scrolled_panel = scrolled_panel
cpanel = wx.Panel(main_panel, -1)
cpanel.SetBackgroundColour((100, 150, 100))
b = wx.Button(cpanel, -1, size=(40,40))
self.Bind(wx.EVT_BUTTON, self.OnClick, b)
self.b = b
text = "Ooga booga\n" * 50
static_text=wx.StaticText(scrolled_panel, -1, text)
main_sizer=wx.BoxSizer(wx.VERTICAL)
main_sizer.Add(scrolled_panel, 1, wx.EXPAND)
main_sizer.Add(cpanel, 1, wx.EXPAND)
main_panel.SetSizer(main_sizer)
text_sizer=wx.BoxSizer(wx.VERTICAL)
text_sizer.Add(static_text, 1, wx.EXPAND)
scrolled_panel.SetSizer(text_sizer)
self.main_panel.SetFocus()
self.Show()
def OnClick(self, evt):
print "click"
if __name__=="__main__":
class MyApp(wx.App):
def OnInit(self):
frame = MyFrame(None, -1)
frame.Show(True)
self.SetTopWindow(frame)
return True
app = MyApp(0)
app.MainLoop()
For keyboard control, like setting action from the home key, I think you'll need to bind to those events, and respond appropriately, such as using mypanel.Scroll(0,0) for the home key (and remember to call evt.Skip() for the keyboard events you don't act on). (Edit: I don't think there are any default key bindings for scrolling. I'm not sure I'd want any either, for example, what should happen if there's a scrolled panel within a scrolled panel?)
|
Scrolling through a `wx.ScrolledPanel` with the mouse wheel and arrow keys
|
In my wxPython application I've created a wx.ScrolledPanel, in which there is a big wx.StaticBitmap that needs to be scrolled.
The scroll bars do appear and I can scroll with them, but I'd also like to be able to scroll with the mouse wheel and the arrow keys on the keyboard. It would be nice if the "Home", "Page Up", and those other keys would also function as expected.
How do I do this?
UPDATE:
I see the problem. The ScrolledPanel is able to scroll, but only when it is under focus. Problem is, how do I get to be under focus? Even clicking on it doesn't do it. Only if I put a text control inside of it I can focus on it and thus scroll with the wheel. But I don't want to have a text control in it. So how do I make it focus?
UPDATE 2:
Here is a code sample that shows this phenomena. Uncomment to see how a text control makes the mouse wheel work.
import wx, wx.lib.scrolledpanel
class MyFrame(wx.Frame):
def __init__(self, *args, **kwargs):
wx.Frame.__init__(self, *args, **kwargs)
scrolled_panel = \
wx.lib.scrolledpanel.ScrolledPanel(parent=self, id=-1)
scrolled_panel.SetupScrolling()
text = "Ooga booga\n" * 50
static_text=wx.StaticText(scrolled_panel, -1, text)
sizer=wx.BoxSizer(wx.VERTICAL)
sizer.Add(static_text, wx.EXPAND, 0)
# Uncomment the following 2 lines to see how adding
# a text control to the scrolled panel makes the
# mouse wheel work.
#
#text_control=wx.TextCtrl(scrolled_panel, -1)
#sizer.Add(text_control, wx.EXPAND, 0)
scrolled_panel.SetSizer(sizer)
self.Show()
if __name__=="__main__":
app = wx.PySimpleApp()
my_frame=MyFrame(None, -1)
#import cProfile; cProfile.run("app.MainLoop()")
app.MainLoop()
|
[
"Problem is on window Frame gets the focus and child panel is not getting the Focus (on ubuntu linux it is working fine). Workaround can be as simple as to redirect Frame focus event to set focus to panel e.g.\nimport wx, wx.lib.scrolledpanel\n\nclass MyFrame(wx.Frame):\n def __init__(self, *args, **kwargs):\n wx.Frame.__init__(self, *args, **kwargs)\n\n self.panel = scrolled_panel = \\\n wx.lib.scrolledpanel.ScrolledPanel(parent=self, id=-1)\n scrolled_panel.SetupScrolling()\n\n text = \"Ooga booga\\n\" * 50\n static_text=wx.StaticText(scrolled_panel, -1, text)\n sizer=wx.BoxSizer(wx.VERTICAL)\n sizer.Add(static_text, wx.EXPAND, 0)\n\n scrolled_panel.SetSizer(sizer)\n\n self.Show()\n\n self.panel.SetFocus()\n scrolled_panel.Bind(wx.EVT_SET_FOCUS, self.onFocus)\n\n def onFocus(self, event):\n self.panel.SetFocus()\n\nif __name__==\"__main__\":\n app = wx.PySimpleApp()\n my_frame=MyFrame(None, -1)\n app.MainLoop()\n\nor onmouse move over panel, set focus to it, and all keys + mousewheeel will start working e.g.\nimport wx, wx.lib.scrolledpanel\n\nclass MyFrame(wx.Frame):\n def __init__(self, *args, **kwargs):\n wx.Frame.__init__(self, *args, **kwargs)\n\n self.panel = scrolled_panel = \\\n wx.lib.scrolledpanel.ScrolledPanel(parent=self, id=-1)\n scrolled_panel.SetupScrolling()\n\n scrolled_panel.Bind(wx.EVT_MOTION, self.onMouseMove)\n\n text = \"Ooga booga\\n\" * 50\n static_text=wx.StaticText(scrolled_panel, -1, text)\n sizer=wx.BoxSizer(wx.VERTICAL)\n sizer.Add(static_text, wx.EXPAND, 0)\n\n scrolled_panel.SetSizer(sizer)\n\n self.Show()\n\n def onMouseMove(self, event):\n self.panel.SetFocus()\n\nif __name__==\"__main__\":\n app = wx.PySimpleApp()\n my_frame=MyFrame(None, -1)\n app.MainLoop()\n\n",
"Here's an example that should do what you want, I hope. (Edit: In retrospect, this doesnt' quite work, for example, when there are two scrolled panels... I'll leave it up here though so peole can downvote it or whatever.) Basically I put everything in a panel inside the frame (generally a good idea), and then set the focus to this main panel. \nimport wx\nimport wx, wx.lib.scrolledpanel\n\nclass MyFrame(wx.Frame):\n def __init__(self, *args, **kwargs):\n wx.Frame.__init__(self, *args, **kwargs)\n main_panel = wx.Panel(self, -1)\n main_panel.SetBackgroundColour((150, 100, 100))\n self.main_panel = main_panel\n\n scrolled_panel = \\\n wx.lib.scrolledpanel.ScrolledPanel(parent=main_panel, id=-1)\n scrolled_panel.SetupScrolling()\n self.scrolled_panel = scrolled_panel\n\n cpanel = wx.Panel(main_panel, -1)\n cpanel.SetBackgroundColour((100, 150, 100))\n b = wx.Button(cpanel, -1, size=(40,40))\n self.Bind(wx.EVT_BUTTON, self.OnClick, b)\n self.b = b\n\n text = \"Ooga booga\\n\" * 50\n static_text=wx.StaticText(scrolled_panel, -1, text)\n main_sizer=wx.BoxSizer(wx.VERTICAL)\n main_sizer.Add(scrolled_panel, 1, wx.EXPAND)\n main_sizer.Add(cpanel, 1, wx.EXPAND)\n main_panel.SetSizer(main_sizer)\n\n text_sizer=wx.BoxSizer(wx.VERTICAL)\n text_sizer.Add(static_text, 1, wx.EXPAND)\n scrolled_panel.SetSizer(text_sizer)\n\n self.main_panel.SetFocus()\n\n self.Show()\n\n def OnClick(self, evt):\n print \"click\"\n\n\nif __name__==\"__main__\":\n class MyApp(wx.App):\n\n def OnInit(self):\n frame = MyFrame(None, -1)\n frame.Show(True)\n self.SetTopWindow(frame)\n return True\n app = MyApp(0)\n app.MainLoop()\n\nFor keyboard control, like setting action from the home key, I think you'll need to bind to those events, and respond appropriately, such as using mypanel.Scroll(0,0) for the home key (and remember to call evt.Skip() for the keyboard events you don't act on). (Edit: I don't think there are any default key bindings for scrolling. I'm not sure I'd want any either, for example, what should happen if there's a scrolled panel within a scrolled panel?)\n"
] |
[
3,
0
] |
[] |
[] |
[
"python",
"scroll",
"user_interface",
"wxpython"
] |
stackoverflow_0001147581_python_scroll_user_interface_wxpython.txt
|
Q:
python function for retrieving key and encryption
M2Crypto package is not showing the 'recipient_public_key.pem' file at linux terminal.
How do I get/connect with recipient public key.
Exactly, I need to check how can I open this file through linux commands.
import M2Crypto
def encrypt():
recip = M2Crypto.RSA.load_pub_key(open('recipient_public_key.pem','rb').read())
print recip;
plaintext = whatever i need to encrypt
msg = recip.public_encrypt(plaintext,RSA.pkcs1_padding)
print msg;
after calling the function its not giving any output and even any error
i also tried as 'Will' said
pk = open('public_key.pem','rb').read()
print pk;
rsa = M2Crypto.RSA.load_pub_key(pk)
what is the mistake I am not getting?
A:
I have never used M2Crypto, but according to the API documentation, load_pub_key expects the file name as the argument, not the key itself. Try
recip = M2Crypto.RSA.load_pub_key('recipient_public_key.pem')
|
python function for retrieving key and encryption
|
M2Crypto package is not showing the 'recipient_public_key.pem' file at linux terminal.
How do I get/connect with recipient public key.
Exactly, I need to check how can I open this file through linux commands.
import M2Crypto
def encrypt():
recip = M2Crypto.RSA.load_pub_key(open('recipient_public_key.pem','rb').read())
print recip;
plaintext = whatever i need to encrypt
msg = recip.public_encrypt(plaintext,RSA.pkcs1_padding)
print msg;
after calling the function its not giving any output and even any error
i also tried as 'Will' said
pk = open('public_key.pem','rb').read()
print pk;
rsa = M2Crypto.RSA.load_pub_key(pk)
what is the mistake I am not getting?
|
[
"I have never used M2Crypto, but according to the API documentation, load_pub_key expects the file name as the argument, not the key itself. Try\nrecip = M2Crypto.RSA.load_pub_key('recipient_public_key.pem')\n\n"
] |
[
1
] |
[] |
[] |
[
"python"
] |
stackoverflow_0001157442_python.txt
|
Q:
Seeding random in django
In a view in django I use random.random(). How often do I have to call random.seed()?
One time for every request?
One time for every season?
One time while the webserver is running?
A:
Don't set the seed.
The only time you want to set the seed is if you want to make sure that the same events keep happening. For example, if you don't want to let players cheat in your game you can save the seed, and then set it when they load their game. Then no matter how many times they save + reload, it still gives the same outcomes.
A:
Call random.seed() rarely if at all.
To be random, you must allow the random number generator to run without touching the seed. The sequence of numbers is what's random. If you change the seed, you start a new sequence. The seed values may not be very random, leading to problems.
Depending on how many numbers you need, you can consider resetting the seed from /dev/random periodically.
You should try to reset the seed just before you've used up the previous seed. You don't get the full 32 bits of randomness, so you might want to reset the seed after generating 2**28 numbers.
A:
It really depends on what you need the random number for. Use some experimentation to find out if it makes any difference. You should also consider that there is actually a pattern to pseudo-random numbers. Does it make a difference to you if someone can possible guess the next random number? If not, seed it once at the start of a session or when the server first starts up.
Seeding once at the start of the session would probably make the most sense, IMO. This way the user will get a set of pseudo-random numbers throughout their session. If you seed every time a page is served, they aren't guaranteed this.
|
Seeding random in django
|
In a view in django I use random.random(). How often do I have to call random.seed()?
One time for every request?
One time for every season?
One time while the webserver is running?
|
[
"Don't set the seed.\nThe only time you want to set the seed is if you want to make sure that the same events keep happening. For example, if you don't want to let players cheat in your game you can save the seed, and then set it when they load their game. Then no matter how many times they save + reload, it still gives the same outcomes.\n",
"Call random.seed() rarely if at all.\nTo be random, you must allow the random number generator to run without touching the seed. The sequence of numbers is what's random. If you change the seed, you start a new sequence. The seed values may not be very random, leading to problems. \nDepending on how many numbers you need, you can consider resetting the seed from /dev/random periodically.\nYou should try to reset the seed just before you've used up the previous seed. You don't get the full 32 bits of randomness, so you might want to reset the seed after generating 2**28 numbers.\n",
"It really depends on what you need the random number for. Use some experimentation to find out if it makes any difference. You should also consider that there is actually a pattern to pseudo-random numbers. Does it make a difference to you if someone can possible guess the next random number? If not, seed it once at the start of a session or when the server first starts up.\nSeeding once at the start of the session would probably make the most sense, IMO. This way the user will get a set of pseudo-random numbers throughout their session. If you seed every time a page is served, they aren't guaranteed this.\n"
] |
[
4,
3,
0
] |
[] |
[] |
[
"django",
"django_views",
"python",
"random"
] |
stackoverflow_0001156511_django_django_views_python_random.txt
|
Q:
Updated (current) recommendation on Rails versus Django?
(Disclaimer: I asked this question yesterday on Hacker News. While responses were good, there was a notable lack of technical discussion and more of a "you should use rails because that's what you know". Since Joel and Jeff state clearly they don't mind reposts of questions from other sites...and since I really enjoy the answers I find here...here goes)
I realize this post is an infamous "versus" question, and undoubtedly redundant with older posts. However, most of the information I find on Rails versus Django is out of date and based on much older versions of the frameworks, so please forgive me.
First and foremost...I'm a Rails guy. I came to it three years ago and really enjoyed a lot of what it brought to the table. I'm not solely a Ruby guy...I have around 11 years of total experience, including Java, C/C++, Perl, Tcl, (some) Python, and more.
Anyway, I have an idea I believe will take over the world. I've already convinced a few folks it will as well and have friends and family funding to take on some offshore developers and get it in beta as quickly as possible.
Now, however, I am left with the decision of what tech to use. While I've really enjoyed Ruby...I'm growing tired of the magic, and the abuse of open classes. It's very nice when you need to inject some behavior quickly, but it can become a real pain when you have to maintain your project, or any of the plugins it depends on. I personally prefer Ruby over Python (largely because of blocks), but I envy the clarity-first attitude in the Python community. Given this frustration, I'm seriously considering a deep-dive into Django and using it for this project.
The pluses I see on the Rails side are:
Size of community (which, given some of this "community" includes PHP refugees, is not necessarily a plus)
My familiarity and experience
Number of companies using it and striving to improve it
Availability of offshore resources
Drawbacks of Rails include:
Too much magic
Documentation continues to be awful in places
Inconsistent API
Did I mention magic?
The (perceived) pluses on the Django side:
Clarity
Performance...I believe Unladen Swallow will really change the Python landscape and give it a competitive advantage
Google's support of the language itself (see #2)
Drawbacks of Django:
Learning curve
Smaller community
Slower development cycle of the project itself?
(un)Availability of offshore resources
So, this is my thought process so far. I'm pretty comfortable I could come up to speed quickly on Django, and I have the basics of Python still in my memory somewhere. But I wanted to get your opinions as I really respect the vision and experience of a lot of the folks I read on here.
I appreciate your help. I really think this idea will take off, so it's very important to me to make the right technology decision.
And saying to choose Rails simply because I have experience there just doesn't sound right. If that were the case, I'd still be using Perl or C.
Thank you!
A:
[Repost from HN, same link as question, as I would like to hear your(you did not reply on HN) and SO response.]
I am obviously biased, as I run a django development company. That said, Ill start with answering the drawbacks of Django,
Learning curve.:
Not more than any other framework. Plus the Documentation is top notch. (The documentation was what sold me when I was evaluating.)
Smaller community:
Definately true. But beyond a critical size, size of community does not matter. Django is well above that size. (Irc: any given time ~200 Devs. Google group: 14000+ Users )
Slower development cycle of the project itself?:
Why? If you give more details, I can answer that.
(un)Availability of offshore resources:
Definately less than Rails, but still not as bad as you would have thought. A very small list, http://uswaretech.com/blog/2009/03/web-development-companies...
Thats said, given the information you have, I your case I would choose Rails. Even if most of the work you are looking to offshore, your existing Rails experience would be a huge plus, helping you evaluate vendors, keep track.
On a semi-related note, Django is less mature/smaller community is way overblown, some figures,
Years under development. ROR: 5/Django 5
Members in largest google group: ROR 18000+/Django 14000+
Members in Irc currently: Ror 436/Django 401
Commits to repo: Ror ?/Django 11000+
A:
You forgot at least one advantage of Rails -- enhanced testability via RSpec/Cucumber. Really, the main (additional) advantage is the attention to Ruby/Rails from the agile testing community. Using natural language testing should significantly enhance the ability to reason from your tests and promote understandability. In some respects this would offset the "magic" that you abhor by documenting it via easily readable tests.
Beyond that, I would suggest that a new project that you are spending your friends' and family's money on is probably not the ideal situation in which to learn a new language/framework. Why add the additional risk to an already risky venture?
A:
I'm simply going to argue with many of your statements:
Django may have less magic than Rails, but there is still some there. Python is clearer though so you will gain clarity.
Django is renowned for being easy to learn, so I don't think Djangos learning curve is a problem.
Unladen Swallow is so far vapour ware. Never ever EVER make software decisions based on the promise that some software will be available in the future.
Since you already know Rails, you should stick with it unless you know it's going to be painful. Also, if you aren't happy with Rails, I would recommend you go through tutorials for some of the other Python frameworks in existance, like Turbogears 2, BFG and Grok. It may be that you would prefer something less monolithic or more complete that Rails/Django.
http://bfg.repoze.org/
http://grok.zope.org/
http://turbogears.org/
A:
I've got a different perspective about these two frameworks on how they compare. I'm still a noob in these two as I am a Java developer looking for something more exciting to do on my sparetime. I have been observing these two frameworks closely and came up with this:
Rails
As you know Rails is born out of a web based application made by 37signals, which affects the architecture of if. I haven't really use Rails in real application yet though, but I think I might use it for my next pet project.
Basically what I can see from Rails is that it is a monolith type of framework (Though this will change in Rails 3 as it will adopt Merb architecture). This architecture from
my point of view will also affect the way you deliver/package your project. Monolith kind of project I reckon is good if you want to deliver all of the application in one bundle to your customer.
As per the architecture, Rails use plugin if you want extend or add another feature. I reckon this is good if you want to have a community based product where user can add plugin.
They said Ruby is slow, but then if you want to package Rails apps as a product, it's quite worted to package it as war file with JRuby and warble. E.g: Thoughtwork's Mingle use this approach.
With that in mind, IMHO (well DHH also said this in Ruby vs Snakes conference too) Rails is suitable for web application.
Rails has a good built-in ajax support (rjs). Django people it's easy to add Ajax support on django, but an abstraction like in Rails still makes it quite worth it I reckon.
Django
Django born out of a newspaper site, so in one way and the other that also affects the architecture of django itself. I've only used django in my sandbox website and so far I really like building websites with it.
Most of the dirty work has been done for you (RSS Feed framework, Generic view, admin, commentig framework, etc)
Django has an architecture of 'pluggable application'. Which is good if you want to plug already made django applications that is made by the community, or share those application at several of your sites.
As I said if this is an internal/in-house websites I reckon it's really good to use django because you can re-use this apps in several websites. But it would be really tough to deliver this into one bundle type application because usually (well the best practice as I would say) this django apps lives in a PYTHONPATH instead of bundling it all together in your application. Though Pinax distribute the whole apps in one package, and I'm curious how Ellington does it.
As the current Python is faster than the current Ruby(1.8), that makes django itself way faster than Rails (there's alot of benchmark about this on the web). With that kind of performance IMHO django is really suitable for high traffic websites (Think of twitter like traffic websites)
Some people might not agree for me, as they can find workaround to use Rails as websites and django as web application. But this is what I reckon distinguished the two based on their architecture. Thus it will also define what are they good for. Feel free to disagree with me :-)
Cheers.
|
Updated (current) recommendation on Rails versus Django?
|
(Disclaimer: I asked this question yesterday on Hacker News. While responses were good, there was a notable lack of technical discussion and more of a "you should use rails because that's what you know". Since Joel and Jeff state clearly they don't mind reposts of questions from other sites...and since I really enjoy the answers I find here...here goes)
I realize this post is an infamous "versus" question, and undoubtedly redundant with older posts. However, most of the information I find on Rails versus Django is out of date and based on much older versions of the frameworks, so please forgive me.
First and foremost...I'm a Rails guy. I came to it three years ago and really enjoyed a lot of what it brought to the table. I'm not solely a Ruby guy...I have around 11 years of total experience, including Java, C/C++, Perl, Tcl, (some) Python, and more.
Anyway, I have an idea I believe will take over the world. I've already convinced a few folks it will as well and have friends and family funding to take on some offshore developers and get it in beta as quickly as possible.
Now, however, I am left with the decision of what tech to use. While I've really enjoyed Ruby...I'm growing tired of the magic, and the abuse of open classes. It's very nice when you need to inject some behavior quickly, but it can become a real pain when you have to maintain your project, or any of the plugins it depends on. I personally prefer Ruby over Python (largely because of blocks), but I envy the clarity-first attitude in the Python community. Given this frustration, I'm seriously considering a deep-dive into Django and using it for this project.
The pluses I see on the Rails side are:
Size of community (which, given some of this "community" includes PHP refugees, is not necessarily a plus)
My familiarity and experience
Number of companies using it and striving to improve it
Availability of offshore resources
Drawbacks of Rails include:
Too much magic
Documentation continues to be awful in places
Inconsistent API
Did I mention magic?
The (perceived) pluses on the Django side:
Clarity
Performance...I believe Unladen Swallow will really change the Python landscape and give it a competitive advantage
Google's support of the language itself (see #2)
Drawbacks of Django:
Learning curve
Smaller community
Slower development cycle of the project itself?
(un)Availability of offshore resources
So, this is my thought process so far. I'm pretty comfortable I could come up to speed quickly on Django, and I have the basics of Python still in my memory somewhere. But I wanted to get your opinions as I really respect the vision and experience of a lot of the folks I read on here.
I appreciate your help. I really think this idea will take off, so it's very important to me to make the right technology decision.
And saying to choose Rails simply because I have experience there just doesn't sound right. If that were the case, I'd still be using Perl or C.
Thank you!
|
[
"[Repost from HN, same link as question, as I would like to hear your(you did not reply on HN) and SO response.]\nI am obviously biased, as I run a django development company. That said, Ill start with answering the drawbacks of Django,\n\nLearning curve.:\nNot more than any other framework. Plus the Documentation is top notch. (The documentation was what sold me when I was evaluating.)\nSmaller community:\nDefinately true. But beyond a critical size, size of community does not matter. Django is well above that size. (Irc: any given time ~200 Devs. Google group: 14000+ Users )\nSlower development cycle of the project itself?:\nWhy? If you give more details, I can answer that.\n(un)Availability of offshore resources:\nDefinately less than Rails, but still not as bad as you would have thought. A very small list, http://uswaretech.com/blog/2009/03/web-development-companies...\n\nThats said, given the information you have, I your case I would choose Rails. Even if most of the work you are looking to offshore, your existing Rails experience would be a huge plus, helping you evaluate vendors, keep track.\nOn a semi-related note, Django is less mature/smaller community is way overblown, some figures,\n\nYears under development. ROR: 5/Django 5\nMembers in largest google group: ROR 18000+/Django 14000+\nMembers in Irc currently: Ror 436/Django 401\nCommits to repo: Ror ?/Django 11000+\n\n",
"You forgot at least one advantage of Rails -- enhanced testability via RSpec/Cucumber. Really, the main (additional) advantage is the attention to Ruby/Rails from the agile testing community. Using natural language testing should significantly enhance the ability to reason from your tests and promote understandability. In some respects this would offset the \"magic\" that you abhor by documenting it via easily readable tests.\nBeyond that, I would suggest that a new project that you are spending your friends' and family's money on is probably not the ideal situation in which to learn a new language/framework. Why add the additional risk to an already risky venture?\n",
"I'm simply going to argue with many of your statements:\n\nDjango may have less magic than Rails, but there is still some there. Python is clearer though so you will gain clarity. \nDjango is renowned for being easy to learn, so I don't think Djangos learning curve is a problem.\nUnladen Swallow is so far vapour ware. Never ever EVER make software decisions based on the promise that some software will be available in the future.\n\nSince you already know Rails, you should stick with it unless you know it's going to be painful. Also, if you aren't happy with Rails, I would recommend you go through tutorials for some of the other Python frameworks in existance, like Turbogears 2, BFG and Grok. It may be that you would prefer something less monolithic or more complete that Rails/Django.\nhttp://bfg.repoze.org/\nhttp://grok.zope.org/\nhttp://turbogears.org/\n",
"I've got a different perspective about these two frameworks on how they compare. I'm still a noob in these two as I am a Java developer looking for something more exciting to do on my sparetime. I have been observing these two frameworks closely and came up with this:\nRails\nAs you know Rails is born out of a web based application made by 37signals, which affects the architecture of if. I haven't really use Rails in real application yet though, but I think I might use it for my next pet project. \n\nBasically what I can see from Rails is that it is a monolith type of framework (Though this will change in Rails 3 as it will adopt Merb architecture). This architecture from\nmy point of view will also affect the way you deliver/package your project. Monolith kind of project I reckon is good if you want to deliver all of the application in one bundle to your customer. \nAs per the architecture, Rails use plugin if you want extend or add another feature. I reckon this is good if you want to have a community based product where user can add plugin. \nThey said Ruby is slow, but then if you want to package Rails apps as a product, it's quite worted to package it as war file with JRuby and warble. E.g: Thoughtwork's Mingle use this approach.\nWith that in mind, IMHO (well DHH also said this in Ruby vs Snakes conference too) Rails is suitable for web application. \nRails has a good built-in ajax support (rjs). Django people it's easy to add Ajax support on django, but an abstraction like in Rails still makes it quite worth it I reckon. \n\nDjango\nDjango born out of a newspaper site, so in one way and the other that also affects the architecture of django itself. I've only used django in my sandbox website and so far I really like building websites with it. \n\nMost of the dirty work has been done for you (RSS Feed framework, Generic view, admin, commentig framework, etc)\nDjango has an architecture of 'pluggable application'. Which is good if you want to plug already made django applications that is made by the community, or share those application at several of your sites. \nAs I said if this is an internal/in-house websites I reckon it's really good to use django because you can re-use this apps in several websites. But it would be really tough to deliver this into one bundle type application because usually (well the best practice as I would say) this django apps lives in a PYTHONPATH instead of bundling it all together in your application. Though Pinax distribute the whole apps in one package, and I'm curious how Ellington does it.\nAs the current Python is faster than the current Ruby(1.8), that makes django itself way faster than Rails (there's alot of benchmark about this on the web). With that kind of performance IMHO django is really suitable for high traffic websites (Think of twitter like traffic websites)\n\nSome people might not agree for me, as they can find workaround to use Rails as websites and django as web application. But this is what I reckon distinguished the two based on their architecture. Thus it will also define what are they good for. Feel free to disagree with me :-)\nCheers.\n"
] |
[
8,
7,
6,
6
] |
[] |
[] |
[
"django",
"python",
"ruby",
"ruby_on_rails"
] |
stackoverflow_0001153096_django_python_ruby_ruby_on_rails.txt
|
Q:
Forced to use inconsistent file import paths in Python (/Django)
I've recently been having some problems with my imports in Django (Python)... It's better to explain using a file diagram:
- project/
- application/
- file.py
- application2/
- file2.py
In project/application/file.py I have the following:
def test_method():
return "Working"
The problem occurs in project/application2/file2.py, when I try to import the method from above:
from application.file import test_method
Usually works, but sometimes not.
from project.application.file import test_method
Does work, but it goes against Django's portability guidelines as the project folder must always be called the same.
I wouldn't mind, but it's the fact that this issue is occurring inconsistently, most of the time omitting project is fine, but occasionally not (and as far as I can see, with no reason).
I can pretty much guarantee I'm doing something stupid, but has anyone experienced this? Would I be better just putting the project in front of all relevant imports to keep things consistent? Honestly, it's unlikely the project folder name will ever change, I just want things to stick with guidelines where possible.
A:
For import to find a module, it needs to either be in sys.path. Usually, this includes "", so it searches the current directory. If you load "application" from project, it'll find it, since it's in the current directory.
Okay, that's the obvious stuff. A confusing bit is that Python remembers which modules are loaded. If you load application, then you load application2 which imports application, the module "application" is already loaded. It doesn't need to find it on disk; it just uses the one that's already loaded. On the other hand, if you didn't happen to load application yet, it'll search for it--and not find it, since it's not in the same directory as what's loading it ("."), or anywhere else in the path.
That can lead to the weird case where importing sometimes works and sometimes doesn't; it only works if it's already loaded.
If you want to be able to load these modules as just "application", then you need to arrange for project/ to be appended to sys.path.
(Relative imports sound related, but it seems like application and application2 are separate packages--relative imports are used for importing within the same package.)
Finally, be sure to consistently treat the whole thing as a package, or to consistently treat each application as their own package. Do not mix and match. If package/ is in the path (eg. sys.path includes package/..), then you can indeed do "from package.application import foo", but if you then also do "from application import foo", it's possible for Python to not realize these are the same thing--their names are different, and they're in different paths--and end up loading two distinct copies of it, which you definitely don't want.
A:
If you dig into the django philosophy, you will find, that a project is a collection of apps. Some of these apps could depend on other apps, which is just fine. However, what you always want is to make your apps plug-able so you can move them to a different project and use them there as well. To do this, you need to strip all things in your code that's related to your project, so when doing imports you would do.
from aplication.file import test_method
This would be the django way of doing this. Glenn answered why you are getting your errors so I wont go into that part. When you run the command to start a new project: django-admin.py startproject myproject
This will create a folder with a bunch of files that django needs, manage.py settings,py ect, but it will do another thing for you. It will place the folder "myproject" on your python path. In short this means that what ever application you put in that folder, you would be able to import like shown above. You don't need to use django-admin.py to start a project as nothing magical happens, it's just a shortcut. So you can place you application folders anywhere really, you just need to have them on a python path, so you can import from them directly and make your code project independent so it easily can be used in any future project, abiding to the DRY principle that django is built upon.
A:
It is better to always import using the same way - say, using project.app.models - because otherwise, you may find your module is imported twice, which sometimes leads to obscure errors as discussed in this question.
|
Forced to use inconsistent file import paths in Python (/Django)
|
I've recently been having some problems with my imports in Django (Python)... It's better to explain using a file diagram:
- project/
- application/
- file.py
- application2/
- file2.py
In project/application/file.py I have the following:
def test_method():
return "Working"
The problem occurs in project/application2/file2.py, when I try to import the method from above:
from application.file import test_method
Usually works, but sometimes not.
from project.application.file import test_method
Does work, but it goes against Django's portability guidelines as the project folder must always be called the same.
I wouldn't mind, but it's the fact that this issue is occurring inconsistently, most of the time omitting project is fine, but occasionally not (and as far as I can see, with no reason).
I can pretty much guarantee I'm doing something stupid, but has anyone experienced this? Would I be better just putting the project in front of all relevant imports to keep things consistent? Honestly, it's unlikely the project folder name will ever change, I just want things to stick with guidelines where possible.
|
[
"For import to find a module, it needs to either be in sys.path. Usually, this includes \"\", so it searches the current directory. If you load \"application\" from project, it'll find it, since it's in the current directory.\nOkay, that's the obvious stuff. A confusing bit is that Python remembers which modules are loaded. If you load application, then you load application2 which imports application, the module \"application\" is already loaded. It doesn't need to find it on disk; it just uses the one that's already loaded. On the other hand, if you didn't happen to load application yet, it'll search for it--and not find it, since it's not in the same directory as what's loading it (\".\"), or anywhere else in the path.\nThat can lead to the weird case where importing sometimes works and sometimes doesn't; it only works if it's already loaded.\nIf you want to be able to load these modules as just \"application\", then you need to arrange for project/ to be appended to sys.path.\n(Relative imports sound related, but it seems like application and application2 are separate packages--relative imports are used for importing within the same package.)\nFinally, be sure to consistently treat the whole thing as a package, or to consistently treat each application as their own package. Do not mix and match. If package/ is in the path (eg. sys.path includes package/..), then you can indeed do \"from package.application import foo\", but if you then also do \"from application import foo\", it's possible for Python to not realize these are the same thing--their names are different, and they're in different paths--and end up loading two distinct copies of it, which you definitely don't want.\n",
"If you dig into the django philosophy, you will find, that a project is a collection of apps. Some of these apps could depend on other apps, which is just fine. However, what you always want is to make your apps plug-able so you can move them to a different project and use them there as well. To do this, you need to strip all things in your code that's related to your project, so when doing imports you would do.\nfrom aplication.file import test_method\n\nThis would be the django way of doing this. Glenn answered why you are getting your errors so I wont go into that part. When you run the command to start a new project: django-admin.py startproject myproject\nThis will create a folder with a bunch of files that django needs, manage.py settings,py ect, but it will do another thing for you. It will place the folder \"myproject\" on your python path. In short this means that what ever application you put in that folder, you would be able to import like shown above. You don't need to use django-admin.py to start a project as nothing magical happens, it's just a shortcut. So you can place you application folders anywhere really, you just need to have them on a python path, so you can import from them directly and make your code project independent so it easily can be used in any future project, abiding to the DRY principle that django is built upon.\n",
"It is better to always import using the same way - say, using project.app.models - because otherwise, you may find your module is imported twice, which sometimes leads to obscure errors as discussed in this question.\n"
] |
[
4,
2,
0
] |
[] |
[] |
[
"django",
"import",
"path",
"python"
] |
stackoverflow_0001156515_django_import_path_python.txt
|
Q:
Syncing Django users with Google Apps without monkeypatching
I am writing a Django app, and I would like an account to be created on our Google Apps hosted email using the Provisioning API whenever an account is created locally.
I would solely use signals, but since I would like the passwords to be synchronized across sites, I have monkeypatched User.objects.create_user and User.set_password using wrappers to create Google accounts and update passwords respectively.
Monkeypatching seems to be frowned upon, so I would to know, is there a better way to accomplish this?
A:
Have you considered subclassing the User model? This may create a different set of problems, and is only available with newer releases (not sure when the change went in, I'm on trunk).
A:
Subclassing seems the best route, as long as you can change all of your code to use the new class. I think that's supported in the latest release of Django.
A:
Monkeypatching is definitely bad. Hard to say anything since you've given so little code/information. But I assume you have the password in cleartext at some point (in a view, in a form) so why not sync manually then?
A:
I subclass User with Django 1.0.2. You basically makes another table that links to the user_id.
class User(MyBaseModel):
user = models.OneToOneField(User, help_text="The django created User object")
and then at runtime
@login_required
def add(request) :
u = request.user.get_profile()
You can then easily overwrite the needed methods.
And for those that hadn't heard of monkeypatching : http://en.wikipedia.org/wiki/Monkey_patch. It is a derivation from guerrilla patch.
|
Syncing Django users with Google Apps without monkeypatching
|
I am writing a Django app, and I would like an account to be created on our Google Apps hosted email using the Provisioning API whenever an account is created locally.
I would solely use signals, but since I would like the passwords to be synchronized across sites, I have monkeypatched User.objects.create_user and User.set_password using wrappers to create Google accounts and update passwords respectively.
Monkeypatching seems to be frowned upon, so I would to know, is there a better way to accomplish this?
|
[
"Have you considered subclassing the User model? This may create a different set of problems, and is only available with newer releases (not sure when the change went in, I'm on trunk).\n",
"Subclassing seems the best route, as long as you can change all of your code to use the new class. I think that's supported in the latest release of Django. \n",
"Monkeypatching is definitely bad. Hard to say anything since you've given so little code/information. But I assume you have the password in cleartext at some point (in a view, in a form) so why not sync manually then?\n",
"I subclass User with Django 1.0.2. You basically makes another table that links to the user_id. \nclass User(MyBaseModel):\n user = models.OneToOneField(User, help_text=\"The django created User object\")\n\nand then at runtime\n@login_required\ndef add(request) :\n u = request.user.get_profile()\n\nYou can then easily overwrite the needed methods.\nAnd for those that hadn't heard of monkeypatching : http://en.wikipedia.org/wiki/Monkey_patch. It is a derivation from guerrilla patch. \n"
] |
[
1,
0,
0,
0
] |
[] |
[] |
[
"django",
"google_apps",
"monkeypatching",
"python"
] |
stackoverflow_0000429443_django_google_apps_monkeypatching_python.txt
|
Q:
Problem with recursive search of xml document using python
I am trying to write a function that will take an xml object, an arbitrary number of tags, defined by tuples containing a tag name, attribute and attribute value (e.g ('tag1', 'id', '1')) and return the most specific node possible. My code is below:
from xml.dom import minidom
def _search(object, *pargs):
if len(pargs) == 0:
print "length of pargs was zero"
return object
else:
print "length of pargs is %s" % len(pargs)
if pargs[0][1]:
for element in object.getElementsByTagName(pargs[0][0]):
if element.attributes[pargs[0][1]].value == pargs[0][2]:
_search(element, *pargs[1:])
else:
if object.getElementsByTagName(pargs[0][0]) == 1:
_search(element, *pargs[1:])
def main():
xmldoc = minidom.parse('./example.xml')
tag1 = ('catalog_item', 'gender', "Men's")
tag2 = ('size', 'description', 'Large')
tag3 = ('color_swatch', '', '')
args = (tag1, tag2, tag3)
node = _search(xmldoc, *args)
node.toxml()
if __name__ == "__main__":
main()
Unfortunately, this doesn't seem to work. Here's the output when I run the script:
$ ./secondsearch.py
length of pargs is 3
length of pargs is 2
length of pargs is 1
Traceback (most recent call last):
File "./secondsearch.py", line 35, in <module>
main()
File "./secondsearch.py", line 32, in main
node.toxml()
AttributeError: 'NoneType' object has no attribute 'toxml'
Why isn't the 'if len(pargs) == 0' clause being exercised? If I do manage to get the xml object returned to my main method, can I then pass the object into some other function (which could change the value of the node, or append a child node, etc.)?
Background: Using python to automate testing processes, environment is is cygwin on winxp/vista/7, python version is 2.5.2. I would prefer to stay within the standard library if at all possible.
Here's the working code:
def _search(object, *pargs):
if len(pargs) == 0:
print "length of pargs was zero"
else:
print "length of pargs is %s" % len(pargs)
for element in object.getElementsByTagName(pargs[0][0]):
if pargs[0][1]:
if element.attributes[pargs[0][1]].value == pargs[0][2]:
return _search(element, *pargs[1:])
else:
if object.getElementsByTagName(pargs[0][0]) == 1:
return _search(element, *pargs[1:])
return object
A:
Shouldn't you be inserting a return in front of your recursive calls to _search? The way you have it now, some exit paths from _search don't have a return statement, so they will return None - which leads to the exception you're seeing.
A:
I assume you're using http://www.eggheadcafe.com/community/aspnet/17/10084853/xml-viewer.aspx as your sample data...
As Vinay pointed out, you don't return anything from your recursive calls to_search.
In your else case, you don't define the value of element, but you pass it into the _search().
Also, you don't do anything if pargs[0][1] is empty, but object.getElementsByTagName(pargs[0][0]) returns more than one Node... (which is also why your pargs == 0 case never gets hit...)
And after all that, if that sample data is correct, there are two matching nodes. so you'll have a NodeList containing:
<color_swatch image="red_cardigan.jpg">Red</color_swatch>
<color_swatch image="burgundy_cardigan.jpg">Burgundy</color_swatch>
and you can't call .toxml() on a NodeList...
|
Problem with recursive search of xml document using python
|
I am trying to write a function that will take an xml object, an arbitrary number of tags, defined by tuples containing a tag name, attribute and attribute value (e.g ('tag1', 'id', '1')) and return the most specific node possible. My code is below:
from xml.dom import minidom
def _search(object, *pargs):
if len(pargs) == 0:
print "length of pargs was zero"
return object
else:
print "length of pargs is %s" % len(pargs)
if pargs[0][1]:
for element in object.getElementsByTagName(pargs[0][0]):
if element.attributes[pargs[0][1]].value == pargs[0][2]:
_search(element, *pargs[1:])
else:
if object.getElementsByTagName(pargs[0][0]) == 1:
_search(element, *pargs[1:])
def main():
xmldoc = minidom.parse('./example.xml')
tag1 = ('catalog_item', 'gender', "Men's")
tag2 = ('size', 'description', 'Large')
tag3 = ('color_swatch', '', '')
args = (tag1, tag2, tag3)
node = _search(xmldoc, *args)
node.toxml()
if __name__ == "__main__":
main()
Unfortunately, this doesn't seem to work. Here's the output when I run the script:
$ ./secondsearch.py
length of pargs is 3
length of pargs is 2
length of pargs is 1
Traceback (most recent call last):
File "./secondsearch.py", line 35, in <module>
main()
File "./secondsearch.py", line 32, in main
node.toxml()
AttributeError: 'NoneType' object has no attribute 'toxml'
Why isn't the 'if len(pargs) == 0' clause being exercised? If I do manage to get the xml object returned to my main method, can I then pass the object into some other function (which could change the value of the node, or append a child node, etc.)?
Background: Using python to automate testing processes, environment is is cygwin on winxp/vista/7, python version is 2.5.2. I would prefer to stay within the standard library if at all possible.
Here's the working code:
def _search(object, *pargs):
if len(pargs) == 0:
print "length of pargs was zero"
else:
print "length of pargs is %s" % len(pargs)
for element in object.getElementsByTagName(pargs[0][0]):
if pargs[0][1]:
if element.attributes[pargs[0][1]].value == pargs[0][2]:
return _search(element, *pargs[1:])
else:
if object.getElementsByTagName(pargs[0][0]) == 1:
return _search(element, *pargs[1:])
return object
|
[
"Shouldn't you be inserting a return in front of your recursive calls to _search? The way you have it now, some exit paths from _search don't have a return statement, so they will return None - which leads to the exception you're seeing.\n",
"I assume you're using http://www.eggheadcafe.com/community/aspnet/17/10084853/xml-viewer.aspx as your sample data... \nAs Vinay pointed out, you don't return anything from your recursive calls to_search.\nIn your else case, you don't define the value of element, but you pass it into the _search().\nAlso, you don't do anything if pargs[0][1] is empty, but object.getElementsByTagName(pargs[0][0]) returns more than one Node... (which is also why your pargs == 0 case never gets hit...)\nAnd after all that, if that sample data is correct, there are two matching nodes. so you'll have a NodeList containing:\n <color_swatch image=\"red_cardigan.jpg\">Red</color_swatch>\n <color_swatch image=\"burgundy_cardigan.jpg\">Burgundy</color_swatch>\n\nand you can't call .toxml() on a NodeList...\n"
] |
[
2,
2
] |
[] |
[] |
[
"python",
"xml"
] |
stackoverflow_0001157768_python_xml.txt
|
Q:
Django Double Escaping Quotes etc
I'm experiencing what I would consider somewhat strange behavior. Specifically if I have a string like this:
1984: Curriculum Unit
by Donald R. Hogue, Center for Learning, George Orwell
"A center for learning publication"--Cover.
It results in the following after being auto-escaped by the Django template system:
1984: Curriculum Unit
by Donald R. Hogue, Center for Learning, George Orwell
"A center for learning publication"--Cover.
The problem seems to be that the " (quote), which should become " is being escaped twice, resulting in &". This results in strange looking formatting. I'm using Django 1.0.2, so it should be up to date, (though I should note I'm using the Ubuntu 9.04 included package python-django) but this behavior seems contrary to the intended behavior.
I've looked a little at django.utils.html.py which includes the actual function:
def escape(html):
"""Returns the given HTML with ampersands, quotes and carets encoded."""
return mark_safe(force_unicode(html).replace('&','&').replace('<','<').replace('>', '>').replace('"', '"').replace("'",'''))
escape = allow_lazy(escape, unicode)
Anyway, that looks like it should escape the & before anything else, which would be fine. So my suspicion is that it is being called twice. Any thoughts?
Thanks.
Update: I was suspicious that it might have something to do with Ubuntu's Django, which it lists as "1.0.2-1" so I installed "1.0.2-final" and am experiencing the same problem.
A:
You shouldn't have to think about escaping in 1.0 . If you have a template
<html>
<body>
& == & in HTML
</body>
</html>
It should encode the & to & before printing.
If you have a variable
<html>
<body>
{{ msg }}
</body>
</html>
and
def view(request) :
msg = "& == & in HTML"
if should be printed the same way.
The only time you want to do the encoding yourself is if you need to paste in raw html. Like:
def view(request) :
msg = '<img src="http://example.com/pretty.jpg" />This picture is very pretty'
and in your template
<html>
<body>
{{ msg|safe }}
</body>
</html>
A:
Oh hardy har har,
Silly me, Google is so smart that they already escaped those chars in the XML I was parsing. Wouldn't you know it, an hour of fiddling only to realize Google outsmarted me again!
P.S. In case anyone else ever comes across a similar problem, I'm specifically referring to the XML returned when doing this sort of query: http://books.google.com/books/feeds/volumes?q=1984 , the data is already escaped for you! That being said, it does put me on edge a little bit because putting |safe in my templates will mean that if I ever get data from another source that I don't trust so much... Anyway, thanks for reading!
|
Django Double Escaping Quotes etc
|
I'm experiencing what I would consider somewhat strange behavior. Specifically if I have a string like this:
1984: Curriculum Unit
by Donald R. Hogue, Center for Learning, George Orwell
"A center for learning publication"--Cover.
It results in the following after being auto-escaped by the Django template system:
1984: Curriculum Unit
by Donald R. Hogue, Center for Learning, George Orwell
"A center for learning publication"--Cover.
The problem seems to be that the " (quote), which should become " is being escaped twice, resulting in &". This results in strange looking formatting. I'm using Django 1.0.2, so it should be up to date, (though I should note I'm using the Ubuntu 9.04 included package python-django) but this behavior seems contrary to the intended behavior.
I've looked a little at django.utils.html.py which includes the actual function:
def escape(html):
"""Returns the given HTML with ampersands, quotes and carets encoded."""
return mark_safe(force_unicode(html).replace('&','&').replace('<','<').replace('>', '>').replace('"', '"').replace("'",'''))
escape = allow_lazy(escape, unicode)
Anyway, that looks like it should escape the & before anything else, which would be fine. So my suspicion is that it is being called twice. Any thoughts?
Thanks.
Update: I was suspicious that it might have something to do with Ubuntu's Django, which it lists as "1.0.2-1" so I installed "1.0.2-final" and am experiencing the same problem.
|
[
"You shouldn't have to think about escaping in 1.0 . If you have a template\n<html>\n <body>\n & == & in HTML\n </body>\n</html>\n\nIt should encode the & to & before printing. \nIf you have a variable\n<html>\n <body>\n {{ msg }}\n </body>\n</html>\n\nand \ndef view(request) :\n msg = \"& == & in HTML\"\n\nif should be printed the same way.\nThe only time you want to do the encoding yourself is if you need to paste in raw html. Like:\ndef view(request) :\n msg = '<img src=\"http://example.com/pretty.jpg\" />This picture is very pretty'\n\nand in your template\n<html>\n <body>\n {{ msg|safe }}\n </body>\n</html>\n\n",
"Oh hardy har har,\nSilly me, Google is so smart that they already escaped those chars in the XML I was parsing. Wouldn't you know it, an hour of fiddling only to realize Google outsmarted me again!\nP.S. In case anyone else ever comes across a similar problem, I'm specifically referring to the XML returned when doing this sort of query: http://books.google.com/books/feeds/volumes?q=1984 , the data is already escaped for you! That being said, it does put me on edge a little bit because putting |safe in my templates will mean that if I ever get data from another source that I don't trust so much... Anyway, thanks for reading! \n"
] |
[
1,
1
] |
[] |
[] |
[
"django",
"python"
] |
stackoverflow_0001157725_django_python.txt
|
Q:
Creating DateTime from user inputted date
I'm pretty new to Python and App Engine, but what I'm trying to do is store a model which contains a DateProperty, and that DateProperty is populated with a Date entered by the user in a web form.
I've got the model of:
class Memory(db.Model):
author = db.UserProperty()
content = db.StringProperty(multiline=True)
date = db.DateProperty()
and then create an instance with:
memory = Memory()
memory.author = users.get_current_user()
memory.content = self.request.get('content')
But as soon as I try to do anything with the date value, I break it. I'm assuming - and entering - the date value in this format: 2009-07-21
I've tried:
memory.date = time.strptime(self.request.get('date'), '%Y-%m-%d')
memory.date = db.DateProperty(self.request.get('date'))
memory.date = self.request.get('date') (wishful thinking I guess)
and a few other options I can't even remember now. Everything I try leads to an ImportError with a giant stack trace ending in:
: No
module named _multiprocessing
args = ('No module named _multiprocessing',)
message = 'No module named _multiprocessing'
I have no idea what to make of that.
I come from a PHP world where strtotime() was my magic function that gave me everything I needed for conversions, and the date() function could handle the rest of the formatting. Now I see things with inline lambda (??) functions and what not.
What am I missing on something that would seem to be so simple.
A:
You were right with strptime:
>>> dt = time.strptime('2009-07-21', '%Y-%m-%d')
>>> dt
time.struct_time(tm_year=2009, tm_mon=7, tm_mday=21, tm_hour=0, tm_min=0, tm_sec
=0, tm_wday=1, tm_yday=202, tm_isdst=-1)
>>>
You got struct that can be used by other functions. For example display date in M/D/Y convention:
>>> time.strftime('%m/%d/%Y', dt)
'07/21/2009'
Another example (import datetime module):
>>> dt = datetime.datetime.strptime('2009-07-21', '%Y-%m-%d')
>>> td = datetime.timedelta(days=20)
>>> dt+td
datetime.datetime(2009, 8, 10, 0, 0)
A:
Yeah, PHP's is much nicer. I'm using this library
http://labix.org/python-dateutil
>>> import dateutil.parser
>>> dateutil.parser.parse("may 2 1984")
datetime.datetime(1984, 5, 2, 0, 0)
A:
perhaps you are using the wrong class? I'm not sure what type your model should take
but try:
from datetime import datetime
myValue = datetime.strptime(self.request.get('date'), '%Y-%m-%d')
I use a datetime object in MySQL with MySQLdb (and a datetime field)
...likewise you can try
from datetime import datetime
myValue = datetime.strptime(self.request.get('date'), '%Y-%m-%d').date()
(notice the [obj].date() at the end)
|
Creating DateTime from user inputted date
|
I'm pretty new to Python and App Engine, but what I'm trying to do is store a model which contains a DateProperty, and that DateProperty is populated with a Date entered by the user in a web form.
I've got the model of:
class Memory(db.Model):
author = db.UserProperty()
content = db.StringProperty(multiline=True)
date = db.DateProperty()
and then create an instance with:
memory = Memory()
memory.author = users.get_current_user()
memory.content = self.request.get('content')
But as soon as I try to do anything with the date value, I break it. I'm assuming - and entering - the date value in this format: 2009-07-21
I've tried:
memory.date = time.strptime(self.request.get('date'), '%Y-%m-%d')
memory.date = db.DateProperty(self.request.get('date'))
memory.date = self.request.get('date') (wishful thinking I guess)
and a few other options I can't even remember now. Everything I try leads to an ImportError with a giant stack trace ending in:
: No
module named _multiprocessing
args = ('No module named _multiprocessing',)
message = 'No module named _multiprocessing'
I have no idea what to make of that.
I come from a PHP world where strtotime() was my magic function that gave me everything I needed for conversions, and the date() function could handle the rest of the formatting. Now I see things with inline lambda (??) functions and what not.
What am I missing on something that would seem to be so simple.
|
[
"You were right with strptime:\n>>> dt = time.strptime('2009-07-21', '%Y-%m-%d')\n>>> dt\n time.struct_time(tm_year=2009, tm_mon=7, tm_mday=21, tm_hour=0, tm_min=0, tm_sec\n =0, tm_wday=1, tm_yday=202, tm_isdst=-1)\n>>>\n\nYou got struct that can be used by other functions. For example display date in M/D/Y convention:\n>>> time.strftime('%m/%d/%Y', dt)\n'07/21/2009'\n\nAnother example (import datetime module):\n>>> dt = datetime.datetime.strptime('2009-07-21', '%Y-%m-%d')\n>>> td = datetime.timedelta(days=20)\n>>> dt+td\ndatetime.datetime(2009, 8, 10, 0, 0)\n\n",
"Yeah, PHP's is much nicer. I'm using this library \nhttp://labix.org/python-dateutil\n>>> import dateutil.parser\n>>> dateutil.parser.parse(\"may 2 1984\")\ndatetime.datetime(1984, 5, 2, 0, 0)\n\n",
"perhaps you are using the wrong class? I'm not sure what type your model should take\nbut try:\nfrom datetime import datetime\n\nmyValue = datetime.strptime(self.request.get('date'), '%Y-%m-%d')\n\nI use a datetime object in MySQL with MySQLdb (and a datetime field)\n...likewise you can try\nfrom datetime import datetime\n\nmyValue = datetime.strptime(self.request.get('date'), '%Y-%m-%d').date()\n\n(notice the [obj].date() at the end)\n"
] |
[
0,
0,
0
] |
[] |
[] |
[
"datetime",
"python"
] |
stackoverflow_0001157794_datetime_python.txt
|
Q:
Qt GraphicsScene constantly redrawing
I've written my own implementation of QGraphicsView.drawItems(), to fit the needs of my application. The method as such works fine, however, it is called repeatedly, even if it does not need to be redrawn. This causes the application to max out processor utilization.
Do I need to somehow signal that the drawing is finished? I read the source in the git tree, and I couldn't see any such thing being done.
The app is in Python/PyQt, and my draw-method looks like this:
def drawItems(self, painter, items, options):
markupColors={'manual':QColor(0, 0, 255),
'automatic':QColor(255, 0, 0),
'user':QColor(0, 255, 0)}
for index in xrange(len(items)):
item=items[index]
option=options[index]
dataAsInt, dataIsInt=item.data(self.DRAWABLE_INDEX).toInt()
drawable=None
if dataIsInt:
drawable=self.drawables[dataAsInt]
item.setPen(markupColors[drawable.source])
item.paint(painter, option, None)
The view's method is overridden by "monkey-patching", like this:
self.ui.imageArea.drawItems=self.drawer.drawItems
The above method is self.drawer.drawItems in the last statement.
Any ideas why this happens?
A:
I think this causes the problem:
item.setPen(markupColors[drawable.source])
If you take a look at the source code:
void QAbstractGraphicsShapeItem::setPen(const QPen &pen)
{
Q_D(QAbstractGraphicsShapeItem);
prepareGeometryChange();
d->pen = pen;
d->boundingRect = QRectF();
update();
}
It calls update() each time pen is set.
|
Qt GraphicsScene constantly redrawing
|
I've written my own implementation of QGraphicsView.drawItems(), to fit the needs of my application. The method as such works fine, however, it is called repeatedly, even if it does not need to be redrawn. This causes the application to max out processor utilization.
Do I need to somehow signal that the drawing is finished? I read the source in the git tree, and I couldn't see any such thing being done.
The app is in Python/PyQt, and my draw-method looks like this:
def drawItems(self, painter, items, options):
markupColors={'manual':QColor(0, 0, 255),
'automatic':QColor(255, 0, 0),
'user':QColor(0, 255, 0)}
for index in xrange(len(items)):
item=items[index]
option=options[index]
dataAsInt, dataIsInt=item.data(self.DRAWABLE_INDEX).toInt()
drawable=None
if dataIsInt:
drawable=self.drawables[dataAsInt]
item.setPen(markupColors[drawable.source])
item.paint(painter, option, None)
The view's method is overridden by "monkey-patching", like this:
self.ui.imageArea.drawItems=self.drawer.drawItems
The above method is self.drawer.drawItems in the last statement.
Any ideas why this happens?
|
[
"I think this causes the problem:\nitem.setPen(markupColors[drawable.source])\n\nIf you take a look at the source code:\nvoid QAbstractGraphicsShapeItem::setPen(const QPen &pen)\n{\n Q_D(QAbstractGraphicsShapeItem);\n prepareGeometryChange();\n d->pen = pen;\n d->boundingRect = QRectF();\n update();\n}\n\nIt calls update() each time pen is set.\n"
] |
[
0
] |
[] |
[] |
[
"python",
"qt"
] |
stackoverflow_0001157773_python_qt.txt
|
Q:
Which library should I use to write an XLS from Linux / Python?
I'd love a good native Python library to write XLS, but it doesn't seem to exist. Happily, Jython does.
So I'm trying to decide between jexcelapi and Apache HSSF:
http://www.andykhan.com/jexcelapi/tutorial.html#writing
http://poi.apache.org/hssf/quick-guide.html
(I can't use COM automation because I'm not on Windows, and even if I was, I couldn't afford Office licenses.)
My initial thoughts are that POI/HSSF is very thorough, but also very Java-- everything seems a bit harder than it needs to be. Good documentation, but my head hurts trying to bridge the gap between what it describes and what I need to accomplish.
jexcepapi seems to have a simpler, nicer (for me) interface, but doesn't have very good documentation or community.
Which would you use, and why?
A:
What's wrong with xlwt?
A:
+1 for xlwt. See Matt Harrison's blog for posts on how to use xlwt and how to deal with large spreadsheets. Also, check out the python-excel group on Google "If you use Python to read, write or otherwise manipulate Excel files".
A:
I'd use JExcelApi, but only because I've used it before. Never have touched HSSF. Biggest show-stopper I can recall is JExcelApi doesn't support multiple formats in one cell (e.g. half the text in bold, the other half in italic or something like that). I think in general JExcelApi is more limited than HSSF, but the limitations never got in my way.
And yes, documentation is sparse for the interface (and nonexistent for the underlying mechanisms), but I thought it was doable...
A:
i personally dis-advise JExcel if you intent to use anything more then very simple text to excel and vice versa.
the more advanced features are abstracted very leaky from the underlying (basically undocumented) low-level code / (documented) Excel specs.
another problem we ran into is jexcel fails fatally when encountering invalid formulas.
and if you need to parse client supplied spreadsheets this is a problem.
also the new POI version support (almost) seemless both xls and xlsx at the same time.
A:
Excel exposes the same OLE automation API used by VBA to anything that supports COM. You can use win32com (which is included with ActiveState Python by default) to manipulate spreadsheets in much the same way that you would do in VBA.
|
Which library should I use to write an XLS from Linux / Python?
|
I'd love a good native Python library to write XLS, but it doesn't seem to exist. Happily, Jython does.
So I'm trying to decide between jexcelapi and Apache HSSF:
http://www.andykhan.com/jexcelapi/tutorial.html#writing
http://poi.apache.org/hssf/quick-guide.html
(I can't use COM automation because I'm not on Windows, and even if I was, I couldn't afford Office licenses.)
My initial thoughts are that POI/HSSF is very thorough, but also very Java-- everything seems a bit harder than it needs to be. Good documentation, but my head hurts trying to bridge the gap between what it describes and what I need to accomplish.
jexcepapi seems to have a simpler, nicer (for me) interface, but doesn't have very good documentation or community.
Which would you use, and why?
|
[
"What's wrong with xlwt?\n",
"+1 for xlwt. See Matt Harrison's blog for posts on how to use xlwt and how to deal with large spreadsheets. Also, check out the python-excel group on Google \"If you use Python to read, write or otherwise manipulate Excel files\".\n",
"I'd use JExcelApi, but only because I've used it before. Never have touched HSSF. Biggest show-stopper I can recall is JExcelApi doesn't support multiple formats in one cell (e.g. half the text in bold, the other half in italic or something like that). I think in general JExcelApi is more limited than HSSF, but the limitations never got in my way.\n And yes, documentation is sparse for the interface (and nonexistent for the underlying mechanisms), but I thought it was doable...\n",
"i personally dis-advise JExcel if you intent to use anything more then very simple text to excel and vice versa.\nthe more advanced features are abstracted very leaky from the underlying (basically undocumented) low-level code / (documented) Excel specs.\nanother problem we ran into is jexcel fails fatally when encountering invalid formulas.\nand if you need to parse client supplied spreadsheets this is a problem.\nalso the new POI version support (almost) seemless both xls and xlsx at the same time.\n",
"Excel exposes the same OLE automation API used by VBA to anything that supports COM. You can use win32com (which is included with ActiveState Python by default) to manipulate spreadsheets in much the same way that you would do in VBA.\n"
] |
[
18,
3,
1,
1,
0
] |
[] |
[] |
[
"hssf",
"java",
"jexcelapi",
"python",
"xls"
] |
stackoverflow_0000245225_hssf_java_jexcelapi_python_xls.txt
|
Q:
How can I parse marked up text for further processing?
See updated input and output data at Edit-1.
What I am trying to accomplish is turning
+ 1
+ 1.1
+ 1.1.1
- 1.1.1.1
- 1.1.1.2
+ 1.2
- 1.2.1
- 1.2.2
- 1.3
+ 2
- 3
into a python data structure such as
[{'1': [{'1.1': {'1.1.1': ['1.1.1.1', '1.1.1.2']}, '1.2': ['1.2.1', '1.2.2']}, '1.3'], '2': {}}, ['3',]]
I've looked at many different wiki markup languages, markdown, restructured text, etc but they are all extremely complicated for me to understand how it works since they must cover a large amount of tags and syntax (I would only need the "list" parts of most of these but converted to python instead of html of course.)
I've also taken a look at tokenizers, lexers and parsers but again they are much more complicated than I need and that I can understand.
I have no idea where to begin and would appreciate any help possible on this subject. Thanks
Edit-1: Yes the character at the beginning of the line matters, from the required output from before and now it could be seen that the * denotes a root node with children, the + has children and the - has no children (root or otherwise) and is just extra information pertaining to that node. The * is not important and can be interchanged with + (I can get root status other ways.)
Therefore the new requirement would be using only * to denote a node with or without children and - cannot have children. I've also changed it so the key isn't the text after the * since that will no doubt changer later to an actual title.
For example
* 1
* 1.1
* 1.2
- Note for 1.2
* 2
* 3
- Note for root
would give
[{'title': '1', 'children': [{'title': '1.1', 'children': []}, {'title': '1.2', 'children': []}]}, {'title': '2', 'children': [], 'notes': ['Note for 1.2', ]}, {'title': '3', 'children': []}, 'Note for root']
Or if you have another idea to represent the outline in python then bring it forward.
A:
Edit: thanks to the clarification and change in the spec I've edited my code, still using an explicit Node class as an intermediate step for clarity -- the logic is to turn the list of lines into a list of nodes, then turn that list of nodes into a tree (by using their indent attribute appropriately), then print that tree in a readable form (this is just a "debug-help" step, to check the tree is well constructed, and can of course get commented out in the final version of the script -- which, just as of course, will take the lines from a file rather than having them hardcoded for debugging!-), finally build the desired Python structure and print it. Here's the code, and as we'll see after that the result is almost as the OP specifies with one exception -- but, the code first:
import sys
class Node(object):
def __init__(self, title, indent):
self.title = title
self.indent = indent
self.children = []
self.notes = []
self.parent = None
def __repr__(self):
return 'Node(%s, %s, %r, %s)' % (
self.indent, self.parent, self.title, self.notes)
def aspython(self):
result = dict(title=self.title, children=topython(self.children))
if self.notes:
result['notes'] = self.notes
return result
def print_tree(node):
print ' ' * node.indent, node.title
for subnode in node.children:
print_tree(subnode)
for note in node.notes:
print ' ' * node.indent, 'Note:', note
def topython(nodelist):
return [node.aspython() for node in nodelist]
def lines_to_tree(lines):
nodes = []
for line in lines:
indent = len(line) - len(line.lstrip())
marker, body = line.strip().split(None, 1)
if marker == '*':
nodes.append(Node(body, indent))
elif marker == '-':
nodes[-1].notes.append(body)
else:
print>>sys.stderr, "Invalid marker %r" % marker
tree = Node('', -1)
curr = tree
for node in nodes:
while node.indent <= curr.indent:
curr = curr.parent
node.parent = curr
curr.children.append(node)
curr = node
return tree
data = """\
* 1
* 1.1
* 1.2
- Note for 1.2
* 2
* 3
- Note for root
""".splitlines()
def main():
tree = lines_to_tree(data)
print_tree(tree)
print
alist = topython(tree.children)
print alist
if __name__ == '__main__':
main()
When run, this emits:
1
1.1
1.2
Note: 1.2
2
3
Note: 3
[{'children': [{'children': [], 'title': '1.1'}, {'notes': ['Note for 1.2'], 'children': [], 'title': '1.2'}], 'title': '1'}, {'children': [], 'title': '2'}, {'notes': ['Note for root'], 'children': [], 'title': '3'}]
Apart from the ordering of keys (which is immaterial and not guaranteed in a dict, of course), this is almost as requested -- except that here all notes appear as dict entries with a key of notes and a value that's a list of strings (but the notes entry is omitted if the list would be empty, roughly as done in the example in the question).
In the current version of the question, how to represent the notes is slightly unclear; one note appears as a stand-alone string, others as entries whose value is a string (instead of a list of strings as I'm using). It's not clear what's supposed to imply that the note must appear as a stand-alone string in one case and as a dict entry in all others, so this scheme I'm using is more regular; and if a note (if any) is a single string rather than a list, would that mean it's an error if more than one note appears for a node? In the latter regard, this scheme I'm using is more general (lets a node have any number of notes from 0 up, instead of just 0 or 1 as apparently implied in the question).
Having written so much code (the pre-edit answer was about as long and helped clarify and change the specs) to provide (I hope) 99% of the desired solution, I hope this satisfies the original poster, since the last few tweaks to code and/or specs to make them match each other should be easy for him to do!
A:
Since you're dealing with an outline situation, you can simplify things by using a stack. Basically, you want to create a stack that has dicts corresponding to the depth of the outline. When you parse a new line and the depth of the outline has increased, you push a new dict onto the stack that was referenced by the previous dict at the top of the stack. When you parse a line that has a lower depth, you pop the stack to get back to the parent. And when you encounter a line that has the same depth, you add it to the dict at the top of the stack.
A:
Stacks are a really useful datastructure when parsing trees. You just keep the path from the last added node up to the root on the stack at all times so you can find the correct parent by the length of the indent. Something like this should work for parsing your last example:
import re
line_tokens = re.compile('( *)(\\*|-) (.*)')
def parse_tree(data):
stack = [{'title': 'Root node', 'children': []}]
for line in data.split("\n"):
indent, symbol, content = line_tokens.match(line).groups()
while len(indent) + 1 < len(stack):
stack.pop() # Remove everything up to current parent
if symbol == '-':
stack[-1].setdefault('notes', []).append(content)
elif symbol == '*':
node = {'title': content, 'children': []}
stack[-1]['children'].append(node)
stack.append(node) # Add as the current deepest node
return stack[0]
A:
The syntax you`re using is very similar to Yaml. It has some differences, but it’s quite easy to learn — it’s main focus is to be human readable (and writable).
Take look at Yaml website. There are some python bindings, documentation and other stuff there.
http://www.yaml.org
|
How can I parse marked up text for further processing?
|
See updated input and output data at Edit-1.
What I am trying to accomplish is turning
+ 1
+ 1.1
+ 1.1.1
- 1.1.1.1
- 1.1.1.2
+ 1.2
- 1.2.1
- 1.2.2
- 1.3
+ 2
- 3
into a python data structure such as
[{'1': [{'1.1': {'1.1.1': ['1.1.1.1', '1.1.1.2']}, '1.2': ['1.2.1', '1.2.2']}, '1.3'], '2': {}}, ['3',]]
I've looked at many different wiki markup languages, markdown, restructured text, etc but they are all extremely complicated for me to understand how it works since they must cover a large amount of tags and syntax (I would only need the "list" parts of most of these but converted to python instead of html of course.)
I've also taken a look at tokenizers, lexers and parsers but again they are much more complicated than I need and that I can understand.
I have no idea where to begin and would appreciate any help possible on this subject. Thanks
Edit-1: Yes the character at the beginning of the line matters, from the required output from before and now it could be seen that the * denotes a root node with children, the + has children and the - has no children (root or otherwise) and is just extra information pertaining to that node. The * is not important and can be interchanged with + (I can get root status other ways.)
Therefore the new requirement would be using only * to denote a node with or without children and - cannot have children. I've also changed it so the key isn't the text after the * since that will no doubt changer later to an actual title.
For example
* 1
* 1.1
* 1.2
- Note for 1.2
* 2
* 3
- Note for root
would give
[{'title': '1', 'children': [{'title': '1.1', 'children': []}, {'title': '1.2', 'children': []}]}, {'title': '2', 'children': [], 'notes': ['Note for 1.2', ]}, {'title': '3', 'children': []}, 'Note for root']
Or if you have another idea to represent the outline in python then bring it forward.
|
[
"Edit: thanks to the clarification and change in the spec I've edited my code, still using an explicit Node class as an intermediate step for clarity -- the logic is to turn the list of lines into a list of nodes, then turn that list of nodes into a tree (by using their indent attribute appropriately), then print that tree in a readable form (this is just a \"debug-help\" step, to check the tree is well constructed, and can of course get commented out in the final version of the script -- which, just as of course, will take the lines from a file rather than having them hardcoded for debugging!-), finally build the desired Python structure and print it. Here's the code, and as we'll see after that the result is almost as the OP specifies with one exception -- but, the code first:\nimport sys\n\nclass Node(object):\n def __init__(self, title, indent):\n self.title = title\n self.indent = indent\n self.children = []\n self.notes = []\n self.parent = None\n def __repr__(self):\n return 'Node(%s, %s, %r, %s)' % (\n self.indent, self.parent, self.title, self.notes)\n def aspython(self):\n result = dict(title=self.title, children=topython(self.children))\n if self.notes:\n result['notes'] = self.notes\n return result\n\ndef print_tree(node):\n print ' ' * node.indent, node.title\n for subnode in node.children:\n print_tree(subnode)\n for note in node.notes:\n print ' ' * node.indent, 'Note:', note\n\ndef topython(nodelist):\n return [node.aspython() for node in nodelist]\n\ndef lines_to_tree(lines):\n nodes = []\n for line in lines:\n indent = len(line) - len(line.lstrip())\n marker, body = line.strip().split(None, 1)\n if marker == '*':\n nodes.append(Node(body, indent))\n elif marker == '-':\n nodes[-1].notes.append(body)\n else:\n print>>sys.stderr, \"Invalid marker %r\" % marker\n\n tree = Node('', -1)\n curr = tree\n for node in nodes:\n while node.indent <= curr.indent:\n curr = curr.parent\n node.parent = curr\n curr.children.append(node)\n curr = node\n\n return tree\n\n\ndata = \"\"\"\\\n* 1\n * 1.1\n * 1.2\n - Note for 1.2\n* 2\n* 3\n- Note for root\n\"\"\".splitlines()\n\ndef main():\n tree = lines_to_tree(data)\n print_tree(tree)\n print\n alist = topython(tree.children)\n print alist\n\nif __name__ == '__main__':\n main()\n\nWhen run, this emits:\n 1\n 1.1\n 1.2\n Note: 1.2\n 2\n 3\n Note: 3\n\n[{'children': [{'children': [], 'title': '1.1'}, {'notes': ['Note for 1.2'], 'children': [], 'title': '1.2'}], 'title': '1'}, {'children': [], 'title': '2'}, {'notes': ['Note for root'], 'children': [], 'title': '3'}]\n\nApart from the ordering of keys (which is immaterial and not guaranteed in a dict, of course), this is almost as requested -- except that here all notes appear as dict entries with a key of notes and a value that's a list of strings (but the notes entry is omitted if the list would be empty, roughly as done in the example in the question).\nIn the current version of the question, how to represent the notes is slightly unclear; one note appears as a stand-alone string, others as entries whose value is a string (instead of a list of strings as I'm using). It's not clear what's supposed to imply that the note must appear as a stand-alone string in one case and as a dict entry in all others, so this scheme I'm using is more regular; and if a note (if any) is a single string rather than a list, would that mean it's an error if more than one note appears for a node? In the latter regard, this scheme I'm using is more general (lets a node have any number of notes from 0 up, instead of just 0 or 1 as apparently implied in the question).\nHaving written so much code (the pre-edit answer was about as long and helped clarify and change the specs) to provide (I hope) 99% of the desired solution, I hope this satisfies the original poster, since the last few tweaks to code and/or specs to make them match each other should be easy for him to do!\n",
"Since you're dealing with an outline situation, you can simplify things by using a stack. Basically, you want to create a stack that has dicts corresponding to the depth of the outline. When you parse a new line and the depth of the outline has increased, you push a new dict onto the stack that was referenced by the previous dict at the top of the stack. When you parse a line that has a lower depth, you pop the stack to get back to the parent. And when you encounter a line that has the same depth, you add it to the dict at the top of the stack.\n",
"Stacks are a really useful datastructure when parsing trees. You just keep the path from the last added node up to the root on the stack at all times so you can find the correct parent by the length of the indent. Something like this should work for parsing your last example:\nimport re\nline_tokens = re.compile('( *)(\\\\*|-) (.*)')\n\ndef parse_tree(data):\n stack = [{'title': 'Root node', 'children': []}]\n for line in data.split(\"\\n\"):\n indent, symbol, content = line_tokens.match(line).groups() \n while len(indent) + 1 < len(stack):\n stack.pop() # Remove everything up to current parent\n if symbol == '-':\n stack[-1].setdefault('notes', []).append(content)\n elif symbol == '*':\n node = {'title': content, 'children': []}\n stack[-1]['children'].append(node)\n stack.append(node) # Add as the current deepest node\n return stack[0]\n\n",
"The syntax you`re using is very similar to Yaml. It has some differences, but it’s quite easy to learn — it’s main focus is to be human readable (and writable). \nTake look at Yaml website. There are some python bindings, documentation and other stuff there.\n\nhttp://www.yaml.org\n\n"
] |
[
6,
1,
1,
0
] |
[] |
[] |
[
"lexer",
"markdown",
"markup",
"parsing",
"python"
] |
stackoverflow_0001090280_lexer_markdown_markup_parsing_python.txt
|
Q:
django - QuerySet recursive order by method
I may have a classic problem, but I didn't find any snippet allowing me to do it.
I want to sort this model by its fullname.
class ProductType(models.Model):
parent = models.ForeignKey('self', related_name='child_set')
name = models.CharField(max_length=128)
def get_fullname(self):
if self.parent is None:
return self.name
return u'%s - %s' % (unicode(self.parent), self.name)
fullname = property(get_fullname)
I tried sorting by "parent", got infinite loop error. "parent__id" did not sort well.
I could not understand how to use annotate() for concatenating string fields.
I added a custom manager with sorted(), but it returns a list object and prevents my forms.ModelChoiceField to work.
Here's the sort
def all(self):
return sorted(super(ProductTypeManager, self), key=lambda o: o.fullname)
What else is there in the djangonic jungle ?
Thanks for your help.
A:
I would probably create a denomalised field and order on that. Depending on your preferences you might wnat to override .save(), or use a signal to poplate the denormalised field.
class ProductType(models.Model):
parent = models.ForeignKey('self', related_name='child_set')
name = models.CharField(max_length=128)
full_name = models.CharField(max_length=128*4)
def save(self, *args, **kwargs):
if not full_name:
self.full_name = self.get_fullname()
super(ProductType, self).save(*args, **kwargs)
def get_fullname(self):
if self.parent is None:
return self.name
return u'%s - %s' % (unicode(self.parent), self.name)
Then do a normal order by full_name
A:
Or, if what you're trying to do is to generate a tree structure, have a look at django-mptt. It also allows for ordering on a manually set order.
A:
This might work:
ProductType.objects.alL().order_by('parent__name', 'name')
A:
agreed :
ProductType.objects.all().order_by('parent__name', 'name')
http://docs.djangoproject.com/en/dev/ref/models/querysets/#order-by-fields
A:
I would definitely explore the route you mentioned as 1) above:
ProductType.objects.order_by('parent__name', 'name')
Why is it erroring with an infinite loop? Is your example data referencing itself?
|
django - QuerySet recursive order by method
|
I may have a classic problem, but I didn't find any snippet allowing me to do it.
I want to sort this model by its fullname.
class ProductType(models.Model):
parent = models.ForeignKey('self', related_name='child_set')
name = models.CharField(max_length=128)
def get_fullname(self):
if self.parent is None:
return self.name
return u'%s - %s' % (unicode(self.parent), self.name)
fullname = property(get_fullname)
I tried sorting by "parent", got infinite loop error. "parent__id" did not sort well.
I could not understand how to use annotate() for concatenating string fields.
I added a custom manager with sorted(), but it returns a list object and prevents my forms.ModelChoiceField to work.
Here's the sort
def all(self):
return sorted(super(ProductTypeManager, self), key=lambda o: o.fullname)
What else is there in the djangonic jungle ?
Thanks for your help.
|
[
"I would probably create a denomalised field and order on that. Depending on your preferences you might wnat to override .save(), or use a signal to poplate the denormalised field.\nclass ProductType(models.Model):\n parent = models.ForeignKey('self', related_name='child_set')\n name = models.CharField(max_length=128)\n full_name = models.CharField(max_length=128*4)\n\n def save(self, *args, **kwargs):\n if not full_name:\n self.full_name = self.get_fullname()\n super(ProductType, self).save(*args, **kwargs)\n\n\n def get_fullname(self):\n if self.parent is None:\n return self.name\n return u'%s - %s' % (unicode(self.parent), self.name)\n\nThen do a normal order by full_name\n",
"Or, if what you're trying to do is to generate a tree structure, have a look at django-mptt. It also allows for ordering on a manually set order.\n",
"This might work:\nProductType.objects.alL().order_by('parent__name', 'name')\n\n",
"agreed :\nProductType.objects.all().order_by('parent__name', 'name')\nhttp://docs.djangoproject.com/en/dev/ref/models/querysets/#order-by-fields\n",
"I would definitely explore the route you mentioned as 1) above:\nProductType.objects.order_by('parent__name', 'name')\n\nWhy is it erroring with an infinite loop? Is your example data referencing itself? \n"
] |
[
2,
1,
0,
0,
0
] |
[] |
[] |
[
"django",
"python"
] |
stackoverflow_0001158267_django_python.txt
|
Q:
backport function modifiers to python2.1
I have some code I developed in python 2.4++ and you bet, I have to backport it to python 2.1!
function decorators were so attractive that I have used @classmethod at a few spots, without taking notice of the fact that it is only available starting at version 2.4. the same functionality is offered by function modifiers but these appeared in python 2.2. cfr: http://www.python.org/dev/peps/pep-0318/
now some of our customers appear to be still dependent on python 2.1 (ArcGIS 9.1 ships with it and makes it not upgradable), where not even the function modifiers are available...
I have been looking for some function modifier definitions in python 2.1, but I did not find any (I mean: working). anybody successfully solved this problem?
to be more concrete, I need a way to run this 2.4 code in python 2.1:
Python 2.4.6 (#2, Mar 19 2009, 10:00:53)
[GCC 4.3.3] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> class sic:
... def f(cls):
... print cls.__name__
... f = classmethod(f)
...
>>> sic().f()
sic
>>> sic.f()
sic
>>>
A:
Just like in my old recipe for 2.1 staticmethod:
class staticmethod:
def __init__(self, thefunc): self.f = thefunc
def __call__(self, *a, **k): return self.f(*a, **k)
you should be able to do a 2.1 classmethod as:
class classmethod:
def __init__(self, thefunc): self.f = thefunc
def __call__(self, obj, *a, **k): return self.f(obj.__class__, *a, **k)
No @-syntax of course, but rather the old way (like in 2.2):
class sic:
def f(cls): ...
f = classmethod(f)
If this doesn't work (sorry, been many many years since I had a Python 2.1 around to test), the class will need to be supplied more explicitly -- and since you call classmethod before the class object exists, it will need to be by name -- assuming a global class,
class classmethod2:
def __init__(self, thefunc, clsnam):
self.f = thefunc
self.clsnam = clsnam
def __call__(self, *a, **k):
klass = globals()[self.clsnam]
return self.f(klass, *a, **k)
class sic2:
def f(cls): ...
f = classmethod2(f, 'sic2')
It's really hard to find elegant ways to get the class object (suppressing the need for self is the easy part, and what suffices for staticmethod: you just need to wrap the function into a non-function callable) since 2.1 had only legacy (old-style classes), no usable metaclasses, and thus no really good way to have sic2.f() magically get that cls.
Since the lack of @ syntax in 2.1 inevitably requires editing of code that uses @classmethod, an alternative is to move the functionality (decorating some methods to be "class" ones) to right AFTER the end of the class statement (the advantage is that the class object does exist at that time).
class classmethod3:
def __init__(self, thefunc, klass):
self.f = thefunc
self.klass = klass
def __call__(self, *a, **k):
return self.f(self.klass, *a, **k)
def decorate(klass, klassmethodnames):
for n in klassmethodnames:
thefunc = klass.__dict__[n]
setattr(klass, n, classmethod3(thefunc, klass))
class sic2:
def f(cls): ...
def g(self): ...
def h(cls): ...
decorate(sic2, ['f', 'h'])
A:
If just the @classmethod need to be backported to Python 2.1.
There is a recipe of Classmethod emulation in python2.1
Hope this help.
|
backport function modifiers to python2.1
|
I have some code I developed in python 2.4++ and you bet, I have to backport it to python 2.1!
function decorators were so attractive that I have used @classmethod at a few spots, without taking notice of the fact that it is only available starting at version 2.4. the same functionality is offered by function modifiers but these appeared in python 2.2. cfr: http://www.python.org/dev/peps/pep-0318/
now some of our customers appear to be still dependent on python 2.1 (ArcGIS 9.1 ships with it and makes it not upgradable), where not even the function modifiers are available...
I have been looking for some function modifier definitions in python 2.1, but I did not find any (I mean: working). anybody successfully solved this problem?
to be more concrete, I need a way to run this 2.4 code in python 2.1:
Python 2.4.6 (#2, Mar 19 2009, 10:00:53)
[GCC 4.3.3] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> class sic:
... def f(cls):
... print cls.__name__
... f = classmethod(f)
...
>>> sic().f()
sic
>>> sic.f()
sic
>>>
|
[
"Just like in my old recipe for 2.1 staticmethod:\nclass staticmethod:\n def __init__(self, thefunc): self.f = thefunc\n def __call__(self, *a, **k): return self.f(*a, **k)\n\nyou should be able to do a 2.1 classmethod as:\nclass classmethod:\n def __init__(self, thefunc): self.f = thefunc\n def __call__(self, obj, *a, **k): return self.f(obj.__class__, *a, **k)\n\nNo @-syntax of course, but rather the old way (like in 2.2):\nclass sic:\n def f(cls): ...\n f = classmethod(f)\n\nIf this doesn't work (sorry, been many many years since I had a Python 2.1 around to test), the class will need to be supplied more explicitly -- and since you call classmethod before the class object exists, it will need to be by name -- assuming a global class,\nclass classmethod2:\n def __init__(self, thefunc, clsnam):\n self.f = thefunc\n self.clsnam = clsnam\n def __call__(self, *a, **k):\n klass = globals()[self.clsnam]\n return self.f(klass, *a, **k)\n\nclass sic2:\n def f(cls): ...\n f = classmethod2(f, 'sic2')\n\nIt's really hard to find elegant ways to get the class object (suppressing the need for self is the easy part, and what suffices for staticmethod: you just need to wrap the function into a non-function callable) since 2.1 had only legacy (old-style classes), no usable metaclasses, and thus no really good way to have sic2.f() magically get that cls.\nSince the lack of @ syntax in 2.1 inevitably requires editing of code that uses @classmethod, an alternative is to move the functionality (decorating some methods to be \"class\" ones) to right AFTER the end of the class statement (the advantage is that the class object does exist at that time).\nclass classmethod3:\n def __init__(self, thefunc, klass):\n self.f = thefunc\n self.klass = klass\n def __call__(self, *a, **k):\n return self.f(self.klass, *a, **k)\n\ndef decorate(klass, klassmethodnames):\n for n in klassmethodnames:\n thefunc = klass.__dict__[n]\n setattr(klass, n, classmethod3(thefunc, klass))\n\nclass sic2:\n def f(cls): ...\n def g(self): ...\n def h(cls): ...\ndecorate(sic2, ['f', 'h'])\n\n",
"If just the @classmethod need to be backported to Python 2.1.\nThere is a recipe of Classmethod emulation in python2.1\nHope this help.\n"
] |
[
2,
1
] |
[] |
[] |
[
"backport",
"python",
"syntax"
] |
stackoverflow_0001159023_backport_python_syntax.txt
|
Q:
How to replace a column using Python's built-in .csv writer module?
I need to do a find and replace (specific to one column of URLs) in a huge Excel .csv file. Since I'm in the beginning stages of trying to teach myself a scripting language, I figured I'd try to implement the solution in python.
I'm having trouble with the "replace" part of the solution. I've read the official csv module documentation about how to use the writer, but there isn't really a clear enough example for me (yes, I'm slow). So, now for the question: how does one iterate through the rows of a csv file with a writer object?
p.s. apologies in advance for the clumsy code, I'm still learning :)
import csv
csvfile = open("PALTemplateData.csv")
csvout = open("PALTemplateDataOUT.csv")
dialect = csv.Sniffer().sniff(csvfile.read(1024))
csvfile.seek(0)
reader = csv.reader(csvfile, dialect)
writer = csv.writer(csvout, dialect)
total=0;
needchange=0;
changed = 0;
temp = ''
changeList = []
for row in reader:
total=total+1
temp = row[len(row)-1]
if '/?' in temp:
needchange=needchange+1;
changeList.append(row.index)
for row in writer: #this doesn't compile, hence the question
if row.index in changeList:
changed=changed+1
temp = row[len(row)-1]
temp.replace('/?', '?')
row[len(row)-1] = temp
writer.writerow(row)
print('Total URLs:', total)
print('Total URLs to change:', needchange)
print('Total URLs changed:', changed)
A:
The reason you're getting an error is that the writer doesn't have data to iterate over. You're supposed to give it the data - presumably, you'd have some sort of list or generator that produces the rows to write out.
I'd suggest just combining the two loops, like so:
for row in reader:
row[-1] = row[-1].replace('/?', '?')
writer.writerow(row)
And with that, you don't even need total, needchange, and changeList. (There are a bunch of optimizations in there that I unfortunately don't have time to explain, but I'll see if I can edit that info in later)
A:
You should only have one loop and read and write at the same time - if your replacements only affect one line at a time, you don't need to loop over the data twice.
for row in reader:
total=total+1
temp = row[len(row)-1]
if '/?' in temp:
temp = row[len(row)-1]
temp.replace('/?', '?')
row[len(row)-1] = temp
writer.writerow(row)
This is just to illustrate the loop, not sure if the replacement code will work like this.
A:
Once you have your csv in a big list, one easy way to replace a column in a list would be to transpose your matrix, replace the row, and then transpose it back:
mydata = [[1, 'a', 10], [2, 'b', 20], [3, 'c', 30]]
def transpose(matrix):
return [[matrix[x][y] for x in range(len(matrix))] for y in range(len(matrix[0]))]
transposedData = transpose(mydata)
print transposedData
>>> [[1, 2, 3], ['a', 'b', 'c'], [10, 20, 30]]
editedData = transposedData[:2] + [50,70,90]
print editedData
>>> [[1, 2, 3], ['a', 'b', 'c'], [50, 70, 90]]
mydata = transpose(editedData)
print mydata
>>> [[1, 'a', 50], [2, 'b', 70], [3, 'c', 90]]
|
How to replace a column using Python's built-in .csv writer module?
|
I need to do a find and replace (specific to one column of URLs) in a huge Excel .csv file. Since I'm in the beginning stages of trying to teach myself a scripting language, I figured I'd try to implement the solution in python.
I'm having trouble with the "replace" part of the solution. I've read the official csv module documentation about how to use the writer, but there isn't really a clear enough example for me (yes, I'm slow). So, now for the question: how does one iterate through the rows of a csv file with a writer object?
p.s. apologies in advance for the clumsy code, I'm still learning :)
import csv
csvfile = open("PALTemplateData.csv")
csvout = open("PALTemplateDataOUT.csv")
dialect = csv.Sniffer().sniff(csvfile.read(1024))
csvfile.seek(0)
reader = csv.reader(csvfile, dialect)
writer = csv.writer(csvout, dialect)
total=0;
needchange=0;
changed = 0;
temp = ''
changeList = []
for row in reader:
total=total+1
temp = row[len(row)-1]
if '/?' in temp:
needchange=needchange+1;
changeList.append(row.index)
for row in writer: #this doesn't compile, hence the question
if row.index in changeList:
changed=changed+1
temp = row[len(row)-1]
temp.replace('/?', '?')
row[len(row)-1] = temp
writer.writerow(row)
print('Total URLs:', total)
print('Total URLs to change:', needchange)
print('Total URLs changed:', changed)
|
[
"The reason you're getting an error is that the writer doesn't have data to iterate over. You're supposed to give it the data - presumably, you'd have some sort of list or generator that produces the rows to write out.\nI'd suggest just combining the two loops, like so:\nfor row in reader:\n row[-1] = row[-1].replace('/?', '?')\n writer.writerow(row)\n\nAnd with that, you don't even need total, needchange, and changeList. (There are a bunch of optimizations in there that I unfortunately don't have time to explain, but I'll see if I can edit that info in later)\n",
"You should only have one loop and read and write at the same time - if your replacements only affect one line at a time, you don't need to loop over the data twice.\nfor row in reader:\n total=total+1\n temp = row[len(row)-1]\n if '/?' in temp:\n temp = row[len(row)-1]\n temp.replace('/?', '?')\n row[len(row)-1] = temp\n writer.writerow(row)\n\nThis is just to illustrate the loop, not sure if the replacement code will work like this.\n",
"Once you have your csv in a big list, one easy way to replace a column in a list would be to transpose your matrix, replace the row, and then transpose it back:\nmydata = [[1, 'a', 10], [2, 'b', 20], [3, 'c', 30]]\n\ndef transpose(matrix):\n return [[matrix[x][y] for x in range(len(matrix))] for y in range(len(matrix[0]))]\n\ntransposedData = transpose(mydata)\nprint transposedData\n>>> [[1, 2, 3], ['a', 'b', 'c'], [10, 20, 30]]\n\neditedData = transposedData[:2] + [50,70,90]\nprint editedData\n>>> [[1, 2, 3], ['a', 'b', 'c'], [50, 70, 90]]\n\nmydata = transpose(editedData)\nprint mydata\n>>> [[1, 'a', 50], [2, 'b', 70], [3, 'c', 90]]\n\n"
] |
[
6,
1,
0
] |
[] |
[] |
[
"csv",
"file_io",
"python"
] |
stackoverflow_0001019200_csv_file_io_python.txt
|
Q:
How do I disable PythonWin's “Redirecting output to win32trace remote collector” feature without uninstalling PythonWin?
When I run a wxPython application, it prints the string “Redirecting output to win32trace remote collector”and I must open PythonWin's trace collector tool to view that trace output.
Since I'm not interested in collecting this output, how should I disable this feature?
A:
You can even pass that when you instantiate your wx.App():
if __name__ == "__main__":
app = wx.App(redirect=False) #or 0
app.MainLoop()
wxPython wx.App docs
A:
This message deceived me into thinking win32trace was preventing me from seeing uncaught exceptions in the regular console (of my IDE). The real issue was that wxPython by default redirects stdout/stderr to a popup window that quickly disappeared after an uncaught exception. To solve that problem, I simply had to pass redirect=0 to the superclass constructor of my application.
class MyApp(wx.App):
def __init__(self):
# Prevent wxPython from redirecting stdout/stderr:
super(MyApp, self).__init__(redirect=0)
That fix notwithstanding, I am still curious about how to control win32trace.
A:
It seems to be an Problem with TortoiseHG. It also happens when using win32gui.GetOpenFileNameW.
Uninstalling solves this problem.
Unfortunately i found no real solution how to fix this.
|
How do I disable PythonWin's “Redirecting output to win32trace remote collector” feature without uninstalling PythonWin?
|
When I run a wxPython application, it prints the string “Redirecting output to win32trace remote collector”and I must open PythonWin's trace collector tool to view that trace output.
Since I'm not interested in collecting this output, how should I disable this feature?
|
[
"You can even pass that when you instantiate your wx.App():\nif __name__ == \"__main__\":\n app = wx.App(redirect=False) #or 0\n app.MainLoop()\n\nwxPython wx.App docs\n",
"This message deceived me into thinking win32trace was preventing me from seeing uncaught exceptions in the regular console (of my IDE). The real issue was that wxPython by default redirects stdout/stderr to a popup window that quickly disappeared after an uncaught exception. To solve that problem, I simply had to pass redirect=0 to the superclass constructor of my application.\nclass MyApp(wx.App):\n def __init__(self):\n # Prevent wxPython from redirecting stdout/stderr:\n super(MyApp, self).__init__(redirect=0)\n\nThat fix notwithstanding, I am still curious about how to control win32trace.\n",
"It seems to be an Problem with TortoiseHG. It also happens when using win32gui.GetOpenFileNameW.\nUninstalling solves this problem.\nUnfortunately i found no real solution how to fix this.\n"
] |
[
2,
1,
1
] |
[] |
[] |
[
"python",
"windows",
"wxpython"
] |
stackoverflow_0000306901_python_windows_wxpython.txt
|
Q:
Where to put message queue consumer in Django?
I'm using Carrot for a message queue in a Django project and followed the tutorial, and it works fine. But the example runs in the console, and I'm wondering how I apply this in Django. The publisher class I'm calling from one of my models in models.py, so that's OK. But I have no idea where to put the consumer class.
Since it just sits there with .wait(), I don't know at what point or where I need to instantiate it so that it's always running and listening for messages!
Thanks!
A:
The consumer is simply a long running script in the example you cite from the tutorial. It pops a message from the queue, does something, then calls wait and essentially goes to sleep until another message comes in.
This script could just be running at the console under your account or configured as a unix daemon or a win32 service. In production, you'd want to make sure that if it dies, it can be restarted, etc (a daemon or service would be more appropriate here).
Or you could take out the wait call and run it under the windows scheduler or as a cron job. So it processes the queue every n minutes or something and exits. It really depends on your application requirements, how fast your queue is filling up, etc.
Does that make sense or have I totally missed what you were asking?
A:
If what you are doing is processing tasks, please check out celery: http://github.com/ask/celery/
|
Where to put message queue consumer in Django?
|
I'm using Carrot for a message queue in a Django project and followed the tutorial, and it works fine. But the example runs in the console, and I'm wondering how I apply this in Django. The publisher class I'm calling from one of my models in models.py, so that's OK. But I have no idea where to put the consumer class.
Since it just sits there with .wait(), I don't know at what point or where I need to instantiate it so that it's always running and listening for messages!
Thanks!
|
[
"The consumer is simply a long running script in the example you cite from the tutorial. It pops a message from the queue, does something, then calls wait and essentially goes to sleep until another message comes in. \nThis script could just be running at the console under your account or configured as a unix daemon or a win32 service. In production, you'd want to make sure that if it dies, it can be restarted, etc (a daemon or service would be more appropriate here). \nOr you could take out the wait call and run it under the windows scheduler or as a cron job. So it processes the queue every n minutes or something and exits. It really depends on your application requirements, how fast your queue is filling up, etc.\nDoes that make sense or have I totally missed what you were asking? \n",
"If what you are doing is processing tasks, please check out celery: http://github.com/ask/celery/\n"
] |
[
5,
0
] |
[] |
[] |
[
"amqp",
"django",
"message_queue",
"python",
"rabbitmq"
] |
stackoverflow_0001112645_amqp_django_message_queue_python_rabbitmq.txt
|
Q:
Where are Man -pages for the module MySQLdb in Python?
I would like to get Python's documentation for MySQLdb in Man -format such that I can read them in terminal.
Where are Man -pages for MySQLdb in Python?
A:
Have you tried using pydoc? Try running the following command.
pydoc MySQLdb
That should give you something close to what you're looking for.
A:
You may have to convert it yourself. MySQLdb doesn't come with man pages (as far as I know) but the documentation can be accessed e.g. from the project page. The user guide has a format reasonably similar to a man page so you could probably try to work with that.
Note that you can just download the user guide and use an HTML-aware pager like less to read it in the terminal.
|
Where are Man -pages for the module MySQLdb in Python?
|
I would like to get Python's documentation for MySQLdb in Man -format such that I can read them in terminal.
Where are Man -pages for MySQLdb in Python?
|
[
"Have you tried using pydoc? Try running the following command.\npydoc MySQLdb\n\nThat should give you something close to what you're looking for.\n",
"You may have to convert it yourself. MySQLdb doesn't come with man pages (as far as I know) but the documentation can be accessed e.g. from the project page. The user guide has a format reasonably similar to a man page so you could probably try to work with that.\nNote that you can just download the user guide and use an HTML-aware pager like less to read it in the terminal.\n"
] |
[
2,
1
] |
[] |
[] |
[
"mysql",
"python"
] |
stackoverflow_0001160345_mysql_python.txt
|
Q:
redirect browser in SimpleHTTPServer.py?
I am partially through implementing the functionality of SimpleHTTPServer.py in Scheme. I am having some good fun with HTTP request/response mechanism. While going through the above file, I came across this- " # redirect browser - doing basically what apache does" in the code".
Why is this redirection necessary in such a scenario?
A:
It simplifies things to treat the trailing / as irrelevant when the user does a GET on a directory, so that (say) http://www.foo.com/bar and http://www.foo.com/bar/ have exactly the same effect. Simplest (though not fastest, see Souders' books;-) is to have the former cause a redirect to the latter.
A:
Imagine you serve a page
http://mydomain.com/bla
that contains
<a href="more.html">Read more...</a>
On click, the user's browser would retrieve http://mydomain.com/more.html. Had you instead served
http://mydomain.com/bla/
(with the same content), the browser would retrieve http://mydomain.com/bla/more.html. To avoid this ambiguity, the redirection appends a slash if the URL points to a directory.
|
redirect browser in SimpleHTTPServer.py?
|
I am partially through implementing the functionality of SimpleHTTPServer.py in Scheme. I am having some good fun with HTTP request/response mechanism. While going through the above file, I came across this- " # redirect browser - doing basically what apache does" in the code".
Why is this redirection necessary in such a scenario?
|
[
"It simplifies things to treat the trailing / as irrelevant when the user does a GET on a directory, so that (say) http://www.foo.com/bar and http://www.foo.com/bar/ have exactly the same effect. Simplest (though not fastest, see Souders' books;-) is to have the former cause a redirect to the latter.\n",
"Imagine you serve a page\nhttp://mydomain.com/bla\n\nthat contains\n<a href=\"more.html\">Read more...</a>\n\nOn click, the user's browser would retrieve http://mydomain.com/more.html. Had you instead served\nhttp://mydomain.com/bla/\n\n(with the same content), the browser would retrieve http://mydomain.com/bla/more.html. To avoid this ambiguity, the redirection appends a slash if the URL points to a directory.\n"
] |
[
3,
3
] |
[] |
[] |
[
"python",
"racket",
"scheme"
] |
stackoverflow_0001160329_python_racket_scheme.txt
|
Q:
How to use a custom site-package using pth-files for Python 2.6?
I'm trying to setup a custom site-package directory (Python 2.6 on Windows Vista). For example the directory should be '~\lib\python2.6' ( C:\Users\wierob\lib\python2.6). Hence calling 'setup.py install' should copy packages to C:\Users\wierob\lib\python2.6.
Following the instructions here:
I've created a pth-file in site-packages directory of the Python installation (C:\Python26\Lib\site-packages). This file contains a single line:
import os, site; site.addsitedir(os.path.expanduser('~/lib/python2.6'))
Additionally I have a pydistutils.cfg my home directory (C:\Users\wierob) that contains:
[install]
install_lib = ~/lib/python2.6
install_scripts = ~/bin
When I run 'setup.py install' I get the following error message:
C:\Users\wierob\Documents\Python\workspace\rsreader>setup.py install
running install
Checking .pth file support in C:\Users\wierob\lib\python2.6\
C:\Python26\pythonw.exe -E -c pass
TEST FAILED: C:\Users\wierob\lib\python2.6\ does NOT support .pth files
error: bad install directory or PYTHONPATH
You are attempting to install a package to a directory that is not
on PYTHONPATH and which Python does not read ".pth" files from. The
installation directory you specified (via --install-dir, --prefix, or
the distutils default setting) was:
C:\Users\wierob\lib\python2.6\
So it seems that the pth-file does not work. Although, if I enter
site.addsitedir(os.path.expanduser('~/lib/python2.6'))
in an interactive python session the directory is succesfully added to sys.path.
Any ideas? Thanks.
A:
The pth-file seems to be ignored if encoded in UTF-8 with BOM.
Saving the pth-file in ANSI or UTF-8 without BOM works.
A:
According to documentation you should put paths to .pth file so maybe entering:
C:\Users\wierob\lib\python2.6
will work
|
How to use a custom site-package using pth-files for Python 2.6?
|
I'm trying to setup a custom site-package directory (Python 2.6 on Windows Vista). For example the directory should be '~\lib\python2.6' ( C:\Users\wierob\lib\python2.6). Hence calling 'setup.py install' should copy packages to C:\Users\wierob\lib\python2.6.
Following the instructions here:
I've created a pth-file in site-packages directory of the Python installation (C:\Python26\Lib\site-packages). This file contains a single line:
import os, site; site.addsitedir(os.path.expanduser('~/lib/python2.6'))
Additionally I have a pydistutils.cfg my home directory (C:\Users\wierob) that contains:
[install]
install_lib = ~/lib/python2.6
install_scripts = ~/bin
When I run 'setup.py install' I get the following error message:
C:\Users\wierob\Documents\Python\workspace\rsreader>setup.py install
running install
Checking .pth file support in C:\Users\wierob\lib\python2.6\
C:\Python26\pythonw.exe -E -c pass
TEST FAILED: C:\Users\wierob\lib\python2.6\ does NOT support .pth files
error: bad install directory or PYTHONPATH
You are attempting to install a package to a directory that is not
on PYTHONPATH and which Python does not read ".pth" files from. The
installation directory you specified (via --install-dir, --prefix, or
the distutils default setting) was:
C:\Users\wierob\lib\python2.6\
So it seems that the pth-file does not work. Although, if I enter
site.addsitedir(os.path.expanduser('~/lib/python2.6'))
in an interactive python session the directory is succesfully added to sys.path.
Any ideas? Thanks.
|
[
"The pth-file seems to be ignored if encoded in UTF-8 with BOM.\nSaving the pth-file in ANSI or UTF-8 without BOM works.\n",
"According to documentation you should put paths to .pth file so maybe entering:\nC:\\Users\\wierob\\lib\\python2.6\n\nwill work\n"
] |
[
1,
0
] |
[] |
[] |
[
"python"
] |
stackoverflow_0001159650_python.txt
|
Q:
Creating a board game simulator (Python?) (Pygame?)
I've decided to start working on programming an old favorite of mine. I've never done a game before and also never done a large project in Python.
The game is the old Avalon Hill game Russian Campaign
I've been playing with PyGame a little bit and was wondering if there were reasons not to try to do this with PyGame and go after some other engine/language.
What would be the disadvantages of using Pygame to build this?
I'm not worried about AI, primarily I'd just love to get a minimal two player version of the game up and running. Bonuses would be the ability to save the state of the game and also to play over a network.
Do's and Dont's for starting this project would be greatly appreciated.
A:
Separate the "back-end" engine (which keeps track of board state, receives move orders from front-ends, generates random numbers to resolve battles, sends updates to front-ends, deals with saving and restoring specific games, ...) from "front-end" ones, which basically supply user interfaces for all of this.
PyGame is one suitable technology for a client-side front-end, but you could implement multiple front-ends (maybe a PyGame one, a browser-based one, a text-based one for debugging, etc, etc). The back-end of course could care less about PyGame or other UI technologies. Python is fine for most front-ends (except ones that need to be in Javascript, Actionscript, etc, if you write front-ends for browsers, Flash, etc;-) and definitely fine for thre back-end.
Run back-end and front-ends as separate processes and communicate as simply as you possibly can -- for a turn-based game (as I believe this one is), XML-RPC or some even simpler variant (JSON payloads going back and forth over HTTP POST and replies to them, say) would seem best.
I'd start with the back-end (probably using JSON for payloads, as I mentioned), as a dirt-simple WSGI server (maybe with a touch of werkzeug or the like to help out with mdidleware), and a simple-as-dirt debugging command-line client. At each step I would then be enriching either the server side (back-end) or the client side (front-end) carefully avoiding doing too-big OR any simultaneous "steps". I wouldn't use "heavy" technologies nor any big frameworks doing magical things behind my back (no ORMs, Django, SOAP, ...).
Make sure you use a good source code repository (say hg, or maybe svn if you know you'll be doing it all alone, or bazaar or git if you already know them).
A:
I don't think you should care about multiple-plateforms support, separation of front-ends and back-ends, multiple processes with communication using XML-RPC and JSON, server, etc.
Drop your bonuses and concentrate on your main idea : a turn-based, two players game. It's your first game so you'll have a lot to learn and taking care of all this at once can be overwhelming.
|
Creating a board game simulator (Python?) (Pygame?)
|
I've decided to start working on programming an old favorite of mine. I've never done a game before and also never done a large project in Python.
The game is the old Avalon Hill game Russian Campaign
I've been playing with PyGame a little bit and was wondering if there were reasons not to try to do this with PyGame and go after some other engine/language.
What would be the disadvantages of using Pygame to build this?
I'm not worried about AI, primarily I'd just love to get a minimal two player version of the game up and running. Bonuses would be the ability to save the state of the game and also to play over a network.
Do's and Dont's for starting this project would be greatly appreciated.
|
[
"Separate the \"back-end\" engine (which keeps track of board state, receives move orders from front-ends, generates random numbers to resolve battles, sends updates to front-ends, deals with saving and restoring specific games, ...) from \"front-end\" ones, which basically supply user interfaces for all of this.\nPyGame is one suitable technology for a client-side front-end, but you could implement multiple front-ends (maybe a PyGame one, a browser-based one, a text-based one for debugging, etc, etc). The back-end of course could care less about PyGame or other UI technologies. Python is fine for most front-ends (except ones that need to be in Javascript, Actionscript, etc, if you write front-ends for browsers, Flash, etc;-) and definitely fine for thre back-end.\nRun back-end and front-ends as separate processes and communicate as simply as you possibly can -- for a turn-based game (as I believe this one is), XML-RPC or some even simpler variant (JSON payloads going back and forth over HTTP POST and replies to them, say) would seem best.\nI'd start with the back-end (probably using JSON for payloads, as I mentioned), as a dirt-simple WSGI server (maybe with a touch of werkzeug or the like to help out with mdidleware), and a simple-as-dirt debugging command-line client. At each step I would then be enriching either the server side (back-end) or the client side (front-end) carefully avoiding doing too-big OR any simultaneous \"steps\". I wouldn't use \"heavy\" technologies nor any big frameworks doing magical things behind my back (no ORMs, Django, SOAP, ...).\nMake sure you use a good source code repository (say hg, or maybe svn if you know you'll be doing it all alone, or bazaar or git if you already know them).\n",
"I don't think you should care about multiple-plateforms support, separation of front-ends and back-ends, multiple processes with communication using XML-RPC and JSON, server, etc.\nDrop your bonuses and concentrate on your main idea : a turn-based, two players game. It's your first game so you'll have a lot to learn and taking care of all this at once can be overwhelming.\n"
] |
[
25,
2
] |
[] |
[] |
[
"pygame",
"python"
] |
stackoverflow_0001157245_pygame_python.txt
|
Q:
How to Replace a column in a CSV file in Python?
I have 2 csv files. I need to replace a column in one file with a column from the other file but they have to stay sorted according to an ID column.
Here's an example:
file1:
ID, transect, 90mdist
1, a, 10,
2, b, 20,
3, c, 30,
file2:
ID, transect, 90mdist
1, a, 50
2, b, 70
3, c, 90
basically I created a new file with the correct 90mdist and I need to insert it into the old file but it has to line up with the same ID #.
It's my understanding that Python treats csv files as a string. so I can either use a dictionary or convert the data into a list and then change it? which way is best?
Any help would be greatly appreciated!!
A:
The CSV Module in the Python Library is what you need here.
It allows you to read and write CSV files, treating lines a tuples or lists of items.
Just read in the file with the corrected values, store the in a dictionary keyed with the line's ID.
Then read in the second file, replacing the relevant column with the data from the dict and write out to a third file.
Done.
A:
Try this:
from __future__ import with_statement
import csv
def twiddle_csv(file1, file2):
def mess_with_record(record):
record['90mdist'] = 2 * int(record['90mdist']) + 30
with open(file1, "r") as fin:
with open(file2, "w") as fout:
fields = ['ID', 'transect', '90mdist']
reader = csv.DictReader(fin, fieldnames=fields)
writer = csv.DictWriter(fout, fieldnames=fields)
fout.write(",".join(fields) + '\n')
reader.next() # Skip the column header
for record in reader:
mess_with_record(record)
writer.writerow(record)
if __name__ == '__main__':
twiddle_csv('file1', 'file2')
A couple of caveats:
DictReader seems to use the first row
as data, even if it matches the
fields. Call reader.next() to skip.
Data rows cannot have trailing commas. They will be interpreted as empty columns.
DictWriter does not appear to write out the column headers. DIY.
A:
Once you have your csv lists, one easy way to replace a column in one matrix with another would be to transpose the matrices, replace the row, and then transpose back your edited matrix. Here is an example with your data:
csv1 = [['1', 'a', '10'], ['2', 'b', '20'], ['3', 'c', '30']]
csv2 = [['1', 'a', '50'], ['2', 'b', '70'], ['3', 'c', '90']]
# transpose in Python is zip(*myData)
transposedCSV1, transposedCSV2 = zip(*csv1), zip(*csv2)
print transposedCSV1
>>> [['1', '2', '3'], ['a', 'b', 'c'], ['10', '20', '30']]
csv1 = transposedCSV1[:2] + [transposedCSV2[2]]
print csv1
>>> [['1', '2', '3'], ['a', 'b', 'c'], ['50', '70', '90']]
csv1 = zip(*csv1)
print csv1
>>> [['1', 'a', '50'], ['2', 'b', '70'], ['3', 'c', '90']]
A:
If you're only doing this as a one-off, why bother with Python at all? Excel or OpenOffice Calc will open the two CSV files for you, then you can just cut and paste the column from one to the other.
If the two lists of IDs are not exactly the same then a simple VB macro would do it for you.
|
How to Replace a column in a CSV file in Python?
|
I have 2 csv files. I need to replace a column in one file with a column from the other file but they have to stay sorted according to an ID column.
Here's an example:
file1:
ID, transect, 90mdist
1, a, 10,
2, b, 20,
3, c, 30,
file2:
ID, transect, 90mdist
1, a, 50
2, b, 70
3, c, 90
basically I created a new file with the correct 90mdist and I need to insert it into the old file but it has to line up with the same ID #.
It's my understanding that Python treats csv files as a string. so I can either use a dictionary or convert the data into a list and then change it? which way is best?
Any help would be greatly appreciated!!
|
[
"The CSV Module in the Python Library is what you need here.\nIt allows you to read and write CSV files, treating lines a tuples or lists of items.\nJust read in the file with the corrected values, store the in a dictionary keyed with the line's ID.\nThen read in the second file, replacing the relevant column with the data from the dict and write out to a third file.\nDone.\n",
"Try this:\nfrom __future__ import with_statement\n\nimport csv\n\ndef twiddle_csv(file1, file2):\n def mess_with_record(record):\n record['90mdist'] = 2 * int(record['90mdist']) + 30\n with open(file1, \"r\") as fin:\n with open(file2, \"w\") as fout:\n fields = ['ID', 'transect', '90mdist']\n reader = csv.DictReader(fin, fieldnames=fields)\n writer = csv.DictWriter(fout, fieldnames=fields)\n fout.write(\",\".join(fields) + '\\n')\n reader.next() # Skip the column header\n for record in reader:\n mess_with_record(record)\n writer.writerow(record)\n\nif __name__ == '__main__':\n twiddle_csv('file1', 'file2')\n\nA couple of caveats:\n\nDictReader seems to use the first row\nas data, even if it matches the\nfields. Call reader.next() to skip.\nData rows cannot have trailing commas. They will be interpreted as empty columns.\nDictWriter does not appear to write out the column headers. DIY.\n\n",
"Once you have your csv lists, one easy way to replace a column in one matrix with another would be to transpose the matrices, replace the row, and then transpose back your edited matrix. Here is an example with your data:\ncsv1 = [['1', 'a', '10'], ['2', 'b', '20'], ['3', 'c', '30']]\ncsv2 = [['1', 'a', '50'], ['2', 'b', '70'], ['3', 'c', '90']]\n\n# transpose in Python is zip(*myData)\ntransposedCSV1, transposedCSV2 = zip(*csv1), zip(*csv2)\nprint transposedCSV1\n>>> [['1', '2', '3'], ['a', 'b', 'c'], ['10', '20', '30']]\n\ncsv1 = transposedCSV1[:2] + [transposedCSV2[2]]\nprint csv1\n>>> [['1', '2', '3'], ['a', 'b', 'c'], ['50', '70', '90']]\n\ncsv1 = zip(*csv1)\nprint csv1\n>>> [['1', 'a', '50'], ['2', 'b', '70'], ['3', 'c', '90']]\n\n",
"If you're only doing this as a one-off, why bother with Python at all? Excel or OpenOffice Calc will open the two CSV files for you, then you can just cut and paste the column from one to the other. \nIf the two lists of IDs are not exactly the same then a simple VB macro would do it for you.\n"
] |
[
7,
2,
0,
0
] |
[] |
[] |
[
"csv",
"python"
] |
stackoverflow_0001159524_csv_python.txt
|
Q:
models.py getting huge, what is the best way to break it up?
Directions from my supervisor:
"I want to avoid putting any logic in the models.py. From here on out, let's use that as only classes for accessing the database, and keep all logic in external classes that use the models classes, or wrap them."
I feel like this is the wrong way to go. I feel that keeping logic out of the models just to keep the file small is a bad idea. If the logic is best in the model, that's where it really should go regardless of file size.
So is there a simple way to just use includes? In PHP-speak, I'd like to propose to the supervisor that we just have models.py include() the model classes from other places. Conceptually, this would allow the models to have all the logic we want, yet keep file size down via increasing the number of files (which leads to less revision control problems like conflicts, etc.).
So, is there a simple way to remove model classes from the models.py file, but still have the models work with all of the Django tools? Or, is there a completely different yet elegant solution to the general problem of a "large" models.py file? Any input would be appreciated.
A:
It's natural for model classes to contain methods to operate on the model. If I have a Book model, with a method book.get_noun_count(), that's where it belongs--I don't want to have to write "get_noun_count(book)", unless the method actually intrinsically belongs with some other package. (It might--for example, if I have a package for accessing Amazon's API with "get_amazon_product_id(book)".)
I cringed when Django's documentation suggested putting models in a single file, and I took a few minutes from the very beginning to figure out how to split it into a proper subpackage.
site/models/__init__.py
site/models/book.py
__init__.py looks like:
from .book import Book
so I can still write "from site.models import Book".
The following is only required for versions prior to Django 1.7, see
https://code.djangoproject.com/ticket/3591
The only trick is that you need to explicitly set each model's application, due to a bug in Django: it assumes that the application name is the third-to-last entry in the model path. "site.models.Book" results in "site", which is correct; "site.models.book.Book" makes it think the application name is "models". This is a pretty nasty hack on Django's part; it should probably search the list of installed applications for a prefix match.
class Book(models.Model):
class Meta: app_label = "site"
You could probably use a base class or metaclass to generalize this, but I haven't bothered with that yet.
A:
Django is designed to let you build many small applications instead of one big application.
Inside every large application are many small applications struggling to be free.
If your models.py feels big, you're doing too much. Stop. Relax. Decompose.
Find smaller, potentially reusable small application components, or pieces. You don't have to actually reuse them. Just think about them as potentially reusable.
Consider your upgrade paths and decompose applications that you might want to replace some day. You don't have to actually replace them, but you can consider them as a stand-alone "module" of programming that might get replaced with something cooler in the future.
We have about a dozen applications, each model.py is no more than about 400 lines of code. They're all pretty focused on less than about half-dozen discrete class definitions. (These aren't hard limits, they're observations about our code.)
We decompose early and often.
A:
I can't quite get which of many possible problems you might have. Here are some possibilities with answers:
multiple models in the same file
Put them into separate files. If there are dependencies, use import to pull in the
additional models.
extraneous logic / utility functions in models.py
Put the extra logic into separate files.
static methods for selecting some model instances from database
Create a new Manager in a separate file.
methods obviously related to the model
save, __unicode__ and get_absolute_url are examples.
|
models.py getting huge, what is the best way to break it up?
|
Directions from my supervisor:
"I want to avoid putting any logic in the models.py. From here on out, let's use that as only classes for accessing the database, and keep all logic in external classes that use the models classes, or wrap them."
I feel like this is the wrong way to go. I feel that keeping logic out of the models just to keep the file small is a bad idea. If the logic is best in the model, that's where it really should go regardless of file size.
So is there a simple way to just use includes? In PHP-speak, I'd like to propose to the supervisor that we just have models.py include() the model classes from other places. Conceptually, this would allow the models to have all the logic we want, yet keep file size down via increasing the number of files (which leads to less revision control problems like conflicts, etc.).
So, is there a simple way to remove model classes from the models.py file, but still have the models work with all of the Django tools? Or, is there a completely different yet elegant solution to the general problem of a "large" models.py file? Any input would be appreciated.
|
[
"It's natural for model classes to contain methods to operate on the model. If I have a Book model, with a method book.get_noun_count(), that's where it belongs--I don't want to have to write \"get_noun_count(book)\", unless the method actually intrinsically belongs with some other package. (It might--for example, if I have a package for accessing Amazon's API with \"get_amazon_product_id(book)\".)\nI cringed when Django's documentation suggested putting models in a single file, and I took a few minutes from the very beginning to figure out how to split it into a proper subpackage.\nsite/models/__init__.py\nsite/models/book.py\n\n__init__.py looks like:\nfrom .book import Book\n\nso I can still write \"from site.models import Book\".\n\n\nThe following is only required for versions prior to Django 1.7, see\n https://code.djangoproject.com/ticket/3591\n\nThe only trick is that you need to explicitly set each model's application, due to a bug in Django: it assumes that the application name is the third-to-last entry in the model path. \"site.models.Book\" results in \"site\", which is correct; \"site.models.book.Book\" makes it think the application name is \"models\". This is a pretty nasty hack on Django's part; it should probably search the list of installed applications for a prefix match.\nclass Book(models.Model):\n class Meta: app_label = \"site\"\n\nYou could probably use a base class or metaclass to generalize this, but I haven't bothered with that yet.\n",
"Django is designed to let you build many small applications instead of one big application.\nInside every large application are many small applications struggling to be free.\nIf your models.py feels big, you're doing too much. Stop. Relax. Decompose.\nFind smaller, potentially reusable small application components, or pieces. You don't have to actually reuse them. Just think about them as potentially reusable.\nConsider your upgrade paths and decompose applications that you might want to replace some day. You don't have to actually replace them, but you can consider them as a stand-alone \"module\" of programming that might get replaced with something cooler in the future.\nWe have about a dozen applications, each model.py is no more than about 400 lines of code. They're all pretty focused on less than about half-dozen discrete class definitions. (These aren't hard limits, they're observations about our code.)\nWe decompose early and often. \n",
"I can't quite get which of many possible problems you might have. Here are some possibilities with answers:\n\nmultiple models in the same file\nPut them into separate files. If there are dependencies, use import to pull in the \nadditional models.\nextraneous logic / utility functions in models.py \nPut the extra logic into separate files. \nstatic methods for selecting some model instances from database\nCreate a new Manager in a separate file.\nmethods obviously related to the model\nsave, __unicode__ and get_absolute_url are examples.\n\n"
] |
[
115,
64,
6
] |
[] |
[] |
[
"django",
"django_models",
"models",
"python"
] |
stackoverflow_0001160579_django_django_models_models_python.txt
|
Q:
Can you point me to a large Python open-source project?
I would like to see how a large (>40 developers) project done with Python looks like:
how the code looks like
what folder structure they use
what tools they use
how they set up the collaboration environment
what kind of documentation they provide
It doesn't matter what type of software it is (server, client, application, web, ...) but I would prefer something mature (version 1.0 already done)
A:
The Django web framework.
Also, Twisted Matrix.
I am not sure about the exact number of developers, though.
A:
Trac - which coincidentally is also usable for the collaboration environment part of your question.
A:
Roundup - Issue Tracker
Twisted - Network Programming Framework
Zenoss - Network Monitor
Mercurial - SCM Tool
A:
There are about 40 developers working on the language itself. You can take a look at the repository or download the source [ftp] to see style, organization, &c.
Here are some other large Python projects (lines-of-code large).
A:
Chandler is a really huge one that had problems because of its size and the developers working on it, so you can learn from their failures. There's a book written about it too.
Wingware Python IDE is a huge project, unfortunately it's closed source. But I think it's still interesting to see what a large desktop application is like in Python.
A:
The Plone CMS and the Zope application server on which Plone runs.
A:
Perhaps more low-level than you're looking for but the NumPy and SciPy projects are very mature, open source, numerical and scientific programming libraries. Although the API is Python, much of the low-level work is done in C or Fortran.
The IPython project is a pure-python project that is also quite mature.
A:
Is pinax big enough? or ella?
I'm not sure of the developer count, but they are big and have a fair number of forks.
Django would probably qualify.
A:
PyQt4 is a large project.
Here is a list with the most popular python projects.
A:
Pylons.
Even it is 0.9.8, it is quite mature
|
Can you point me to a large Python open-source project?
|
I would like to see how a large (>40 developers) project done with Python looks like:
how the code looks like
what folder structure they use
what tools they use
how they set up the collaboration environment
what kind of documentation they provide
It doesn't matter what type of software it is (server, client, application, web, ...) but I would prefer something mature (version 1.0 already done)
|
[
"The Django web framework.\nAlso, Twisted Matrix.\nI am not sure about the exact number of developers, though.\n",
"Trac - which coincidentally is also usable for the collaboration environment part of your question.\n",
"\nRoundup - Issue Tracker\nTwisted - Network Programming Framework\nZenoss - Network Monitor\nMercurial - SCM Tool\n\n",
"There are about 40 developers working on the language itself. You can take a look at the repository or download the source [ftp] to see style, organization, &c.\nHere are some other large Python projects (lines-of-code large).\n",
"Chandler is a really huge one that had problems because of its size and the developers working on it, so you can learn from their failures. There's a book written about it too.\nWingware Python IDE is a huge project, unfortunately it's closed source. But I think it's still interesting to see what a large desktop application is like in Python.\n",
"The Plone CMS and the Zope application server on which Plone runs.\n",
"Perhaps more low-level than you're looking for but the NumPy and SciPy projects are very mature, open source, numerical and scientific programming libraries. Although the API is Python, much of the low-level work is done in C or Fortran.\nThe IPython project is a pure-python project that is also quite mature.\n",
"Is pinax big enough? or ella? \nI'm not sure of the developer count, but they are big and have a fair number of forks.\nDjango would probably qualify.\n",
"PyQt4 is a large project.\n\nHere is a list with the most popular python projects.\n",
"Pylons.\nEven it is 0.9.8, it is quite mature\n"
] |
[
11,
9,
6,
6,
5,
3,
3,
2,
2,
1
] |
[] |
[] |
[
"open_source",
"python"
] |
stackoverflow_0001161339_open_source_python.txt
|
Q:
how do I read everything currently in a subprocess.stdout pipe and then return?
I'm using python's subprocess module to interact with a program via the stdin and stdout pipes. If I call the subprocesses readline() on stdout, it hangs because it is waiting for a newline.
How can I do a read of all the characters in the stdout pipe of a subprocess instance? If it matters, I'm running in Linux.
A:
Someone else appears to have had the same problem, you can see the related discussion here.
If you are running on Linux you can use select to wait for input on the process' stdout. Alternatively you change the mode of the process' stdout to non-blocking using
import fcntl, os
fcntl.fcntl(your_process.stdout, fcntl.F_SETFL, os.O_NONBLOCK)
after which you can loop using read() until you encounter a newline character (if you want to process the output one line at a time).
A:
You should loop using read() against a set number of characters.
|
how do I read everything currently in a subprocess.stdout pipe and then return?
|
I'm using python's subprocess module to interact with a program via the stdin and stdout pipes. If I call the subprocesses readline() on stdout, it hangs because it is waiting for a newline.
How can I do a read of all the characters in the stdout pipe of a subprocess instance? If it matters, I'm running in Linux.
|
[
"Someone else appears to have had the same problem, you can see the related discussion here. \nIf you are running on Linux you can use select to wait for input on the process' stdout. Alternatively you change the mode of the process' stdout to non-blocking using\nimport fcntl, os \nfcntl.fcntl(your_process.stdout, fcntl.F_SETFL, os.O_NONBLOCK)\n\nafter which you can loop using read() until you encounter a newline character (if you want to process the output one line at a time).\n",
"You should loop using read() against a set number of characters. \n"
] |
[
4,
2
] |
[] |
[] |
[
"linux",
"python"
] |
stackoverflow_0001161580_linux_python.txt
|
Q:
python docstrings
ok so I decided to learn python (perl, c, c++, java, objective-c, ruby and a bit of erlang and scala under my belt). and I keep on getting the following error when I try executing this:
Tue Jul 21{stevenhirsch@steven-hirschs-macbook-pro-2}/projects/python:-->./apache_logs.py
File "./apache_logs.py", line 17
print __doc__
^
SyntaxError: invalid syntax
#!/usr/local/bin/python
"""
USAGE:
apache_logs.py
"""
import sys
import os
if __name__ == "__main__":
if not len(sys.argv) > 1:
print __doc__
sys.exit(1)
infile_name = sys.argv[1]
I know it must be something really stupid but I've googled and read the documentation without finding anything. The docs all seem to state that what I've coded should work.
Many thanks in advance for your help!!
A:
What version of Python do you have? In Python 3, print was changed to work like a function rather than a statement, i.e. print('Hello World') instead of print 'Hello World'
I can recommend you to keep using Python 2.6 unless you're doing some brand new production development. Python 3 is still pretty new.
|
python docstrings
|
ok so I decided to learn python (perl, c, c++, java, objective-c, ruby and a bit of erlang and scala under my belt). and I keep on getting the following error when I try executing this:
Tue Jul 21{stevenhirsch@steven-hirschs-macbook-pro-2}/projects/python:-->./apache_logs.py
File "./apache_logs.py", line 17
print __doc__
^
SyntaxError: invalid syntax
#!/usr/local/bin/python
"""
USAGE:
apache_logs.py
"""
import sys
import os
if __name__ == "__main__":
if not len(sys.argv) > 1:
print __doc__
sys.exit(1)
infile_name = sys.argv[1]
I know it must be something really stupid but I've googled and read the documentation without finding anything. The docs all seem to state that what I've coded should work.
Many thanks in advance for your help!!
|
[
"What version of Python do you have? In Python 3, print was changed to work like a function rather than a statement, i.e. print('Hello World') instead of print 'Hello World'\nI can recommend you to keep using Python 2.6 unless you're doing some brand new production development. Python 3 is still pretty new.\n"
] |
[
5
] |
[] |
[] |
[
"python",
"syntax_error"
] |
stackoverflow_0001161810_python_syntax_error.txt
|
Q:
Add data to Django form class using modelformset_factory
I have a problem where I need to display a lot of forms for detail data for a hierarchical data set. I want to display some relational fields as labels for the forms and I'm struggling with a way to do this in a more robust way. Here is the code...
class Category(models.Model):
name = models.CharField(max_length=160)
class Item(models.Model):
category = models.ForeignKey('Category')
name = models.CharField(max_length=160)
weight = models.IntegerField(default=0)
class Meta:
ordering = ('category','weight','name')
class BudgetValue(models.Model):
value = models.IntegerField()
plan = models.ForeignKey('Plan')
item = models.ForeignKey('Item')
I use the modelformset_factory to create a formset of budgetvalue forms for a particular plan. What I'd like is item name and category name for each BudgetValue. When I iterate through the forms each one will be labeled properly.
class BudgetValueForm(forms.ModelForm):
item = forms.ModelChoiceField(queryset=Item.objects.all(),widget=forms.HiddenInput())
plan = forms.ModelChoiceField(queryset=Plan.objects.all(),widget=forms.HiddenInput())
category = "" < assign dynamically on form creation >
item = "" < assign dynamically on form creation >
class Meta:
model = BudgetValue
fields = ('item','plan','value')
What I started out with is just creating a dictionary of budgetvalue.item.category.name, budgetvalue.item.name, and the form for each budget value. This gets passed to the template and I render it as I intended. I'm assuming that the ordering of the forms in the formset and the querset used to genererate the formset keep the budgetvalues in the same order and the dictionary is created correctly. That is the budgetvalue.item.name is associated with the correct form. This scares me and I'm thinking there has to be a better way. Any help would be greatly appreciated.
A:
Well, I figured out the answer to my own question. I've overridden the init class on the form and accessed the instance of the model form. Works exactly as I wanted and it was easy.
class BudgetValueForm(forms.ModelForm):
item = forms.ModelChoiceField(queryset=Item.objects.all(),widget=forms.HiddenInput())
plan = forms.ModelChoiceField(queryset=Plan.objects.all(),widget=forms.HiddenInput())
def __init__(self, *args, **kwargs):
super(BudgetValueForm, self).__init__(*args, **kwargs)
self.itemname = self.instance.item.name
self.categoryname = self.instance.item.category.name
class Meta:
model = BudgetValue
fields = ('item','plan','value')
|
Add data to Django form class using modelformset_factory
|
I have a problem where I need to display a lot of forms for detail data for a hierarchical data set. I want to display some relational fields as labels for the forms and I'm struggling with a way to do this in a more robust way. Here is the code...
class Category(models.Model):
name = models.CharField(max_length=160)
class Item(models.Model):
category = models.ForeignKey('Category')
name = models.CharField(max_length=160)
weight = models.IntegerField(default=0)
class Meta:
ordering = ('category','weight','name')
class BudgetValue(models.Model):
value = models.IntegerField()
plan = models.ForeignKey('Plan')
item = models.ForeignKey('Item')
I use the modelformset_factory to create a formset of budgetvalue forms for a particular plan. What I'd like is item name and category name for each BudgetValue. When I iterate through the forms each one will be labeled properly.
class BudgetValueForm(forms.ModelForm):
item = forms.ModelChoiceField(queryset=Item.objects.all(),widget=forms.HiddenInput())
plan = forms.ModelChoiceField(queryset=Plan.objects.all(),widget=forms.HiddenInput())
category = "" < assign dynamically on form creation >
item = "" < assign dynamically on form creation >
class Meta:
model = BudgetValue
fields = ('item','plan','value')
What I started out with is just creating a dictionary of budgetvalue.item.category.name, budgetvalue.item.name, and the form for each budget value. This gets passed to the template and I render it as I intended. I'm assuming that the ordering of the forms in the formset and the querset used to genererate the formset keep the budgetvalues in the same order and the dictionary is created correctly. That is the budgetvalue.item.name is associated with the correct form. This scares me and I'm thinking there has to be a better way. Any help would be greatly appreciated.
|
[
"Well, I figured out the answer to my own question. I've overridden the init class on the form and accessed the instance of the model form. Works exactly as I wanted and it was easy.\nclass BudgetValueForm(forms.ModelForm):\n item = forms.ModelChoiceField(queryset=Item.objects.all(),widget=forms.HiddenInput())\n plan = forms.ModelChoiceField(queryset=Plan.objects.all(),widget=forms.HiddenInput())\n\n def __init__(self, *args, **kwargs): \n super(BudgetValueForm, self).__init__(*args, **kwargs) \n self.itemname = self.instance.item.name \n self.categoryname = self.instance.item.category.name \n\n class Meta:\n model = BudgetValue\n fields = ('item','plan','value')\n\n"
] |
[
3
] |
[] |
[] |
[
"django",
"django_forms",
"python"
] |
stackoverflow_0001161618_django_django_forms_python.txt
|
Q:
How to implement a scripting language into a C application?
I have a C application and I want to include a Scripting Language to put certain functionality into scripts. I just have no experience with that and don't know exactly where to start (Still learning C and trying to understand the application).
How does embedding and communication between my app and the scripts actually work? I think I need the interpreter for the scripting language as a library (.dll on Windows or C Source Code that can be compiled into my application)? And then can I do something like
interpreter->run("myscript", some_object);
How would the script know about the properties of the object? Say my script wants to read or modify some_object->some_field?
Are there any scripting languages that are optimized for that sort of embedding? I know that there is Lua which is popular in game dev, and languages like Python, Perl, PHP or Ruby which seem to be more targeted as stand-alone applications, but my knowledge in the deep architecture does not allow more educated guesses :) (Tagged Lua and Python because they would be my favorites, but as long as it runs on x86 Windows, Linux and Mac OS X, I'm open for other scripting languages as long as they are easy to implement into a C application)
A:
Lua. It has a very small footprint, is rather fast, and I found it (subjectively) to have the most pleasant API to interact with C.
If you want to touch the Lua objects from C - it's quite easy using the built-in APIs. If you want to touch C data from Lua - it's a bit more work, typically you'd need to make wrapper methods to expose what you want to allow the Lua to modify.
Small code base and tight control over the amount of default libraries introduced into your embeded interpreter also means that you can make reasonable assumptions over the security.
The only odd part is the 1-based array numbering, however, it was not that big of a deal compared to what I thought, given the existence of the iterators.
How to integrate with C: the distribution tarball for Lua has a directory "etc" with a few very good useful examples that should quickly get you started. Specifically - etc/min.c shows how to start up an interpreter, make it interpret the file, and make it call the C function ('print' in that case). From there on you can go by reading the Lua documentation and the source of the standard libraries included with the distribution.
A:
Some useful links:
Embedding Python
Embedding Lua: http://www.lua.org/manual/5.1/manual.html#3, http://www.ibm.com/developerworks/opensource/library/l-embed-lua/index.html
Embedding Ruby
Embedding PLT Scheme
Embedding PERL
Embedding TCL
Embedding JavaScript
Embedding PHP
I am familiar with Python. Python is a very rich language, and has a huge number of libraries available.
A:
Here's the document from the Python website for embedding Python 2.6...
http://docs.python.org/extending/embedding.html
A:
Lua is totally optimized for exactly this sort of embedding. A good starting point is Roberto Ierusalimschy's book Programming in Lua; you can get the previous edition free online.
How does your script know about the properties of your C object?
Imagine for a moment your object is defined like this:
typedef struct my_object *Object;
Object some_object;
What does your C code know about the properties of that object? Almost nothing, that's what. All you can do is
Pass around pointers to an object, put them in data structures, etc.
Call functions that actually know what's inside a struct my_object.
Lua gets access to C objects in exactly the same way: indirectly through functions:
You make API calls to put a pointer to the object on Lua's stack, from which it can go into Lua data structures, variables, or anywhere else in the Lua universe.
You define functions that know about the object's internals, and you export those functions to Lua.
There is a lot of stuff in the "auxiliary library" to help you. Don't overlook it!
All of this is explained with crystal clarity in the third part of Roberto's book, which includes examples. One fine point is
You have the choice of allocating the memory yourself ("light userdata") or having Lua allocate the memory. It's generally better to have Lua allocate the memory because it can then free the object automatically when it's no longer needed, and you can also associated a Lua metatable, which allows you (among other tricks) to allow the object to participate in standard Lua operations like looking up fields, not just function calls.
A final note: althought it's possible to use SWIG or toLua or other tools to try to generate code to connect C and Lua, I urge you to write the code yourself, by hand. It's actually quite easy to to, and it's the only way to understand what's really going on.
A:
Lua is designed for exactly this purpose, and fairly easy to work with.
Another thing worth looking at would be QtScript, which is Javascript based, although this would involve some work to "qt-ify" your app.
A:
You may also want to take a look at SWIG, the Simplified Wrapper and Interface Generator. As one would guess, it generates much of the boiler plate code to interface your C/C++ code to the scripting engine (which can be quite cumbersome to do manually).
It supports Python and Lua (your preferences) and many other languages. It is quite easy to generate a module that extends the scripting language. Extending and embedding, which is what you desire, takes a bit more effort.
A:
You might take a look at Game Scripting Mastery. As i am interested in the high level aspect of computer games aswell this book has been recommended to me very often.
Unfortunately the book seems to be out of print (at least in Europe).
A:
Most scripting language allow embedding in C and usually allow you to expose certain objects or even functions from your C code to the script so it can manipulate the objects and call the functions.
As said Lua is designed for this purpose embedding, using the interpreter you can expose objects to the script and call lua functions from C, search for embedding lua in C and you should find a lot of information, also don't miss the lua manual section "The Application Programming Interface"
Although Python is more suitable for stand-alone usage, it can also be embedded, it can be useful in case your scripts use the vast amount libraries provided with Python.
|
How to implement a scripting language into a C application?
|
I have a C application and I want to include a Scripting Language to put certain functionality into scripts. I just have no experience with that and don't know exactly where to start (Still learning C and trying to understand the application).
How does embedding and communication between my app and the scripts actually work? I think I need the interpreter for the scripting language as a library (.dll on Windows or C Source Code that can be compiled into my application)? And then can I do something like
interpreter->run("myscript", some_object);
How would the script know about the properties of the object? Say my script wants to read or modify some_object->some_field?
Are there any scripting languages that are optimized for that sort of embedding? I know that there is Lua which is popular in game dev, and languages like Python, Perl, PHP or Ruby which seem to be more targeted as stand-alone applications, but my knowledge in the deep architecture does not allow more educated guesses :) (Tagged Lua and Python because they would be my favorites, but as long as it runs on x86 Windows, Linux and Mac OS X, I'm open for other scripting languages as long as they are easy to implement into a C application)
|
[
"Lua. It has a very small footprint, is rather fast, and I found it (subjectively) to have the most pleasant API to interact with C.\nIf you want to touch the Lua objects from C - it's quite easy using the built-in APIs. If you want to touch C data from Lua - it's a bit more work, typically you'd need to make wrapper methods to expose what you want to allow the Lua to modify.\nSmall code base and tight control over the amount of default libraries introduced into your embeded interpreter also means that you can make reasonable assumptions over the security.\nThe only odd part is the 1-based array numbering, however, it was not that big of a deal compared to what I thought, given the existence of the iterators.\nHow to integrate with C: the distribution tarball for Lua has a directory \"etc\" with a few very good useful examples that should quickly get you started. Specifically - etc/min.c shows how to start up an interpreter, make it interpret the file, and make it call the C function ('print' in that case). From there on you can go by reading the Lua documentation and the source of the standard libraries included with the distribution.\n",
"Some useful links:\n\nEmbedding Python\nEmbedding Lua: http://www.lua.org/manual/5.1/manual.html#3, http://www.ibm.com/developerworks/opensource/library/l-embed-lua/index.html\nEmbedding Ruby\nEmbedding PLT Scheme\nEmbedding PERL\nEmbedding TCL\nEmbedding JavaScript\nEmbedding PHP\n\nI am familiar with Python. Python is a very rich language, and has a huge number of libraries available.\n",
"Here's the document from the Python website for embedding Python 2.6...\nhttp://docs.python.org/extending/embedding.html\n",
"Lua is totally optimized for exactly this sort of embedding. A good starting point is Roberto Ierusalimschy's book Programming in Lua; you can get the previous edition free online.\nHow does your script know about the properties of your C object?\nImagine for a moment your object is defined like this:\ntypedef struct my_object *Object;\nObject some_object;\n\nWhat does your C code know about the properties of that object? Almost nothing, that's what. All you can do is \n\nPass around pointers to an object, put them in data structures, etc.\nCall functions that actually know what's inside a struct my_object.\n\nLua gets access to C objects in exactly the same way: indirectly through functions:\n\nYou make API calls to put a pointer to the object on Lua's stack, from which it can go into Lua data structures, variables, or anywhere else in the Lua universe.\nYou define functions that know about the object's internals, and you export those functions to Lua.\nThere is a lot of stuff in the \"auxiliary library\" to help you. Don't overlook it!\n\nAll of this is explained with crystal clarity in the third part of Roberto's book, which includes examples. One fine point is\n\nYou have the choice of allocating the memory yourself (\"light userdata\") or having Lua allocate the memory. It's generally better to have Lua allocate the memory because it can then free the object automatically when it's no longer needed, and you can also associated a Lua metatable, which allows you (among other tricks) to allow the object to participate in standard Lua operations like looking up fields, not just function calls.\n\nA final note: althought it's possible to use SWIG or toLua or other tools to try to generate code to connect C and Lua, I urge you to write the code yourself, by hand. It's actually quite easy to to, and it's the only way to understand what's really going on.\n",
"Lua is designed for exactly this purpose, and fairly easy to work with.\nAnother thing worth looking at would be QtScript, which is Javascript based, although this would involve some work to \"qt-ify\" your app.\n",
"You may also want to take a look at SWIG, the Simplified Wrapper and Interface Generator. As one would guess, it generates much of the boiler plate code to interface your C/C++ code to the scripting engine (which can be quite cumbersome to do manually).\nIt supports Python and Lua (your preferences) and many other languages. It is quite easy to generate a module that extends the scripting language. Extending and embedding, which is what you desire, takes a bit more effort.\n",
"You might take a look at Game Scripting Mastery. As i am interested in the high level aspect of computer games aswell this book has been recommended to me very often. \nUnfortunately the book seems to be out of print (at least in Europe).\n",
"Most scripting language allow embedding in C and usually allow you to expose certain objects or even functions from your C code to the script so it can manipulate the objects and call the functions.\nAs said Lua is designed for this purpose embedding, using the interpreter you can expose objects to the script and call lua functions from C, search for embedding lua in C and you should find a lot of information, also don't miss the lua manual section \"The Application Programming Interface\"\nAlthough Python is more suitable for stand-alone usage, it can also be embedded, it can be useful in case your scripts use the vast amount libraries provided with Python.\n"
] |
[
17,
17,
8,
8,
4,
3,
2,
1
] |
[] |
[] |
[
"c",
"lua",
"python",
"scripting"
] |
stackoverflow_0001158396_c_lua_python_scripting.txt
|
Q:
Retrieving Raw_Input from a system ran script
I'm using the OS.System command to call a python script.
example:
OS.System("call jython script.py")
In the script I'm calling, the following command is present:
x = raw_input("Waiting for input")
If I run script.py from the command line I can input data no problem, if I run it via the automated approach I get an EOFError. I've read in the past that this happens because the system expects a computer to be running it and therefore could never receive input data in this way.
So the question is how can I get python to wait for user input while being run in an automated way?
A:
The problem is the way you run your child script. Since you use os.system() the script's input channel is closed immediately and the raw_input() prompt hits an EOF (end of file). And even if that didn't happen, you wouldn't have a way to actually send some input text to the child as I assume you'd want given that you are using raw_input().
You should use the subprocess module instead.
import subprocess
from subprocess import PIPE
p = subprocess.Popen(["jython", "script.py"], stdin=PIPE, stdout=PIPE)
print p.communicate("My input")
A:
Your question is a bit unclear. What is the process calling your Python script and how is it being run? If the parent process has no standard input, the child won't have it either.
|
Retrieving Raw_Input from a system ran script
|
I'm using the OS.System command to call a python script.
example:
OS.System("call jython script.py")
In the script I'm calling, the following command is present:
x = raw_input("Waiting for input")
If I run script.py from the command line I can input data no problem, if I run it via the automated approach I get an EOFError. I've read in the past that this happens because the system expects a computer to be running it and therefore could never receive input data in this way.
So the question is how can I get python to wait for user input while being run in an automated way?
|
[
"The problem is the way you run your child script. Since you use os.system() the script's input channel is closed immediately and the raw_input() prompt hits an EOF (end of file). And even if that didn't happen, you wouldn't have a way to actually send some input text to the child as I assume you'd want given that you are using raw_input().\nYou should use the subprocess module instead.\nimport subprocess\nfrom subprocess import PIPE\n\np = subprocess.Popen([\"jython\", \"script.py\"], stdin=PIPE, stdout=PIPE)\nprint p.communicate(\"My input\")\n\n",
"Your question is a bit unclear. What is the process calling your Python script and how is it being run? If the parent process has no standard input, the child won't have it either.\n"
] |
[
2,
0
] |
[] |
[] |
[
"jython",
"python"
] |
stackoverflow_0001161959_jython_python.txt
|
Q:
trac-past-commit-hook on remote repository
Trying to set up the svn commit with trac using this script.
It is being called without issue, but the problem is this line here:
144 repos = self.env.get_repository()
Because I am calling this remotely self.env_get_repository() looks for the repository using the server drive and not the local drive mapping. That is, it is looking for E:/Projects/svn/InfoProj and not Y:/Projects/sv/InfoProj
I noticed a changeset on the trac set for being able to call get_repository() and passing in the path as the variable, but it seems this hasn't made it into the latest stable release yet.
This version of the script (the one submitted by code monkey) appears to do things differently, but is throwing an error that seems related:
154 if url is None:
155 url = self.env.config.get('project', 'url')
156 self.env.href = Href(url)
157 self.env.abs_href = Href(url)
Lines 156 / 157 throw error: Warning: TypeError: 'str' object is not callable
The 10.3 stable version of the script throws a completely different error:
Warning: NameError: global name 'core' is not defined
I'm setting up trac for the first time on a Windows box with a remote repository. I'm using trac 0.11 stable with Python 2.6.
I thought there would have been a lot more people out there trying to commit across servers who had come across this problem. I've looked around and couldn't find a solution. I'm supposing Linux has a more graceful way of handling this.
Thanks in advance.
A:
This is totally do-able and just requires a couple of small hacks... woo hoo!
The problem I was having is that get_repository reads the value of the svn repository from the trac.ini file. This was pointing at E:/ and not at Y:/. The simple fix involves a check to see if the repository is at repository_dir and if not, then check at a new variable remote_repository_dir. The second part of the fix involves removing the error message from cache.py that checks to see if the current repository address matches the one being passed in.
As always, use this at your own risk and back everything up before hand!!!
First open you trac.ini file and add a new variable 'remote_repository_dir' underneath the 'repository_dir' variable. Remote repository dir will point to the mapped drive on your local machine. It should now look something like this:
repository_dir = E:/Projects/svn/InfoProj
remote_repository_dir = Y:/Projects/svn/InfoProj
Next we will modify the api.py file to check for the new variable if it can't find the repository at the repository_dir location. Around :71 you should have something like this:
repository_dir = Option('trac', 'repository_dir', '',
"""Path to local repository. This can also be a relative path
(''since 0.11'').""")
Underneath this line add:
remote_repository_dir = Option('trac', 'remote_repository_dir', '',
"""Path to remote repository.""")
Next near :156 you will have this:
rtype, rdir = self.repository_type, self.repository_dir
if not os.path.isabs(rdir):
rdir = os.path.join(self.env.path, rdir)
Change that to this:
rtype, rdir = self.repository_type, self.repository_dir
if not os.path.isdir(rdir):
rdir = self.remote_repository_dir
if not os.path.isabs(rdir):
rdir = os.path.join(self.env.path, rdir)
Finally you will need to remove the alert in the cache.py file (note this is not the best way to do this, you should be able to include the remote variable as part of the check, but for now it works).
In cache.py near :97 it should look like this:
if repository_dir:
# directory part of the repo name can vary on case insensitive fs
if os.path.normcase(repository_dir) != os.path.normcase(self.name):
self.log.info("'repository_dir' has changed from %r to %r"
% (repository_dir, self.name))
raise TracError(_("The 'repository_dir' has changed, a "
"'trac-admin resync' operation is needed."))
elif repository_dir is None: #
self.log.info('Storing initial "repository_dir": %s' % self.name)
cursor.execute("INSERT INTO system (name,value) VALUES (%s,%s)",
(CACHE_REPOSITORY_DIR, self.name,))
else: # 'repository_dir' cleared by a resync
self.log.info('Resetting "repository_dir": %s' % self.name)
cursor.execute("UPDATE system SET value=%s WHERE name=%s",
(self.name, CACHE_REPOSITORY_DIR))
We are going to remove the first part of the if statement so it now should look like this:
if repository_dir is None: #
self.log.info('Storing initial "repository_dir": %s' % self.name)
cursor.execute("INSERT INTO system (name,value) VALUES (%s,%s)",
(CACHE_REPOSITORY_DIR, self.name,))
else: # 'repository_dir' cleared by a resync
self.log.info('Resetting "repository_dir": %s' % self.name)
cursor.execute("UPDATE system SET value=%s WHERE name=%s",
(self.name, CACHE_REPOSITORY_DIR))
Warning! Doing this will mean that it no longer gives you an error if your directory has changed and you need a resync.
Hope this helps someone.
|
trac-past-commit-hook on remote repository
|
Trying to set up the svn commit with trac using this script.
It is being called without issue, but the problem is this line here:
144 repos = self.env.get_repository()
Because I am calling this remotely self.env_get_repository() looks for the repository using the server drive and not the local drive mapping. That is, it is looking for E:/Projects/svn/InfoProj and not Y:/Projects/sv/InfoProj
I noticed a changeset on the trac set for being able to call get_repository() and passing in the path as the variable, but it seems this hasn't made it into the latest stable release yet.
This version of the script (the one submitted by code monkey) appears to do things differently, but is throwing an error that seems related:
154 if url is None:
155 url = self.env.config.get('project', 'url')
156 self.env.href = Href(url)
157 self.env.abs_href = Href(url)
Lines 156 / 157 throw error: Warning: TypeError: 'str' object is not callable
The 10.3 stable version of the script throws a completely different error:
Warning: NameError: global name 'core' is not defined
I'm setting up trac for the first time on a Windows box with a remote repository. I'm using trac 0.11 stable with Python 2.6.
I thought there would have been a lot more people out there trying to commit across servers who had come across this problem. I've looked around and couldn't find a solution. I'm supposing Linux has a more graceful way of handling this.
Thanks in advance.
|
[
"This is totally do-able and just requires a couple of small hacks... woo hoo!\nThe problem I was having is that get_repository reads the value of the svn repository from the trac.ini file. This was pointing at E:/ and not at Y:/. The simple fix involves a check to see if the repository is at repository_dir and if not, then check at a new variable remote_repository_dir. The second part of the fix involves removing the error message from cache.py that checks to see if the current repository address matches the one being passed in.\nAs always, use this at your own risk and back everything up before hand!!!\nFirst open you trac.ini file and add a new variable 'remote_repository_dir' underneath the 'repository_dir' variable. Remote repository dir will point to the mapped drive on your local machine. It should now look something like this:\nrepository_dir = E:/Projects/svn/InfoProj\nremote_repository_dir = Y:/Projects/svn/InfoProj \n\nNext we will modify the api.py file to check for the new variable if it can't find the repository at the repository_dir location. Around :71 you should have something like this:\nrepository_dir = Option('trac', 'repository_dir', '',\n \"\"\"Path to local repository. This can also be a relative path\n (''since 0.11'').\"\"\")\n\nUnderneath this line add:\nremote_repository_dir = Option('trac', 'remote_repository_dir', '',\n \"\"\"Path to remote repository.\"\"\") \n\nNext near :156 you will have this:\n rtype, rdir = self.repository_type, self.repository_dir\n if not os.path.isabs(rdir):\n rdir = os.path.join(self.env.path, rdir)\n\nChange that to this:\n rtype, rdir = self.repository_type, self.repository_dir\n if not os.path.isdir(rdir):\n rdir = self.remote_repository_dir\n if not os.path.isabs(rdir):\n rdir = os.path.join(self.env.path, rdir)\n\nFinally you will need to remove the alert in the cache.py file (note this is not the best way to do this, you should be able to include the remote variable as part of the check, but for now it works).\nIn cache.py near :97 it should look like this:\n if repository_dir:\n # directory part of the repo name can vary on case insensitive fs\n if os.path.normcase(repository_dir) != os.path.normcase(self.name):\n self.log.info(\"'repository_dir' has changed from %r to %r\"\n % (repository_dir, self.name))\n raise TracError(_(\"The 'repository_dir' has changed, a \"\n \"'trac-admin resync' operation is needed.\"))\n elif repository_dir is None: # \n self.log.info('Storing initial \"repository_dir\": %s' % self.name)\n cursor.execute(\"INSERT INTO system (name,value) VALUES (%s,%s)\",\n (CACHE_REPOSITORY_DIR, self.name,))\n else: # 'repository_dir' cleared by a resync\n self.log.info('Resetting \"repository_dir\": %s' % self.name)\n cursor.execute(\"UPDATE system SET value=%s WHERE name=%s\",\n (self.name, CACHE_REPOSITORY_DIR))\n\nWe are going to remove the first part of the if statement so it now should look like this:\n if repository_dir is None: # \n self.log.info('Storing initial \"repository_dir\": %s' % self.name)\n cursor.execute(\"INSERT INTO system (name,value) VALUES (%s,%s)\",\n (CACHE_REPOSITORY_DIR, self.name,))\n else: # 'repository_dir' cleared by a resync\n self.log.info('Resetting \"repository_dir\": %s' % self.name)\n cursor.execute(\"UPDATE system SET value=%s WHERE name=%s\",\n (self.name, CACHE_REPOSITORY_DIR))\n\nWarning! Doing this will mean that it no longer gives you an error if your directory has changed and you need a resync.\nHope this helps someone.\n"
] |
[
0
] |
[] |
[] |
[
"python",
"svn",
"trac",
"windows"
] |
stackoverflow_0001141157_python_svn_trac_windows.txt
|
Q:
Easiest way to pop up interactive Python console?
My application has a Python interpreter embedded in it. However there's currently not any way to inspect anything about Python directly. I'd like to be able to pop up an interactive shell at various points to inspect what's going on in Python.
I've found several similar questions which pointed me to code.InteractiveConsole and IPython. However neither of those seem to do anything when I call them - the call appears to complete okay, but nothing visible happens, presumably because my Python instance isn't outputting anywhere I can see.
It was pretty optimistic to think that they'd just magically pop up a new window for me, but it would be nice if I could get that to happen. So, does anybody know if there is an easy way to achieve this (or something similar), or do I have to roll my own dialog and pass the input to Python and display output myself?
Thanks :)
A:
What have you tried with IPython? Is it the snippets from the documentation:
Embedding IPython (IPython docs)
How about some of the code samples from elsewhere:
Embedding IPython in GUI apps is trivial
Embedding IPython in a PyGTK application
I know I fooled around with this a while back and the samples seemed to work, but then I never got a chance to go any further for other reasons.
A:
I know this isn't what you're asking, but when I've wanted to debug compiled Python (using Py2Exe), I've been very pleased to realize that I can add breakpoints to the exe and it will actually stop there when I start the executable from a console window. Simply add:
import pdb
pdb.set_trace()
where you want your code to stop, and you'll have yourself an interactive debugging session with a compiled executable. Python is awesome that way :)
|
Easiest way to pop up interactive Python console?
|
My application has a Python interpreter embedded in it. However there's currently not any way to inspect anything about Python directly. I'd like to be able to pop up an interactive shell at various points to inspect what's going on in Python.
I've found several similar questions which pointed me to code.InteractiveConsole and IPython. However neither of those seem to do anything when I call them - the call appears to complete okay, but nothing visible happens, presumably because my Python instance isn't outputting anywhere I can see.
It was pretty optimistic to think that they'd just magically pop up a new window for me, but it would be nice if I could get that to happen. So, does anybody know if there is an easy way to achieve this (or something similar), or do I have to roll my own dialog and pass the input to Python and display output myself?
Thanks :)
|
[
"What have you tried with IPython? Is it the snippets from the documentation:\n\nEmbedding IPython (IPython docs)\n\nHow about some of the code samples from elsewhere:\n\nEmbedding IPython in GUI apps is trivial\nEmbedding IPython in a PyGTK application\n\nI know I fooled around with this a while back and the samples seemed to work, but then I never got a chance to go any further for other reasons.\n",
"I know this isn't what you're asking, but when I've wanted to debug compiled Python (using Py2Exe), I've been very pleased to realize that I can add breakpoints to the exe and it will actually stop there when I start the executable from a console window. Simply add:\nimport pdb\npdb.set_trace()\n\nwhere you want your code to stop, and you'll have yourself an interactive debugging session with a compiled executable. Python is awesome that way :)\n"
] |
[
1,
1
] |
[] |
[] |
[
"debugging",
"python"
] |
stackoverflow_0001162277_debugging_python.txt
|
Q:
win32api.dll Will Not Install
I am trying to start a Buildbot Buildslave on a Windows XP virtual machine:
python buildbot start .
ImportError: No module named win32api.
Google tells me that win32api is win32api.dll. I downloaded the file from www.dll-files.com and followed the guide found on that site (http://www.dll-files.com/unzip.php). When I try to run regvr32 win32api.dll, it tells me that the specified module could not be found.
tl;dr - Where do I put win32api.dll so Windows will install it? Am I trying to use the wrong file? (using python version 2.6)
A:
win32api belongs Python for Windows extensions, Aka Pywn32.
have u installed it?
A:
Install ActivePython (http://www.activestate.com/activepython/) - it's a Python distro that comes bundled with the Windows dlls. It's what everyone else does.
|
win32api.dll Will Not Install
|
I am trying to start a Buildbot Buildslave on a Windows XP virtual machine:
python buildbot start .
ImportError: No module named win32api.
Google tells me that win32api is win32api.dll. I downloaded the file from www.dll-files.com and followed the guide found on that site (http://www.dll-files.com/unzip.php). When I try to run regvr32 win32api.dll, it tells me that the specified module could not be found.
tl;dr - Where do I put win32api.dll so Windows will install it? Am I trying to use the wrong file? (using python version 2.6)
|
[
"win32api belongs Python for Windows extensions, Aka Pywn32.\nhave u installed it?\n",
"Install ActivePython (http://www.activestate.com/activepython/) - it's a Python distro that comes bundled with the Windows dlls. It's what everyone else does.\n"
] |
[
5,
0
] |
[] |
[] |
[
"buildbot",
"dll",
"python",
"twisted",
"windows"
] |
stackoverflow_0001161178_buildbot_dll_python_twisted_windows.txt
|
Q:
How would you model this database relationship?
I'm modeling a database relationship in django, and I'd like to have other opinions. The relationship is kind of a two-to-many relationship. For example, a patient can have two physicians: an attending and a primary. A physician obviously has many patients.
The application does need to know which one is which; further, there are cases where an attending physician of one patient can be the primary of another. Lastly, both attending and primary are often the same.
At first, I was thinking two foreign keys from the patient table into the physician table. However, I think django disallows this. Additionally, on second thought, this is really a many(two)-to-many relationship.
Therefore, how can I model this relationship with django while maintaining the physician type as it pertains to a patient? Perhaps I will need to store the physician type on the many-to-many association table?
Thanks,
Pete
A:
How about something like this:
class Patient(models.Model):
primary_physician = models.ForeignKey('Physician', related_name='primary_patients')
attending_physicial = models.ForeignKey('Physician', related_name='attending_patients')
This allows you to have two foreign keys to the same model; the Physician model will also have fields called primary_patients and attending_patients.
A:
Consider using a many-to-many join table. Use application logic to prevent more than two physicians per patient.
Physician
Physician_ID
...
Patient
Patient_ID
...
Physician_Patient
Physician_ID int not null
Patient_ID int not null
Type ENUM ('Primary', 'Attending')
PRIMARY KEY (Physician_ID, Patient_ID)
KEY (Patient_ID)
A:
I agree with your conclusion. I would store the physician type in the many-to-many linking table.
|
How would you model this database relationship?
|
I'm modeling a database relationship in django, and I'd like to have other opinions. The relationship is kind of a two-to-many relationship. For example, a patient can have two physicians: an attending and a primary. A physician obviously has many patients.
The application does need to know which one is which; further, there are cases where an attending physician of one patient can be the primary of another. Lastly, both attending and primary are often the same.
At first, I was thinking two foreign keys from the patient table into the physician table. However, I think django disallows this. Additionally, on second thought, this is really a many(two)-to-many relationship.
Therefore, how can I model this relationship with django while maintaining the physician type as it pertains to a patient? Perhaps I will need to store the physician type on the many-to-many association table?
Thanks,
Pete
|
[
"How about something like this:\nclass Patient(models.Model):\n primary_physician = models.ForeignKey('Physician', related_name='primary_patients')\n attending_physicial = models.ForeignKey('Physician', related_name='attending_patients')\n\nThis allows you to have two foreign keys to the same model; the Physician model will also have fields called primary_patients and attending_patients.\n",
"Consider using a many-to-many join table. Use application logic to prevent more than two physicians per patient.\nPhysician\n Physician_ID\n ...\n\nPatient\n Patient_ID\n ...\n\nPhysician_Patient\n Physician_ID int not null\n Patient_ID int not null\n Type ENUM ('Primary', 'Attending')\n PRIMARY KEY (Physician_ID, Patient_ID)\n KEY (Patient_ID)\n\n",
"I agree with your conclusion. I would store the physician type in the many-to-many linking table.\n"
] |
[
10,
1,
0
] |
[] |
[] |
[
"database",
"database_design",
"django",
"python"
] |
stackoverflow_0001162877_database_database_design_django_python.txt
|
Q:
Python Math Library Independent of C Math Library and Platform Independent?
Does the built-in Python math library basically use C's math library or does Python have a C-independent math library? Also, is the Python math library platform independent?
A:
at the bottom of the page it says:
Note: The math module consists mostly of thin wrappers around the platform C math library functions. Behavior in exceptional cases is loosely specified by the C standards, and Python inherits much of its math-function error-reporting behavior from the platform C implementation. As a result, the specific exceptions raised in error cases (and even whether some arguments are considered to be exceptional at all) are not defined in any useful cross-platform or cross-release way. For example, whether math.log(0) returns -Inf or raises ValueError or OverflowError isn’t defined, and in cases where math.log(0) raises OverflowError, math.log(0L) may raise ValueError instead.
All functions return a quiet NaN if at least one of the args is NaN. Signaling NaNs raise an exception. The exception type still depends on the platform and libm implementation. It’s usually ValueError for EDOM and OverflowError for errno ERANGE.
Changed in version 2.6: In earlier versions of Python the outcome of an operation with NaN as input depended on platform and libm implementation.
A:
Python uses the C library it is linked against. On Windows, there is no 'platform C library'.. and indeed there are multiple versions of MicrosoftCRunTimeLibrarys (MSCRTs) around on any version.
|
Python Math Library Independent of C Math Library and Platform Independent?
|
Does the built-in Python math library basically use C's math library or does Python have a C-independent math library? Also, is the Python math library platform independent?
|
[
"at the bottom of the page it says:\n\nNote: The math module consists mostly of thin wrappers around the platform C math library functions. Behavior in exceptional cases is loosely specified by the C standards, and Python inherits much of its math-function error-reporting behavior from the platform C implementation. As a result, the specific exceptions raised in error cases (and even whether some arguments are considered to be exceptional at all) are not defined in any useful cross-platform or cross-release way. For example, whether math.log(0) returns -Inf or raises ValueError or OverflowError isn’t defined, and in cases where math.log(0) raises OverflowError, math.log(0L) may raise ValueError instead.\nAll functions return a quiet NaN if at least one of the args is NaN. Signaling NaNs raise an exception. The exception type still depends on the platform and libm implementation. It’s usually ValueError for EDOM and OverflowError for errno ERANGE.\nChanged in version 2.6: In earlier versions of Python the outcome of an operation with NaN as input depended on platform and libm implementation.\n\n",
"Python uses the C library it is linked against. On Windows, there is no 'platform C library'.. and indeed there are multiple versions of MicrosoftCRunTimeLibrarys (MSCRTs) around on any version.\n"
] |
[
5,
2
] |
[] |
[] |
[
"python"
] |
stackoverflow_0001160061_python.txt
|
Q:
Connecting C# (frontend) to an apache/php/python (backend)
Overview: We are looking to write a C# user interface to select parts of our web applications. This is for a very captive audience (internally, for example).
Our web applications are written in PHP and/or Python using Apache as the web server.
Why? A well thought out native Windows interface can at times be far more effective than living with the rules imposed by a web browser.
Question: What is the best way to communicate between C# and PHP/Python using HTTPS? I'm speaking mostly of serialization / unserialization and conversion of the various data types resident in each language.
Ideally, we would have strongly typed structs or objects to work with in C#, and appropriate data structures created in PHP/Python to work with on that end. Code generators are fine.
I've looked at Apache Thrift, considered extending our internal data libraries, reviewed Google's Protocol Buffers, etc... Thrift looks promising, but their documentation is very sparse.
Keeping developer overhead to a minimum is essential.
Keeping performance reasonable , especially on the server side, is important.
Comments on the usefulness of XMLRPC, SOAP, or other related technologies would be welcome.
Any pointers?
A:
I have no real experience with PHP, but I've done plenty of Python back-end web services consumed by front-end clients in a variety of languages and environment. SOAP is the only technology, out of those I've tried, that has mostly left a sour taste in my mouth -- too much "ceremony"/overhead. (Back in the far past I also tried Corba and, as soon as I was trying to interoperate among independed implementations for different languages, the feeling wasn't all that different;-).
XML-RPC, JSON, and protocol buffers, all proved quite usable for me.
Protocol buffers is what we normally use within Google, and I'm not sure what you find so under-documented about them -- please ask specific questions and I'll see what I can do to make our documentation better, officially or unofficially! Their main advantage is that they're so "tight" on the wire -- minimal overhead with maximum flexibility. JSON is great, too -- and not just for ease of use in Javascript clients, either: sometimes I've used it as the default format for communication among different languages, too, when no JS was involved at all!
Once you have your web app set up to emit (say) a protocol buffer, it's not hard at all to make it able to emit XML or JSON on request - one ?outputformat=JSON extra parameter in the GET request is all it takes, and picking the right output serializer is trivially easy (in Python, but, I'm sure, in PHP as well).
"Getting strongly typed objects" on your C# end is, in my view, a job you can best do in a C# layer on your end. No direct experience with that, but, for example, I have wrapped reception of protocol buffers in C++ into factory classes that spewed out perfectly formed and statically typed objects (or raised exceptions when the incoming data was not semantically correct); I know it wouldn't be any harder for JSON or XML, and I very much doubt it would be any harder for Java, C#, Python if you cared, or any other language that's any use at all in the real world!-)
A:
Using web services sounds like the most appropriate way for your scenario.
A:
I have done this using a PHP SOAP Server and VB.Net client. Once you connect the VB.Net/C# client to the server (the location of the WSDL file) C# will automatically detect all the functions and all the objects that are exposed. Making programming much easier.
I would also recommend using NuSOAP which I found to be more functional. http://sourceforge.net/projects/nusoap/
A:
I recommend the PHP/Java Bridge. Don't let the name fool you. This can be used to connect both PHP and Python to any ECMA-335 virtual machine (Java and C#)!
http://php-java-bridge.sourceforge.net/pjb/
To answer your comment:
The communication works in both directions, the JSR 223 interface can be used to connect to a running PHP server (Apache/IIS, FastCGI, ...) so that Java components can call PHP instances and PHP scripts can invoke CLR (e.g. VB.NET, C#, COM) or Java (e.g. Java, KAWA, JRuby) based applications or transfer control back to the environment where the request came from. The bridge can be set up to automatically start a PHP front-end or start a Java/.NET back end, if needed.
|
Connecting C# (frontend) to an apache/php/python (backend)
|
Overview: We are looking to write a C# user interface to select parts of our web applications. This is for a very captive audience (internally, for example).
Our web applications are written in PHP and/or Python using Apache as the web server.
Why? A well thought out native Windows interface can at times be far more effective than living with the rules imposed by a web browser.
Question: What is the best way to communicate between C# and PHP/Python using HTTPS? I'm speaking mostly of serialization / unserialization and conversion of the various data types resident in each language.
Ideally, we would have strongly typed structs or objects to work with in C#, and appropriate data structures created in PHP/Python to work with on that end. Code generators are fine.
I've looked at Apache Thrift, considered extending our internal data libraries, reviewed Google's Protocol Buffers, etc... Thrift looks promising, but their documentation is very sparse.
Keeping developer overhead to a minimum is essential.
Keeping performance reasonable , especially on the server side, is important.
Comments on the usefulness of XMLRPC, SOAP, or other related technologies would be welcome.
Any pointers?
|
[
"I have no real experience with PHP, but I've done plenty of Python back-end web services consumed by front-end clients in a variety of languages and environment. SOAP is the only technology, out of those I've tried, that has mostly left a sour taste in my mouth -- too much \"ceremony\"/overhead. (Back in the far past I also tried Corba and, as soon as I was trying to interoperate among independed implementations for different languages, the feeling wasn't all that different;-).\nXML-RPC, JSON, and protocol buffers, all proved quite usable for me.\nProtocol buffers is what we normally use within Google, and I'm not sure what you find so under-documented about them -- please ask specific questions and I'll see what I can do to make our documentation better, officially or unofficially! Their main advantage is that they're so \"tight\" on the wire -- minimal overhead with maximum flexibility. JSON is great, too -- and not just for ease of use in Javascript clients, either: sometimes I've used it as the default format for communication among different languages, too, when no JS was involved at all!\nOnce you have your web app set up to emit (say) a protocol buffer, it's not hard at all to make it able to emit XML or JSON on request - one ?outputformat=JSON extra parameter in the GET request is all it takes, and picking the right output serializer is trivially easy (in Python, but, I'm sure, in PHP as well).\n\"Getting strongly typed objects\" on your C# end is, in my view, a job you can best do in a C# layer on your end. No direct experience with that, but, for example, I have wrapped reception of protocol buffers in C++ into factory classes that spewed out perfectly formed and statically typed objects (or raised exceptions when the incoming data was not semantically correct); I know it wouldn't be any harder for JSON or XML, and I very much doubt it would be any harder for Java, C#, Python if you cared, or any other language that's any use at all in the real world!-)\n",
"Using web services sounds like the most appropriate way for your scenario.\n",
"I have done this using a PHP SOAP Server and VB.Net client. Once you connect the VB.Net/C# client to the server (the location of the WSDL file) C# will automatically detect all the functions and all the objects that are exposed. Making programming much easier.\nI would also recommend using NuSOAP which I found to be more functional. http://sourceforge.net/projects/nusoap/\n",
"I recommend the PHP/Java Bridge. Don't let the name fool you. This can be used to connect both PHP and Python to any ECMA-335 virtual machine (Java and C#)!\nhttp://php-java-bridge.sourceforge.net/pjb/\nTo answer your comment:\n\nThe communication works in both directions, the JSR 223 interface can be used to connect to a running PHP server (Apache/IIS, FastCGI, ...) so that Java components can call PHP instances and PHP scripts can invoke CLR (e.g. VB.NET, C#, COM) or Java (e.g. Java, KAWA, JRuby) based applications or transfer control back to the environment where the request came from. The bridge can be set up to automatically start a PHP front-end or start a Java/.NET back end, if needed.\n\n"
] |
[
4,
0,
0,
0
] |
[] |
[] |
[
"c#",
"data_structures",
"php",
"python",
"web_applications"
] |
stackoverflow_0001023187_c#_data_structures_php_python_web_applications.txt
|
Q:
How to convert a list of longs into a comma separated string in python
I'm new to python, and have a list of longs which I want to join together into a comma separated string.
In PHP I'd do something like this:
$output = implode(",", $array)
In Python, I'm not sure how to do this. I've tried using join, but this doesn't work since the elements are the wrong type (i.e., not strings). Do I need to create a copy of the list and convert each element in the copy from a long into a string? Or is there a simpler way to do it?
A:
You have to convert the ints to strings and then you can join them:
','.join([str(i) for i in list_of_ints])
A:
You can use map to transform a list, then join them up.
",".join( map( str, list_of_things ) )
BTW, this works for any objects (not just longs).
A:
You can omit the square brackets from heikogerlach's answer since Python 2.5, I think:
','.join(str(i) for i in list_of_ints)
This is extremely similar, but instead of building a (potentially large) temporary list of all the strings, it will generate them one at a time, as needed by the join function.
A:
and yet another version more (pretty cool, eh?)
str(list_of_numbers)[1:-1]
A:
Just for the sake of it, you can also use string formatting:
",".join("{0}".format(i) for i in list_of_things)
|
How to convert a list of longs into a comma separated string in python
|
I'm new to python, and have a list of longs which I want to join together into a comma separated string.
In PHP I'd do something like this:
$output = implode(",", $array)
In Python, I'm not sure how to do this. I've tried using join, but this doesn't work since the elements are the wrong type (i.e., not strings). Do I need to create a copy of the list and convert each element in the copy from a long into a string? Or is there a simpler way to do it?
|
[
"You have to convert the ints to strings and then you can join them:\n','.join([str(i) for i in list_of_ints])\n\n",
"You can use map to transform a list, then join them up.\n\",\".join( map( str, list_of_things ) )\n\nBTW, this works for any objects (not just longs).\n",
"You can omit the square brackets from heikogerlach's answer since Python 2.5, I think:\n','.join(str(i) for i in list_of_ints)\nThis is extremely similar, but instead of building a (potentially large) temporary list of all the strings, it will generate them one at a time, as needed by the join function.\n",
"and yet another version more (pretty cool, eh?)\nstr(list_of_numbers)[1:-1]\n\n",
"Just for the sake of it, you can also use string formatting:\n\",\".join(\"{0}\".format(i) for i in list_of_things)\n\n"
] |
[
69,
20,
11,
5,
2
] |
[] |
[] |
[
"python"
] |
stackoverflow_0000438684_python.txt
|
Q:
Why can't I import this Zope component in a Python 2.4 virtualenv?
I'm trying to install Plone 3.3rc4 with plone.app.blob and repoze but nothing I've tried has worked so far. For one attempt I've pip-installed repoze.zope2, Plone, and plone.app.blob into a virtualenv. I have this version of DocumentTemplate in the virtualenv's site-packages directory and I'm trying to get it running in RHEL5.
For some reason when I try to run paster serve etc/zope2.ini in this environment way Python gives the message ImportError: No module named DT_Util? DT_Util.py exists in the directory, __init__.py is there too, and the C module it depends on is there. I suspect there's some circular dependency or failure when importing the C extension. Of course this module would work in a normal Zope install...
>>> import DocumentTemplate
Traceback (most recent call last):
File "<stdin>", line 1, in ?
File "DocumentTemplate/__init__.py", line 21, in ?
File ".../lib/python2.4/site-packages/DocumentTemplate/DocumentTemplate.py", line 112, in ?
from DT_String import String, File
File ".../lib/python2.4/site-packages/DocumentTemplate/DT_String.py", line 19, in ?
from DocumentTemplate.DT_Util import ParseError, InstanceDict
ImportError: No module named DT_Util
A:
I must say I doubt DocumentTemplate from Zope will work standalone. You are welcome to try though. :-)
Note that DT_Util imports C extensions:
from DocumentTemplate.cDocumentTemplate import InstanceDict, TemplateDict
from DocumentTemplate.cDocumentTemplate import render_blocks, safe_callable
from DocumentTemplate.cDocumentTemplate import join_unicode
You'll need to make sure those are compiled. My guess is that importing the cDocumentTemplate module fails and thus the import of DT_Util fails.
|
Why can't I import this Zope component in a Python 2.4 virtualenv?
|
I'm trying to install Plone 3.3rc4 with plone.app.blob and repoze but nothing I've tried has worked so far. For one attempt I've pip-installed repoze.zope2, Plone, and plone.app.blob into a virtualenv. I have this version of DocumentTemplate in the virtualenv's site-packages directory and I'm trying to get it running in RHEL5.
For some reason when I try to run paster serve etc/zope2.ini in this environment way Python gives the message ImportError: No module named DT_Util? DT_Util.py exists in the directory, __init__.py is there too, and the C module it depends on is there. I suspect there's some circular dependency or failure when importing the C extension. Of course this module would work in a normal Zope install...
>>> import DocumentTemplate
Traceback (most recent call last):
File "<stdin>", line 1, in ?
File "DocumentTemplate/__init__.py", line 21, in ?
File ".../lib/python2.4/site-packages/DocumentTemplate/DocumentTemplate.py", line 112, in ?
from DT_String import String, File
File ".../lib/python2.4/site-packages/DocumentTemplate/DT_String.py", line 19, in ?
from DocumentTemplate.DT_Util import ParseError, InstanceDict
ImportError: No module named DT_Util
|
[
"I must say I doubt DocumentTemplate from Zope will work standalone. You are welcome to try though. :-)\nNote that DT_Util imports C extensions:\nfrom DocumentTemplate.cDocumentTemplate import InstanceDict, TemplateDict\nfrom DocumentTemplate.cDocumentTemplate import render_blocks, safe_callable\nfrom DocumentTemplate.cDocumentTemplate import join_unicode\n\nYou'll need to make sure those are compiled. My guess is that importing the cDocumentTemplate module fails and thus the import of DT_Util fails.\n"
] |
[
1
] |
[] |
[] |
[
"python",
"virtualenv",
"zope"
] |
stackoverflow_0001161670_python_virtualenv_zope.txt
|
Q:
Finding the coordinates of tiles that are covered by a rectangle with x,y,w,h pixel coordinates
Say I have a tile based system using 16x16 pixels. How would you find out what tiles are covered by a rectangle defined by floating point pixel units?
for eg,
rect(x=16.0,y=16.0, w=1.0, h=1.0) -> tile(x=1, y=1, w=1, h=1)
rect(x=16.0,y=16.0, w=16.0, h=16.0) -> tile(x=1, y=1, w=1, h=1) (still within same tile)
rect(x=24.0,y=24.0, w=8.0, y=8.0) -> (x=1,y=1,w=1,h=1) (still within same tile)
rect(x=24.0,y=24.0, w=8.1, y=8.1) -> (x=1,y=1,w=2,h=2)
The only way I can do this reliably is by using a loop. Is there a better way? Dividing by 16 gives me the wrong answer on edge cases. Here's some example code I use in python:
#!/usr/bin/env python
import math
TILE_W = 16
TILE_H = 16
def get_tile(x,y,w,h):
t_x = int(x / TILE_W)
t_x2 = t_x
while t_x2*TILE_W < (x+w):
t_x2 += 1
t_w = t_x2-t_x
t_y = int( y / TILE_H)
t_y2 = t_y
while t_y2*TILE_H < (y+h):
t_y2 += 1
t_h = t_y2-t_y
return t_x,t_y,t_w,t_h
(x,y) = 16.0,16.0
(w,h) = 1.0, 1.0
assert get_tile(x,y,w,h) == (1,1,1,1)
(x,y) = 16.0,16.0
(w,h) = 15.0, 15.0
assert get_tile(x,y,w,h) == (1,1,1,1)
(x,y) = 16.0,16.0
(w,h) = 16.0, 16.0
assert get_tile(x,y,w,h) == (1,1,1,1)
(x,y) = 16.0,16.0
(w,h) = 16.1, 16.1
assert get_tile(x,y,w,h) == (1,1,2,2)
(x,y) = 24.0, 24.0
(w,h) = 1.0, 1.0
assert get_tile(x,y,w,h) == (1,1,1,1)
(x,y) = 24.0, 24.0
(w,h) = 8.0, 8.0
assert get_tile(x,y,w,h) == (1,1,1,1)
(x,y) = 24.0, 24.0
(w,h) = 8.1, 8.1
assert get_tile(x,y,w,h) == (1,1,2,2)
(x,y) = 24.0, 24.0
(w,h) = 9.0, 9.0
assert get_tile(x,y,w,h) == (1,1,2,2)
A:
Matt's solution with bug-fixes:
from __future__ import division
import math
TILE_W = TILE_H = 16
def get_tile(x,y,w,h):
x1 = int(math.floor(x/TILE_W))
x2 = int(math.ceil((x + w)/TILE_W))
y1 = int(math.floor(y/TILE_H))
y2 = int(math.ceil((y + h)/TILE_H))
return x1, y1, x2-x1, y2-y1
A:
here is the one which passes your test cases, tell me if there is any edge case
TILE_W = TILE_H = 16
from math import floor, ceil
def get_tile2(x,y,w,h):
x1 = int(x/TILE_W)
y1 = int(y/TILE_H)
x2 = int((x+w)/TILE_W)
y2 = int((y+h)/TILE_H)
if (x+w)%16 == 0: #edge case
x2-=1
if (y+h)%16 == 0: #edge case
y2-=1
tw = x2-x1 + 1
th = y2-y1 + 1
return x1, y1, tw, th
(x,y) = 16.0, 16.0
(w,h) = 1.0, 1.0
assert get_tile2(x,y,w,h) == (1,1,1,1)
(x,y) = 16.0, 16.0
(w,h) = 15.0, 15.0
assert get_tile2(x,y,w,h) == (1,1,1,1)
(x,y) = 16.0, 16.0
(w,h) = 16.0, 16.0
assert get_tile2(x,y,w,h) == (1,1,1,1)
(x,y) = 16.0, 16.0
(w,h) = 16.1, 16.1
assert get_tile2(x,y,w,h) == (1,1,2,2)
I am now explicitly checking for the edge case, but be aware that floating point comparison sometime may not seem obvious and result may not be as expected.
A:
You could try aligning you pixel coordinates ot integers before dividing by tile width:
xlower = int(floor(x))
xupper = int(ceil(x + w))
A:
This could probably be condensed a bit more, but here you go.
def get_tile(x,y,w,h):
x1 = int(x / TILE_W)
x2 = (x + w) / TILE_W
y1 = int(y / TILE_H)
y2 = (x + w) / TILE_H
if int(x2) == x2:
x2 = int(x2 - 1)
else:
x2 = int(x2)
if int(y2) == y2:
y2 = int(y2 - 1)
else:
y2 = int(y2)
tw = x2 - x1 + 1
th = y2 - y1 + 1
return x1, y1, tw, th
|
Finding the coordinates of tiles that are covered by a rectangle with x,y,w,h pixel coordinates
|
Say I have a tile based system using 16x16 pixels. How would you find out what tiles are covered by a rectangle defined by floating point pixel units?
for eg,
rect(x=16.0,y=16.0, w=1.0, h=1.0) -> tile(x=1, y=1, w=1, h=1)
rect(x=16.0,y=16.0, w=16.0, h=16.0) -> tile(x=1, y=1, w=1, h=1) (still within same tile)
rect(x=24.0,y=24.0, w=8.0, y=8.0) -> (x=1,y=1,w=1,h=1) (still within same tile)
rect(x=24.0,y=24.0, w=8.1, y=8.1) -> (x=1,y=1,w=2,h=2)
The only way I can do this reliably is by using a loop. Is there a better way? Dividing by 16 gives me the wrong answer on edge cases. Here's some example code I use in python:
#!/usr/bin/env python
import math
TILE_W = 16
TILE_H = 16
def get_tile(x,y,w,h):
t_x = int(x / TILE_W)
t_x2 = t_x
while t_x2*TILE_W < (x+w):
t_x2 += 1
t_w = t_x2-t_x
t_y = int( y / TILE_H)
t_y2 = t_y
while t_y2*TILE_H < (y+h):
t_y2 += 1
t_h = t_y2-t_y
return t_x,t_y,t_w,t_h
(x,y) = 16.0,16.0
(w,h) = 1.0, 1.0
assert get_tile(x,y,w,h) == (1,1,1,1)
(x,y) = 16.0,16.0
(w,h) = 15.0, 15.0
assert get_tile(x,y,w,h) == (1,1,1,1)
(x,y) = 16.0,16.0
(w,h) = 16.0, 16.0
assert get_tile(x,y,w,h) == (1,1,1,1)
(x,y) = 16.0,16.0
(w,h) = 16.1, 16.1
assert get_tile(x,y,w,h) == (1,1,2,2)
(x,y) = 24.0, 24.0
(w,h) = 1.0, 1.0
assert get_tile(x,y,w,h) == (1,1,1,1)
(x,y) = 24.0, 24.0
(w,h) = 8.0, 8.0
assert get_tile(x,y,w,h) == (1,1,1,1)
(x,y) = 24.0, 24.0
(w,h) = 8.1, 8.1
assert get_tile(x,y,w,h) == (1,1,2,2)
(x,y) = 24.0, 24.0
(w,h) = 9.0, 9.0
assert get_tile(x,y,w,h) == (1,1,2,2)
|
[
"Matt's solution with bug-fixes:\nfrom __future__ import division\nimport math\n\nTILE_W = TILE_H = 16\n\ndef get_tile(x,y,w,h):\n x1 = int(math.floor(x/TILE_W))\n x2 = int(math.ceil((x + w)/TILE_W))\n y1 = int(math.floor(y/TILE_H))\n y2 = int(math.ceil((y + h)/TILE_H))\n return x1, y1, x2-x1, y2-y1\n\n",
"here is the one which passes your test cases, tell me if there is any edge case\nTILE_W = TILE_H = 16\n\nfrom math import floor, ceil\n\ndef get_tile2(x,y,w,h):\n x1 = int(x/TILE_W)\n y1 = int(y/TILE_H)\n x2 = int((x+w)/TILE_W)\n y2 = int((y+h)/TILE_H)\n if (x+w)%16 == 0: #edge case\n x2-=1\n if (y+h)%16 == 0: #edge case\n y2-=1\n tw = x2-x1 + 1\n th = y2-y1 + 1\n return x1, y1, tw, th\n\n(x,y) = 16.0, 16.0\n(w,h) = 1.0, 1.0\nassert get_tile2(x,y,w,h) == (1,1,1,1)\n\n(x,y) = 16.0, 16.0\n(w,h) = 15.0, 15.0\nassert get_tile2(x,y,w,h) == (1,1,1,1)\n\n(x,y) = 16.0, 16.0\n(w,h) = 16.0, 16.0\nassert get_tile2(x,y,w,h) == (1,1,1,1)\n\n(x,y) = 16.0, 16.0 \n(w,h) = 16.1, 16.1\nassert get_tile2(x,y,w,h) == (1,1,2,2)\n\nI am now explicitly checking for the edge case, but be aware that floating point comparison sometime may not seem obvious and result may not be as expected.\n",
"You could try aligning you pixel coordinates ot integers before dividing by tile width:\nxlower = int(floor(x))\nxupper = int(ceil(x + w))\n\n",
"This could probably be condensed a bit more, but here you go.\ndef get_tile(x,y,w,h):\n\n x1 = int(x / TILE_W)\n x2 = (x + w) / TILE_W\n\n y1 = int(y / TILE_H)\n y2 = (x + w) / TILE_H\n\n if int(x2) == x2:\n x2 = int(x2 - 1)\n else:\n x2 = int(x2)\n\n if int(y2) == y2:\n y2 = int(y2 - 1)\n else:\n y2 = int(y2)\n\n tw = x2 - x1 + 1\n th = y2 - y1 + 1\n\n return x1, y1, tw, th\n\n"
] |
[
1,
0,
0,
0
] |
[] |
[] |
[
"algorithm",
"coordinates",
"geometry",
"math",
"python"
] |
stackoverflow_0001108929_algorithm_coordinates_geometry_math_python.txt
|
Q:
Python object creation
I am pretty new to Python world and trying to learn it.
This is what I am trying to achieve: I want to create a Car class, its constructor checks for the input to set the object carName as the input. I try to do this by using the java logic but I seem to fail :)
class Car():
carName = "" #how can I define a non assigned variable anyway like "String carName;" in java
def __self__(self,input):
self.carName = input
def showName():
print carName
a = Car("bmw")
a.showName()
A:
derived from object for new-style class
use __init__ to initialize the new instance, not __self__
__main__ is helpful too.
class Car(object):
def __init__(self,input):
self.carName = input
def showName(self):
print self.carName
def main():
a = Car("bmw")
a.showName()
if __name__ == "__main__":
main()
A:
You don't define a variable, and you use init and self.
Like this:
class Car(Object):
def __init__(self,input):
self.carName = input
def showName(self):
print self.carName
a = Car("bmw")
a.showName()
A:
this is not correct!
class Car():
carName = "" #how can I define a non assigned variable anyway like "String carName;" in java
def __self__(self,input):
self.carName = input
the first carName is a class Variable like static member in c++
the second carName (self.carName) is an instance variable,
if you want to set the class variable with the constructor you have to do it like this:
class Car():
carName = "" #how can I define a non assigned variable anyway like "String carName;" in java
def __self__(self,input):
Car.carName = input
|
Python object creation
|
I am pretty new to Python world and trying to learn it.
This is what I am trying to achieve: I want to create a Car class, its constructor checks for the input to set the object carName as the input. I try to do this by using the java logic but I seem to fail :)
class Car():
carName = "" #how can I define a non assigned variable anyway like "String carName;" in java
def __self__(self,input):
self.carName = input
def showName():
print carName
a = Car("bmw")
a.showName()
|
[
"derived from object for new-style class\nuse __init__ to initialize the new instance, not __self__\n__main__ is helpful too.\nclass Car(object):\n def __init__(self,input):\n self.carName = input\n\n def showName(self):\n print self.carName\ndef main():\n a = Car(\"bmw\")\n a.showName()\nif __name__ == \"__main__\":\n main()\n\n",
"You don't define a variable, and you use init and self.\nLike this:\nclass Car(Object):\n def __init__(self,input):\n self.carName = input\n\n def showName(self):\n print self.carName\n\na = Car(\"bmw\")\na.showName()\n\n",
"this is not correct!\nclass Car():\n carName = \"\" #how can I define a non assigned variable anyway like \"String carName;\" in java\n def __self__(self,input):\n self.carName = input\n\nthe first carName is a class Variable like static member in c++\nthe second carName (self.carName) is an instance variable,\nif you want to set the class variable with the constructor you have to do it like this:\nclass Car():\n carName = \"\" #how can I define a non assigned variable anyway like \"String carName;\" in java\n def __self__(self,input):\n Car.carName = input\n\n"
] |
[
14,
2,
1
] |
[] |
[] |
[
"class",
"object",
"python"
] |
stackoverflow_0001164309_class_object_python.txt
|
Q:
Non-recursive means of printing a list in Python
Is there a way to perform the following in a non-recursive fashion:
my_list = [
"level 1-1",
"level 1-2",
"level 1-3",
[
"level 2-1",
"level 2-2",
"level 2-3",
[
"level 3-1",
"level 3-2"
]
],
"level 1-4",
"level 1-5"
]
def print_list(the_list, indent_level=0):
for item in the_list:
if isinstance(item, list):
print_list(item, indent_level + 1)
else:
print "\t" * indent_level, item
print_list(my_list)
A:
stack = [(my_list, -1)]
while stack:
item, level = stack.pop()
if isinstance(item, list):
for i in reversed(item):
stack.append((i, level+1))
else:
print "\t" * level, item
A:
def print_list(the_list, indent_level=0):
stack = [iter(the_list)]
while stack:
try:
item = stack[-1].next()
except StopIteration:
stack.pop()
indent_level -= 1
continue
if isinstance(item, list):
indent_level += 1
stack.append(iter(item))
else:
print "\t" * indent_level, item
A:
Here's a variation of Martin Löwis' version that uses for/else instead of manually catching StopIteration, and len(stack) instead of keeping track of the indent level.
def print_list(the_list):
stack = [iter(the_list)]
while stack:
for item in stack[-1]:
if isinstance(item, (list, tuple)):
stack.append(iter(item))
break
else:
print '\t' * (len(stack)-1), item
else:
stack.pop()
A:
Note that this depens on the input not containing tuples.
l1 = my_list
done = False
# Repeatedly turn the list elements into tuples of the form
# (indent, item) until there are no more lists.
while not done:
done = True
l2 = []
for item in l1:
if isinstance(item,tuple):
indent = item[0]
item = item[1]
else:
indent = 0
if isinstance(item,list):
l2.extend( zip( (indent + 1,) * len(item), item) )
done = False
else:
l2.append((indent,item))
l1 = l2
for indent, item in l1:
print "\t" * indent, item
A:
Everyone has given solutions which are
production ready
use stack, so has same problem as recursion
or go thru list multiple time
Here is a solution lateral solution :)
not production ready but fun
no stack or anything like that, no lists in sight
--
def my_print(the_list):
level = -1
out = []
levelUp="levelup"
levelDown="leveldown"
s = repr(the_list).replace("', '","\n").replace(
"', ['", "\n%s\n"%levelUp).replace("['", "\n%s\n"%levelUp).replace(
"']", "\n%s\n"%levelDown).replace("], '", "\n%s\n"%levelDown)
for line in s.splitlines():
if not line: continue
if line == levelUp:
level+=1
elif line == levelDown:
level-=1
else:
print "\t"*level,line
my_print(my_list)
It assumes the your list text will not have some special substrings.
|
Non-recursive means of printing a list in Python
|
Is there a way to perform the following in a non-recursive fashion:
my_list = [
"level 1-1",
"level 1-2",
"level 1-3",
[
"level 2-1",
"level 2-2",
"level 2-3",
[
"level 3-1",
"level 3-2"
]
],
"level 1-4",
"level 1-5"
]
def print_list(the_list, indent_level=0):
for item in the_list:
if isinstance(item, list):
print_list(item, indent_level + 1)
else:
print "\t" * indent_level, item
print_list(my_list)
|
[
"stack = [(my_list, -1)]\nwhile stack:\n item, level = stack.pop()\n\n if isinstance(item, list):\n for i in reversed(item):\n stack.append((i, level+1))\n else:\n print \"\\t\" * level, item\n\n",
"def print_list(the_list, indent_level=0):\n stack = [iter(the_list)]\n while stack:\n try:\n item = stack[-1].next()\n except StopIteration:\n stack.pop()\n indent_level -= 1\n continue\n if isinstance(item, list):\n indent_level += 1\n stack.append(iter(item))\n else:\n print \"\\t\" * indent_level, item\n\n",
"Here's a variation of Martin Löwis' version that uses for/else instead of manually catching StopIteration, and len(stack) instead of keeping track of the indent level.\ndef print_list(the_list):\n stack = [iter(the_list)]\n while stack:\n for item in stack[-1]:\n if isinstance(item, (list, tuple)):\n stack.append(iter(item))\n break\n else:\n print '\\t' * (len(stack)-1), item\n else:\n stack.pop()\n\n",
"Note that this depens on the input not containing tuples.\nl1 = my_list\ndone = False\n\n# Repeatedly turn the list elements into tuples of the form\n# (indent, item) until there are no more lists.\nwhile not done:\n done = True\n l2 = []\n for item in l1:\n if isinstance(item,tuple):\n indent = item[0]\n item = item[1]\n else:\n indent = 0\n if isinstance(item,list):\n l2.extend( zip( (indent + 1,) * len(item), item) )\n done = False\n else:\n l2.append((indent,item))\n l1 = l2\n\nfor indent, item in l1:\n print \"\\t\" * indent, item\n\n",
"Everyone has given solutions which are\n\nproduction ready\nuse stack, so has same problem as recursion\nor go thru list multiple time\n\nHere is a solution lateral solution :)\n\nnot production ready but fun\nno stack or anything like that, no lists in sight\n\n--\ndef my_print(the_list):\n level = -1\n out = []\n levelUp=\"levelup\"\n levelDown=\"leveldown\"\n\n s = repr(the_list).replace(\"', '\",\"\\n\").replace(\n \"', ['\", \"\\n%s\\n\"%levelUp).replace(\"['\", \"\\n%s\\n\"%levelUp).replace(\n \"']\", \"\\n%s\\n\"%levelDown).replace(\"], '\", \"\\n%s\\n\"%levelDown)\n\n for line in s.splitlines():\n if not line: continue\n if line == levelUp:\n level+=1\n elif line == levelDown:\n level-=1\n else:\n print \"\\t\"*level,line\n\nmy_print(my_list)\n\nIt assumes the your list text will not have some special substrings.\n"
] |
[
4,
2,
2,
0,
0
] |
[] |
[] |
[
"python",
"recursion"
] |
stackoverflow_0001163429_python_recursion.txt
|
Q:
SQLAlchemy - Models - using dynamic fields - ActiveRecord
How close can I get to defining a model in SQLAlchemy like:
class Person(Base):
pass
And just have it dynamically pick up the field names? anyway to get naming conventions to control the relationships between tables? I guess I'm looking for something similar to RoR's ActiveRecord but in Python.
Not sure if this matters but I'll be trying to use this under IronPython rather than cPython.
A:
It is very simple to automatically pick up the field names:
from sqlalchemy import Table
from sqlalchemy.orm import MetaData, mapper
metadata = MetaData()
metadata.bind = engine
person_table = Table(metadata, "tablename", autoload=True)
class Person(object):
pass
mapper(Person, person_table)
Using this approach, you have to define the relationships in the call to mapper(), so no auto-discovery of relationships.
To automatically map classes to tables with same name, you could do:
def map_class(class_):
table = Table(metadata, class_.__name__, autoload=True)
mapper(class_, table)
map_class(Person)
map_class(Order)
Elixir might do everything you want.
A:
AFAIK sqlalchemy intentionally decouples database metadata and class layout.
You may should investigate Elixir (http://elixir.ematia.de/trac/wiki): Active Record Pattern for sqlalchemy, but you have to define the classes, not the database tables.
|
SQLAlchemy - Models - using dynamic fields - ActiveRecord
|
How close can I get to defining a model in SQLAlchemy like:
class Person(Base):
pass
And just have it dynamically pick up the field names? anyway to get naming conventions to control the relationships between tables? I guess I'm looking for something similar to RoR's ActiveRecord but in Python.
Not sure if this matters but I'll be trying to use this under IronPython rather than cPython.
|
[
"It is very simple to automatically pick up the field names:\nfrom sqlalchemy import Table\nfrom sqlalchemy.orm import MetaData, mapper\n\nmetadata = MetaData()\nmetadata.bind = engine\n\nperson_table = Table(metadata, \"tablename\", autoload=True)\n\nclass Person(object):\n pass\n\nmapper(Person, person_table)\n\nUsing this approach, you have to define the relationships in the call to mapper(), so no auto-discovery of relationships.\nTo automatically map classes to tables with same name, you could do:\ndef map_class(class_):\n table = Table(metadata, class_.__name__, autoload=True)\n mapper(class_, table)\n\nmap_class(Person)\nmap_class(Order)\n\nElixir might do everything you want.\n",
"AFAIK sqlalchemy intentionally decouples database metadata and class layout. \nYou may should investigate Elixir (http://elixir.ematia.de/trac/wiki): Active Record Pattern for sqlalchemy, but you have to define the classes, not the database tables.\n"
] |
[
4,
2
] |
[] |
[] |
[
"activerecord",
"ironpython",
"python",
"sqlalchemy"
] |
stackoverflow_0001165002_activerecord_ironpython_python_sqlalchemy.txt
|
Q:
Python Notation?
I've just started using Python and I was thinking about which notation I should use. I've read the PEP 8 guide about notation for Python and I agree with most stuff there except function names (which I prefer in mixedCase style).
In C++ I use a modified version of the Hungarian notation where I don't include information about type but only about the scope of a variable (for instance lVariable for a local variable and mVariable for a member variable of a class, g for global, s for static, in for a function's input and out for a function's output.)
I don't know if this notation style has a name but I was wondering whether it's a good idea not to use such a notation style in Python. I am not extremely familiar with Python so you guys/gals might see issues that I can't imagine yet.
I'm also interested to see what you think of it in general :) Some people might say it makes the code less readable, but I've become used to it and code written without these labels is the code that is less readable for me.
A:
(Almost every Python programmer will say it makes the code less readable, but I've become used to it and code written without these labels is the code that is less readable for me)
FTFY.
Seriously though, it will help you but confuse and annoy other Python programmers that try to read your code.
This also isn't as necessary because of how Python itself works. For example you would never need your "mVariable" form because it's obvious in Python:
class Example(object):
def__init__(self):
self.my_member_var = "Hello"
def sample(self):
print self.my_member_var
e = Example()
e.sample()
print e.my_member_var
No matter how you access a member variable (using self.foo or myinstance.foo) it's always clear that it's a member.
The other cases might not be so painfully obvious, but if your code isn't simple enough that a reader can keep in mind "the 'names' variable is a parameter" while reading a function you're probably doing something wrong.
A:
Use PEP-8. It is almost universal in the Python world.
A:
I violate PEP8 in my code. I use:
lowercaseCamelCase for methods and functions
_prefixedWithUnderscoreLowercaseCamelCase for "private" methods
underscore_spaced for variables (any)
_prefixed_with_underscore_variables for "private" self variables (attributes)
CapitalizedCamelCase for classes and modules (although I am moving to lowercasedmodules)
I never liked hungarian notation. A variable name should be easy and concise, provide sufficient information to be clear where (in which scope) it's used and what is its purpose, easy to read, concerned about the meaning of what it refers to, not its technical mumbo-jumbo (eg. type).
The reason behind my violations are due to practical considerations, and previous experience.
in C++ and Java, it's tradition to have CapitalizedCamel for classes and lowercaseCamel for member functions.
I worked on a codebase where the underscore prefix was used to indicate private but not that much private. We did not want to mess with the python name mangling (double underscore). This gave us the chance to violate a bit the formalities and peek the internal class state during unit testing.
A:
There exists a handy pep-8 compliance script you can run against your code:
http://github.com/cburroughs/pep8.py/tree/master
A:
It'll depend on the project and the target audience.
If you're building an open source application/plug-in/library, stick with the PEP guidelines.
If this is a project for your company, stick with the company conventions, or something similar.
If this is your own personal project, then use what ever convention is fluid and easy for you to use.
I hope this makes sense.
A:
You should simply be consistent with your naming conventions in your own code. However, if you intend to release your code to other developers you should stick to PEP-8.
For example the 4 spaces vs. 1 tab is a big deal when you have a collaborative project. People submitting code to a source repository with tabs requires developers to be constantly arguing over whitespace issues (which in Python is a BIG deal).
Python and all languages have preferred conventions. You should learn them.
Java likes mixedCaseStuff.
C likes szHungarianNotation.
Python prefers stuff_with_underscores.
You can write Java code with_python_type_function_names.
You can write Python code with javaStyleMixedCaseFunctionNamesThatAreSupposedToBeReallyExplict
as long as your consistant :p
|
Python Notation?
|
I've just started using Python and I was thinking about which notation I should use. I've read the PEP 8 guide about notation for Python and I agree with most stuff there except function names (which I prefer in mixedCase style).
In C++ I use a modified version of the Hungarian notation where I don't include information about type but only about the scope of a variable (for instance lVariable for a local variable and mVariable for a member variable of a class, g for global, s for static, in for a function's input and out for a function's output.)
I don't know if this notation style has a name but I was wondering whether it's a good idea not to use such a notation style in Python. I am not extremely familiar with Python so you guys/gals might see issues that I can't imagine yet.
I'm also interested to see what you think of it in general :) Some people might say it makes the code less readable, but I've become used to it and code written without these labels is the code that is less readable for me.
|
[
"\n(Almost every Python programmer will say it makes the code less readable, but I've become used to it and code written without these labels is the code that is less readable for me)\n\nFTFY.\nSeriously though, it will help you but confuse and annoy other Python programmers that try to read your code.\nThis also isn't as necessary because of how Python itself works. For example you would never need your \"mVariable\" form because it's obvious in Python:\nclass Example(object):\n def__init__(self):\n self.my_member_var = \"Hello\"\n\n def sample(self):\n print self.my_member_var\n\ne = Example()\ne.sample()\nprint e.my_member_var\n\nNo matter how you access a member variable (using self.foo or myinstance.foo) it's always clear that it's a member.\nThe other cases might not be so painfully obvious, but if your code isn't simple enough that a reader can keep in mind \"the 'names' variable is a parameter\" while reading a function you're probably doing something wrong.\n",
"Use PEP-8. It is almost universal in the Python world.\n",
"I violate PEP8 in my code. I use: \n\nlowercaseCamelCase for methods and functions\n_prefixedWithUnderscoreLowercaseCamelCase for \"private\" methods\nunderscore_spaced for variables (any)\n_prefixed_with_underscore_variables for \"private\" self variables (attributes)\nCapitalizedCamelCase for classes and modules (although I am moving to lowercasedmodules)\n\nI never liked hungarian notation. A variable name should be easy and concise, provide sufficient information to be clear where (in which scope) it's used and what is its purpose, easy to read, concerned about the meaning of what it refers to, not its technical mumbo-jumbo (eg. type).\nThe reason behind my violations are due to practical considerations, and previous experience.\n\nin C++ and Java, it's tradition to have CapitalizedCamel for classes and lowercaseCamel for member functions.\nI worked on a codebase where the underscore prefix was used to indicate private but not that much private. We did not want to mess with the python name mangling (double underscore). This gave us the chance to violate a bit the formalities and peek the internal class state during unit testing.\n\n",
"There exists a handy pep-8 compliance script you can run against your code:\nhttp://github.com/cburroughs/pep8.py/tree/master\n",
"It'll depend on the project and the target audience.\nIf you're building an open source application/plug-in/library, stick with the PEP guidelines.\nIf this is a project for your company, stick with the company conventions, or something similar.\nIf this is your own personal project, then use what ever convention is fluid and easy for you to use.\nI hope this makes sense.\n",
"You should simply be consistent with your naming conventions in your own code. However, if you intend to release your code to other developers you should stick to PEP-8.\nFor example the 4 spaces vs. 1 tab is a big deal when you have a collaborative project. People submitting code to a source repository with tabs requires developers to be constantly arguing over whitespace issues (which in Python is a BIG deal).\nPython and all languages have preferred conventions. You should learn them.\nJava likes mixedCaseStuff.\nC likes szHungarianNotation.\nPython prefers stuff_with_underscores.\nYou can write Java code with_python_type_function_names.\nYou can write Python code with javaStyleMixedCaseFunctionNamesThatAreSupposedToBeReallyExplict\nas long as your consistant :p\n"
] |
[
8,
7,
4,
3,
2,
1
] |
[] |
[] |
[
"naming_conventions",
"notation",
"python"
] |
stackoverflow_0001161658_naming_conventions_notation_python.txt
|
Q:
GQL Query on date equality in Python
Ok, you guys were quick and helpful last time so I'm going back to the well ;)
Disclaimer: I'm new to python and very new to App Engine. What I'm trying to do is a simple modification of the example from the AppEngine tutorial.
I've got my date value being stored in my Memory class:
class Memory(db.Model):
author = db.UserProperty()
content = db.StringProperty(multiline=True)
date = db.DateProperty(auto_now_add=True)
and now I want to be able to lookup records for a certain date. I wasn't sure exactly how to do it so I tried a few things including:
memories = db.GqlQuery("SELECT * from Memory where date = '2007-07-20')
and
memories = Memory.all()
memories.filter("date=", datetime.strptime(self.request.get('date'), '%Y-%m-%d').date())
and
memories = Memory.all()
memories.filter("date=", self.request.get('date'))
But every time I run it, I get an ImportError. Frankly, I'm not even sure how to parse these error message I get when the app fails but I'd just be happy to be able to look up the Memory records for a certain date.
EDIT: FULL SOURCE BELOW
import cgi
import time
from datetime import datetime
from google.appengine.api import users
from google.appengine.ext import webapp
from google.appengine.ext.webapp.util import run_wsgi_app
from google.appengine.ext import db
class Memory(db.Model):
author = db.UserProperty()
content = db.StringProperty(multiline=True)
date = db.DateProperty()
class MainPage(webapp.RequestHandler):
def get(self):
self.response.out.write('<html><body>')
memories = db.GqlQuery('SELECT * from Memory ORDER BY date DESC LIMIT 10')
for memory in memories:
self.response.out.write('<b>%s</b> wrote: ' % memory.author.nickname())
self.response.out.write('<em>%s</em>' % memory.date)
self.response.out.write('<blockquote>%s</blockquote>' % cgi.escape(memory.content))
self.response.out.write("""
<div style="float: left;">
<form action="/post" method="post">
<fieldset>
<legend>Record</legend>
<div><label>Memory:</label><input type="text" name="content" /></textarea></div>
<div><label>Date:</label><input type="text" name="date" /></div>
<div><input type="submit" value="Record memory" /></div>
</fieldset>
</form>
</div>
<div style="float: left;">
<form action="/lookup" method="post">
<fieldset>
<legend>Lookup</legend>
<div><label>Date:</label><input type="text" name="date" /></div>
<div><input type="submit" value="Lookup memory" /></div>
</fieldset>
</form>
</div>""")
self.response.out.write('</body></html>')
class PostMemory(webapp.RequestHandler):
def post(self):
memory = Memory()
if users.get_current_user():
memory.author = users.get_current_user()
memory.content = self.request.get('content')
memory.date = datetime.strptime(self.request.get('date'), '%Y-%m-%d').date()
memory.put()
self.redirect('/')
class LookupMemory(webapp.RequestHandler):
def post(self):
memories = db.GqlQuery("SELECT * FROM Memory WHERE date = '2009-07-21'")
for memory in memories:
self.response.out.write('<b>%s</b> wrote: ' % memory.author.nickname())
self.response.out.write('<em>%s</em>' % memory.date)
self.response.out.write('<blockquote>%s</blockquote>' % cgi.escape(memory.content))
application = webapp.WSGIApplication([('/', MainPage), ('/post', PostMemory), ('/lookup', LookupMemory)], debug=True)
def main():
run_wsgi_app(application)
if __name__ == '__main__':
main()
A:
You're trying to use GQL syntax with non-GQL Query objects. Your options are:
Use the Query object and pass in a datetime.date object: q = Memory.all().filter("date =", datetime.date.today())
Use a GqlQuery and use the DATE syntax: q = db.GqlQuery("SELECT * FROM Memory WHERE date = DATE(2007, 07, 20)")
Use a GqlQuery and pass in a datetime.date object: q = db.GqlQuery("SELECT * FROM Memory WHERE date = :1", datetime.date.today())
A:
memories.filter("date=DATE(2007, 7, 20)")
Refer to GQL Reference.
A:
class Memory(db.Model):
author = db.UserProperty()
content = db.StringProperty(multiline=True)
date = db.DateProperty(auto_now_add=True)
I think that you are either getting import errors for memory or your are getting an import error for datetime
if Memory is in another .py file, e.g otherpyfile.py, you will need to do from otherpyfile import Memory and then use it that way
if its a datetime issue then you will need to import datetime. Your first answer had a mismatch of quotes so sorted that. I sorted your middle one so that if you import datetime
memories = db.GqlQuery("SELECT * from Memory where date = '2007-07-20'")
memories = Memory.all().filter("date=", datetime.datetime.strptime(self.request.get('date'), '%Y-%m-%d').date())
memories = Memory.all().filter("date=", self.request.get('date'))
The appengine error screen isn't always helpful so have a look at the logs that are being thrown in the command prompt. If you see that error it might be worth dumping the short stacktrace it does so I can try help you further.
|
GQL Query on date equality in Python
|
Ok, you guys were quick and helpful last time so I'm going back to the well ;)
Disclaimer: I'm new to python and very new to App Engine. What I'm trying to do is a simple modification of the example from the AppEngine tutorial.
I've got my date value being stored in my Memory class:
class Memory(db.Model):
author = db.UserProperty()
content = db.StringProperty(multiline=True)
date = db.DateProperty(auto_now_add=True)
and now I want to be able to lookup records for a certain date. I wasn't sure exactly how to do it so I tried a few things including:
memories = db.GqlQuery("SELECT * from Memory where date = '2007-07-20')
and
memories = Memory.all()
memories.filter("date=", datetime.strptime(self.request.get('date'), '%Y-%m-%d').date())
and
memories = Memory.all()
memories.filter("date=", self.request.get('date'))
But every time I run it, I get an ImportError. Frankly, I'm not even sure how to parse these error message I get when the app fails but I'd just be happy to be able to look up the Memory records for a certain date.
EDIT: FULL SOURCE BELOW
import cgi
import time
from datetime import datetime
from google.appengine.api import users
from google.appengine.ext import webapp
from google.appengine.ext.webapp.util import run_wsgi_app
from google.appengine.ext import db
class Memory(db.Model):
author = db.UserProperty()
content = db.StringProperty(multiline=True)
date = db.DateProperty()
class MainPage(webapp.RequestHandler):
def get(self):
self.response.out.write('<html><body>')
memories = db.GqlQuery('SELECT * from Memory ORDER BY date DESC LIMIT 10')
for memory in memories:
self.response.out.write('<b>%s</b> wrote: ' % memory.author.nickname())
self.response.out.write('<em>%s</em>' % memory.date)
self.response.out.write('<blockquote>%s</blockquote>' % cgi.escape(memory.content))
self.response.out.write("""
<div style="float: left;">
<form action="/post" method="post">
<fieldset>
<legend>Record</legend>
<div><label>Memory:</label><input type="text" name="content" /></textarea></div>
<div><label>Date:</label><input type="text" name="date" /></div>
<div><input type="submit" value="Record memory" /></div>
</fieldset>
</form>
</div>
<div style="float: left;">
<form action="/lookup" method="post">
<fieldset>
<legend>Lookup</legend>
<div><label>Date:</label><input type="text" name="date" /></div>
<div><input type="submit" value="Lookup memory" /></div>
</fieldset>
</form>
</div>""")
self.response.out.write('</body></html>')
class PostMemory(webapp.RequestHandler):
def post(self):
memory = Memory()
if users.get_current_user():
memory.author = users.get_current_user()
memory.content = self.request.get('content')
memory.date = datetime.strptime(self.request.get('date'), '%Y-%m-%d').date()
memory.put()
self.redirect('/')
class LookupMemory(webapp.RequestHandler):
def post(self):
memories = db.GqlQuery("SELECT * FROM Memory WHERE date = '2009-07-21'")
for memory in memories:
self.response.out.write('<b>%s</b> wrote: ' % memory.author.nickname())
self.response.out.write('<em>%s</em>' % memory.date)
self.response.out.write('<blockquote>%s</blockquote>' % cgi.escape(memory.content))
application = webapp.WSGIApplication([('/', MainPage), ('/post', PostMemory), ('/lookup', LookupMemory)], debug=True)
def main():
run_wsgi_app(application)
if __name__ == '__main__':
main()
|
[
"You're trying to use GQL syntax with non-GQL Query objects. Your options are:\n\nUse the Query object and pass in a datetime.date object: q = Memory.all().filter(\"date =\", datetime.date.today())\nUse a GqlQuery and use the DATE syntax: q = db.GqlQuery(\"SELECT * FROM Memory WHERE date = DATE(2007, 07, 20)\")\nUse a GqlQuery and pass in a datetime.date object: q = db.GqlQuery(\"SELECT * FROM Memory WHERE date = :1\", datetime.date.today())\n\n",
"memories.filter(\"date=DATE(2007, 7, 20)\")\n\nRefer to GQL Reference.\n",
"class Memory(db.Model):\n author = db.UserProperty()\n content = db.StringProperty(multiline=True)\n date = db.DateProperty(auto_now_add=True)\n\nI think that you are either getting import errors for memory or your are getting an import error for datetime\nif Memory is in another .py file, e.g otherpyfile.py, you will need to do from otherpyfile import Memory and then use it that way\nif its a datetime issue then you will need to import datetime. Your first answer had a mismatch of quotes so sorted that. I sorted your middle one so that if you import datetime \nmemories = db.GqlQuery(\"SELECT * from Memory where date = '2007-07-20'\")\n\nmemories = Memory.all().filter(\"date=\", datetime.datetime.strptime(self.request.get('date'), '%Y-%m-%d').date())\n\nmemories = Memory.all().filter(\"date=\", self.request.get('date'))\n\nThe appengine error screen isn't always helpful so have a look at the logs that are being thrown in the command prompt. If you see that error it might be worth dumping the short stacktrace it does so I can try help you further.\n"
] |
[
2,
1,
0
] |
[] |
[] |
[
"google_app_engine",
"python"
] |
stackoverflow_0001162644_google_app_engine_python.txt
|
Q:
fast-ish python/jython IPC?
All I want to do is make some RPC calls over sockets. I have a server that does backendish stuff running jython 2.5. I need to make some calls from a frontend server running Django on CPython. I've been beating my head against a wall getting any form of IPC going.
The list of things I've tried:
Apache Thrift doesn't have any actual releases, just snapshots. I'd like to use something stable.
JSON-RPC is interesting, and it should be able to run over sockets, but in practice most of the implementations only seem to work over HTTP. HTTP overhead is exactly what I'm trying to avoid.
Protocol Buffers is really only a serialization protocol. From what I gather protobuf provides interface generation for RPC, but it's only the interface. Actually writing all the connection code is up to the user. If I'm going to be stuck using sockets, I'll just use JSON for serialization. It's simpler and faster.
Pyro doesn't work properly with Jython as a server. Some sort of socket timeout issue. I've sent a message to the mailing list.
pysage Yay for message passing! Only it requires python 2.6 or the processing module (which has compiled extensions). Jython is version 2.5 and doesn't allow compiled extensions.
Candygram is an interesting alternative to pysage, but as far as I can tell it's unmaintained. I haven't even tried it out with Jython. Any experiences with it?
Twisted Perspective Broker Twisted doesn't work on Jython.
I know that it'd be a snap doing this with XML-RPC, which makes me even more cranky. I want to avoid the overhead of HTTP, but at the same time I really don't want to get down and dirty with sockets to implement my own protocol. I'll do it wrong if I do.
Any ideas? I'm probably going to cry for about 20 minutes and then just use XML-RPC.
A:
Have you considered Hessian? From the blurb:
The Hessian binary web service
protocol makes web services usable
without requiring a large framework,
and without learning yet another
alphabet soup of protocols. Because it
is a binary protocol, it is
well-suited to sending binary data
without any need to extend the
protocol with attachments.
It has Python client and Java server (and more besides).
Update: If you're dead against HTTP, why not just use SocketServer and pickle? Not much of a protocol needed, hard to get wrong. Send / receive pickled strings with length prefixes.
A:
How about using sockets, but with the help of asyncore and asynchat?
Some links:
An example
http://docs.python.org/library/asyncore.html
http://docs.python.org/library/asynchat.html
A:
Two that look the most interesting to me:
Gearman and Python bindings. It's quite a bit faster now that it's been re-written in C (originally perl). It's used in production (although I can't point to any examples of the python bindings being used in production). It has very interesting (to me) interfaces into MySQL and Postgresql. Finally, todays tweet from Django's Jacob Kaplan-Moss.
RabbitMQ although because it's just a message queue you'll still have to serialize your own messages unless you also use celery.
A:
My favorite..
zeroc's ice
A:
Have you thought about using CORBA? It's fast, portable and object oriented...
I have only used it on the Java side (I think you could use a pure java broker with no problems from Jython), and with IIOP you should be able to interoperate with the CPython client.
|
fast-ish python/jython IPC?
|
All I want to do is make some RPC calls over sockets. I have a server that does backendish stuff running jython 2.5. I need to make some calls from a frontend server running Django on CPython. I've been beating my head against a wall getting any form of IPC going.
The list of things I've tried:
Apache Thrift doesn't have any actual releases, just snapshots. I'd like to use something stable.
JSON-RPC is interesting, and it should be able to run over sockets, but in practice most of the implementations only seem to work over HTTP. HTTP overhead is exactly what I'm trying to avoid.
Protocol Buffers is really only a serialization protocol. From what I gather protobuf provides interface generation for RPC, but it's only the interface. Actually writing all the connection code is up to the user. If I'm going to be stuck using sockets, I'll just use JSON for serialization. It's simpler and faster.
Pyro doesn't work properly with Jython as a server. Some sort of socket timeout issue. I've sent a message to the mailing list.
pysage Yay for message passing! Only it requires python 2.6 or the processing module (which has compiled extensions). Jython is version 2.5 and doesn't allow compiled extensions.
Candygram is an interesting alternative to pysage, but as far as I can tell it's unmaintained. I haven't even tried it out with Jython. Any experiences with it?
Twisted Perspective Broker Twisted doesn't work on Jython.
I know that it'd be a snap doing this with XML-RPC, which makes me even more cranky. I want to avoid the overhead of HTTP, but at the same time I really don't want to get down and dirty with sockets to implement my own protocol. I'll do it wrong if I do.
Any ideas? I'm probably going to cry for about 20 minutes and then just use XML-RPC.
|
[
"Have you considered Hessian? From the blurb:\n\nThe Hessian binary web service\n protocol makes web services usable\n without requiring a large framework,\n and without learning yet another\n alphabet soup of protocols. Because it\n is a binary protocol, it is\n well-suited to sending binary data\n without any need to extend the\n protocol with attachments.\n\nIt has Python client and Java server (and more besides).\nUpdate: If you're dead against HTTP, why not just use SocketServer and pickle? Not much of a protocol needed, hard to get wrong. Send / receive pickled strings with length prefixes.\n",
"How about using sockets, but with the help of asyncore and asynchat?\nSome links:\n\nAn example\nhttp://docs.python.org/library/asyncore.html\nhttp://docs.python.org/library/asynchat.html\n\n",
"Two that look the most interesting to me:\n\nGearman and Python bindings. It's quite a bit faster now that it's been re-written in C (originally perl). It's used in production (although I can't point to any examples of the python bindings being used in production). It has very interesting (to me) interfaces into MySQL and Postgresql. Finally, todays tweet from Django's Jacob Kaplan-Moss.\nRabbitMQ although because it's just a message queue you'll still have to serialize your own messages unless you also use celery.\n\n",
"My favorite..\nzeroc's ice\n",
"Have you thought about using CORBA? It's fast, portable and object oriented...\nI have only used it on the Java side (I think you could use a pure java broker with no problems from Jython), and with IIOP you should be able to interoperate with the CPython client.\n"
] |
[
6,
5,
2,
2,
0
] |
[] |
[] |
[
"ipc",
"jython",
"python",
"rpc",
"twisted"
] |
stackoverflow_0001163574_ipc_jython_python_rpc_twisted.txt
|
Q:
Including current date in python logging file
I have a process that I run every day. It uses Python logging. How would I configure the python logging module to write to a file containing the current date in the file name?
Because I restart the process every morning the TimedRotatingFileHandler won't work. The project is larger, so I would be interested in keeping the code required for logging into a logging configuration file.
A:
You can use the TimedRotatingFileHandler. For example:
import logging
import logging.handlers
LOG_FILENAME = '/tmp/log'
# Set up a specific logger with our desired output level
log = logging.getLogger(__name__)
log.setLevel(logging.DEBUG)
handler = logging.handlers.TimedRotatingFileHandler(LOG_FILENAME, when='D')
log.addHandler(handler)
But this will probably only work if your program runs for more than one day. If your script starts daily in a cron job you're better off manually formatting the filename which you pass to your log handler to include a timestamp.
A:
You may be interested in the TimedRotatingFileHandler see http://docs.python.org/library/logging.html#logging.handlers.TimedRotatingFileHandler
|
Including current date in python logging file
|
I have a process that I run every day. It uses Python logging. How would I configure the python logging module to write to a file containing the current date in the file name?
Because I restart the process every morning the TimedRotatingFileHandler won't work. The project is larger, so I would be interested in keeping the code required for logging into a logging configuration file.
|
[
"You can use the TimedRotatingFileHandler. For example:\nimport logging\nimport logging.handlers\n\nLOG_FILENAME = '/tmp/log'\n\n# Set up a specific logger with our desired output level\nlog = logging.getLogger(__name__)\nlog.setLevel(logging.DEBUG)\nhandler = logging.handlers.TimedRotatingFileHandler(LOG_FILENAME, when='D')\nlog.addHandler(handler)\n\nBut this will probably only work if your program runs for more than one day. If your script starts daily in a cron job you're better off manually formatting the filename which you pass to your log handler to include a timestamp.\n",
"You may be interested in the TimedRotatingFileHandler see http://docs.python.org/library/logging.html#logging.handlers.TimedRotatingFileHandler\n"
] |
[
9,
0
] |
[] |
[] |
[
"logging",
"python"
] |
stackoverflow_0001165856_logging_python.txt
|
Q:
Multiple statements in list compherensions in Python?
Is it possible to have something like:
list1 = ...
currentValue = 0
list2 = [currentValue += i, i for i in list1]
I tried that but didn't work? What's the proper syntax to write those?
EDIT: the print statement was an example. Actually I am incrementing a value outside the loop.
A:
Statements cannot go inside of expressions in Python; it was a complication that was deliberately designed out of the language. For this problem, try using a complication that did make it into the language: generators. Watch:
def total_and_item(sequence):
total = 0
for i in sequence:
total += i
yield (total, i)
list2 = list(total_and_item(list1))
The generator keeps a running tally of the items seen so far, and prefixes it to each item, just like it looks like you example tries to do. Of course, a straightforward loop might be even simpler, that creates an empty list at the top and just calls append() a lot! :-)
A:
I'm not quite sure what you're trying to do but it's probably something like
list2 = [(i, i*2, i) for i in list1]
print list2
The statement in the list comprehension has to be a single statement, but you could always make it a function call:
def foo(i):
print i
print i * 2
return i
list2 = [foo(i) for i in list1]
A:
As pjz said, you can use functions, so here you can use a closure to keep track of the counter value:
# defines a closure to enclose the sum variable
def make_counter(init_value=0):
sum = [init_value]
def inc(x=0):
sum[0] += x
return sum[0]
return inc
Then you do what you want with list1:
list1 = range(5) # list1 = [0, 1, 2, 3, 4]
And now with just two lines, we get list2:
counter = make_counter(10) # counter with initial value of 10
list2 = reduce(operator.add, ([counter(x), x] for x in list1))
In the end, list2 contains:
[10, 0, 11, 1, 13, 2, 16, 3, 20, 4]
which is what you wanted, and you can get the value of the counter after the loop with one call:
counter() # value is 20
Finally, you can replace the closure stuff by any kind of operation you want, here we have an increment, but it's really up to you.
Note also that we use a reduce to flatten list2, and this little trick requires you to import operator before calling the line with the reduce:
import operator
A:
Here's an example from another question:
[i for i,x in enumerate(testlist) if x == 1]
the enumerate generator returns a 2-tuple which goes into i,x.
A:
First of all, you likely don't want to use print. It doesn't return anything, so use a conventional for loop if you just want to print out stuff. What you are looking for is:
>>> list1 = (1,2,3,4)
>>> list2 = [(i, i*2) for i in list1] # Notice the braces around both items
>>> print(list2)
[(1, 2), (2, 4), (3, 6), (4, 8)]
A:
Print is a weird thing to call in a list comprehension. It'd help if you showed us what output you want, not just the code that doesn't work.
Here are two guesses for you. Either way, the important point is that the value statement in a list comprehension has to be a single value. You can't insert multiple items all at once. (If that's what you're trying to do, skip to the 2nd example.)
list1 = [1, 2, 3]
list2 = [(i, i*2, i) for i in list1]
# list2 = [(1, 2, 1), (2, 4, 2), (3, 6, 3)]
To get a flat list:
list1 = [1, 2, 3]
tmp = [(i, i*2) for i in list1]
list2 = []
map(list2.extend, tmp)
# list2 = [1, 2, 1, 2, 4, 2, 3, 6, 3]
Edit:
Incrementing a value in the middle of the list comprehension is still weird. If you really need to do it, you're better off just writing a regular for loop, and appending values as you go. In Python, cleverness like that is almost always branded as "unpythonic." Do it if you must, but you will get no end of flak in forums like this. ;)
A:
For your edited example:
currentValue += sum(list1)
or:
for x in list1:
currentValue += x
List comprehensions are great, I love them, but there's nothing wrong with the humble for loop and you shouldn't be afraid to use it :-)
EDIT: "But what if I wanna increment different than the collected values?"
Well, what do you want to increment by? You have the entire power of python at your command!
Increment by x-squared?
for x in list1:
currentValue += x**2
Increment by some function of x and its position in the list?
for i, x in enumerate(list1):
currentValue += i*x
A:
Why would you create a duplicate list. It seems like all that list comprehension would do is just sum the contents.
Why not just.
list2 = list(list1) #this makes a copy
currentValue = sum(list2)
A:
You can't do multiple statements, but you can do a function call. To do what you seem to want above, you could do:
list1 = ...
list2 = [ (sum(list1[:i], i) for i in list1 ]
in general, since list comprehensions are part of the 'functional' part of python, you're restricted to... functions. Other folks have suggested that you could write your own functions if necessary, and that's also a valid suggestion.
|
Multiple statements in list compherensions in Python?
|
Is it possible to have something like:
list1 = ...
currentValue = 0
list2 = [currentValue += i, i for i in list1]
I tried that but didn't work? What's the proper syntax to write those?
EDIT: the print statement was an example. Actually I am incrementing a value outside the loop.
|
[
"Statements cannot go inside of expressions in Python; it was a complication that was deliberately designed out of the language. For this problem, try using a complication that did make it into the language: generators. Watch:\ndef total_and_item(sequence):\n total = 0\n for i in sequence:\n total += i\n yield (total, i)\n\nlist2 = list(total_and_item(list1))\n\nThe generator keeps a running tally of the items seen so far, and prefixes it to each item, just like it looks like you example tries to do. Of course, a straightforward loop might be even simpler, that creates an empty list at the top and just calls append() a lot! :-)\n",
"I'm not quite sure what you're trying to do but it's probably something like\nlist2 = [(i, i*2, i) for i in list1]\nprint list2\n\nThe statement in the list comprehension has to be a single statement, but you could always make it a function call:\ndef foo(i):\n print i\n print i * 2\n return i\nlist2 = [foo(i) for i in list1]\n\n",
"As pjz said, you can use functions, so here you can use a closure to keep track of the counter value:\n# defines a closure to enclose the sum variable\ndef make_counter(init_value=0):\n sum = [init_value]\n def inc(x=0):\n sum[0] += x\n return sum[0]\n return inc\n\nThen you do what you want with list1:\nlist1 = range(5) # list1 = [0, 1, 2, 3, 4]\n\nAnd now with just two lines, we get list2:\ncounter = make_counter(10) # counter with initial value of 10\nlist2 = reduce(operator.add, ([counter(x), x] for x in list1))\n\nIn the end, list2 contains:\n[10, 0, 11, 1, 13, 2, 16, 3, 20, 4]\n\nwhich is what you wanted, and you can get the value of the counter after the loop with one call:\ncounter() # value is 20\n\nFinally, you can replace the closure stuff by any kind of operation you want, here we have an increment, but it's really up to you.\nNote also that we use a reduce to flatten list2, and this little trick requires you to import operator before calling the line with the reduce:\nimport operator\n\n",
"Here's an example from another question:\n[i for i,x in enumerate(testlist) if x == 1]\n\nthe enumerate generator returns a 2-tuple which goes into i,x.\n",
"First of all, you likely don't want to use print. It doesn't return anything, so use a conventional for loop if you just want to print out stuff. What you are looking for is:\n>>> list1 = (1,2,3,4)\n>>> list2 = [(i, i*2) for i in list1] # Notice the braces around both items\n>>> print(list2)\n[(1, 2), (2, 4), (3, 6), (4, 8)]\n\n",
"Print is a weird thing to call in a list comprehension. It'd help if you showed us what output you want, not just the code that doesn't work.\nHere are two guesses for you. Either way, the important point is that the value statement in a list comprehension has to be a single value. You can't insert multiple items all at once. (If that's what you're trying to do, skip to the 2nd example.)\nlist1 = [1, 2, 3]\nlist2 = [(i, i*2, i) for i in list1]\n# list2 = [(1, 2, 1), (2, 4, 2), (3, 6, 3)]\n\nTo get a flat list:\nlist1 = [1, 2, 3]\ntmp = [(i, i*2) for i in list1]\nlist2 = []\nmap(list2.extend, tmp)\n# list2 = [1, 2, 1, 2, 4, 2, 3, 6, 3]\n\nEdit:\nIncrementing a value in the middle of the list comprehension is still weird. If you really need to do it, you're better off just writing a regular for loop, and appending values as you go. In Python, cleverness like that is almost always branded as \"unpythonic.\" Do it if you must, but you will get no end of flak in forums like this. ;)\n",
"For your edited example:\ncurrentValue += sum(list1)\n\nor:\nfor x in list1:\n currentValue += x\n\nList comprehensions are great, I love them, but there's nothing wrong with the humble for loop and you shouldn't be afraid to use it :-)\nEDIT: \"But what if I wanna increment different than the collected values?\"\nWell, what do you want to increment by? You have the entire power of python at your command!\nIncrement by x-squared?\nfor x in list1:\n currentValue += x**2\n\nIncrement by some function of x and its position in the list?\nfor i, x in enumerate(list1):\n currentValue += i*x\n\n",
"Why would you create a duplicate list. It seems like all that list comprehension would do is just sum the contents.\nWhy not just.\nlist2 = list(list1) #this makes a copy\ncurrentValue = sum(list2)\n\n",
"You can't do multiple statements, but you can do a function call. To do what you seem to want above, you could do:\nlist1 = ...\nlist2 = [ (sum(list1[:i], i) for i in list1 ]\n\nin general, since list comprehensions are part of the 'functional' part of python, you're restricted to... functions. Other folks have suggested that you could write your own functions if necessary, and that's also a valid suggestion.\n"
] |
[
32,
4,
3,
2,
1,
1,
1,
1,
0
] |
[] |
[] |
[
"list_comprehension",
"python"
] |
stackoverflow_0000774876_list_comprehension_python.txt
|
Q:
Running Python code in different processors
In order to do quality assurance in a critical multicore (8) workstation, I want to run the same code in different processors but not in parallel or concurrently.
I need to run it 8 times, one run for each processor.
What I don't know is how to select the processor I want.
How can this be accomplished in Python?
A:
In Linux with schedutils, I believe you'd use taskset -c X python foo.py to run that specific Python process on CPU X (exactly how you identify your CPUs may vary, but I believe numbers such as 1, 2, 3, ... should work anywhere). I'm sure Windows, BSD versions, etc, have similar commands to support direct processor assignment, but I don't know them.
A:
Which process goes on which core is normaly decided by your OS. On linux there is taskset from the schedutils package to explicitly run a program on a processor.
Python 2.6 has a multiprocessing module that takes python functions and runs them in seperate processes, probably moving each new process to a different core.
|
Running Python code in different processors
|
In order to do quality assurance in a critical multicore (8) workstation, I want to run the same code in different processors but not in parallel or concurrently.
I need to run it 8 times, one run for each processor.
What I don't know is how to select the processor I want.
How can this be accomplished in Python?
|
[
"In Linux with schedutils, I believe you'd use taskset -c X python foo.py to run that specific Python process on CPU X (exactly how you identify your CPUs may vary, but I believe numbers such as 1, 2, 3, ... should work anywhere). I'm sure Windows, BSD versions, etc, have similar commands to support direct processor assignment, but I don't know them.\n",
"Which process goes on which core is normaly decided by your OS. On linux there is taskset from the schedutils package to explicitly run a program on a processor.\nPython 2.6 has a multiprocessing module that takes python functions and runs them in seperate processes, probably moving each new process to a different core.\n"
] |
[
5,
3
] |
[] |
[] |
[
"multicore",
"python"
] |
stackoverflow_0001166392_multicore_python.txt
|
Q:
How do I filter the choices in a ModelForm that has a CharField with the choices attribute (and hence a Select Field)
I understand I am able to filter queryset of Foreignkey or Many2ManyFields, however, how do I do that for a simple CharField that is a Select Widget (Select Tag).
For example:
PRODUCT_STATUS = (
("unapproved", "Unapproved"),
("approved", "Listed"),
#("Backorder","Backorder"),
#("oos","Out of Stock"),
#("preorder","Preorder"),
("userdisabled", "User Disabled"),
("disapproved", "Disapproved by admin"),
)
and the Field:
o_status = models.CharField(max_length=100, choices=PRODUCT_STATUS, verbose_name="Product Status", default="approved")
Suppose I wish to limit it to just "approved" and "userdisabled" instead showing the full array (which is what I want to show in the admin), how do I do it?
Thanks!
A:
class YourModelForm(forms.ModelForm):
def __init__(self, *args, **kwargs):
super(YourModelForm, self).__init__(*args, **kwargs)
self.fields['your_field'].choices = (('a', 'A'), ('b', 'B'))
class Meta:
model = YourModel
I guess this ain't too different from overriding a queryset from a ForeignKey or M2M attribute.
PS: Thanks peritus from #django at irc.freenode.net
|
How do I filter the choices in a ModelForm that has a CharField with the choices attribute (and hence a Select Field)
|
I understand I am able to filter queryset of Foreignkey or Many2ManyFields, however, how do I do that for a simple CharField that is a Select Widget (Select Tag).
For example:
PRODUCT_STATUS = (
("unapproved", "Unapproved"),
("approved", "Listed"),
#("Backorder","Backorder"),
#("oos","Out of Stock"),
#("preorder","Preorder"),
("userdisabled", "User Disabled"),
("disapproved", "Disapproved by admin"),
)
and the Field:
o_status = models.CharField(max_length=100, choices=PRODUCT_STATUS, verbose_name="Product Status", default="approved")
Suppose I wish to limit it to just "approved" and "userdisabled" instead showing the full array (which is what I want to show in the admin), how do I do it?
Thanks!
|
[
"class YourModelForm(forms.ModelForm):\n def __init__(self, *args, **kwargs):\n super(YourModelForm, self).__init__(*args, **kwargs)\n self.fields['your_field'].choices = (('a', 'A'), ('b', 'B'))\n\n class Meta:\n model = YourModel\n\nI guess this ain't too different from overriding a queryset from a ForeignKey or M2M attribute.\nPS: Thanks peritus from #django at irc.freenode.net\n"
] |
[
0
] |
[] |
[] |
[
"django",
"python"
] |
stackoverflow_0001166649_django_python.txt
|
Q:
Using Python from within Java
Possible Duplicate:
Java Python Integration
I have a large existing codebase written in 100% Java, but I would like to use Python for some new sections of it. I need to do some text and language processing, and I'd much rather use Python and a library like NLTK to do this.
I'm aware of the Jython project, but it looks like this represents a way to use Java and its libraries from within Python, rather than the other way round - am I wrong about this?
If not, what would be the best method to interface between Java and Python, such that (ideally) I can call a method in Python and have the result returned to Java?
A:
I'm aware of the Jython project, but
it looks like this represents a way to
use Java and its libraries from within
Python, rather than the other way
round - am I wrong about this?
Yes, you are wrong. You can either call a command line interpreter to run python code using Jyton or use python code from Java. In the past there was also a python-to-Java compiler, but it got discontinued with Jython 2.2
A:
I would write a Python module to handle the text and language processing, and then build a small bridge in jython that your java program can interact with. The jython bridge will be a very simple one, that's really only responsible for forwarding calls to the python module, and return the answer from the python module to the java module. Jython is really easy to use, and setup shouldn't take you more than 15 minutes.
Best of luck!
A:
I don't think you could use NLTK from Jython, since it depends on Numpy which isn't ported to the JVM. If you need NLTK or any other native CPython extension, you might consider using some IPC mechanism to communicate between CPython and the JVM. That being said, there is a project to allow calling CPython from Java, called Jepp:
http://jepp.sourceforge.net/
The reverse (calling Java code from CPython) is the goal of JPype and javaclass:
sourceforge.net/projects/jpype/
pypi.python.org/pypi/javaclass/0.1
I've never used any of these project, so I cant't vow for their quality.
A:
Jython is a Python implementation running on the JVM. You can find information about embedding Python in an existing Java app in the user guide.
I don't know the environment that you're working in, but be aware that mixing languages in the same app can quickly lead to a mess. I recommend creating Java interfaces to represent the operations that you plan to use, along with separately-packaged implementation classes that wrap the Python code.
A:
IN my opinion, Jython is exactly what you are looking at.
It is an implementation of Python within the JVM; as such, you can freely exchange objects and, for instance, inherit from a Java class (with some limitations).
Note that, its major strength point (being on top of of JVM) is also its major drawback, because it cannot use all (C)Python extension written in C (or in any other compiled language); this may have an impact on what you are willing to do with your text processing.
For more information about what is Jython, its potential and its limitations, I suggest you reading the Jython FAQ.
A:
Simply run the Python interpreter as a subprocess from within Java.
Write your Python functionality as a proper script, which reads from stdin and writes to stdout.
Use the Java Runtime class to spawn a subprocess that runs your Python script. This is very simple to do and provides a very clean interface.
Edit
import simplejson
import sys
for request in sys.stdin.readlines():
args = simplejson.loads( request )
result = myFunction( args['this'], args['that'] )
sys.stdout.writeline( simplejson.dumps( result ) + "\n" )
The interface is simple, structured and very low overhead.
A:
Remember to first check from those paying for the development that they're OK with the codebase needing a developer who knows both Python and Java from now on, and other cost and maintainability effects you've undoubtedly already accounted for.
See: http://www.acm.org/about/se-code 1.06, 2.03, 2.09, 4.03, 4.05, 6.07
|
Using Python from within Java
|
Possible Duplicate:
Java Python Integration
I have a large existing codebase written in 100% Java, but I would like to use Python for some new sections of it. I need to do some text and language processing, and I'd much rather use Python and a library like NLTK to do this.
I'm aware of the Jython project, but it looks like this represents a way to use Java and its libraries from within Python, rather than the other way round - am I wrong about this?
If not, what would be the best method to interface between Java and Python, such that (ideally) I can call a method in Python and have the result returned to Java?
|
[
"\nI'm aware of the Jython project, but\n it looks like this represents a way to\n use Java and its libraries from within\n Python, rather than the other way\n round - am I wrong about this?\n\nYes, you are wrong. You can either call a command line interpreter to run python code using Jyton or use python code from Java. In the past there was also a python-to-Java compiler, but it got discontinued with Jython 2.2\n",
"I would write a Python module to handle the text and language processing, and then build a small bridge in jython that your java program can interact with. The jython bridge will be a very simple one, that's really only responsible for forwarding calls to the python module, and return the answer from the python module to the java module. Jython is really easy to use, and setup shouldn't take you more than 15 minutes. \nBest of luck!\n",
"I don't think you could use NLTK from Jython, since it depends on Numpy which isn't ported to the JVM. If you need NLTK or any other native CPython extension, you might consider using some IPC mechanism to communicate between CPython and the JVM. That being said, there is a project to allow calling CPython from Java, called Jepp:\nhttp://jepp.sourceforge.net/\nThe reverse (calling Java code from CPython) is the goal of JPype and javaclass:\nsourceforge.net/projects/jpype/\npypi.python.org/pypi/javaclass/0.1\nI've never used any of these project, so I cant't vow for their quality.\n",
"Jython is a Python implementation running on the JVM. You can find information about embedding Python in an existing Java app in the user guide.\nI don't know the environment that you're working in, but be aware that mixing languages in the same app can quickly lead to a mess. I recommend creating Java interfaces to represent the operations that you plan to use, along with separately-packaged implementation classes that wrap the Python code.\n",
"IN my opinion, Jython is exactly what you are looking at.\nIt is an implementation of Python within the JVM; as such, you can freely exchange objects and, for instance, inherit from a Java class (with some limitations). \nNote that, its major strength point (being on top of of JVM) is also its major drawback, because it cannot use all (C)Python extension written in C (or in any other compiled language); this may have an impact on what you are willing to do with your text processing.\nFor more information about what is Jython, its potential and its limitations, I suggest you reading the Jython FAQ.\n",
"Simply run the Python interpreter as a subprocess from within Java.\nWrite your Python functionality as a proper script, which reads from stdin and writes to stdout.\nUse the Java Runtime class to spawn a subprocess that runs your Python script. This is very simple to do and provides a very clean interface.\n\nEdit\nimport simplejson\nimport sys\nfor request in sys.stdin.readlines():\n args = simplejson.loads( request )\n result = myFunction( args['this'], args['that'] )\n sys.stdout.writeline( simplejson.dumps( result ) + \"\\n\" )\n\nThe interface is simple, structured and very low overhead.\n",
"Remember to first check from those paying for the development that they're OK with the codebase needing a developer who knows both Python and Java from now on, and other cost and maintainability effects you've undoubtedly already accounted for.\nSee: http://www.acm.org/about/se-code 1.06, 2.03, 2.09, 4.03, 4.05, 6.07\n"
] |
[
34,
6,
4,
2,
2,
0,
0
] |
[] |
[] |
[
"java",
"jython",
"python",
"rpc"
] |
stackoverflow_0001164810_java_jython_python_rpc.txt
|
Q:
Issues with inspect.py when used inside Jython
I am using an application developed in Jython. When I try to use the inspect.py in that, it shows error message.
My code goes like this
import inspect,os,sys,pprint,imp
def handle_stackframe_without_leak(getframe):
frame = inspect.currentframe()
try:
function = inspect.getframeinfo(getframe)
print inspect.getargvalues(getframe)
finally:
del frame
#
def raja(a):
handle_stackframe_without_leak(inspect.currentframe())
print a
#
def callraja():
handle_stackframe_without_leak(inspect.currentframe())
raja("[email protected]")
#
callraja()
raja("[email protected]")
#
When I run this using python.exe, there are no issues. However, using this inside the app throwing the following error
File "C:\Program Files\jython221ondiffjava\Lib\inspect.py", line 722, in getframeinfo
File "C:\Program Files\jython221ondiffjava\Lib\inspect.py", line 413, in findsource
File "C:\Program Files\jython221ondiffjava\Lib\sre.py", line 179, in compile
File "C:\Program Files\jython221ondiffjava\Lib\sre.py", line 227, in _compile
File "C:\Program Files\jython221ondiffjava\Lib\sre_compile.py", line 437, in compile
File "C:\Program Files\jython221ondiffjava\Lib\sre_compile.py", line 421, in _code
File "C:\Program Files\jython221ondiffjava\Lib\sre_compile.py", line 143, in _compile
ValueError: ('unsupported operand type', 'branch')
at org.python.core.Py.makeException(Unknown Source)
at sre_compile$py._compile$1(C:\Program Files\jython221ondiffjava\Lib\sre_compile.py:143)
at sre_compile$py.call_function(C:\Program Files\jython221ondiffjava\Lib\sre_compile.py)
at org.python.core.PyTableCode.call(Unknown Source)
at org.python.core.PyTableCode.call(Unknown Source)
at org.python.core.PyFunction.__call__(Unknown Source)
at sre_compile$py._code$11(C:\Program Files\jython221ondiffjava\Lib\sre_compile.py:421)
at sre_compile$py.call_function(C:\Program Files\jython221ondiffjava\Lib\sre_compile.py)
at org.python.core.PyTableCode.call(Unknown Source)
at org.python.core.PyTableCode.call(Unknown Source)
at org.python.core.PyFunction.__call__(Unknown Source)
at sre_compile$py.compile$12(C:\Program Files\jython221ondiffjava\Lib\sre_compile.py:437)
at sre_compile$py.call_function(C:\Program Files\jython221ondiffjava\Lib\sre_compile.py)
at org.python.core.PyTableCode.call(Unknown Source)
at org.python.core.PyTableCode.call(Unknown Source)
at org.python.core.PyFunction.__call__(Unknown Source)
at org.python.core.PyObject.invoke(Unknown Source)
at sre$py._compile$13(C:\Program Files\jython221ondiffjava\Lib\sre.py:227)
at sre$py.call_function(C:\Program Files\jython221ondiffjava\Lib\sre.py)
at org.python.core.PyTableCode.call(Unknown Source)
at org.python.core.PyTableCode.call(Unknown Source)
at org.python.core.PyTableCode.call(Unknown Source)
at org.python.core.PyFunction.__call__(Unknown Source)
at sre$py.compile$8(C:\Program Files\jython221ondiffjava\Lib\sre.py:179)
at sre$py.call_function(C:\Program Files\jython221ondiffjava\Lib\sre.py)
at org.python.core.PyTableCode.call(Unknown Source)
at org.python.core.PyTableCode.call(Unknown Source)
at org.python.core.PyTableCode.call(Unknown Source)
at org.python.core.PyFunction.__call__(Unknown Source)
at org.python.core.PyObject.invoke(Unknown Source)
at inspect$py.findsource$24(C:\Program Files\jython221ondiffjava\Lib\inspect.py:413)
at inspect$py.call_function(C:\Program Files\jython221ondiffjava\Lib\inspect.py)
at org.python.core.PyTableCode.call(Unknown Source)
at org.python.core.PyTableCode.call(Unknown Source)
at org.python.core.PyFunction.__call__(Unknown Source)
at inspect$py.getframeinfo$54(C:\Program Files\jython221ondiffjava\Lib\inspect.py:722)
at inspect$py.call_function(C:\Program Files\jython221ondiffjava\Lib\inspect.py)
at org.python.core.PyTableCode.call(Unknown Source)
at org.python.core.PyTableCode.call(Unknown Source)
at org.python.core.PyTableCode.call(Unknown Source)
at org.python.core.PyFunction.__call__(Unknown Source)
at org.python.core.PyObject.invoke(Unknown Source)
at custom$py.handle_stackframe_without_leak$4(C:\Program Files\<my app>\jars\custom.py:29)
at custom$py.call_function(C:\Program Files\<my app>\.\jars\custom.py)
at org.python.core.PyTableCode.call(Unknown Source)
at org.python.core.PyTableCode.call(Unknown Source)
at org.python.core.PyFunction.__call__(Unknown Source)
at definitions$py.gotonotificationprofile$122(C:\Program Files\<my app>\.\jars\definitions.py:1738)
at definitions$py.call_function(C:\Program Files\<my app>\.\jars\definitions.py)
at org.python.core.PyTableCode.call(Unknown Source)
at org.python.core.PyTableCode.call(Unknown Source)
at org.python.core.PyFunction.__call__(Unknown Source)
at notificationcases$py.A003$2(C:\Program Files\<my app>\.\jars\notificationcases.py:143)
at notificationcases$py.call_function(C:\Program Files\<my app>\.\jars\notificationcases.py)
at org.python.core.PyTableCode.call(Unknown Source)
at org.python.core.PyTableCode.call(Unknown Source)
at org.python.core.PyFunction.__call__(Unknown Source)
at org.python.pycode._pyx171.f$0(003:8)
at org.python.pycode._pyx171.call_function(003)
at org.python.core.PyTableCode.call(Unknown Source)
at org.python.core.PyCode.call(Unknown Source)
at org.python.core.Py.runCode(Unknown Source)
at org.python.util.PythonInterpreter.execfile(Unknown Source)
Any help will be appreciated.
Thanks
Rajasankar
A:
Have you tried running your program on the command line with Jython (so outside of the app)? When I run your program with Jython 2.2.1 or Jython 2.5.0, I get identical output as from Python.
A:
This might help http://grinder.sourceforge.net/faq.html#re-problems.
For a quick check, try adding import re in findsource method (C:\Program Files\jython221ondiffjava\Lib\inspect.py)
def findsource(object):
"""Return the entire source file and starting line number for an object.
(...snip...)"""
import re
file = getsourcefile(object) or getfile(object)
Can't promise anything, though...
|
Issues with inspect.py when used inside Jython
|
I am using an application developed in Jython. When I try to use the inspect.py in that, it shows error message.
My code goes like this
import inspect,os,sys,pprint,imp
def handle_stackframe_without_leak(getframe):
frame = inspect.currentframe()
try:
function = inspect.getframeinfo(getframe)
print inspect.getargvalues(getframe)
finally:
del frame
#
def raja(a):
handle_stackframe_without_leak(inspect.currentframe())
print a
#
def callraja():
handle_stackframe_without_leak(inspect.currentframe())
raja("[email protected]")
#
callraja()
raja("[email protected]")
#
When I run this using python.exe, there are no issues. However, using this inside the app throwing the following error
File "C:\Program Files\jython221ondiffjava\Lib\inspect.py", line 722, in getframeinfo
File "C:\Program Files\jython221ondiffjava\Lib\inspect.py", line 413, in findsource
File "C:\Program Files\jython221ondiffjava\Lib\sre.py", line 179, in compile
File "C:\Program Files\jython221ondiffjava\Lib\sre.py", line 227, in _compile
File "C:\Program Files\jython221ondiffjava\Lib\sre_compile.py", line 437, in compile
File "C:\Program Files\jython221ondiffjava\Lib\sre_compile.py", line 421, in _code
File "C:\Program Files\jython221ondiffjava\Lib\sre_compile.py", line 143, in _compile
ValueError: ('unsupported operand type', 'branch')
at org.python.core.Py.makeException(Unknown Source)
at sre_compile$py._compile$1(C:\Program Files\jython221ondiffjava\Lib\sre_compile.py:143)
at sre_compile$py.call_function(C:\Program Files\jython221ondiffjava\Lib\sre_compile.py)
at org.python.core.PyTableCode.call(Unknown Source)
at org.python.core.PyTableCode.call(Unknown Source)
at org.python.core.PyFunction.__call__(Unknown Source)
at sre_compile$py._code$11(C:\Program Files\jython221ondiffjava\Lib\sre_compile.py:421)
at sre_compile$py.call_function(C:\Program Files\jython221ondiffjava\Lib\sre_compile.py)
at org.python.core.PyTableCode.call(Unknown Source)
at org.python.core.PyTableCode.call(Unknown Source)
at org.python.core.PyFunction.__call__(Unknown Source)
at sre_compile$py.compile$12(C:\Program Files\jython221ondiffjava\Lib\sre_compile.py:437)
at sre_compile$py.call_function(C:\Program Files\jython221ondiffjava\Lib\sre_compile.py)
at org.python.core.PyTableCode.call(Unknown Source)
at org.python.core.PyTableCode.call(Unknown Source)
at org.python.core.PyFunction.__call__(Unknown Source)
at org.python.core.PyObject.invoke(Unknown Source)
at sre$py._compile$13(C:\Program Files\jython221ondiffjava\Lib\sre.py:227)
at sre$py.call_function(C:\Program Files\jython221ondiffjava\Lib\sre.py)
at org.python.core.PyTableCode.call(Unknown Source)
at org.python.core.PyTableCode.call(Unknown Source)
at org.python.core.PyTableCode.call(Unknown Source)
at org.python.core.PyFunction.__call__(Unknown Source)
at sre$py.compile$8(C:\Program Files\jython221ondiffjava\Lib\sre.py:179)
at sre$py.call_function(C:\Program Files\jython221ondiffjava\Lib\sre.py)
at org.python.core.PyTableCode.call(Unknown Source)
at org.python.core.PyTableCode.call(Unknown Source)
at org.python.core.PyTableCode.call(Unknown Source)
at org.python.core.PyFunction.__call__(Unknown Source)
at org.python.core.PyObject.invoke(Unknown Source)
at inspect$py.findsource$24(C:\Program Files\jython221ondiffjava\Lib\inspect.py:413)
at inspect$py.call_function(C:\Program Files\jython221ondiffjava\Lib\inspect.py)
at org.python.core.PyTableCode.call(Unknown Source)
at org.python.core.PyTableCode.call(Unknown Source)
at org.python.core.PyFunction.__call__(Unknown Source)
at inspect$py.getframeinfo$54(C:\Program Files\jython221ondiffjava\Lib\inspect.py:722)
at inspect$py.call_function(C:\Program Files\jython221ondiffjava\Lib\inspect.py)
at org.python.core.PyTableCode.call(Unknown Source)
at org.python.core.PyTableCode.call(Unknown Source)
at org.python.core.PyTableCode.call(Unknown Source)
at org.python.core.PyFunction.__call__(Unknown Source)
at org.python.core.PyObject.invoke(Unknown Source)
at custom$py.handle_stackframe_without_leak$4(C:\Program Files\<my app>\jars\custom.py:29)
at custom$py.call_function(C:\Program Files\<my app>\.\jars\custom.py)
at org.python.core.PyTableCode.call(Unknown Source)
at org.python.core.PyTableCode.call(Unknown Source)
at org.python.core.PyFunction.__call__(Unknown Source)
at definitions$py.gotonotificationprofile$122(C:\Program Files\<my app>\.\jars\definitions.py:1738)
at definitions$py.call_function(C:\Program Files\<my app>\.\jars\definitions.py)
at org.python.core.PyTableCode.call(Unknown Source)
at org.python.core.PyTableCode.call(Unknown Source)
at org.python.core.PyFunction.__call__(Unknown Source)
at notificationcases$py.A003$2(C:\Program Files\<my app>\.\jars\notificationcases.py:143)
at notificationcases$py.call_function(C:\Program Files\<my app>\.\jars\notificationcases.py)
at org.python.core.PyTableCode.call(Unknown Source)
at org.python.core.PyTableCode.call(Unknown Source)
at org.python.core.PyFunction.__call__(Unknown Source)
at org.python.pycode._pyx171.f$0(003:8)
at org.python.pycode._pyx171.call_function(003)
at org.python.core.PyTableCode.call(Unknown Source)
at org.python.core.PyCode.call(Unknown Source)
at org.python.core.Py.runCode(Unknown Source)
at org.python.util.PythonInterpreter.execfile(Unknown Source)
Any help will be appreciated.
Thanks
Rajasankar
|
[
"Have you tried running your program on the command line with Jython (so outside of the app)? When I run your program with Jython 2.2.1 or Jython 2.5.0, I get identical output as from Python.\n",
"This might help http://grinder.sourceforge.net/faq.html#re-problems.\nFor a quick check, try adding import re in findsource method (C:\\Program Files\\jython221ondiffjava\\Lib\\inspect.py)\n\ndef findsource(object):\n \"\"\"Return the entire source file and starting line number for an object.\n (...snip...)\"\"\"\n import re\n file = getsourcefile(object) or getfile(object)\n\nCan't promise anything, though... \n"
] |
[
1,
0
] |
[] |
[] |
[
"inspect",
"jython",
"module",
"python"
] |
stackoverflow_0001108958_inspect_jython_module_python.txt
|
Q:
Executing code for a custom Django 404 page
I am getting ready to deploy my first Django application and am hitting a bit of a roadblock. My base template relies on me passing in the session object so that it can read out the currently logged in user's name. This isn't a problem when I control the code that is calling a template.
However, as part of getting this app ready to be deployed, I need to create a 404.html page. I extended my base template just like I've done with my other pages, but I don't see a way to pass in the session object so that I can utilize it. Is there a way to have Django call a custom method to render your 404 rather than just rendering your 404.html for you?
A:
You need to override the default view handler for the 404 error. Here is the documentation on how to create your own custom 404 view function:
http://docs.djangoproject.com/en/dev/topics/http/views/#customizing-error-views
A:
Define your own 404 handler. See Django URLs, specifically the part about handler404.
|
Executing code for a custom Django 404 page
|
I am getting ready to deploy my first Django application and am hitting a bit of a roadblock. My base template relies on me passing in the session object so that it can read out the currently logged in user's name. This isn't a problem when I control the code that is calling a template.
However, as part of getting this app ready to be deployed, I need to create a 404.html page. I extended my base template just like I've done with my other pages, but I don't see a way to pass in the session object so that I can utilize it. Is there a way to have Django call a custom method to render your 404 rather than just rendering your 404.html for you?
|
[
"You need to override the default view handler for the 404 error. Here is the documentation on how to create your own custom 404 view function:\nhttp://docs.djangoproject.com/en/dev/topics/http/views/#customizing-error-views\n",
"Define your own 404 handler. See Django URLs, specifically the part about handler404.\n"
] |
[
13,
4
] |
[] |
[] |
[
"django",
"python"
] |
stackoverflow_0001167434_django_python.txt
|
Q:
How to return an alternate column element from the intersect command?
I am currently using the following code to get the intersection date column
of two sets of financial data. The arrays include date, o,h,l,cl
#find intersection of date strings
def intersect(seq1, seq2):
res = [] # start empty
for x in seq1: # scan seq1
if x in seq2: # common item?
res.append(x)
return res
x = intersect(seta[:,0], setb[:,0]) # mixed types
print x
The problem is it only returns the column for which it found the
intersection of both, namely the date column.
I would like it to somehow return a different column array
including both the cls values of each set ... ie..
if date is common to both return a 2X1 array of the two corresponding
cls columns. Any ideas? thanks.
A:
Okay, here is a complete solution.
Get a python library to download stocks quotes
Get some quotes
start_date, end_date = '20090309', '20090720'
ibm_data = get_historical_prices('IBM', start_date, end_date)
msft_data = get_historical_prices('MSFT', start_date, end_date)
Convert rows into date-keyed dictionaries of dictionaries
def quote_series(series):
columns = ['open', 'high', 'low', 'close', 'volume']
return dict((item[0], dict(zip(columns, item[1:]))) for item in series[1:])
ibm = quote_series(ibm_data)
msft = quote_series(msft_data)
Do the intersection of dates thing
ibm_dates = set(ibm.keys())
msft_dates = set(msft.keys())
both = ibm_dates.intersection(msft_dates)
for d in sorted(both):
print d, ibm[d], msft[d]
A:
How's that:
def intersect(seq1, seq2):
if seq1[0] == seq2[0]: # compare the date columns
return (seq1[4], seq2[4]) # return 2-tuple with the cls values
|
How to return an alternate column element from the intersect command?
|
I am currently using the following code to get the intersection date column
of two sets of financial data. The arrays include date, o,h,l,cl
#find intersection of date strings
def intersect(seq1, seq2):
res = [] # start empty
for x in seq1: # scan seq1
if x in seq2: # common item?
res.append(x)
return res
x = intersect(seta[:,0], setb[:,0]) # mixed types
print x
The problem is it only returns the column for which it found the
intersection of both, namely the date column.
I would like it to somehow return a different column array
including both the cls values of each set ... ie..
if date is common to both return a 2X1 array of the two corresponding
cls columns. Any ideas? thanks.
|
[
"Okay, here is a complete solution.\nGet a python library to download stocks quotes\nGet some quotes\nstart_date, end_date = '20090309', '20090720'\nibm_data = get_historical_prices('IBM', start_date, end_date)\nmsft_data = get_historical_prices('MSFT', start_date, end_date)\n\nConvert rows into date-keyed dictionaries of dictionaries\ndef quote_series(series):\n columns = ['open', 'high', 'low', 'close', 'volume']\n return dict((item[0], dict(zip(columns, item[1:]))) for item in series[1:])\n\nibm = quote_series(ibm_data)\nmsft = quote_series(msft_data)\n\nDo the intersection of dates thing\nibm_dates = set(ibm.keys())\nmsft_dates = set(msft.keys())\n\nboth = ibm_dates.intersection(msft_dates)\n\nfor d in sorted(both):\n print d, ibm[d], msft[d]\n\n",
"How's that:\ndef intersect(seq1, seq2):\n if seq1[0] == seq2[0]: # compare the date columns\n return (seq1[4], seq2[4]) # return 2-tuple with the cls values\n\n"
] |
[
0,
0
] |
[] |
[] |
[
"intersection",
"python"
] |
stackoverflow_0001167908_intersection_python.txt
|
Q:
Middleware for both Django and Pylons
It appears to me that Django and Pylons have different ideas on how middleware should work. I like that Pylons follows the standardized PEP 333, but Django seems to have more widespread adoption. Is it possible to write middleware to be used in both?
The project that involves said middleware is porting a security toolkit called ESAPI from Java to Python. Because Java is so standards oriented, it is pretty easy to be framework agnostic. In Python, different frameworks have different ideas on how basic things like HttpRequest objects and middleware work, so this seems more difficult.
Apparently, new users cannot post more than one hyperlink. See below for links to Django and Pylons middleware info.
A:
Pylons uses standard WSGI middleware. If you deploy Django via WSGI, you can also use WSGI middleware at that point. You can't, however, currently use WSGI middleware via the standard Django MIDDLEWARE_CLASSES option in settings.py.
That said, there is currently a Google Summer of Code project to enable the use of WSGI middleware in Django itself. I haven't been following the status of this project, but the code is available in the Http WSGI improvements branch.
A:
For Pylons the term middleware means WSGI (PEP 333) middleware, whereas Django means its own internal mechanism for middleware.
However, if you run Django under apache+mod_wsgi (instead of e.g. mod_python or lighttpd+flup) you can also include WSGI middleware in Django. This isn't typically done though because much of the functionality you'll find in WSGI middleware is already built-in to Django proper or Django middleware.
The differences between WSGI and Django middleware are small enough that it should be easy enough to convert code between the two. The tougher problem is when they use external libraries like ORM's.
The WSGI Wiki has a good list of WSGI middleware.
|
Middleware for both Django and Pylons
|
It appears to me that Django and Pylons have different ideas on how middleware should work. I like that Pylons follows the standardized PEP 333, but Django seems to have more widespread adoption. Is it possible to write middleware to be used in both?
The project that involves said middleware is porting a security toolkit called ESAPI from Java to Python. Because Java is so standards oriented, it is pretty easy to be framework agnostic. In Python, different frameworks have different ideas on how basic things like HttpRequest objects and middleware work, so this seems more difficult.
Apparently, new users cannot post more than one hyperlink. See below for links to Django and Pylons middleware info.
|
[
"Pylons uses standard WSGI middleware. If you deploy Django via WSGI, you can also use WSGI middleware at that point. You can't, however, currently use WSGI middleware via the standard Django MIDDLEWARE_CLASSES option in settings.py.\nThat said, there is currently a Google Summer of Code project to enable the use of WSGI middleware in Django itself. I haven't been following the status of this project, but the code is available in the Http WSGI improvements branch.\n",
"For Pylons the term middleware means WSGI (PEP 333) middleware, whereas Django means its own internal mechanism for middleware.\nHowever, if you run Django under apache+mod_wsgi (instead of e.g. mod_python or lighttpd+flup) you can also include WSGI middleware in Django. This isn't typically done though because much of the functionality you'll find in WSGI middleware is already built-in to Django proper or Django middleware.\nThe differences between WSGI and Django middleware are small enough that it should be easy enough to convert code between the two. The tougher problem is when they use external libraries like ORM's.\nThe WSGI Wiki has a good list of WSGI middleware.\n"
] |
[
3,
0
] |
[] |
[] |
[
"django",
"middleware",
"pylons",
"python"
] |
stackoverflow_0001167903_django_middleware_pylons_python.txt
|
Q:
Python scripts in /usr/bin
I'm writing a pretty basic application in python (it's only one file at the moment). My question is how do I get it so the python script is able to be run in /usr/bin without the .py extension?
For example, instead of running
python htswap.py args
from the directory where it currently is, I want to be able to cd to any directory and do
htswap args
Thanks in advance!
A:
Simply strip off the .py extension by renaming the file. Then, you have to put the following line at the top of your file:
#!/usr/bin/env python
env is a little program that sets up the environment so that the right python interpreter is executed.
You also have to make your file executable, with the command
chmod a+x htswap
And dump it into /usr/local/bin. This is cleaner than /usr/bin, because the contents of that directory are usually managed by the operating system.
A:
The first line of the file should be
#!/usr/bin/env python
You should remove the .py extension, and make the file executable, using
chmod ugo+x htswap
EDIT: Thomas points out correctly that such scripts should be placed in /usr/local/bin rather than in /usr/bin. Please upvote his answer (at the expense of mine, perhaps. Seven upvotes (as we speak) for this kind of stuff is ridiculous)
A:
Shebang?
#!/usr/bin/env python
Put that at the beginning of your file and you're set
A:
add #!/usr/bin/env python to the very top of htswap.py and rename htswap.py to htswap then do a command: chmod +x htswap to make htswap executable.
A:
I see in the official Python tutorials, http://docs.python.org/tutorial/index.html, that
#! /usr/bin/env python
is used just as the answers above suggest. Note that you can also use the following
#!/usr/bin/python
This is the style you'll see for in shell scripts, like bash scripts. For example
#!/bin/bash
Seeing that the official tuts go with the first option that is probably your best bet. Consistency in code is something to strive for!
|
Python scripts in /usr/bin
|
I'm writing a pretty basic application in python (it's only one file at the moment). My question is how do I get it so the python script is able to be run in /usr/bin without the .py extension?
For example, instead of running
python htswap.py args
from the directory where it currently is, I want to be able to cd to any directory and do
htswap args
Thanks in advance!
|
[
"Simply strip off the .py extension by renaming the file. Then, you have to put the following line at the top of your file:\n#!/usr/bin/env python\n\nenv is a little program that sets up the environment so that the right python interpreter is executed.\nYou also have to make your file executable, with the command\nchmod a+x htswap\n\nAnd dump it into /usr/local/bin. This is cleaner than /usr/bin, because the contents of that directory are usually managed by the operating system.\n",
"The first line of the file should be\n#!/usr/bin/env python\n\nYou should remove the .py extension, and make the file executable, using\nchmod ugo+x htswap\n\nEDIT: Thomas points out correctly that such scripts should be placed in /usr/local/bin rather than in /usr/bin. Please upvote his answer (at the expense of mine, perhaps. Seven upvotes (as we speak) for this kind of stuff is ridiculous)\n",
"Shebang?\n#!/usr/bin/env python\n\nPut that at the beginning of your file and you're set\n",
"add #!/usr/bin/env python to the very top of htswap.py and rename htswap.py to htswap then do a command: chmod +x htswap to make htswap executable.\n",
"I see in the official Python tutorials, http://docs.python.org/tutorial/index.html, that \n#! /usr/bin/env python\n\nis used just as the answers above suggest. Note that you can also use the following\n#!/usr/bin/python\n\nThis is the style you'll see for in shell scripts, like bash scripts. For example\n#!/bin/bash\n\nSeeing that the official tuts go with the first option that is probably your best bet. Consistency in code is something to strive for!\n"
] |
[
47,
14,
2,
1,
0
] |
[] |
[] |
[
"python",
"scripting",
"unix"
] |
stackoverflow_0001168042_python_scripting_unix.txt
|
Q:
Why does this Python script only read the last RSS post into the file?
Im trying to fix a Python script which takes the posts from a specific RSS feed and strips them down and inputs them into a text file. As you can see beneath, there are two main print functions. One prints only to the shell once run, but it shows all of the posts, which is what I want it to do. Now, the second part is where the problem lies. It only prints out the last post of the RSS feed into a text, not the whole thing, as the first function does. I've also tried to make the second function (f = open()) the same way as the first with the %s instead of a new print-line pr. variable.
If anyone could tell me why the script doesnt post more than one (the last) post of the RSS feed into the text, but the whole thing in the shell, and what modifications I need to fix it, I would really appreciate it :)
Here is the code:
import urllib
import sys
import xml.dom.minidom
#The url of the feed
address = 'http://www.vg.no/export/Alle/rdf.hbs?kat=nyheter'
#Our actual xml document
document = xml.dom.minidom.parse(urllib.urlopen(address))
for item in document.getElementsByTagName('item'):
title = item.getElementsByTagName('title')[0].firstChild.data
link = item.getElementsByTagName('link')[0].firstChild.data
description = item.getElementsByTagName('description')[0].firstChild.data
str = link.strip("http://go.vg.no/cgi-bin/go.cgi/rssart/")
print "\n"
print "------------------------------------------------------------------"
print '''"%s"\n\n%s\n\n(%s)''' % (title.encode('UTF8', 'replace'),
description.encode('UTF8','replace'),
str.encode('UTF8','replace'))
print "------------------------------------------------------------------"
print "\n"
f = open('lawl.txt','w')
print >>f, "----------------------Nyeste paa VG-------------------------------"
print >>f, title.encode('UTF8','replace')
print >>f, description.encode('UTF8','replace')
print >>f, str.encode('UTF8','replace')
print >>f, "------------------------------------------------------------------"
print >>f, "\n"
A:
Your print >>f are after the for loop, so they are run once, and operate on the data that you last saved to title, description, and str.
You should open the file before the for loop and then put the print >>f lines inside the loop.
import urllib
import sys
import xml.dom.minidom
#The url of the feed
address = 'http://www.vg.no/export/Alle/rdf.hbs?kat=nyheter'
f = open('lawl.txt','w')
#Our actual xml document
document = xml.dom.minidom.parse(urllib.urlopen(address))
for item in document.getElementsByTagName('item'):
title = item.getElementsByTagName('title')[0].firstChild.data
link = item.getElementsByTagName('link')[0].firstChild.data
description = item.getElementsByTagName('description')[0].firstChild.data
str = link.strip("http://go.vg.no/cgi-bin/go.cgi/rssart/")
print "\n"
print "------------------------------------------------------------------"
print '''"%s"\n\n%s\n\n(%s)''' % (title.encode('UTF8', 'replace'),
description.encode('UTF8','replace'),
str.encode('UTF8','replace'))
print "------------------------------------------------------------------"
print "\n"
print >>f, "----------------------Nyeste paa VG-------------------------------"
print >>f, title.encode('UTF8','replace')
print >>f, description.encode('UTF8','replace')
print >>f, str.encode('UTF8','replace')
print >>f, "------------------------------------------------------------------"
print >>f, "\n"
A:
You iterate over all posts, assign their attributes to the variables and print to terminal.
Then you print the variables (which happen to hold the results of the last assignment) to file. So you get a single post here.
Need to iterate too if you want more than one.
|
Why does this Python script only read the last RSS post into the file?
|
Im trying to fix a Python script which takes the posts from a specific RSS feed and strips them down and inputs them into a text file. As you can see beneath, there are two main print functions. One prints only to the shell once run, but it shows all of the posts, which is what I want it to do. Now, the second part is where the problem lies. It only prints out the last post of the RSS feed into a text, not the whole thing, as the first function does. I've also tried to make the second function (f = open()) the same way as the first with the %s instead of a new print-line pr. variable.
If anyone could tell me why the script doesnt post more than one (the last) post of the RSS feed into the text, but the whole thing in the shell, and what modifications I need to fix it, I would really appreciate it :)
Here is the code:
import urllib
import sys
import xml.dom.minidom
#The url of the feed
address = 'http://www.vg.no/export/Alle/rdf.hbs?kat=nyheter'
#Our actual xml document
document = xml.dom.minidom.parse(urllib.urlopen(address))
for item in document.getElementsByTagName('item'):
title = item.getElementsByTagName('title')[0].firstChild.data
link = item.getElementsByTagName('link')[0].firstChild.data
description = item.getElementsByTagName('description')[0].firstChild.data
str = link.strip("http://go.vg.no/cgi-bin/go.cgi/rssart/")
print "\n"
print "------------------------------------------------------------------"
print '''"%s"\n\n%s\n\n(%s)''' % (title.encode('UTF8', 'replace'),
description.encode('UTF8','replace'),
str.encode('UTF8','replace'))
print "------------------------------------------------------------------"
print "\n"
f = open('lawl.txt','w')
print >>f, "----------------------Nyeste paa VG-------------------------------"
print >>f, title.encode('UTF8','replace')
print >>f, description.encode('UTF8','replace')
print >>f, str.encode('UTF8','replace')
print >>f, "------------------------------------------------------------------"
print >>f, "\n"
|
[
"Your print >>f are after the for loop, so they are run once, and operate on the data that you last saved to title, description, and str.\nYou should open the file before the for loop and then put the print >>f lines inside the loop.\nimport urllib\nimport sys\nimport xml.dom.minidom\n\n#The url of the feed\naddress = 'http://www.vg.no/export/Alle/rdf.hbs?kat=nyheter'\n\nf = open('lawl.txt','w')\n\n#Our actual xml document\ndocument = xml.dom.minidom.parse(urllib.urlopen(address))\nfor item in document.getElementsByTagName('item'):\n title = item.getElementsByTagName('title')[0].firstChild.data\n link = item.getElementsByTagName('link')[0].firstChild.data\n description = item.getElementsByTagName('description')[0].firstChild.data\n\n str = link.strip(\"http://go.vg.no/cgi-bin/go.cgi/rssart/\")\n print \"\\n\"\n print \"------------------------------------------------------------------\"\n print '''\"%s\"\\n\\n%s\\n\\n(%s)''' % (title.encode('UTF8', 'replace'),\n description.encode('UTF8','replace'),\n str.encode('UTF8','replace'))\n print \"------------------------------------------------------------------\"\n print \"\\n\"\n\n print >>f, \"----------------------Nyeste paa VG-------------------------------\"\n print >>f, title.encode('UTF8','replace')\n print >>f, description.encode('UTF8','replace')\n print >>f, str.encode('UTF8','replace')\n print >>f, \"------------------------------------------------------------------\"\n print >>f, \"\\n\"\n\n",
"You iterate over all posts, assign their attributes to the variables and print to terminal.\nThen you print the variables (which happen to hold the results of the last assignment) to file. So you get a single post here.\nNeed to iterate too if you want more than one.\n"
] |
[
2,
1
] |
[] |
[] |
[
"python",
"rss",
"xml"
] |
stackoverflow_0001168844_python_rss_xml.txt
|
Q:
Autocompletion not working with PyQT4 and PyKDE4 in most of the IDEs
I am trying to develop a plasmoid using python. I have tried eclipse with pydev, vim with pythoncomplete, PIDA and also Komodo, but none of them could give me autocmpletion for method names or members for the classes belonging to PyQT4 or PyKDE4. I added the folders in /usr/share/pyshare in the PYTHONPATH list for the IDEs.
Do I need to do something else ?
A:
There is a number of ways to do it, PyQt4 provides enough information about method names for any object inspecting IDE:
>>> from PyQt4 import QtGui
>>> dir(QtGui.QToolBox)
['Box', ... contextMenuPolicy', 'count', 'create', 'currentChanged'...]
All those functions are built-in. This means that you have to push some IDEs slightly to notice them. Be aware that there are no docstrings in compiled PyQt and methods have a funny signature.
Other possibility is using QScintilla2 and.api file generated during PyQt4 build process. Eric4 IDE is prepared exactly for that.
<shameless-plug>
You can also try Komodo IDE/Komodo Edit and a CIX file (download here) that I hacked together not so long ago:
and,
Edit: Installation instructions for Komodo 5:
Edit -> Preferences -> Code Intelligence
Add an API Catalog...
Select CIX file, press Open
There is no point 4.
</shameless-plug>
A:
What about WingIDE, It's not free but it's Feature List has "auto-completion for wxPython, PyGTK, and PyQt "
|
Autocompletion not working with PyQT4 and PyKDE4 in most of the IDEs
|
I am trying to develop a plasmoid using python. I have tried eclipse with pydev, vim with pythoncomplete, PIDA and also Komodo, but none of them could give me autocmpletion for method names or members for the classes belonging to PyQT4 or PyKDE4. I added the folders in /usr/share/pyshare in the PYTHONPATH list for the IDEs.
Do I need to do something else ?
|
[
"There is a number of ways to do it, PyQt4 provides enough information about method names for any object inspecting IDE:\n>>> from PyQt4 import QtGui\n>>> dir(QtGui.QToolBox) \n['Box', ... contextMenuPolicy', 'count', 'create', 'currentChanged'...]\n\nAll those functions are built-in. This means that you have to push some IDEs slightly to notice them. Be aware that there are no docstrings in compiled PyQt and methods have a funny signature.\nOther possibility is using QScintilla2 and.api file generated during PyQt4 build process. Eric4 IDE is prepared exactly for that.\n<shameless-plug>\nYou can also try Komodo IDE/Komodo Edit and a CIX file (download here) that I hacked together not so long ago:\n\nand,\n\nEdit: Installation instructions for Komodo 5:\n\nEdit -> Preferences -> Code Intelligence\nAdd an API Catalog...\nSelect CIX file, press Open\nThere is no point 4.\n\n</shameless-plug>\n",
"What about WingIDE, It's not free but it's Feature List has \"auto-completion for wxPython, PyGTK, and PyQt \"\n"
] |
[
4,
0
] |
[] |
[] |
[
"plasmoid",
"pykde",
"pyqt4",
"python"
] |
stackoverflow_0001167065_plasmoid_pykde_pyqt4_python.txt
|
Q:
Smart date interpretation
I can't remember which application I was using, but I do recall it having really neat date parsing/interpretation.
For example, you could type in 'two days ago' or 'tomorrow' and it would understand.
Any libraries to suggest? Bonus points if usable from Python.
A:
Perhaps you are thinking of PHP's strtotime() function, the Swiss Army Knife of date parsing:
Man, what did I do before strtotime(). Oh, I know, I had a 482 line function to parse date formats and return timestamps. And I still could not do really cool stuff. Like tonight I needed to figure out when Thanksgiving was in the US. I knew it was the 4th Thursday in November. So, I started with some math stuff and checking what day of the week Nov. 1 would fall on. All that was making my head hurt. So, I just tried this for fun.
strtotime("thursday, november ".date("Y")." + 3 weeks")
That gives me Thanksgiving. Awesome.
Sadly, there does not appear to be a Python equivalent. The closest thing I could find is the dateutil.parser module.
A:
See my SO answer for links to three Python date parsing libraries. The one of these most commonly used is python-dateutils but unfortunately it can't handle all formats.
A:
The simple one I have seen for python is here.
It uses pyparsing and is only a small script, but it does what you ask. However, the advantage being it would be pretty easy to extend and improve on if needed. Pyparsing is relatively easy to learn as parsing goes.
|
Smart date interpretation
|
I can't remember which application I was using, but I do recall it having really neat date parsing/interpretation.
For example, you could type in 'two days ago' or 'tomorrow' and it would understand.
Any libraries to suggest? Bonus points if usable from Python.
|
[
"Perhaps you are thinking of PHP's strtotime() function, the Swiss Army Knife of date parsing:\n\nMan, what did I do before strtotime(). Oh, I know, I had a 482 line function to parse date formats and return timestamps. And I still could not do really cool stuff. Like tonight I needed to figure out when Thanksgiving was in the US. I knew it was the 4th Thursday in November. So, I started with some math stuff and checking what day of the week Nov. 1 would fall on. All that was making my head hurt. So, I just tried this for fun.\nstrtotime(\"thursday, november \".date(\"Y\").\" + 3 weeks\")\n\nThat gives me Thanksgiving. Awesome.\n\nSadly, there does not appear to be a Python equivalent. The closest thing I could find is the dateutil.parser module.\n",
"See my SO answer for links to three Python date parsing libraries. The one of these most commonly used is python-dateutils but unfortunately it can't handle all formats.\n",
"The simple one I have seen for python is here.\nIt uses pyparsing and is only a small script, but it does what you ask. However, the advantage being it would be pretty easy to extend and improve on if needed. Pyparsing is relatively easy to learn as parsing goes.\n"
] |
[
8,
6,
2
] |
[] |
[] |
[
"date_parsing",
"python"
] |
stackoverflow_0001169000_date_parsing_python.txt
|
Q:
Boolean evaluation in a lambda
Just tooling around for my own amusement, and I want to use a lambda, because I feel like it. Can I replace this function with a lambda?
def isodd(number):
if (number%2 == 0):
return False
else:
return True
Elementary, yes. But I'm interested to know...
A:
And if you don't really need a function you can replace it even without a lambda. :)
(number % 2 != 0)
by itself is an expression that evaluates to True or False. Or even plainer,
bool(number % 2)
which you can simplify like so:
if number % 2:
print "Odd!"
else:
print "Even!"
But if that's readable or not is probably in the eye of the beholder.
A:
lambda num: num % 2 != 0
A:
Yes you can:
isodd = lambda x: x % 2 != 0
A:
Others already gave you replies that cover your particular case. In general, however, when you actually need an if-statement, you can use the conditional expression. For example, if you'd have to return strings "False" and "True" rather than boolean values, you could do this:
lambda num: "False" if num%2==0 else "True"
The definition of this expression in Python language reference is as follows:
The expression x if C else y first evaluates C (not x); if C is true, x is evaluated and its value is returned; otherwise, y is evaluated and its value is returned.
A:
And also don't forget that you can emulate complex conditional sentences with simple short-circuit logic, taking advantage that "and" and "or" return some of their ellements (the last one evaluated)... for example, in this case, supposing you'd want to return something different than True or False
lambda x: x%2 and "Odd" or "Even"
A:
isodd = lambda number: number %2 != 0
A:
isodd = lambda number: (False, True)[number & 1]
A:
Any time you see yourself writing:
if (some condition):
return True
else:
return False
you should replace it with a single line:
return (some condition)
Your function then becomes:
def isodd(number):
return number % 2 != 0
You should be able to see how to get from there to the lambda solution that others have provided.
|
Boolean evaluation in a lambda
|
Just tooling around for my own amusement, and I want to use a lambda, because I feel like it. Can I replace this function with a lambda?
def isodd(number):
if (number%2 == 0):
return False
else:
return True
Elementary, yes. But I'm interested to know...
|
[
"And if you don't really need a function you can replace it even without a lambda. :)\n(number % 2 != 0)\n\nby itself is an expression that evaluates to True or False. Or even plainer,\nbool(number % 2)\n\nwhich you can simplify like so:\nif number % 2:\n print \"Odd!\"\nelse:\n print \"Even!\"\n\nBut if that's readable or not is probably in the eye of the beholder.\n",
"lambda num: num % 2 != 0\n\n",
"Yes you can:\nisodd = lambda x: x % 2 != 0\n\n",
"Others already gave you replies that cover your particular case. In general, however, when you actually need an if-statement, you can use the conditional expression. For example, if you'd have to return strings \"False\" and \"True\" rather than boolean values, you could do this:\nlambda num: \"False\" if num%2==0 else \"True\"\n\nThe definition of this expression in Python language reference is as follows:\n\nThe expression x if C else y first evaluates C (not x); if C is true, x is evaluated and its value is returned; otherwise, y is evaluated and its value is returned.\n\n",
"And also don't forget that you can emulate complex conditional sentences with simple short-circuit logic, taking advantage that \"and\" and \"or\" return some of their ellements (the last one evaluated)... for example, in this case, supposing you'd want to return something different than True or False\nlambda x: x%2 and \"Odd\" or \"Even\"\n\n",
"isodd = lambda number: number %2 != 0\n\n",
"isodd = lambda number: (False, True)[number & 1]\n",
"Any time you see yourself writing:\nif (some condition):\n return True\nelse:\n return False\n\nyou should replace it with a single line:\nreturn (some condition)\n\nYour function then becomes:\ndef isodd(number):\n return number % 2 != 0\n\nYou should be able to see how to get from there to the lambda solution that others have provided.\n"
] |
[
16,
11,
11,
8,
6,
5,
3,
2
] |
[] |
[] |
[
"lambda",
"python"
] |
stackoverflow_0001168236_lambda_python.txt
|
Q:
Find module name of the originating exception in Python
Example:
>>> try:
... myapp.foo.doSomething()
... except Exception, e:
... print 'Thrown from:', modname(e)
Thrown from: myapp.util.url
In the above example, the exception was actually thrown at myapp/util/url.py module. Is there a way to get the __name__ of that module?
My intention is to use this in logging.getLogger function.
A:
This should work:
import inspect
try:
some_bad_code()
except Exception, e:
frm = inspect.trace()[-1]
mod = inspect.getmodule(frm[0])
print 'Thrown from', mod.__name__
EDIT: Stephan202 mentions a corner case. In this case, I think we could default to the file name.
import inspect
try:
import bad_module
except Exception, e:
frm = inspect.trace()[-1]
mod = inspect.getmodule(frm[0])
modname = mod.__name__ if mod else frm[1]
print 'Thrown from', modname
The problem is that if the module doesn't get loaded (because an exception was thrown while reading the code in that file), then the inspect.getmodule call returns None. So, we just use the name of the file referenced by the offending frame. (Thanks for pointing this out, Stephan202!)
A:
You can use the traceback module, along with sys.exc_info(), to get the traceback programmatically:
try:
myapp.foo.doSomething()
except Exception, e:
exc_type, exc_value, exc_tb = sys.exc_info()
filename, line_num, func_name, text = traceback.extract_tb(exc_tb)[-1]
print 'Thrown from: %s' % filename
A:
This should do the trick:
import inspect
def modname():
t=inspect.trace()
if t:
return t[-1][1]
A:
Python's logging package already supports this - check the documentation. You just have to specify %(module)s in the format string. However, this gives you the module where the exception was caught - not necessarily the same as the one where it was raised. The traceback, of course, gives you the precise location where the exception was raised.
|
Find module name of the originating exception in Python
|
Example:
>>> try:
... myapp.foo.doSomething()
... except Exception, e:
... print 'Thrown from:', modname(e)
Thrown from: myapp.util.url
In the above example, the exception was actually thrown at myapp/util/url.py module. Is there a way to get the __name__ of that module?
My intention is to use this in logging.getLogger function.
|
[
"This should work:\nimport inspect\n\ntry:\n some_bad_code()\nexcept Exception, e:\n frm = inspect.trace()[-1]\n mod = inspect.getmodule(frm[0])\n print 'Thrown from', mod.__name__\n\nEDIT: Stephan202 mentions a corner case. In this case, I think we could default to the file name.\nimport inspect\n\ntry:\n import bad_module\nexcept Exception, e:\n frm = inspect.trace()[-1]\n mod = inspect.getmodule(frm[0])\n modname = mod.__name__ if mod else frm[1]\n print 'Thrown from', modname\n\nThe problem is that if the module doesn't get loaded (because an exception was thrown while reading the code in that file), then the inspect.getmodule call returns None. So, we just use the name of the file referenced by the offending frame. (Thanks for pointing this out, Stephan202!)\n",
"You can use the traceback module, along with sys.exc_info(), to get the traceback programmatically:\ntry:\n myapp.foo.doSomething()\nexcept Exception, e:\n exc_type, exc_value, exc_tb = sys.exc_info()\n filename, line_num, func_name, text = traceback.extract_tb(exc_tb)[-1]\n print 'Thrown from: %s' % filename\n\n",
"This should do the trick:\nimport inspect\ndef modname():\n t=inspect.trace()\n if t:\n return t[-1][1]\n\n",
"Python's logging package already supports this - check the documentation. You just have to specify %(module)s in the format string. However, this gives you the module where the exception was caught - not necessarily the same as the one where it was raised. The traceback, of course, gives you the precise location where the exception was raised.\n"
] |
[
12,
8,
0,
0
] |
[
"I have a story about how CrashKit computes class names and package names from Python stack traces on the company blog: “Python stack trace saga”. Working code included.\n"
] |
[
-2
] |
[
"exception",
"introspection",
"logging",
"python",
"stack_trace"
] |
stackoverflow_0001095601_exception_introspection_logging_python_stack_trace.txt
|
Q:
Python OS X 10.5 development environment
I would like to try out the Google App Engine Python environment, which the docs say runs 2.5.2. As I use OS X Leopard, I have Python 2.5.1 installed, but would like the latest 2.5.x version installed (not 2.6 or 3.0). It seems the latest version is 2.5.4
So, I went to here:
http://wiki.python.org/moin/MacPython/Leopard
and stopped because I am worried installing the latest version might mess with the standard install. I really just want one version installed.
So my questions are how do I safely install the latest 2.5.x? Is it possible to fully replace the built in version, and if so would that hurt any Mac tools?
Cheers,
Shane
A:
You can install python on your Mac, and it won't mess with the default installation. However, I strongly recommend that you use MacPorts to install Python, since that will make it much easier for you to install Python libraries and packages further down the road. Additionally, if you try to install a program or library with MacPorts that depends on Python, MacPorts will download a copy of Python, even if you have MacPython installed, so you might end up with redundant copies of Python if you install MacPython but then choose to use MacPorts at a later date. To install Python with MacPorts, download and install MacPorts, then type:
sudo port install python25 python_select
sudo python_select python25
Run the following command to view all the MacPorts packages for Python:
port list | grep py25-
You can install any of the packages on the list by simply typing:
sudo port install packagename
In the above, replace packagename with the name of the package. On my first install I always run
sudo port install py25-setuptools
[ NOTE: These commands need to be run from the Terminal -- Applications > Utilities > Terminal.app ]
A:
Your current python is in /System/Library/Frameworks/Python.framework/.
If you install MacPython, it will go into /Library/Frameworks/Python.framework/. The installer will modify your $PATH (environment variable) so that typing python at the command line will run the version it installs.
You can easily get back the old version by modifying the path again.
You will have to reinstall any third-party modules you are using. This is because third-party modules go into Python.framework/Versions/Current/lib/python2.5/site-packages/ for the version you're running.
Since you're not modifying the system version, you aren't in danger of affecting any Apple system tools that rely on it.
(in fact, arguably it is safer to install MacPython from the start, and never touch the Apple-supplied version. See here for a similar situation involving Perl, where Apple updated the version of Perl in /System and broke a lot of people's setups)
You may also be interested in virtualenv.
|
Python OS X 10.5 development environment
|
I would like to try out the Google App Engine Python environment, which the docs say runs 2.5.2. As I use OS X Leopard, I have Python 2.5.1 installed, but would like the latest 2.5.x version installed (not 2.6 or 3.0). It seems the latest version is 2.5.4
So, I went to here:
http://wiki.python.org/moin/MacPython/Leopard
and stopped because I am worried installing the latest version might mess with the standard install. I really just want one version installed.
So my questions are how do I safely install the latest 2.5.x? Is it possible to fully replace the built in version, and if so would that hurt any Mac tools?
Cheers,
Shane
|
[
"You can install python on your Mac, and it won't mess with the default installation. However, I strongly recommend that you use MacPorts to install Python, since that will make it much easier for you to install Python libraries and packages further down the road. Additionally, if you try to install a program or library with MacPorts that depends on Python, MacPorts will download a copy of Python, even if you have MacPython installed, so you might end up with redundant copies of Python if you install MacPython but then choose to use MacPorts at a later date. To install Python with MacPorts, download and install MacPorts, then type:\n\nsudo port install python25 python_select\nsudo python_select python25\n\nRun the following command to view all the MacPorts packages for Python:\n\nport list | grep py25-\n\nYou can install any of the packages on the list by simply typing:\n\nsudo port install packagename\n\nIn the above, replace packagename with the name of the package. On my first install I always run\n\nsudo port install py25-setuptools\n\n[ NOTE: These commands need to be run from the Terminal -- Applications > Utilities > Terminal.app ]\n",
"Your current python is in /System/Library/Frameworks/Python.framework/.\nIf you install MacPython, it will go into /Library/Frameworks/Python.framework/. The installer will modify your $PATH (environment variable) so that typing python at the command line will run the version it installs.\nYou can easily get back the old version by modifying the path again.\nYou will have to reinstall any third-party modules you are using. This is because third-party modules go into Python.framework/Versions/Current/lib/python2.5/site-packages/ for the version you're running.\nSince you're not modifying the system version, you aren't in danger of affecting any Apple system tools that rely on it.\n(in fact, arguably it is safer to install MacPython from the start, and never touch the Apple-supplied version. See here for a similar situation involving Perl, where Apple updated the version of Perl in /System and broke a lot of people's setups)\nYou may also be interested in virtualenv.\n"
] |
[
7,
3
] |
[] |
[] |
[
"development_environment",
"google_app_engine",
"macos",
"python"
] |
stackoverflow_0001169025_development_environment_google_app_engine_macos_python.txt
|
Q:
Can I damage the system by running time.sleep() with this newbie code in Python?
Im sure there is a better way to do this, but I am quite the newbie so I did it the only way I could figure it out. The thing is, I have a script that updates a textfile with the newest posts from an RSS feed (I got some help from you guys to figure it out). But I want this script to be automated, so I made this:
import time
import os
seconds = 3600
kjor = 'python vg.py'
time.sleep(seconds)
os.system(kjor)
time.sleep(seconds)
os.system(kjor)
time.sleep(seconds)
os.system(kjor)
I continued with copying those 24x downwards. I know this problably can be done alot better with some loop (while?), but Im afraid I dont have alot of knowledge in that field (yet).
My question, however, is as following: Can the system be damaged in any way if I let this run over a longer period of time?
A:
To answer your question, no, this won't hurt anything. While the time.sleeps are sleeping, the program will take very little processing power and the rest of the system can run normally.
Now, as for your looping issue. If you want the code run forever (or until you stop the program) the code you want is
while True:
os.system(kjor)
time.sleep(seconds)
This is, literally, and infinite loop, but in this case that (is probably) what you want.
If you are attached to having a particular number of iterations, then you could do something like sunqiang's answer (repeated here)
for loop in xrange(240):
os.system(kjor)
time.sleep(seconds)
Finally, if you are on a Unix platform (such as Linux or Mac) you should take a look at cron, as it is designed to set up recurring programs to run and particular time periods. You could set it up to run your script every minute and it will happily do so until the end of time (or you remove it, whichever comes first).
A:
Use xrange please, don't copying your code 24x times.
for loop in xrange(240):
time.sleep(seconds)
os.system(kjor)
It will not damage your system, as far as I know.
A:
It does not damage any system and it is pretty common as well.
Just create a loop so as your application will gently stop running after some time;
Or better yet, make it check for a condition, maybe listen to a tcp port waiting for someone to ask it to quit (then you'll need to create a second application to send this quit message).
|
Can I damage the system by running time.sleep() with this newbie code in Python?
|
Im sure there is a better way to do this, but I am quite the newbie so I did it the only way I could figure it out. The thing is, I have a script that updates a textfile with the newest posts from an RSS feed (I got some help from you guys to figure it out). But I want this script to be automated, so I made this:
import time
import os
seconds = 3600
kjor = 'python vg.py'
time.sleep(seconds)
os.system(kjor)
time.sleep(seconds)
os.system(kjor)
time.sleep(seconds)
os.system(kjor)
I continued with copying those 24x downwards. I know this problably can be done alot better with some loop (while?), but Im afraid I dont have alot of knowledge in that field (yet).
My question, however, is as following: Can the system be damaged in any way if I let this run over a longer period of time?
|
[
"To answer your question, no, this won't hurt anything. While the time.sleeps are sleeping, the program will take very little processing power and the rest of the system can run normally.\nNow, as for your looping issue. If you want the code run forever (or until you stop the program) the code you want is\n while True:\n os.system(kjor)\n time.sleep(seconds)\n\nThis is, literally, and infinite loop, but in this case that (is probably) what you want.\nIf you are attached to having a particular number of iterations, then you could do something like sunqiang's answer (repeated here)\nfor loop in xrange(240):\n os.system(kjor)\n time.sleep(seconds)\n\nFinally, if you are on a Unix platform (such as Linux or Mac) you should take a look at cron, as it is designed to set up recurring programs to run and particular time periods. You could set it up to run your script every minute and it will happily do so until the end of time (or you remove it, whichever comes first).\n",
"Use xrange please, don't copying your code 24x times.\nfor loop in xrange(240):\n time.sleep(seconds)\n os.system(kjor)\n\nIt will not damage your system, as far as I know.\n",
"It does not damage any system and it is pretty common as well.\nJust create a loop so as your application will gently stop running after some time; \nOr better yet, make it check for a condition, maybe listen to a tcp port waiting for someone to ask it to quit (then you'll need to create a second application to send this quit message).\n"
] |
[
9,
1,
1
] |
[] |
[] |
[
"python",
"while_loop"
] |
stackoverflow_0001169185_python_while_loop.txt
|
Q:
Python Unicode Regular Expression
I am using python 2.4 and I am having some problems with unicode regular expressions. I have tried to put together a very clear and concise example of my problem. It looks as though there is some problem with how Python is recognizing the different character encodings, or a problem with my understanding. Thank you very much for taking a look!
#!/usr/bin/python
#
# This is a simple python program designed to show my problems with regular expressions and character encoding in python
# Written by Brian J. Stinar
# Thanks for the help!
import urllib # To get files off the Internet
import chardet # To identify charactor encodings
import re # Python Regular Expressions
#import ponyguruma # Python Onyguruma Regular Expressions - this can be uncommented if you feel like messing with it, but I have the same issue no matter which RE's I'm using
rawdata = urllib.urlopen('http://www.cs.unm.edu/~brian.stinar/legal.html').read()
print (chardet.detect(rawdata))
#print (rawdata)
ISO_8859_2_encoded = rawdata.decode('ISO-8859-2') # Let's grab this as text
UTF_8_encoded = ISO_8859_2_encoded.encode('utf-8') # and encode the text as UTF-8
print(chardet.detect(UTF_8_encoded)) # Looks good
# This totally doesn't work, even though you can see UNSUBSCRIBE in the HTML
# Eventually, I want to recognize the entire physical address and UNSUBSCRIBE above it
re_UNSUB_amsterdam = re.compile(".*UNSUBSCRIBE.*", re.UNICODE)
print (str(re_UNSUB_amsterdam.match(UTF_8_encoded)) + "\t\t\t\t\t--- RE for UNSUBSCRIBE on UTF-8")
print (str(re_UNSUB_amsterdam.match(rawdata)) + "\t\t\t\t\t--- RE for UNSUBSCRIBE on raw data")
re_amsterdam = re.compile(".*Adobe.*", re.UNICODE)
print (str(re_amsterdam.match(rawdata)) + "\t--- RE for 'Adobe' on raw data") # However, this work?!?
print (str(re_amsterdam.match(UTF_8_encoded)) + "\t--- RE for 'Adobe' on UTF-8")
'''
# In additon, I tried this regular expression library much to the same unsatisfactory result
new_re = ponyguruma.Regexp(".*UNSUBSCRIBE.*")
if new_re.match(UTF_8_encoded) != None:
print("Ponyguruma RE matched! \t\t\t--- RE for UNSUBSCRIBE on UTF-8")
else:
print("Ponyguruma RE did not match\t\t--- RE for UNSUBSCRIBE on UTF-8")
if new_re.match(rawdata) != None:
print("Ponyguruma RE matched! \t\t\t--- RE for UNSUBSCRIBE on raw data")
else:
print("Ponyguruma RE did not match\t\t--- RE for UNSUBSCRIBE on raw data")
new_re = ponyguruma.Regexp(".*Adobe.*")
if new_re.match(UTF_8_encoded) != None:
print("Ponyguruma RE matched! \t\t\t--- RE for Adobe on UTF-8")
else:
print("Ponyguruma RE did not match\t\t\t--- RE for Adobe on UTF-8")
new_re = ponyguruma.Regexp(".*Adobe.*")
if new_re.match(rawdata) != None:
print("Ponyguruma RE matched! \t\t\t--- RE for Adobe on raw data")
else:
print("Ponyguruma RE did not match\t\t\t--- RE for Adobe on raw data")
'''
I am working on a substitution project, and am having a difficult time with the non-ASCII encoded files. This problem is part of a bigger project - eventually I would like to substitute the text with other text (I got this working in ASCII, but I can't identify occurrences in other encodings yet.) Thanks again.
http://brian-stinar.blogspot.com
-Brian J. Stinar-
A:
You probably want to either enable the DOTALL flag or you want to use the search method instead of the match method. ie:
# DOTALL makes . match newlines
re_UNSUB_amsterdam = re.compile(".*UNSUBSCRIBE.*", re.UNICODE | re.DOTALL)
or:
# search will find matches even if they aren't at the start of the string
... re_UNSUB_amsterdam.search(foo) ...
These will give you different results, but both should give you matches. (See which one is the type you want.)
As an aside: You seem to be getting the encoded text (which is bytes) and decoded text (characters) confused. This isn't uncommon, especially in pre-3.x Python. In particular, this is very suspicious:
ISO_8859_2_encoded = rawdata.decode('ISO-8859-2')
You're de-coding with ISO-8859-2, not en-coding, so call this variable "decoded". (Why not "ISO_8859_2_decoded"? Because ISO_8859_2 is an encoding. A decoded string doesn't have an encoding anymore.)
The rest of your code is trying to do matches on rawdata and on UTF_8_encoded (both encoded strings) when it should probably be using the decoded unicode string instead.
A:
this might help: http://www.daa.com.au/pipermail/pygtk/2009-July/017299.html
A:
With default flag settings, .* doesn't match newlines. UNSUBSCRIBE appears only once, after the first newline. Adobe occurs before the first newline. You could fix that by using re.DOTALL.
HOWEVER you haven't inspected what you got with the Adobe match: it's 1478 bytes wide! Turn on re.DOTALL and it (and the corresponding UNSUBSCRIBE pattern) will match the whole text!!
You definitely need to lose the trailing .* -- you're not interested and it slows down the match. Also you should lose the leading .* and use search() instead of match().
The re.UNICODE flag is of no use to you in this case -- read the manual and see what it does.
Why are you transcoding your data into UTF-8 and searching on that? Just leave in Unicode.
Someone else pointed out that in general you need to decode Ӓ etc thingies before doing any serious work on your data ... but didn't mention the « etc thingies with which your data is peppered :-)
A:
Your question is about regular expressions, but your problem can possibly be solved without them; instead use the standard string replace method.
import urllib
raw = urllib.urlopen('http://www.cs.unm.edu/~brian.stinar/legal.html').read()
decoded = raw.decode('iso-8859-2')
type(decoded) # decoded is now <type 'unicode'>
substituted = decoded.replace(u'UNSUBSCRIBE', u'whatever you prefer')
If nothing else, the above shows how to handle the encoding: simply decode into a unicode string and work with that. But note that this only works well for the case where you have only one or a very small number of substitutions to make (and those substitutions are not pattern based) because replace() can only handle one substitution at a time.
For both string and pattern based substitutions you can do something like this to effect multiple replacements at once:
import re
REPLACEMENTS = ((u'[aA]dobe', u'!twiddle!'),
(u'UNS.*IBE', u'@wobble@'),
(u'Dublin', u'Sydney'))
def replacer(m):
return REPLACEMENTS[list(m.groups()).index(m.group(0))][1]
r = re.compile('|'.join('(%s)' % t[0] for t in REPLACEMENTS))
substituted = r.sub(replacer, decoded)
|
Python Unicode Regular Expression
|
I am using python 2.4 and I am having some problems with unicode regular expressions. I have tried to put together a very clear and concise example of my problem. It looks as though there is some problem with how Python is recognizing the different character encodings, or a problem with my understanding. Thank you very much for taking a look!
#!/usr/bin/python
#
# This is a simple python program designed to show my problems with regular expressions and character encoding in python
# Written by Brian J. Stinar
# Thanks for the help!
import urllib # To get files off the Internet
import chardet # To identify charactor encodings
import re # Python Regular Expressions
#import ponyguruma # Python Onyguruma Regular Expressions - this can be uncommented if you feel like messing with it, but I have the same issue no matter which RE's I'm using
rawdata = urllib.urlopen('http://www.cs.unm.edu/~brian.stinar/legal.html').read()
print (chardet.detect(rawdata))
#print (rawdata)
ISO_8859_2_encoded = rawdata.decode('ISO-8859-2') # Let's grab this as text
UTF_8_encoded = ISO_8859_2_encoded.encode('utf-8') # and encode the text as UTF-8
print(chardet.detect(UTF_8_encoded)) # Looks good
# This totally doesn't work, even though you can see UNSUBSCRIBE in the HTML
# Eventually, I want to recognize the entire physical address and UNSUBSCRIBE above it
re_UNSUB_amsterdam = re.compile(".*UNSUBSCRIBE.*", re.UNICODE)
print (str(re_UNSUB_amsterdam.match(UTF_8_encoded)) + "\t\t\t\t\t--- RE for UNSUBSCRIBE on UTF-8")
print (str(re_UNSUB_amsterdam.match(rawdata)) + "\t\t\t\t\t--- RE for UNSUBSCRIBE on raw data")
re_amsterdam = re.compile(".*Adobe.*", re.UNICODE)
print (str(re_amsterdam.match(rawdata)) + "\t--- RE for 'Adobe' on raw data") # However, this work?!?
print (str(re_amsterdam.match(UTF_8_encoded)) + "\t--- RE for 'Adobe' on UTF-8")
'''
# In additon, I tried this regular expression library much to the same unsatisfactory result
new_re = ponyguruma.Regexp(".*UNSUBSCRIBE.*")
if new_re.match(UTF_8_encoded) != None:
print("Ponyguruma RE matched! \t\t\t--- RE for UNSUBSCRIBE on UTF-8")
else:
print("Ponyguruma RE did not match\t\t--- RE for UNSUBSCRIBE on UTF-8")
if new_re.match(rawdata) != None:
print("Ponyguruma RE matched! \t\t\t--- RE for UNSUBSCRIBE on raw data")
else:
print("Ponyguruma RE did not match\t\t--- RE for UNSUBSCRIBE on raw data")
new_re = ponyguruma.Regexp(".*Adobe.*")
if new_re.match(UTF_8_encoded) != None:
print("Ponyguruma RE matched! \t\t\t--- RE for Adobe on UTF-8")
else:
print("Ponyguruma RE did not match\t\t\t--- RE for Adobe on UTF-8")
new_re = ponyguruma.Regexp(".*Adobe.*")
if new_re.match(rawdata) != None:
print("Ponyguruma RE matched! \t\t\t--- RE for Adobe on raw data")
else:
print("Ponyguruma RE did not match\t\t\t--- RE for Adobe on raw data")
'''
I am working on a substitution project, and am having a difficult time with the non-ASCII encoded files. This problem is part of a bigger project - eventually I would like to substitute the text with other text (I got this working in ASCII, but I can't identify occurrences in other encodings yet.) Thanks again.
http://brian-stinar.blogspot.com
-Brian J. Stinar-
|
[
"You probably want to either enable the DOTALL flag or you want to use the search method instead of the match method. ie:\n# DOTALL makes . match newlines \nre_UNSUB_amsterdam = re.compile(\".*UNSUBSCRIBE.*\", re.UNICODE | re.DOTALL)\n\nor:\n# search will find matches even if they aren't at the start of the string\n... re_UNSUB_amsterdam.search(foo) ...\n\nThese will give you different results, but both should give you matches. (See which one is the type you want.)\nAs an aside: You seem to be getting the encoded text (which is bytes) and decoded text (characters) confused. This isn't uncommon, especially in pre-3.x Python. In particular, this is very suspicious:\nISO_8859_2_encoded = rawdata.decode('ISO-8859-2')\n\nYou're de-coding with ISO-8859-2, not en-coding, so call this variable \"decoded\". (Why not \"ISO_8859_2_decoded\"? Because ISO_8859_2 is an encoding. A decoded string doesn't have an encoding anymore.)\nThe rest of your code is trying to do matches on rawdata and on UTF_8_encoded (both encoded strings) when it should probably be using the decoded unicode string instead.\n",
"this might help: http://www.daa.com.au/pipermail/pygtk/2009-July/017299.html\n",
"With default flag settings, .* doesn't match newlines. UNSUBSCRIBE appears only once, after the first newline. Adobe occurs before the first newline. You could fix that by using re.DOTALL. \nHOWEVER you haven't inspected what you got with the Adobe match: it's 1478 bytes wide! Turn on re.DOTALL and it (and the corresponding UNSUBSCRIBE pattern) will match the whole text!!\nYou definitely need to lose the trailing .* -- you're not interested and it slows down the match. Also you should lose the leading .* and use search() instead of match().\nThe re.UNICODE flag is of no use to you in this case -- read the manual and see what it does.\nWhy are you transcoding your data into UTF-8 and searching on that? Just leave in Unicode.\nSomeone else pointed out that in general you need to decode Ӓ etc thingies before doing any serious work on your data ... but didn't mention the « etc thingies with which your data is peppered :-)\n",
"Your question is about regular expressions, but your problem can possibly be solved without them; instead use the standard string replace method.\nimport urllib\nraw = urllib.urlopen('http://www.cs.unm.edu/~brian.stinar/legal.html').read()\ndecoded = raw.decode('iso-8859-2')\ntype(decoded) # decoded is now <type 'unicode'>\nsubstituted = decoded.replace(u'UNSUBSCRIBE', u'whatever you prefer')\n\nIf nothing else, the above shows how to handle the encoding: simply decode into a unicode string and work with that. But note that this only works well for the case where you have only one or a very small number of substitutions to make (and those substitutions are not pattern based) because replace() can only handle one substitution at a time.\nFor both string and pattern based substitutions you can do something like this to effect multiple replacements at once:\nimport re\nREPLACEMENTS = ((u'[aA]dobe', u'!twiddle!'),\n (u'UNS.*IBE', u'@wobble@'),\n (u'Dublin', u'Sydney'))\n\ndef replacer(m):\n return REPLACEMENTS[list(m.groups()).index(m.group(0))][1]\n\nr = re.compile('|'.join('(%s)' % t[0] for t in REPLACEMENTS))\nsubstituted = r.sub(replacer, decoded)\n\n"
] |
[
2,
0,
0,
0
] |
[] |
[] |
[
"character_encoding",
"python",
"regex"
] |
stackoverflow_0001168894_character_encoding_python_regex.txt
|
Q:
Comparing MD5s in Python
For a programming exercise I designed for myself, and for use in a pretty non-secure system later on, I'm trying to compare MD5 hashes. The one that is stored in a plain text file and is pulled out by the check_pw() function and the one that is created from the submitted password from a CGI form. md5_pw() is used to create all the hashes in the program.
For some reason, if (pair[1] == md5_pw(pw)) always fails, even though my program prints out identical hashes in my error checking lines:
print "this is the pw from the file: ", pair[1], "<br />"
print "this is the md5 pw you entered: ", md5_pw(pw), "<br />"
Where am I messing up?
Code:
def md5_pw(pw):
"""Returns the MD5 hex digest of the pw with addition."""
m = md5.new()
m.update("4hJ2Yq7qdHd9sdjFASh9"+pw)
return m.hexdigest()
def check_pw(user, pw, pwfile):
"""Returns True if the username and password match, False otherwise. pwfile is a xxx.txt format."""
f = open(pwfile)
for line in f:
pair = line.split(":")
print "this is the pw from the file: ", pair[1], "<br />"
print "this is the md5 pw you entered: ", md5_pw(pw), "<br />"
if (pair[0] == user):
print "user matched <br />"
if (pair[1] == md5_pw(pw)):
f.close()
return True
else:
f.close()
print "passmatch a failure"
return False
A:
Your pair[1] probably has a trailing newline. Try:
for line in f:
line = line.rstrip()
pair = line.split(":")
# ...etc
A:
My guess is that there's an problem with the file loading/parsing, most likely caused by a newline character. By paring your code down, I was able to find that your logic was sound:
def md5_pw(pw):
m = md5.new()
m.update("4hJ2Yq7qdHd9sdjFASh9"+pw)
return m.hexdigest()
def check_pw(pw):
pair = ("c317db7d54073ef5d345d6dd8b2c51e6")
if (pair == md5_pw(pw)):
return True
else:
return False
>>> import md5
>>> check_pw('fakepw')
False
>>> check_pw('testpw')
True
("c317db7d54073ef5d345d6dd8b2c51e6" is the md5 hash for "4hJ2Yq7qdHd9sdjFASh9testpw")
|
Comparing MD5s in Python
|
For a programming exercise I designed for myself, and for use in a pretty non-secure system later on, I'm trying to compare MD5 hashes. The one that is stored in a plain text file and is pulled out by the check_pw() function and the one that is created from the submitted password from a CGI form. md5_pw() is used to create all the hashes in the program.
For some reason, if (pair[1] == md5_pw(pw)) always fails, even though my program prints out identical hashes in my error checking lines:
print "this is the pw from the file: ", pair[1], "<br />"
print "this is the md5 pw you entered: ", md5_pw(pw), "<br />"
Where am I messing up?
Code:
def md5_pw(pw):
"""Returns the MD5 hex digest of the pw with addition."""
m = md5.new()
m.update("4hJ2Yq7qdHd9sdjFASh9"+pw)
return m.hexdigest()
def check_pw(user, pw, pwfile):
"""Returns True if the username and password match, False otherwise. pwfile is a xxx.txt format."""
f = open(pwfile)
for line in f:
pair = line.split(":")
print "this is the pw from the file: ", pair[1], "<br />"
print "this is the md5 pw you entered: ", md5_pw(pw), "<br />"
if (pair[0] == user):
print "user matched <br />"
if (pair[1] == md5_pw(pw)):
f.close()
return True
else:
f.close()
print "passmatch a failure"
return False
|
[
"Your pair[1] probably has a trailing newline. Try:\nfor line in f:\n line = line.rstrip()\n pair = line.split(\":\")\n # ...etc\n\n",
"My guess is that there's an problem with the file loading/parsing, most likely caused by a newline character. By paring your code down, I was able to find that your logic was sound:\ndef md5_pw(pw):\n m = md5.new()\n m.update(\"4hJ2Yq7qdHd9sdjFASh9\"+pw)\n return m.hexdigest()\n\ndef check_pw(pw):\n pair = (\"c317db7d54073ef5d345d6dd8b2c51e6\")\n if (pair == md5_pw(pw)):\n return True\n else:\n return False\n\n>>> import md5\n>>> check_pw('fakepw')\nFalse\n>>> check_pw('testpw')\nTrue\n\n(\"c317db7d54073ef5d345d6dd8b2c51e6\" is the md5 hash for \"4hJ2Yq7qdHd9sdjFASh9testpw\")\n"
] |
[
2,
1
] |
[] |
[] |
[
"md5",
"python"
] |
stackoverflow_0001169717_md5_python.txt
|
Q:
To build a similar reputation tracker as Jon's by Python
Jon Skeet has the following reputation tracker which is built by C#.
I am interested in building a similar app by Python such that at least the following modules are used
beautiful soup
defaultdict
We apparently need
to parse the reputation from the site 'https://stackoverflow.com/users/#user-id#' by Bautiful soup
to store the data by defaultdict
How can you build a similar reputation system as Jon's one by Python?
A:
The screenscraping is easy, if I understand the SO HTML format correctly, e.g., to get my rep (as I'm user 95810):
import urllib
import BeautifulSoup
page = urllib.urlopen('http://stackoverflow.com/users/95810')
soup = BeautifulSoup.BeautifulSoup(page)
therep = str(soup.find(text='Reputation').parent.previous.previous).strip()
print int(therep.replace(',',''))
I'm not sure what you want to do with defaultdict here, though -- what further processing do you desire to perform on this int, that would somehow require storing it in a defaultdict?
|
To build a similar reputation tracker as Jon's by Python
|
Jon Skeet has the following reputation tracker which is built by C#.
I am interested in building a similar app by Python such that at least the following modules are used
beautiful soup
defaultdict
We apparently need
to parse the reputation from the site 'https://stackoverflow.com/users/#user-id#' by Bautiful soup
to store the data by defaultdict
How can you build a similar reputation system as Jon's one by Python?
|
[
"The screenscraping is easy, if I understand the SO HTML format correctly, e.g., to get my rep (as I'm user 95810):\nimport urllib\nimport BeautifulSoup\npage = urllib.urlopen('http://stackoverflow.com/users/95810')\nsoup = BeautifulSoup.BeautifulSoup(page)\ntherep = str(soup.find(text='Reputation').parent.previous.previous).strip()\nprint int(therep.replace(',',''))\n\nI'm not sure what you want to do with defaultdict here, though -- what further processing do you desire to perform on this int, that would somehow require storing it in a defaultdict?\n"
] |
[
4
] |
[] |
[] |
[
"python"
] |
stackoverflow_0001168452_python.txt
|
Q:
Publish feeds using Django
I'm publishing a feed from a Django application.
I subclassed django.contrib.syndication.feeds.Feed, everything works fine, except the date that doesn't get published on the feed.
Here's the method I've created on my Feed class
def item_pubdate(self, item):
return item.date
this method never gets called....
A:
According to the Feed Class Reference in the Django documentation, the item_pubdate field is supposed to return a datetime.datetime object. If item.date is just a DateField and not a DateTimeField, that might be causing the problem. If that is the case you could change the method to make a datetime and then return that.
import datetime
def item_pubdate(self, item):
return datetime.datetime.combine(item.date, datetime.time())
A:
This is how mine is setup, and it is working.
class AllFeed(Feed):
def item_pubdate(self, item):
return item.date
A:
I've been banging my head against this one for a while. It seems that the django rss system need a "datetime" object instead of just the date (since it wants a time zone, and the date object doesn't have a time, let alone a time zone...)
I might be wrong though, but it's something that I've found via the error logs.
|
Publish feeds using Django
|
I'm publishing a feed from a Django application.
I subclassed django.contrib.syndication.feeds.Feed, everything works fine, except the date that doesn't get published on the feed.
Here's the method I've created on my Feed class
def item_pubdate(self, item):
return item.date
this method never gets called....
|
[
"According to the Feed Class Reference in the Django documentation, the item_pubdate field is supposed to return a datetime.datetime object. If item.date is just a DateField and not a DateTimeField, that might be causing the problem. If that is the case you could change the method to make a datetime and then return that.\nimport datetime\ndef item_pubdate(self, item):\n return datetime.datetime.combine(item.date, datetime.time())\n\n",
"This is how mine is setup, and it is working.\nclass AllFeed(Feed):\n def item_pubdate(self, item):\n return item.date\n\n",
"I've been banging my head against this one for a while. It seems that the django rss system need a \"datetime\" object instead of just the date (since it wants a time zone, and the date object doesn't have a time, let alone a time zone...)\nI might be wrong though, but it's something that I've found via the error logs.\n"
] |
[
3,
0,
0
] |
[] |
[] |
[
"django",
"python",
"rss"
] |
stackoverflow_0000945001_django_python_rss.txt
|
Q:
Python Wiki Style Doc Generator
Looking for something like PyDoc that can generate a set of Wiki style pages vs the current HTML ones that export out of PyDoc. I would like to be able to export these in Google Code's Wiki as an extension to the current docs up there now.
A:
Take a look at pydoc.TextDoc. If this contains too little markup, you can inherit from it and make it generate markup according to your wiki's syntax.
A:
Have you taken a look at Sphinx?
|
Python Wiki Style Doc Generator
|
Looking for something like PyDoc that can generate a set of Wiki style pages vs the current HTML ones that export out of PyDoc. I would like to be able to export these in Google Code's Wiki as an extension to the current docs up there now.
|
[
"Take a look at pydoc.TextDoc. If this contains too little markup, you can inherit from it and make it generate markup according to your wiki's syntax.\n",
"Have you taken a look at Sphinx?\n"
] |
[
1,
0
] |
[] |
[] |
[
"documentation",
"pydoc",
"python",
"wiki"
] |
stackoverflow_0001169357_documentation_pydoc_python_wiki.txt
|
Q:
Installing usual libraries inside Google App Engine
How should I install (or where should I put and organize) usual python libraries in Google App Engine.
Some libraries require to be installed using setuptools. How can I install that libraries.
A:
You need to unpack the libraries into a subdirectory of your app, and add the library directory to the Python path in your request handler module. Any steps required by setup scripts, you'll have to execute manually, but there generally aren't any unless the library bundles a native module (which aren't supported on App Engine anyway).
If your library contains many files, it's possible to zip them and use zipimport, but that's somewhat more complex, and has performance implications.
For example, suppose you put a library in lib/mylibrary, under your app's directory. In your request handler module, add the following before any of your other imports:
import os
import sys
sys.path.append(os.path.join(os.path.dirname(__file__), "lib/mylibrary"))
(Note that this assumes that your request handler is in the root directory of your app.)
A:
Most of them can be installed using the pip.
Follow 3 first points from the Google wiki.
|
Installing usual libraries inside Google App Engine
|
How should I install (or where should I put and organize) usual python libraries in Google App Engine.
Some libraries require to be installed using setuptools. How can I install that libraries.
|
[
"You need to unpack the libraries into a subdirectory of your app, and add the library directory to the Python path in your request handler module. Any steps required by setup scripts, you'll have to execute manually, but there generally aren't any unless the library bundles a native module (which aren't supported on App Engine anyway).\nIf your library contains many files, it's possible to zip them and use zipimport, but that's somewhat more complex, and has performance implications.\nFor example, suppose you put a library in lib/mylibrary, under your app's directory. In your request handler module, add the following before any of your other imports:\nimport os\nimport sys\nsys.path.append(os.path.join(os.path.dirname(__file__), \"lib/mylibrary\"))\n\n(Note that this assumes that your request handler is in the root directory of your app.)\n",
"Most of them can be installed using the pip. \nFollow 3 first points from the Google wiki.\n"
] |
[
5,
3
] |
[] |
[] |
[
"google_app_engine",
"python"
] |
stackoverflow_0001166685_google_app_engine_python.txt
|
Q:
Intercept slice operations in Python
I want to imitate a normal python list, except whenever elements are added or removed via slicing, I want to 'save' the list. Is this possible? This was my attempt but it will never print 'saving'.
class InterceptedList(list):
def addSave(func):
def newfunc(self, *args):
func(self, *args)
print 'saving'
return newfunc
__setslice__ = addSave(list.__setslice__)
__delslice__ = addSave(list.__delslice__)
>>> l = InterceptedList()
>>> l.extend([1,2,3,4])
>>> l
[1, 2, 3, 4]
>>> l[3:] = [5] # note: 'saving' is not printed
>>> l
[1, 2, 3, 5]
This does work for other methods like append and extend, just not for the slice operations.
EDIT: The real problem is I'm using Jython and not Python and forgot it. The comments on the question are correct. This code does work fine in Python (2.6). However, the code nor the answers work in Jython.
A:
From the Python 3 docs:
__getslice__(), __setslice__() and __delslice__() were killed.
The syntax a[i:j] now translates to a.__getitem__(slice(i, j))
(or __setitem__() or __delitem__(), when used as an assignment
or deletion target, respectively).
A:
"setslice" and "delslice" are deprecated, if you want to do the interception you need to work with python slice objects passed to "setitem" and "delitem". If you want to intecept both slices and ordinary accesses this code works perfectly in python 2.6.2.
class InterceptedList(list):
def addSave(func):
def newfunc(self, *args):
func(self, *args)
print 'saving'
return newfunc
def __setitem__(self, key, value):
print 'saving'
list.__setitem__(self, key, value)
def __delitem__(self, key):
print 'saving'
list.__delitem__(self, key)
A:
That's enough speculation. Let's start using facts instead shall we?
As far as I can tell, the bottom line is that you must override both set of methods.
If you want to implement undo/redo you probably should try using undo stack and set of actions that can do()/undo() themselves.
Code
import profile
import sys
print sys.version
class InterceptedList(list):
def addSave(func):
def newfunc(self, *args):
func(self, *args)
print 'saving'
return newfunc
__setslice__ = addSave(list.__setslice__)
__delslice__ = addSave(list.__delslice__)
class InterceptedList2(list):
def __setitem__(self, key, value):
print 'saving'
list.__setitem__(self, key, value)
def __delitem__(self, key):
print 'saving'
list.__delitem__(self, key)
print("------------Testing setslice------------------")
l = InterceptedList()
l.extend([1,2,3,4])
profile.run("l[3:] = [5]")
profile.run("l[2:6] = [12, 4]")
profile.run("l[-1:] = [42]")
profile.run("l[::2] = [6,6]")
print("-----------Testing setitem--------------------")
l2 = InterceptedList2()
l2.extend([1,2,3,4])
profile.run("l2[3:] = [5]")
profile.run("l2[2:6] = [12,4]")
profile.run("l2[-1:] = [42]")
profile.run("l2[::2] = [6,6]")
Jython 2.5
C:\Users\wuu-local.pyza\Desktop>c:\jython2.5.0\jython.bat intercept.py
2.5.0 (Release_2_5_0:6476, Jun 16 2009, 13:33:26)
[Java HotSpot(TM) Client VM (Sun Microsystems Inc.)]
------------Testing setslice------------------
saving
3 function calls in 0.035 CPU seconds
Ordered by: standard name
ncalls tottime percall cumtime percall filename:lineno(function)
1 0.000 0.000 0.000 0.000 <string>:0(<module>)
1 0.000 0.000 0.000 0.000 intercept.py:9(newfunc)
1 0.034 0.034 0.035 0.035 profile:0(l[3:] = [5])
0 0.000 0.000 profile:0(profiler)
saving
3 function calls in 0.005 CPU seconds
Ordered by: standard name
ncalls tottime percall cumtime percall filename:lineno(function)
1 0.000 0.000 0.001 0.001 <string>:0(<module>)
1 0.001 0.001 0.001 0.001 intercept.py:9(newfunc)
1 0.004 0.004 0.005 0.005 profile:0(l[2:6] = [12, 4])
0 0.000 0.000 profile:0(profiler)
saving
3 function calls in 0.012 CPU seconds
Ordered by: standard name
ncalls tottime percall cumtime percall filename:lineno(function)
1 0.000 0.000 0.000 0.000 <string>:0(<module>)
1 0.000 0.000 0.000 0.000 intercept.py:9(newfunc)
1 0.012 0.012 0.012 0.012 profile:0(l[-1:] = [42])
0 0.000 0.000 profile:0(profiler)
2 function calls in 0.004 CPU seconds
Ordered by: standard name
ncalls tottime percall cumtime percall filename:lineno(function)
1 0.000 0.000 0.000 0.000 <string>:0(<module>)
1 0.004 0.004 0.004 0.004 profile:0(l[::2] = [6,6])
0 0.000 0.000 profile:0(profiler)
-----------Testing setitem--------------------
2 function calls in 0.004 CPU seconds
Ordered by: standard name
ncalls tottime percall cumtime percall filename:lineno(function)
1 0.000 0.000 0.000 0.000 <string>:0(<module>)
1 0.004 0.004 0.004 0.004 profile:0(l2[3:] = [5])
0 0.000 0.000 profile:0(profiler)
2 function calls in 0.006 CPU seconds
Ordered by: standard name
ncalls tottime percall cumtime percall filename:lineno(function)
1 0.000 0.000 0.000 0.000 <string>:0(<module>)
1 0.006 0.006 0.006 0.006 profile:0(l2[2:6] = [12,4])
0 0.000 0.000 profile:0(profiler)
2 function calls in 0.004 CPU seconds
Ordered by: standard name
ncalls tottime percall cumtime percall filename:lineno(function)
1 0.000 0.000 0.000 0.000 <string>:0(<module>)
1 0.004 0.004 0.004 0.004 profile:0(l2[-1:] = [42])
0 0.000 0.000 profile:0(profiler)
saving
3 function calls in 0.007 CPU seconds
Ordered by: standard name
ncalls tottime percall cumtime percall filename:lineno(function)
1 0.000 0.000 0.002 0.002 <string>:0(<module>)
1 0.001 0.001 0.001 0.001 intercept.py:20(__setitem__)
1 0.005 0.005 0.007 0.007 profile:0(l2[::2] = [6,6])
0 0.000 0.000 profile:0(profiler)
Python 2.6.2
C:\Users\wuu-local.pyza\Desktop>python intercept.py
2.6 (r26:66721, Oct 2 2008, 11:35:03) [MSC v.1500 32 bit (Intel)]
------------Testing setslice------------------
saving
4 function calls in 0.002 CPU seconds
Ordered by: standard name
ncalls tottime percall cumtime percall filename:lineno(function)
1 0.002 0.002 0.002 0.002 :0(setprofile)
1 0.000 0.000 0.000 0.000 <string>:1(<module>)
1 0.000 0.000 0.000 0.000 intercept.py:9(newfunc)
1 0.000 0.000 0.002 0.002 profile:0(l[3:] = [5])
0 0.000 0.000 profile:0(profiler)
saving
4 function calls in 0.000 CPU seconds
Ordered by: standard name
ncalls tottime percall cumtime percall filename:lineno(function)
1 0.000 0.000 0.000 0.000 :0(setprofile)
1 0.000 0.000 0.000 0.000 <string>:1(<module>)
1 0.000 0.000 0.000 0.000 intercept.py:9(newfunc)
1 0.000 0.000 0.000 0.000 profile:0(l[2:6] = [12, 4])
0 0.000 0.000 profile:0(profiler)
saving
4 function calls in 0.000 CPU seconds
Ordered by: standard name
ncalls tottime percall cumtime percall filename:lineno(function)
1 0.000 0.000 0.000 0.000 :0(setprofile)
1 0.000 0.000 0.000 0.000 <string>:1(<module>)
1 0.000 0.000 0.000 0.000 intercept.py:9(newfunc)
1 0.000 0.000 0.000 0.000 profile:0(l[-1:] = [42])
0 0.000 0.000 profile:0(profiler)
3 function calls in 0.000 CPU seconds
Ordered by: standard name
ncalls tottime percall cumtime percall filename:lineno(function)
1 0.000 0.000 0.000 0.000 :0(setprofile)
1 0.000 0.000 0.000 0.000 <string>:1(<module>)
1 0.000 0.000 0.000 0.000 profile:0(l[::2] = [6,6])
0 0.000 0.000 profile:0(profiler)
-----------Testing setitem--------------------
3 function calls in 0.000 CPU seconds
Ordered by: standard name
ncalls tottime percall cumtime percall filename:lineno(function)
1 0.000 0.000 0.000 0.000 :0(setprofile)
1 0.000 0.000 0.000 0.000 <string>:1(<module>)
1 0.000 0.000 0.000 0.000 profile:0(l2[3:] = [5])
0 0.000 0.000 profile:0(profiler)
3 function calls in 0.000 CPU seconds
Ordered by: standard name
ncalls tottime percall cumtime percall filename:lineno(function)
1 0.000 0.000 0.000 0.000 :0(setprofile)
1 0.000 0.000 0.000 0.000 <string>:1(<module>)
1 0.000 0.000 0.000 0.000 profile:0(l2[2:6] = [12,4])
0 0.000 0.000 profile:0(profiler)
3 function calls in 0.000 CPU seconds
Ordered by: standard name
ncalls tottime percall cumtime percall filename:lineno(function)
1 0.000 0.000 0.000 0.000 :0(setprofile)
1 0.000 0.000 0.000 0.000 <string>:1(<module>)
1 0.000 0.000 0.000 0.000 profile:0(l2[-1:] = [42])
0 0.000 0.000 profile:0(profiler)
saving
4 function calls in 0.003 CPU seconds
Ordered by: standard name
ncalls tottime percall cumtime percall filename:lineno(function)
1 0.000 0.000 0.000 0.000 :0(setprofile)
1 0.000 0.000 0.003 0.003 <string>:1(<module>)
1 0.002 0.002 0.002 0.002 intercept.py:20(__setitem__)
1 0.000 0.000 0.003 0.003 profile:0(l2[::2] = [6,6])
0 0.000 0.000 profile:0(profiler)
A:
the circumstances where __getslice__ and __setslice__ are called are pretty narrow. Specifically, slicing only occurs when you use a regular slice, where the first and end elements are mentioned exactly once. for any other slice syntax, or no slices at all, __getitem__ or __setitem__ is called.
|
Intercept slice operations in Python
|
I want to imitate a normal python list, except whenever elements are added or removed via slicing, I want to 'save' the list. Is this possible? This was my attempt but it will never print 'saving'.
class InterceptedList(list):
def addSave(func):
def newfunc(self, *args):
func(self, *args)
print 'saving'
return newfunc
__setslice__ = addSave(list.__setslice__)
__delslice__ = addSave(list.__delslice__)
>>> l = InterceptedList()
>>> l.extend([1,2,3,4])
>>> l
[1, 2, 3, 4]
>>> l[3:] = [5] # note: 'saving' is not printed
>>> l
[1, 2, 3, 5]
This does work for other methods like append and extend, just not for the slice operations.
EDIT: The real problem is I'm using Jython and not Python and forgot it. The comments on the question are correct. This code does work fine in Python (2.6). However, the code nor the answers work in Jython.
|
[
"From the Python 3 docs:\n__getslice__(), __setslice__() and __delslice__() were killed. \nThe syntax a[i:j] now translates to a.__getitem__(slice(i, j)) \n(or __setitem__() or __delitem__(), when used as an assignment \nor deletion target, respectively).\n\n",
"\"setslice\" and \"delslice\" are deprecated, if you want to do the interception you need to work with python slice objects passed to \"setitem\" and \"delitem\". If you want to intecept both slices and ordinary accesses this code works perfectly in python 2.6.2.\nclass InterceptedList(list):\n\ndef addSave(func):\n def newfunc(self, *args):\n func(self, *args)\n print 'saving'\n return newfunc\n\ndef __setitem__(self, key, value):\n print 'saving'\n list.__setitem__(self, key, value)\n\ndef __delitem__(self, key):\n print 'saving'\n list.__delitem__(self, key)\n\n",
"That's enough speculation. Let's start using facts instead shall we?\nAs far as I can tell, the bottom line is that you must override both set of methods. \nIf you want to implement undo/redo you probably should try using undo stack and set of actions that can do()/undo() themselves. \nCode\nimport profile\nimport sys\n\nprint sys.version\n\nclass InterceptedList(list):\n\n def addSave(func):\n def newfunc(self, *args):\n func(self, *args)\n print 'saving'\n return newfunc\n\n __setslice__ = addSave(list.__setslice__)\n __delslice__ = addSave(list.__delslice__)\n\n\nclass InterceptedList2(list):\n\n def __setitem__(self, key, value):\n print 'saving'\n list.__setitem__(self, key, value)\n\n def __delitem__(self, key):\n print 'saving'\n list.__delitem__(self, key)\n\n\nprint(\"------------Testing setslice------------------\")\nl = InterceptedList()\nl.extend([1,2,3,4])\nprofile.run(\"l[3:] = [5]\")\nprofile.run(\"l[2:6] = [12, 4]\")\nprofile.run(\"l[-1:] = [42]\")\nprofile.run(\"l[::2] = [6,6]\")\n\nprint(\"-----------Testing setitem--------------------\")\nl2 = InterceptedList2()\nl2.extend([1,2,3,4])\nprofile.run(\"l2[3:] = [5]\")\nprofile.run(\"l2[2:6] = [12,4]\")\nprofile.run(\"l2[-1:] = [42]\")\nprofile.run(\"l2[::2] = [6,6]\")\n\nJython 2.5\nC:\\Users\\wuu-local.pyza\\Desktop>c:\\jython2.5.0\\jython.bat intercept.py\n2.5.0 (Release_2_5_0:6476, Jun 16 2009, 13:33:26)\n[Java HotSpot(TM) Client VM (Sun Microsystems Inc.)]\n------------Testing setslice------------------\nsaving\n 3 function calls in 0.035 CPU seconds\n\n Ordered by: standard name\n\n ncalls tottime percall cumtime percall filename:lineno(function)\n 1 0.000 0.000 0.000 0.000 <string>:0(<module>)\n 1 0.000 0.000 0.000 0.000 intercept.py:9(newfunc)\n 1 0.034 0.034 0.035 0.035 profile:0(l[3:] = [5])\n 0 0.000 0.000 profile:0(profiler)\n\n\nsaving\n 3 function calls in 0.005 CPU seconds\n\n Ordered by: standard name\n\n ncalls tottime percall cumtime percall filename:lineno(function)\n 1 0.000 0.000 0.001 0.001 <string>:0(<module>)\n 1 0.001 0.001 0.001 0.001 intercept.py:9(newfunc)\n 1 0.004 0.004 0.005 0.005 profile:0(l[2:6] = [12, 4])\n 0 0.000 0.000 profile:0(profiler)\n\n\nsaving\n 3 function calls in 0.012 CPU seconds\n\n Ordered by: standard name\n\n ncalls tottime percall cumtime percall filename:lineno(function)\n 1 0.000 0.000 0.000 0.000 <string>:0(<module>)\n 1 0.000 0.000 0.000 0.000 intercept.py:9(newfunc)\n 1 0.012 0.012 0.012 0.012 profile:0(l[-1:] = [42])\n 0 0.000 0.000 profile:0(profiler)\n\n\n 2 function calls in 0.004 CPU seconds\n\n Ordered by: standard name\n\n ncalls tottime percall cumtime percall filename:lineno(function)\n 1 0.000 0.000 0.000 0.000 <string>:0(<module>)\n 1 0.004 0.004 0.004 0.004 profile:0(l[::2] = [6,6])\n 0 0.000 0.000 profile:0(profiler)\n\n\n-----------Testing setitem--------------------\n 2 function calls in 0.004 CPU seconds\n\n Ordered by: standard name\n\n ncalls tottime percall cumtime percall filename:lineno(function)\n 1 0.000 0.000 0.000 0.000 <string>:0(<module>)\n 1 0.004 0.004 0.004 0.004 profile:0(l2[3:] = [5])\n 0 0.000 0.000 profile:0(profiler)\n\n\n 2 function calls in 0.006 CPU seconds\n\n Ordered by: standard name\n\n ncalls tottime percall cumtime percall filename:lineno(function)\n 1 0.000 0.000 0.000 0.000 <string>:0(<module>)\n 1 0.006 0.006 0.006 0.006 profile:0(l2[2:6] = [12,4])\n 0 0.000 0.000 profile:0(profiler)\n\n\n 2 function calls in 0.004 CPU seconds\n\n Ordered by: standard name\n\n ncalls tottime percall cumtime percall filename:lineno(function)\n 1 0.000 0.000 0.000 0.000 <string>:0(<module>)\n 1 0.004 0.004 0.004 0.004 profile:0(l2[-1:] = [42])\n 0 0.000 0.000 profile:0(profiler)\n\n\nsaving\n 3 function calls in 0.007 CPU seconds\n\n Ordered by: standard name\n\n ncalls tottime percall cumtime percall filename:lineno(function)\n 1 0.000 0.000 0.002 0.002 <string>:0(<module>)\n 1 0.001 0.001 0.001 0.001 intercept.py:20(__setitem__)\n 1 0.005 0.005 0.007 0.007 profile:0(l2[::2] = [6,6])\n 0 0.000 0.000 profile:0(profiler)\n\nPython 2.6.2\nC:\\Users\\wuu-local.pyza\\Desktop>python intercept.py\n2.6 (r26:66721, Oct 2 2008, 11:35:03) [MSC v.1500 32 bit (Intel)]\n------------Testing setslice------------------\nsaving\n 4 function calls in 0.002 CPU seconds\n\n Ordered by: standard name\n\n ncalls tottime percall cumtime percall filename:lineno(function)\n 1 0.002 0.002 0.002 0.002 :0(setprofile)\n 1 0.000 0.000 0.000 0.000 <string>:1(<module>)\n 1 0.000 0.000 0.000 0.000 intercept.py:9(newfunc)\n 1 0.000 0.000 0.002 0.002 profile:0(l[3:] = [5])\n 0 0.000 0.000 profile:0(profiler)\n\n\nsaving\n 4 function calls in 0.000 CPU seconds\n\n Ordered by: standard name\n\n ncalls tottime percall cumtime percall filename:lineno(function)\n 1 0.000 0.000 0.000 0.000 :0(setprofile)\n 1 0.000 0.000 0.000 0.000 <string>:1(<module>)\n 1 0.000 0.000 0.000 0.000 intercept.py:9(newfunc)\n 1 0.000 0.000 0.000 0.000 profile:0(l[2:6] = [12, 4])\n 0 0.000 0.000 profile:0(profiler)\n\n\nsaving\n 4 function calls in 0.000 CPU seconds\n\n Ordered by: standard name\n\n ncalls tottime percall cumtime percall filename:lineno(function)\n 1 0.000 0.000 0.000 0.000 :0(setprofile)\n 1 0.000 0.000 0.000 0.000 <string>:1(<module>)\n 1 0.000 0.000 0.000 0.000 intercept.py:9(newfunc)\n 1 0.000 0.000 0.000 0.000 profile:0(l[-1:] = [42])\n 0 0.000 0.000 profile:0(profiler)\n\n\n 3 function calls in 0.000 CPU seconds\n\n Ordered by: standard name\n\n ncalls tottime percall cumtime percall filename:lineno(function)\n 1 0.000 0.000 0.000 0.000 :0(setprofile)\n 1 0.000 0.000 0.000 0.000 <string>:1(<module>)\n 1 0.000 0.000 0.000 0.000 profile:0(l[::2] = [6,6])\n 0 0.000 0.000 profile:0(profiler)\n\n\n-----------Testing setitem--------------------\n 3 function calls in 0.000 CPU seconds\n\n Ordered by: standard name\n\n ncalls tottime percall cumtime percall filename:lineno(function)\n 1 0.000 0.000 0.000 0.000 :0(setprofile)\n 1 0.000 0.000 0.000 0.000 <string>:1(<module>)\n 1 0.000 0.000 0.000 0.000 profile:0(l2[3:] = [5])\n 0 0.000 0.000 profile:0(profiler)\n\n\n 3 function calls in 0.000 CPU seconds\n\n Ordered by: standard name\n\n ncalls tottime percall cumtime percall filename:lineno(function)\n 1 0.000 0.000 0.000 0.000 :0(setprofile)\n 1 0.000 0.000 0.000 0.000 <string>:1(<module>)\n 1 0.000 0.000 0.000 0.000 profile:0(l2[2:6] = [12,4])\n 0 0.000 0.000 profile:0(profiler)\n\n\n 3 function calls in 0.000 CPU seconds\n\n Ordered by: standard name\n\n ncalls tottime percall cumtime percall filename:lineno(function)\n 1 0.000 0.000 0.000 0.000 :0(setprofile)\n 1 0.000 0.000 0.000 0.000 <string>:1(<module>)\n 1 0.000 0.000 0.000 0.000 profile:0(l2[-1:] = [42])\n 0 0.000 0.000 profile:0(profiler)\n\n\nsaving\n 4 function calls in 0.003 CPU seconds\n\n Ordered by: standard name\n\n ncalls tottime percall cumtime percall filename:lineno(function)\n 1 0.000 0.000 0.000 0.000 :0(setprofile)\n 1 0.000 0.000 0.003 0.003 <string>:1(<module>)\n 1 0.002 0.002 0.002 0.002 intercept.py:20(__setitem__)\n 1 0.000 0.000 0.003 0.003 profile:0(l2[::2] = [6,6])\n 0 0.000 0.000 profile:0(profiler)\n\n",
"the circumstances where __getslice__ and __setslice__ are called are pretty narrow. Specifically, slicing only occurs when you use a regular slice, where the first and end elements are mentioned exactly once. for any other slice syntax, or no slices at all, __getitem__ or __setitem__ is called. \n"
] |
[
5,
5,
5,
4
] |
[] |
[] |
[
"intercept",
"jython",
"methods",
"python",
"slice"
] |
stackoverflow_0001166839_intercept_jython_methods_python_slice.txt
|
Q:
Bug with Python UTF-16 output and Windows line endings?
With this code:
test.py
import sys
import codecs
sys.stdout = codecs.getwriter('utf-16')(sys.stdout)
print "test1"
print "test2"
Then I run it as:
test.py > test.txt
In Python 2.6 on Windows 2000, I'm finding that the newline characters are being output as the byte sequence \x0D\x0A\x00 which of course is wrong for UTF-16.
Am I missing something, or is this a bug?
A:
The newline translation is happening inside the stdout file. You're writing "test1\n" to sys.stdout (a StreamWriter). StreamWriter translates this to "t\x00e\x00s\x00t\x001\x00\n\x00", and sends it to the real file, the original sys.stderr.
That file doesn't know that you've converted the data to UTF-16; all it knows is that any \n values in the output stream need to be converted to \x0D\x0A, which results in the output you're seeing.
A:
Try this:
import sys
import codecs
if sys.platform == "win32":
import os, msvcrt
msvcrt.setmode(sys.stdout.fileno(), os.O_BINARY)
class CRLFWrapper(object):
def __init__(self, output):
self.output = output
def write(self, s):
self.output.write(s.replace("\n", "\r\n"))
def __getattr__(self, key):
return getattr(self.output, key)
sys.stdout = CRLFWrapper(codecs.getwriter('utf-16')(sys.stdout))
print "test1"
print "test2"
A:
I've found two solutions so far, but not one that gives output of UTF-16 with Windows-style line endings.
First, to redirect Python print statements to a file with UTF-16 encoding (output Unix style line-endings):
import sys
import codecs
sys.stdout = codecs.open("outputfile.txt", "w", encoding="utf16")
print "test1"
print "test2"
Second, to redirect to stdout with UTF-16 encoding, without line-ending translation corruption (output Unix style line-endings) (thanks to this ActiveState recipe):
import sys
import codecs
sys.stdout = codecs.getwriter('utf-16')(sys.stdout)
if sys.platform == "win32":
import os, msvcrt
msvcrt.setmode(sys.stdout.fileno(), os.O_BINARY)
print "test1"
print "test2"
|
Bug with Python UTF-16 output and Windows line endings?
|
With this code:
test.py
import sys
import codecs
sys.stdout = codecs.getwriter('utf-16')(sys.stdout)
print "test1"
print "test2"
Then I run it as:
test.py > test.txt
In Python 2.6 on Windows 2000, I'm finding that the newline characters are being output as the byte sequence \x0D\x0A\x00 which of course is wrong for UTF-16.
Am I missing something, or is this a bug?
|
[
"The newline translation is happening inside the stdout file. You're writing \"test1\\n\" to sys.stdout (a StreamWriter). StreamWriter translates this to \"t\\x00e\\x00s\\x00t\\x001\\x00\\n\\x00\", and sends it to the real file, the original sys.stderr.\nThat file doesn't know that you've converted the data to UTF-16; all it knows is that any \\n values in the output stream need to be converted to \\x0D\\x0A, which results in the output you're seeing.\n",
"Try this:\nimport sys\nimport codecs\n\nif sys.platform == \"win32\":\n import os, msvcrt\n msvcrt.setmode(sys.stdout.fileno(), os.O_BINARY)\n\nclass CRLFWrapper(object):\n def __init__(self, output):\n self.output = output\n\n def write(self, s):\n self.output.write(s.replace(\"\\n\", \"\\r\\n\"))\n\n def __getattr__(self, key):\n return getattr(self.output, key)\n\nsys.stdout = CRLFWrapper(codecs.getwriter('utf-16')(sys.stdout))\nprint \"test1\"\nprint \"test2\"\n\n",
"I've found two solutions so far, but not one that gives output of UTF-16 with Windows-style line endings.\nFirst, to redirect Python print statements to a file with UTF-16 encoding (output Unix style line-endings):\nimport sys\nimport codecs\n\nsys.stdout = codecs.open(\"outputfile.txt\", \"w\", encoding=\"utf16\")\n\nprint \"test1\"\nprint \"test2\"\n\nSecond, to redirect to stdout with UTF-16 encoding, without line-ending translation corruption (output Unix style line-endings) (thanks to this ActiveState recipe):\nimport sys\nimport codecs\n\nsys.stdout = codecs.getwriter('utf-16')(sys.stdout)\n\nif sys.platform == \"win32\":\n import os, msvcrt\n msvcrt.setmode(sys.stdout.fileno(), os.O_BINARY)\n\nprint \"test1\"\nprint \"test2\"\n\n"
] |
[
3,
3,
0
] |
[] |
[] |
[
"python",
"utf_16",
"windows"
] |
stackoverflow_0001169742_python_utf_16_windows.txt
|
Q:
Error when using a Python constructor
class fileDetails :
def __init__(self,host,usr,pwd,database):
self.host=host
self.usr.usr
self.pwd=pwd
self.database=database
def __init__(self,connection,sql,path):
self.connection=mysql_connection()
self.sql=sql
self.path=path
If I use the constructor then it gives an error:
onnetction = fileDetails('localhost',"root","",'bulsorbit')
TypeError: __init__() takes exactly 4 arguments (5 given)
A:
The overloading of the constructor (or any other function) is not allowed in python. So you cannot define two __init__ functions for your class.
You can have a look to this post or this one
The main ideas are to use default values or to create 'alternate constructors' or to check the number and the type of your args in order to choose which method to apply.
def __init__(self, **args):
Then args will be a dictionary containing all the parameters. So you will be able to make the difference between
connection = fileDetails(host='localhost',usr="root",pwd="",database='bulsorbit')
and
connection = fileDetails(connection="...",sql="...",path="...")
A:
Define a single constructor with optional arguments.
def __init__(self,host='host',usr='user',pwd='pwd',database='db',connection=None,sql=None,path=None):
if connection:
# however you want to store your connection
self.sql=sql
self.path=path
else:
self.host=host
self.usr.usr
self.pwd=pwd
self.database=database
Or something of the sort.
A:
In Python the functions in a class are stored internally in a dictionary (remember that constructors are just regular functions), and so only one function of the same name can exist. Therefore, when defining more than one functions with the same name the last one will overwrite all the previously defined ones and you'll end up with only one function.
I suggest you look into keyword and default arguments to see the proper way of achieving what you want.
A:
maybe you can use len() to choose the right branch:
class Foo(object):
def __init__(self, *args):
if len(args) == 4: # network
self.host = args[0]
self.user = args[1]
self.pwd = args[2]
self.database = args[3]
elif len(args) == 3: # database
self.connection = mysql_connection() # maybe it's args[0]?
self.sql = args[1]
self.path = args[2]
def main():
foo = Foo('localhost',"root","",'bulsorbit')
print foo.host
if __name__ == "__main__":
main()
# output
# localhost
but, sine Explicit is better than implicit. maybe this is workable too:
class Foo(object):
def __init__(self, initdata):
if initdata['style'] == 'network':
self.host = initdata['host']
self.usr = initdata['usr']
self.pwd = initdata['pwd']
self.database = initdata['database']
elif initdata[style] == 'database':
self.connection = mysql_connection()
self.sql = initdata['sql']
self.path = initdata['path']
def main():
data = dict({'style': 'network',
'host': 'localhost',
'usr': 'root',
'pwd': '',
'database': 'database'})
foo = Foo(data)
print foo.host
if __name__ == "__main__":
main()
# output
# localhost
A:
Here's one way to achieve this:
class FileDetails:
def __init__(self, *args, **kwargs):
if len(args) == 3:
self.conn, self.sql, self.path = args
elif len(args) == 4:
self.host, self.usr, self.pw, self.db = args
else:
# handle appropriately
fd1 = FileDetail('connstring', 'select * from foo', '/some/path')
print fd1.conn, fd1.sql, fd1.path
fd2 = FileDetail('host', 'user', 'pass', 'somedb')
print fd2.conn, fd2.usr, fd2.pw, fd2.db
Of course, you should do the appropriate type checking and error handling in the constructor.
A:
On the side note: if you really, really, reallllllyyy must do JiP (Java in Python) then multiple dispatch methods are possible with some additional code eg. here and even beter: here by BDFL.
Personally I try to avoid using them.
|
Error when using a Python constructor
|
class fileDetails :
def __init__(self,host,usr,pwd,database):
self.host=host
self.usr.usr
self.pwd=pwd
self.database=database
def __init__(self,connection,sql,path):
self.connection=mysql_connection()
self.sql=sql
self.path=path
If I use the constructor then it gives an error:
onnetction = fileDetails('localhost',"root","",'bulsorbit')
TypeError: __init__() takes exactly 4 arguments (5 given)
|
[
"The overloading of the constructor (or any other function) is not allowed in python. So you cannot define two __init__ functions for your class.\nYou can have a look to this post or this one\nThe main ideas are to use default values or to create 'alternate constructors' or to check the number and the type of your args in order to choose which method to apply.\ndef __init__(self, **args):\n\nThen args will be a dictionary containing all the parameters. So you will be able to make the difference between\nconnection = fileDetails(host='localhost',usr=\"root\",pwd=\"\",database='bulsorbit')\n\nand\nconnection = fileDetails(connection=\"...\",sql=\"...\",path=\"...\")\n\n",
"Define a single constructor with optional arguments.\ndef __init__(self,host='host',usr='user',pwd='pwd',database='db',connection=None,sql=None,path=None):\n if connection:\n # however you want to store your connection\n self.sql=sql\n self.path=path\n else:\n self.host=host\n self.usr.usr\n self.pwd=pwd\n self.database=database\n\nOr something of the sort.\n",
"In Python the functions in a class are stored internally in a dictionary (remember that constructors are just regular functions), and so only one function of the same name can exist. Therefore, when defining more than one functions with the same name the last one will overwrite all the previously defined ones and you'll end up with only one function.\nI suggest you look into keyword and default arguments to see the proper way of achieving what you want.\n",
"maybe you can use len() to choose the right branch:\nclass Foo(object):\n def __init__(self, *args):\n if len(args) == 4: # network\n self.host = args[0]\n self.user = args[1]\n self.pwd = args[2]\n self.database = args[3]\n elif len(args) == 3: # database\n self.connection = mysql_connection() # maybe it's args[0]?\n self.sql = args[1]\n self.path = args[2]\n\ndef main():\n\n foo = Foo('localhost',\"root\",\"\",'bulsorbit')\n print foo.host\nif __name__ == \"__main__\":\n main()\n# output\n# localhost\n\nbut, sine Explicit is better than implicit. maybe this is workable too:\nclass Foo(object):\n def __init__(self, initdata):\n if initdata['style'] == 'network':\n self.host = initdata['host']\n self.usr = initdata['usr']\n self.pwd = initdata['pwd']\n self.database = initdata['database']\n elif initdata[style] == 'database':\n self.connection = mysql_connection()\n self.sql = initdata['sql']\n self.path = initdata['path']\ndef main():\n data = dict({'style': 'network',\n 'host': 'localhost',\n 'usr': 'root',\n 'pwd': '',\n 'database': 'database'})\n foo = Foo(data)\n print foo.host\nif __name__ == \"__main__\":\n main()\n# output\n# localhost\n\n",
"Here's one way to achieve this:\nclass FileDetails:\n def __init__(self, *args, **kwargs):\n if len(args) == 3:\n self.conn, self.sql, self.path = args\n elif len(args) == 4:\n self.host, self.usr, self.pw, self.db = args\n else:\n # handle appropriately\n\nfd1 = FileDetail('connstring', 'select * from foo', '/some/path')\nprint fd1.conn, fd1.sql, fd1.path\n\nfd2 = FileDetail('host', 'user', 'pass', 'somedb')\nprint fd2.conn, fd2.usr, fd2.pw, fd2.db\n\nOf course, you should do the appropriate type checking and error handling in the constructor.\n",
"On the side note: if you really, really, reallllllyyy must do JiP (Java in Python) then multiple dispatch methods are possible with some additional code eg. here and even beter: here by BDFL.\nPersonally I try to avoid using them. \n"
] |
[
10,
4,
1,
1,
0,
0
] |
[] |
[] |
[
"constructor",
"python"
] |
stackoverflow_0001170731_constructor_python.txt
|
Q:
Fit algorithm does not accept my data
I'm using the algorithm described here to fit Gaussian bell curves to my data.
If I generate my data array with:
x=linspace(1.,100.,100)
data= 17*exp(-((x-10)/3)**2)
everything works fine.
But if I read the data from a text file using
file = open("d:\\test7.txt")
arr=[]
data=[]
def column(matrix,i):
return [row[i] for row in matrix]
for line in file.readlines():
numbers=map(float, line.split())
arr.append(numbers)
data = column(arr,300)
x=linspace(1.,115.,115)
I get the error message:
Traceback (most recent call last):
File "readmatrix.py", line 60, in <module> fit(f, [mu, sigma, height], data)
File "readmatrix.py", line 42, in fit if x is None: x = arange(y.shape[0])
AttributeError: 'list' object has no attribute 'shape'
As far as I can see, the values included in data are correct, it looks like:
[0.108032, 0.86181600000000003, 1.386169, 3.2790530000000002, ... ]
Has someone a clue what I am doing wrong?
Thanks!
A:
The fit function expects the data as a numpy Array (which has a shape attribute) and not a list (which does not), hence the AttributeError.
Convert your data:
def column(matrix,i):
return numpy.asarray([row[i] for row in matrix])
A:
The solution of balpha is not correct; the solution is simply to convert my list to a numpy array via numpy.array.
Thanks for giving me a hint!
|
Fit algorithm does not accept my data
|
I'm using the algorithm described here to fit Gaussian bell curves to my data.
If I generate my data array with:
x=linspace(1.,100.,100)
data= 17*exp(-((x-10)/3)**2)
everything works fine.
But if I read the data from a text file using
file = open("d:\\test7.txt")
arr=[]
data=[]
def column(matrix,i):
return [row[i] for row in matrix]
for line in file.readlines():
numbers=map(float, line.split())
arr.append(numbers)
data = column(arr,300)
x=linspace(1.,115.,115)
I get the error message:
Traceback (most recent call last):
File "readmatrix.py", line 60, in <module> fit(f, [mu, sigma, height], data)
File "readmatrix.py", line 42, in fit if x is None: x = arange(y.shape[0])
AttributeError: 'list' object has no attribute 'shape'
As far as I can see, the values included in data are correct, it looks like:
[0.108032, 0.86181600000000003, 1.386169, 3.2790530000000002, ... ]
Has someone a clue what I am doing wrong?
Thanks!
|
[
"The fit function expects the data as a numpy Array (which has a shape attribute) and not a list (which does not), hence the AttributeError.\nConvert your data:\ndef column(matrix,i):\n return numpy.asarray([row[i] for row in matrix])\n\n",
"The solution of balpha is not correct; the solution is simply to convert my list to a numpy array via numpy.array.\nThanks for giving me a hint!\n"
] |
[
4,
4
] |
[] |
[] |
[
"arrays",
"file_io",
"python"
] |
stackoverflow_0001170962_arrays_file_io_python.txt
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.