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:
Python - List of Strings to Java
I'm getting a list of strings from python code and need to read it in Java. When trying to read it, i get the hashCode
[Ljava.lang.Object;@7cf1bb78
I want to read the values in a list. In python my return is something like
return SUCCESS(OK, params={'data':nameList()})
How would I read this in Java and print the contents not the hashCode. Currently I'm doing like
Object getNames = new Object();
getName = getNameList(); // This is thru Apache XML RPC Client
System.out.println(getName);
Any help or suggestions?
A:
You already have what you want. Try System.out.println(java.util.Arrays.toString(getName)); (the default toString() for an array in Java is not very useful).
A:
The usual way to print out each item in a Java array would be something like:
for (Object name: (Object[]) getNameList()) {
System.out.println(name);
}
But I suspect from your response to Aaron Digulla that (as he says) you're getting an empty array back. Try printing it out on the Python side and see if there's anything in it.
|
Python - List of Strings to Java
|
I'm getting a list of strings from python code and need to read it in Java. When trying to read it, i get the hashCode
[Ljava.lang.Object;@7cf1bb78
I want to read the values in a list. In python my return is something like
return SUCCESS(OK, params={'data':nameList()})
How would I read this in Java and print the contents not the hashCode. Currently I'm doing like
Object getNames = new Object();
getName = getNameList(); // This is thru Apache XML RPC Client
System.out.println(getName);
Any help or suggestions?
|
[
"You already have what you want. Try System.out.println(java.util.Arrays.toString(getName)); (the default toString() for an array in Java is not very useful).\n",
"The usual way to print out each item in a Java array would be something like:\nfor (Object name: (Object[]) getNameList()) {\n System.out.println(name);\n}\n\nBut I suspect from your response to Aaron Digulla that (as he says) you're getting an empty array back. Try printing it out on the Python side and see if there's anything in it.\n"
] |
[
1,
0
] |
[] |
[] |
[
"java",
"python"
] |
stackoverflow_0001720778_java_python.txt
|
Q:
Python .sort() not working as expected
Tackling a few puzzle problems on a quiet Saturday night (wooohoo... not) and am struggling with sort(). The results aren't quite what I expect. The program iterates through every combination from 100 - 999 and checks if the product is a palindome. If it is, append to the list. I need the list sorted :D Here's my program:
list = [] #list of numbers
for x in xrange(100,1000): #loops for first value of combination
for y in xrange(x,1000): #and 2nd value
mult = x*y
reversed = str(mult)[::-1] #reverses the number
if (reversed == str(mult)):
list.append(reversed)
list.sort()
print list[:10]
which nets:
['101101', '10201', '102201', '102201', '105501', '105501', '106601', '108801',
'108801', '110011']
Clearly index 0 is larger then 1. Any idea what's going on? I have a feeling it's got something to do with trailing/leading zeroes, but I had a quick look and I can't see the problem.
Bonus points if you know where the puzzle comes from :P
A:
You are sorting strings, not numbers. '101101' < '10201' because '1' < '2'. Change list.append(reversed) to list.append(int(reversed)) and it will work (or use a different sorting function).
A:
Sort is doing its job. If you intended to store integers in the list, take Lukáš advice. You can also tell sort how to sort, for example by making ints:
list.sort(key=int)
the key parameter takes a function that calculates an item to take the list object's place in all comparisons. An integer will compare numerically as you expect.
(By the way, list is a really bad variable name, as you override the builtin list() type!)
A:
Your list contains strings so it is sorting them alphabetically - try converting the list to integers and then do the sort.
A:
You're sorting strings, not numbers. Strings compare left-to-right.
A:
No need to convert to int. mult already is an int and as you have checked it is a palindrome it will look the same as reversed, so just:
list.append(mult)
A:
You have your numbers stored as strings, so python is sorting them accordingly. So: '101x' comes before '102x' (the same way that 'abcd' will come before 'az').
A:
No, it is sorting properly, just that it is sorting lexographically and you want numeric sorting... so remove the "str()"
A:
The comparator operator is treating your input as strings instead of integers. In string comparsion 2 as the 3rd letter is lexically greater than 1.
reversed = str(mult)[::-1]
|
Python .sort() not working as expected
|
Tackling a few puzzle problems on a quiet Saturday night (wooohoo... not) and am struggling with sort(). The results aren't quite what I expect. The program iterates through every combination from 100 - 999 and checks if the product is a palindome. If it is, append to the list. I need the list sorted :D Here's my program:
list = [] #list of numbers
for x in xrange(100,1000): #loops for first value of combination
for y in xrange(x,1000): #and 2nd value
mult = x*y
reversed = str(mult)[::-1] #reverses the number
if (reversed == str(mult)):
list.append(reversed)
list.sort()
print list[:10]
which nets:
['101101', '10201', '102201', '102201', '105501', '105501', '106601', '108801',
'108801', '110011']
Clearly index 0 is larger then 1. Any idea what's going on? I have a feeling it's got something to do with trailing/leading zeroes, but I had a quick look and I can't see the problem.
Bonus points if you know where the puzzle comes from :P
|
[
"You are sorting strings, not numbers. '101101' < '10201' because '1' < '2'. Change list.append(reversed) to list.append(int(reversed)) and it will work (or use a different sorting function).\n",
"Sort is doing its job. If you intended to store integers in the list, take Lukáš advice. You can also tell sort how to sort, for example by making ints:\nlist.sort(key=int)\n\nthe key parameter takes a function that calculates an item to take the list object's place in all comparisons. An integer will compare numerically as you expect.\n(By the way, list is a really bad variable name, as you override the builtin list() type!)\n",
"Your list contains strings so it is sorting them alphabetically - try converting the list to integers and then do the sort.\n",
"You're sorting strings, not numbers. Strings compare left-to-right.\n",
"No need to convert to int. mult already is an int and as you have checked it is a palindrome it will look the same as reversed, so just:\nlist.append(mult)\n\n",
"You have your numbers stored as strings, so python is sorting them accordingly. So: '101x' comes before '102x' (the same way that 'abcd' will come before 'az').\n",
"No, it is sorting properly, just that it is sorting lexographically and you want numeric sorting... so remove the \"str()\"\n",
"The comparator operator is treating your input as strings instead of integers. In string comparsion 2 as the 3rd letter is lexically greater than 1.\n\nreversed = str(mult)[::-1]\n\n"
] |
[
25,
13,
2,
1,
1,
0,
0,
0
] |
[] |
[] |
[
"list",
"python",
"sorting"
] |
stackoverflow_0001513727_list_python_sorting.txt
|
Q:
Will python.subprocess(cppBinaryExe) compromise cppBinaryExe's performance?
i am quite new to python.subprocess()
if i folk a new process from python, will the execution speed of this new process be compromised?
imagine that i have the
#python
import subprocess
subprocess.call( MyBinary )
basically, is there any difference between
./MyBinary
and
./python ruMyBinary.py
?
A:
No. A separate process is a separate process. It competes for OS resources with all other processes "fairly".
Your python process that simply does subprocess.call is a process, and does consume some system resources. But relatively few, since it will be waiting for a system call to finish. It will occupy a slot in the process table, so it does have a microscopic impact.
A:
Apart from having to actually run the python interpreter, no. So your last example will take some slight time before MyBinary to parse and run the python program and some slight time after it completes to terminate the python program. And the python program will be an existing process which takes up a pid and some amount of memory.
So the running speed of one long-running program won't be affekted. Hovever, if you run your executable thousands of times, any extra wrapping, wether in python or in something else, will cost.
A:
No, the process runs just as if started by any other means.
|
Will python.subprocess(cppBinaryExe) compromise cppBinaryExe's performance?
|
i am quite new to python.subprocess()
if i folk a new process from python, will the execution speed of this new process be compromised?
imagine that i have the
#python
import subprocess
subprocess.call( MyBinary )
basically, is there any difference between
./MyBinary
and
./python ruMyBinary.py
?
|
[
"No. A separate process is a separate process. It competes for OS resources with all other processes \"fairly\".\nYour python process that simply does subprocess.call is a process, and does consume some system resources. But relatively few, since it will be waiting for a system call to finish. It will occupy a slot in the process table, so it does have a microscopic impact.\n",
"Apart from having to actually run the python interpreter, no. So your last example will take some slight time before MyBinary to parse and run the python program and some slight time after it completes to terminate the python program. And the python program will be an existing process which takes up a pid and some amount of memory.\nSo the running speed of one long-running program won't be affekted. Hovever, if you run your executable thousands of times, any extra wrapping, wether in python or in something else, will cost.\n",
"No, the process runs just as if started by any other means.\n"
] |
[
3,
2,
0
] |
[] |
[] |
[
"linux",
"python"
] |
stackoverflow_0001721530_linux_python.txt
|
Q:
python contour for binary 2D matrix
I want to calculate a convex hull around a shape in a binary NxM matrix. The convex hull algorithm expects a list of coordinates, so I take numpy.argwhere(im) to have all shape point coordinates. However, most of those points are not contributing to the convex hull (they lie on the inside of the shape). Because convex hull computation time is at least proportional to the number of points that it gets as input, I devised an idea to filter the plethora of useless points on beforehand and only pass those that span the outline. The idea is quite simple, that for each row in the binary NxM matrix I take only the minimal and maximal indices. So for example:
im = np.array([[1,1,1,0],
[1,0,1,1],
[1,1,0,1],
[0,0,0,0],
[0,1,1,1]], dtype=np.bool)
outline = somefunc(im)
Then outline should read (in tuples or as a 5x2 numpy array, I don't mind):
[(0,0),(0,2),(1,0),(1,3),(2,0),(2,3),(4,1),(4,3)]
Any convex hull tight around this shape (im), must a subset of these points (outline). In other words, if "somefunc()" is efficient in filtering the inside points then it saves time for the convex hull computation.
I have code that does the above trick, but I am hoping someone has a more clever (read faster) approach since I need to run it many many times. The code I have is:
# I have a 2D binary field. random for the purpose of demonstration.
import numpy as np
im = np.random.random((320,360)) > 0.9
# This is my algorithm so far. Notice that coords is sorted.
coords = np.argwhere(im)
left = np.roll(coords[:,0], 1, axis=0) != coords[:,0]
outline = np.vstack([coords[left], coords[left[1:]], coords[-1]])
Another idea I had was to use Python's reduce() so I'd need to run over the list of coords only once. But I have difficulty finding a good reducing function.
Any help would greatly be appreciated!
edit
In the meanwhile I have found a faster way to go from im directly to outline. At least with large images this is significantly faster. In the apparent absence of an external solution I am positing it as the solution to this question.
Still, if somebody knows an even faster method, please speak up :)
A:
In the absence of an acceptable answer I post my best working code as the solution.
def outline(im):
''' Input binary 2D (NxM) image. Ouput array (2xK) of K (y,x) coordinates
where 0 <= K <= 2*M.
'''
topbottom = np.empty((1,2*im.shape[1]), dtype=np.uint16)
topbottom[0,0:im.shape[1]] = np.argmax(im, axis=0)
topbottom[0,im.shape[1]:] = (im.shape[0]-1)-np.argmax(np.flipud(im), axis=0)
mask = np.tile(np.any(im, axis=0), (2,))
xvalues = np.tile(np.arange(im.shape[1]), (1,2))
return np.vstack([topbottom,xvalues])[:,mask].T
A:
This assignment seems to accomplish the same thing as your last two steps:
outline = np.array(dict(reversed(coords)).items() + dict(coords).items())
Don't know if it's any faster, however.
A:
For more general solution, you could use somekind of edge detection method to find only the edge points. I believe (Google..) that NumPy has built-in sobel filter, which will do that.
|
python contour for binary 2D matrix
|
I want to calculate a convex hull around a shape in a binary NxM matrix. The convex hull algorithm expects a list of coordinates, so I take numpy.argwhere(im) to have all shape point coordinates. However, most of those points are not contributing to the convex hull (they lie on the inside of the shape). Because convex hull computation time is at least proportional to the number of points that it gets as input, I devised an idea to filter the plethora of useless points on beforehand and only pass those that span the outline. The idea is quite simple, that for each row in the binary NxM matrix I take only the minimal and maximal indices. So for example:
im = np.array([[1,1,1,0],
[1,0,1,1],
[1,1,0,1],
[0,0,0,0],
[0,1,1,1]], dtype=np.bool)
outline = somefunc(im)
Then outline should read (in tuples or as a 5x2 numpy array, I don't mind):
[(0,0),(0,2),(1,0),(1,3),(2,0),(2,3),(4,1),(4,3)]
Any convex hull tight around this shape (im), must a subset of these points (outline). In other words, if "somefunc()" is efficient in filtering the inside points then it saves time for the convex hull computation.
I have code that does the above trick, but I am hoping someone has a more clever (read faster) approach since I need to run it many many times. The code I have is:
# I have a 2D binary field. random for the purpose of demonstration.
import numpy as np
im = np.random.random((320,360)) > 0.9
# This is my algorithm so far. Notice that coords is sorted.
coords = np.argwhere(im)
left = np.roll(coords[:,0], 1, axis=0) != coords[:,0]
outline = np.vstack([coords[left], coords[left[1:]], coords[-1]])
Another idea I had was to use Python's reduce() so I'd need to run over the list of coords only once. But I have difficulty finding a good reducing function.
Any help would greatly be appreciated!
edit
In the meanwhile I have found a faster way to go from im directly to outline. At least with large images this is significantly faster. In the apparent absence of an external solution I am positing it as the solution to this question.
Still, if somebody knows an even faster method, please speak up :)
|
[
"In the absence of an acceptable answer I post my best working code as the solution.\ndef outline(im):\n ''' Input binary 2D (NxM) image. Ouput array (2xK) of K (y,x) coordinates\n where 0 <= K <= 2*M.\n '''\n topbottom = np.empty((1,2*im.shape[1]), dtype=np.uint16)\n topbottom[0,0:im.shape[1]] = np.argmax(im, axis=0)\n topbottom[0,im.shape[1]:] = (im.shape[0]-1)-np.argmax(np.flipud(im), axis=0)\n mask = np.tile(np.any(im, axis=0), (2,))\n xvalues = np.tile(np.arange(im.shape[1]), (1,2))\n return np.vstack([topbottom,xvalues])[:,mask].T\n\n",
"This assignment seems to accomplish the same thing as your last two steps:\noutline = np.array(dict(reversed(coords)).items() + dict(coords).items())\n\nDon't know if it's any faster, however.\n",
"For more general solution, you could use somekind of edge detection method to find only the edge points. I believe (Google..) that NumPy has built-in sobel filter, which will do that.\n"
] |
[
3,
0,
0
] |
[] |
[] |
[
"algorithm",
"contour",
"numpy",
"python"
] |
stackoverflow_0001601613_algorithm_contour_numpy_python.txt
|
Q:
Is there any "remote console" for twisted server?
I am developing a twisted server. I need to control the memory usage. It is not a good idea to modify code, insert some memory logging command and restart the server. I think it is better to use a "remote console", so that I can type heapy command and see the response from the server directly. All I need is a remote console, I can build one by myself, but I don't like to rebuild a wheel. My question is: is there already any remote console for twisted?
Thanks.
A:
twisted.manhole.telnet uses the deprecated module twisted.protocols.telnet. It is recommended to use twisted.conch.manhole instead.
Here are some tutorials of how to use it:
Writing a client with Twisted.Conch -- twisted.conch documentation
Network programming with the Twisted framework, Part 4 -- IBM developerWorks
Twisted Network Programming Essentials - Chapter 10 -- Online book preview
A:
Take a look at twisted.manhole
|
Is there any "remote console" for twisted server?
|
I am developing a twisted server. I need to control the memory usage. It is not a good idea to modify code, insert some memory logging command and restart the server. I think it is better to use a "remote console", so that I can type heapy command and see the response from the server directly. All I need is a remote console, I can build one by myself, but I don't like to rebuild a wheel. My question is: is there already any remote console for twisted?
Thanks.
|
[
"twisted.manhole.telnet uses the deprecated module twisted.protocols.telnet. It is recommended to use twisted.conch.manhole instead.\nHere are some tutorials of how to use it:\n\nWriting a client with Twisted.Conch -- twisted.conch documentation\nNetwork programming with the Twisted framework, Part 4 -- IBM developerWorks\nTwisted Network Programming Essentials - Chapter 10 -- Online book preview\n\n",
"Take a look at twisted.manhole\n"
] |
[
13,
6
] |
[] |
[] |
[
"console",
"python",
"twisted"
] |
stackoverflow_0001721699_console_python_twisted.txt
|
Q:
Unable to send function arguments from webapp.RequestHandler class
I am getting this errorpage after uploading my application to the google app engine and calling it in the browser.
Traceback (most recent call last):
File "/base/python_lib/versions/1/google/appengine/ext/webapp/__init__.py", line 507, in __call__
handler.get(*groups)
File "/base/data/home/apps/bulkloader160by2/1-5.337695659246114067/new_main.py", line 59, in get
transfer = _transfer_funds(src_key,dest_key,amt)
File "/base/data/home/apps/bulkloader160by2/1-5.337695659246114067/new_main.py", line 24, in _transfer_funds
return db.run_in_transaction(_tx)
File "/base/python_lib/versions/1/google/appengine/api/datastore.py", line 1885, in RunInTransaction
DEFAULT_TRANSACTION_RETRIES, function, *args, **kwargs)
File "/base/python_lib/versions/1/google/appengine/api/datastore.py", line 1982, in RunInTransactionCustomRetries
result = function(*args, **kwargs)
File "/base/data/home/apps/bulkloader160by2/1-5.337695659246114067/new_main.py", line 11, in _tx
account = db.get(src_key)
File "/base/python_lib/versions/1/google/appengine/ext/db/__init__.py", line 1178, in get
keys, multiple = datastore.NormalizeAndTypeCheckKeys(keys)
File "/base/python_lib/versions/1/google/appengine/api/datastore.py", line 136, in NormalizeAndTypeCheckKeys
keys, multiple = NormalizeAndTypeCheck(keys, (basestring, Entity, Key))
File "/base/python_lib/versions/1/google/appengine/api/datastore.py", line 115, in NormalizeAndTypeCheck
(types, arg, typename(arg)))
BadArgumentError: Expected an instance or sequence of (<type 'basestring'>, <class 'google.appengine.api.datastore.Entity'>, <class 'google.appengine.api.datastore_types.Key'>); received None (a NoneType).
I am trying to call the transfer_funds in get method of my handler but I get this error,this is my main.py file,
#!/usr/bin/env python
import wsgiref.handlers
from google.appengine.ext import db
from google.appengine.ext import webapp
from google.appengine.ext.webapp import template
from models import UserDetails
def _transfer_funds(src_key,dest_key,amt):
def _tx():
account = db.get(src_key)
amount = float(amt)
if amount <= 100.0:
if account.balance < amount:
return None
account.balance -= amount
transfer = Transfer(
parent = account,
amount = -amount,
target = db.get(dest_key)
)
db.put([account, transfer])
return transfer
return db.run_in_transaction(_tx)
def _roll_forward(transfer):
def _tx():
dest_transfer = Transfer.get_by_key_name(str(transfer.key()), parent=transfer.target.key())
if not dest_transfer:
dest_transfer = Transfer(
parent = transfer.target.key(),
key_name = str(transfer.key()),
amount = -transfer.amount,
target = transfer.key().parent(),
other = transfer)
account = UserDetails.get(transfer.target.key())
account.balance -= transfer.amount
db.put([account, dest_transfer])
return dest_transfer
dest_transfer = db.run_in_transaction(_tx)
transfer.other = dest_transfer
transfer.put()
return True
## Model class for Transfers / Transactions
class Transfer(db.Model):
amount = db.FloatProperty(required=True)
target = db.ReferenceProperty(reference_class=UserDetails, required=True)
other = db.SelfReferenceProperty()
timestamp = db.DateTimeProperty(required=True, auto_now_add=True)
class MyHandler(webapp.RequestHandler):
def get(self):
src_username = str(self.request.get('from_username'))
dest_username = str(self.request.get('to_username'))
amt = str(self.request.get('amount'))
src_key = db.GqlQuery('SELECT __key__ FROM UserDetails WHERE user_name = :uname', uname = src_username).get()
dest_key = db.GqlQuery('SELECT __key__ FROM UserDetails WHERE user_name = :uname', uname = dest_username).get()
transfer = _transfer_funds(src_key,dest_key,amt)
progress = _roll_forward(transfer)
srcUserDetails = UserDetails.gql('WHERE user_name = :uname', uname = src_username).fetch(1)
destUserDetails = UserDetails.gql('WHERE user_name = :uname', uname = dest_username).fetch(1)
values = {
'progress': progress,
'srcUser': srcUserDetails,
'destUser': destUserDetails
}
self.response.out.write(template.render('transactions.html', values))
def post(self):
self.redirect('/transactions.html')
def main():
app = webapp.WSGIApplication([
(r'.*',MyHandler)], debug=True)
wsgiref.handlers.CGIHandler().run(app)
if __name__ == "__main__":
main()
I understand that GAE does load balancing on the requests but does this also extend to the function calls? Please help me out in understanding why I might be getting this error.
A:
Perhaps in:
account = db.get(src_key)
src_key is None?
A:
You're getting this error because src_key is None, which implies this statement:
src_key = db.GqlQuery('SELECT __key__ FROM UserDetails WHERE user_name = :uname', uname = src_username).get()
Is not matching any rows. Try logging the result of that statement and the username you're using, and make sure records exist that match.
|
Unable to send function arguments from webapp.RequestHandler class
|
I am getting this errorpage after uploading my application to the google app engine and calling it in the browser.
Traceback (most recent call last):
File "/base/python_lib/versions/1/google/appengine/ext/webapp/__init__.py", line 507, in __call__
handler.get(*groups)
File "/base/data/home/apps/bulkloader160by2/1-5.337695659246114067/new_main.py", line 59, in get
transfer = _transfer_funds(src_key,dest_key,amt)
File "/base/data/home/apps/bulkloader160by2/1-5.337695659246114067/new_main.py", line 24, in _transfer_funds
return db.run_in_transaction(_tx)
File "/base/python_lib/versions/1/google/appengine/api/datastore.py", line 1885, in RunInTransaction
DEFAULT_TRANSACTION_RETRIES, function, *args, **kwargs)
File "/base/python_lib/versions/1/google/appengine/api/datastore.py", line 1982, in RunInTransactionCustomRetries
result = function(*args, **kwargs)
File "/base/data/home/apps/bulkloader160by2/1-5.337695659246114067/new_main.py", line 11, in _tx
account = db.get(src_key)
File "/base/python_lib/versions/1/google/appengine/ext/db/__init__.py", line 1178, in get
keys, multiple = datastore.NormalizeAndTypeCheckKeys(keys)
File "/base/python_lib/versions/1/google/appengine/api/datastore.py", line 136, in NormalizeAndTypeCheckKeys
keys, multiple = NormalizeAndTypeCheck(keys, (basestring, Entity, Key))
File "/base/python_lib/versions/1/google/appengine/api/datastore.py", line 115, in NormalizeAndTypeCheck
(types, arg, typename(arg)))
BadArgumentError: Expected an instance or sequence of (<type 'basestring'>, <class 'google.appengine.api.datastore.Entity'>, <class 'google.appengine.api.datastore_types.Key'>); received None (a NoneType).
I am trying to call the transfer_funds in get method of my handler but I get this error,this is my main.py file,
#!/usr/bin/env python
import wsgiref.handlers
from google.appengine.ext import db
from google.appengine.ext import webapp
from google.appengine.ext.webapp import template
from models import UserDetails
def _transfer_funds(src_key,dest_key,amt):
def _tx():
account = db.get(src_key)
amount = float(amt)
if amount <= 100.0:
if account.balance < amount:
return None
account.balance -= amount
transfer = Transfer(
parent = account,
amount = -amount,
target = db.get(dest_key)
)
db.put([account, transfer])
return transfer
return db.run_in_transaction(_tx)
def _roll_forward(transfer):
def _tx():
dest_transfer = Transfer.get_by_key_name(str(transfer.key()), parent=transfer.target.key())
if not dest_transfer:
dest_transfer = Transfer(
parent = transfer.target.key(),
key_name = str(transfer.key()),
amount = -transfer.amount,
target = transfer.key().parent(),
other = transfer)
account = UserDetails.get(transfer.target.key())
account.balance -= transfer.amount
db.put([account, dest_transfer])
return dest_transfer
dest_transfer = db.run_in_transaction(_tx)
transfer.other = dest_transfer
transfer.put()
return True
## Model class for Transfers / Transactions
class Transfer(db.Model):
amount = db.FloatProperty(required=True)
target = db.ReferenceProperty(reference_class=UserDetails, required=True)
other = db.SelfReferenceProperty()
timestamp = db.DateTimeProperty(required=True, auto_now_add=True)
class MyHandler(webapp.RequestHandler):
def get(self):
src_username = str(self.request.get('from_username'))
dest_username = str(self.request.get('to_username'))
amt = str(self.request.get('amount'))
src_key = db.GqlQuery('SELECT __key__ FROM UserDetails WHERE user_name = :uname', uname = src_username).get()
dest_key = db.GqlQuery('SELECT __key__ FROM UserDetails WHERE user_name = :uname', uname = dest_username).get()
transfer = _transfer_funds(src_key,dest_key,amt)
progress = _roll_forward(transfer)
srcUserDetails = UserDetails.gql('WHERE user_name = :uname', uname = src_username).fetch(1)
destUserDetails = UserDetails.gql('WHERE user_name = :uname', uname = dest_username).fetch(1)
values = {
'progress': progress,
'srcUser': srcUserDetails,
'destUser': destUserDetails
}
self.response.out.write(template.render('transactions.html', values))
def post(self):
self.redirect('/transactions.html')
def main():
app = webapp.WSGIApplication([
(r'.*',MyHandler)], debug=True)
wsgiref.handlers.CGIHandler().run(app)
if __name__ == "__main__":
main()
I understand that GAE does load balancing on the requests but does this also extend to the function calls? Please help me out in understanding why I might be getting this error.
|
[
"Perhaps in:\naccount = db.get(src_key)\n\nsrc_key is None?\n",
"You're getting this error because src_key is None, which implies this statement:\n src_key = db.GqlQuery('SELECT __key__ FROM UserDetails WHERE user_name = :uname', uname = src_username).get()\n\nIs not matching any rows. Try logging the result of that statement and the username you're using, and make sure records exist that match.\n"
] |
[
2,
1
] |
[] |
[] |
[
"google_app_engine",
"python"
] |
stackoverflow_0001721156_google_app_engine_python.txt
|
Q:
Diference between appengine_django BaseModel and db.Model
I'm using the Google App Engine helper for Django. This helper includes the following lines in its template:
from appengine_django.models import BaseModel
from google.appengine.ext import db
# Create your models here.
Should I derive my models from db.Model or from BaseModel?
I've tried both and I don't see any difference. Both seem to work, even when using Django forms. Is there any reason not to delete the BaseModel import and derive all models from db.Model?
A:
The BaseModel also does a registration of the inherited model inside django (so f.e. you can request it by calling django.db.models.loading.get_model('app_lable.ModelName') and all other stuff related to this)
A:
BaseModel is a class defined by the Django helper. It extends db.Model in order to make Django work with it better. The reason you need to import both is because the property classes are still used directly from db - but if you use db.Model instead of BaseModel, you may find some features of Django that don't work as expected.
|
Diference between appengine_django BaseModel and db.Model
|
I'm using the Google App Engine helper for Django. This helper includes the following lines in its template:
from appengine_django.models import BaseModel
from google.appengine.ext import db
# Create your models here.
Should I derive my models from db.Model or from BaseModel?
I've tried both and I don't see any difference. Both seem to work, even when using Django forms. Is there any reason not to delete the BaseModel import and derive all models from db.Model?
|
[
"The BaseModel also does a registration of the inherited model inside django (so f.e. you can request it by calling django.db.models.loading.get_model('app_lable.ModelName') and all other stuff related to this)\n",
"BaseModel is a class defined by the Django helper. It extends db.Model in order to make Django work with it better. The reason you need to import both is because the property classes are still used directly from db - but if you use db.Model instead of BaseModel, you may find some features of Django that don't work as expected.\n"
] |
[
1,
0
] |
[] |
[] |
[
"django",
"django_models",
"google_app_engine",
"python"
] |
stackoverflow_0001720157_django_django_models_google_app_engine_python.txt
|
Q:
In the MVC pattern, what goes in the model and what goes in the view?
I'm using the MVC pattern to design some data analysis software (in
Python). I'm not sure whether some functions should go in the model or the controller.
The way I've designed it, the user supplies the program a configuration file which contains the parameters for analysis. The program parses this file to find out what data files to look at and what kinds of calculations to do.
Should the function(s) that do this configuration file parsing be in the model or the controller?
Is there a standard way to organize things in Python when using MVC? I've made the model, controller, and view into separate classes. The controller class contains instances of the model and view classes.
What kind of communication should there be between the model and the view? The way I'm structuring things is so that the controller takes stuff from the model and passes it to the view. The two only communicate through the controller.
A:
The model should be your entity classes, or simply classes that model the problem domain you're working with. And the view anything basically having to do with how your user interacts with the system you're building. The controller marries the two.
A:
On your first point, the parsing should go in the model if it's part of the model class; for instance if you have a Configuration model, then the functions to load up configuration belong in the Model. If it's more of a service (e.g. I'm going to import this file in, and then something else is going to do the mappings) then it should be in the Controller. Without knowing more details it's kind of hard to say but that's the general rule that I follow.
I'm not sure on your second point since I'm not familiar with Python but the typical approach is to separate out your folder structure into Models/Controllers/Views and such, however I'm only familiar with MVC as it relates to web applications so I might be off the mark since your program seems to be a desktop app.
Your third point is exactly right. The model should not talk to the view; the controller communicates to the model and retrieves the information the View needs, and gives the view just that. I guess in essence the view might be working with the Model, but it doesn't know anything about the model (e.g. if it comes from a database, configuration file, xml, whatever)
A:
To put it simply, the model is your data part (the database) and the view is your design part (HTML, CSS, JavaScript, etc.) while a controller is a contract between the model and view :)
|
In the MVC pattern, what goes in the model and what goes in the view?
|
I'm using the MVC pattern to design some data analysis software (in
Python). I'm not sure whether some functions should go in the model or the controller.
The way I've designed it, the user supplies the program a configuration file which contains the parameters for analysis. The program parses this file to find out what data files to look at and what kinds of calculations to do.
Should the function(s) that do this configuration file parsing be in the model or the controller?
Is there a standard way to organize things in Python when using MVC? I've made the model, controller, and view into separate classes. The controller class contains instances of the model and view classes.
What kind of communication should there be between the model and the view? The way I'm structuring things is so that the controller takes stuff from the model and passes it to the view. The two only communicate through the controller.
|
[
"The model should be your entity classes, or simply classes that model the problem domain you're working with. And the view anything basically having to do with how your user interacts with the system you're building. The controller marries the two.\n",
"On your first point, the parsing should go in the model if it's part of the model class; for instance if you have a Configuration model, then the functions to load up configuration belong in the Model. If it's more of a service (e.g. I'm going to import this file in, and then something else is going to do the mappings) then it should be in the Controller. Without knowing more details it's kind of hard to say but that's the general rule that I follow.\nI'm not sure on your second point since I'm not familiar with Python but the typical approach is to separate out your folder structure into Models/Controllers/Views and such, however I'm only familiar with MVC as it relates to web applications so I might be off the mark since your program seems to be a desktop app.\nYour third point is exactly right. The model should not talk to the view; the controller communicates to the model and retrieves the information the View needs, and gives the view just that. I guess in essence the view might be working with the Model, but it doesn't know anything about the model (e.g. if it comes from a database, configuration file, xml, whatever)\n",
"To put it simply, the model is your data part (the database) and the view is your design part (HTML, CSS, JavaScript, etc.) while a controller is a contract between the model and view :)\n"
] |
[
2,
1,
0
] |
[] |
[] |
[
"model_view_controller",
"python"
] |
stackoverflow_0001718813_model_view_controller_python.txt
|
Q:
Haystack Whoosh Spelling Suggestion too greedy
This questions is about Django Haystack, with Whoosh backend.
I would like to use spelling suggestion in my search. The problem is that it is suggesting TOO much.
Say I have two models:
Apples and Oranges.
If I have somethine like this:
result = SearchQuerySet().models(Apples).filter(
content=escaped_value).spelling_suggestion(escaped_value)
it will actually LOOK into Oranges model and return a spelling suggestion from that! It seems like models(Apples) restriction does not work.
I have indexes setup for both models, with "text" attribute as document=True. My spelling is ON. I am using Whoosh as backend.
A:
This is the problem because Haystack creates spelling suggestions based on the fields which have document=True (which in my case are the primary search field in all models and they have the same name). So it does not care about models at all and alway searches across all the knowledgebase.
I filed an issue with haystack and brought it up on the discussion board. Dev is very helpful:
http://groups.google.com/group/django-haystack/browse_thread/thread/025e5ed42ccde8b9#
Issue:
http://github.com/toastdriven/django-haystack/issues/#issue/124
|
Haystack Whoosh Spelling Suggestion too greedy
|
This questions is about Django Haystack, with Whoosh backend.
I would like to use spelling suggestion in my search. The problem is that it is suggesting TOO much.
Say I have two models:
Apples and Oranges.
If I have somethine like this:
result = SearchQuerySet().models(Apples).filter(
content=escaped_value).spelling_suggestion(escaped_value)
it will actually LOOK into Oranges model and return a spelling suggestion from that! It seems like models(Apples) restriction does not work.
I have indexes setup for both models, with "text" attribute as document=True. My spelling is ON. I am using Whoosh as backend.
|
[
"This is the problem because Haystack creates spelling suggestions based on the fields which have document=True (which in my case are the primary search field in all models and they have the same name). So it does not care about models at all and alway searches across all the knowledgebase.\nI filed an issue with haystack and brought it up on the discussion board. Dev is very helpful:\nhttp://groups.google.com/group/django-haystack/browse_thread/thread/025e5ed42ccde8b9#\nIssue:\nhttp://github.com/toastdriven/django-haystack/issues/#issue/124\n"
] |
[
2
] |
[] |
[] |
[
"django",
"django_haystack",
"python",
"whoosh"
] |
stackoverflow_0001718758_django_django_haystack_python_whoosh.txt
|
Q:
django datefield filter
I'd like to use an object filter similar to the following
Shipment.objects.filter(date__gte=datetime.date(2005,1,1))
However there doesn't seem to be support for comparison operators on datetime objects. Is there a method I'm unaware of or should I look into writing a custom filter.
A:
I use date comparison in my code a lot and they work e.g copied a snippet from my calendar code
q.filter(start_date__gt=pay_period.start_date).order_by("start_date")
|
django datefield filter
|
I'd like to use an object filter similar to the following
Shipment.objects.filter(date__gte=datetime.date(2005,1,1))
However there doesn't seem to be support for comparison operators on datetime objects. Is there a method I'm unaware of or should I look into writing a custom filter.
|
[
"I use date comparison in my code a lot and they work e.g copied a snippet from my calendar code\nq.filter(start_date__gt=pay_period.start_date).order_by(\"start_date\")\n\n"
] |
[
4
] |
[] |
[] |
[
"datetime",
"django",
"filter",
"python"
] |
stackoverflow_0001722111_datetime_django_filter_python.txt
|
Q:
How can I measure the execution time of a for loop?
I want to measure the execution time of for loops on various platforms like php, c, python, Java, javascript... How can i measure it?
I know these platforms so i am talking about these:
for (i = 0; i < 1000000; i++)
{
}
I don't want to measure anything within the loop.
Little bit modification:
@all Some of the friends of mine are saying compiler will optimize this code making this loop a useless loop. I agree with this. we can add a small statement like some incremental statement, but the fact is I just want to calculate the execution time of per iteration in a loop in various languages. By adding a incremental statement will add up the execution time and that will effect the results, cause on various platforms, execution time for incrementing a value also differ and that will make a result useless.
In short, in better way I should ask:
I WANT TO CALCULATE THE EXECUTION TIME OF PER ITERATION IN A LOOP on Various PLATFORMS..HOW CAN DO THIS???
edit---
I came to know about Python Profilers
Profiler modules ...which evaluate cpu time... absolute time.. Any suggestions???Meanwhile i am working on this...
A:
Although an answer has been given for C++, it looks from your description ("[You] don't want to measure anything within the loop") like you're trying to measure the time which it takes a program to iterate over an empty loop.
Please take care here: not only will it take varying times from different platforms and processors, but many compilers will optimise away such loops, effectively rendering the answer as "0" for any loop size.
A:
javascript
start = new Date;
for(var i = 0; i < 1000000; i++) {}
time = new Date - start;
A:
Note that it also depends on what exactly you want to achieve: do you care about the time your program waits due to it being preempted by the system scheduler? All the solutions above take actual time elapsed into consideration, but that also involves the time when other processes run instead of your own.
If you don't care about this, all of the solutions above are good. If you do care, you probably need some profiling software to actually see how long the loop takes.
I'd start with a program that does nothing but your loop and (in a linux environment at least) do time you-prg-executable.
Then I'd investigate if there are tools which work like time. Not sure, but I'd look at JRat for java, and gcc's gcov for C and C++. No doubt there are similar tools for the other languages. But, of course, you need to see if they give actual time or not.
A:
The right way to do it in python is to run timeit from the command line:
$ python -m timeit "for i in xrange(100): pass"
100000 loops, best of 3: 2.5 usec per loop
A:
Other version in PHP that doesn't require any extra stuff:
$start = microtime(true);
for (...) {
....
}
$end = microtime(true);
echo ($end - $start).' seconds';
A:
If you're using Python, you can use a module specifically built for timing things. It's called Timeit.
Here are a couple of references I found (just Googled it):
Dive Into Python: Using the Timeit
Module
Python Documentation:
Timeit Module
And here's some example code to get you started quickly:
import timeit
t = timeit.Timer("for i in range(100): pass", "")
# Timeit will run the statement 1,000,000 times by default, and return the time it took for all the runs together (it doesn't try to average them out or anything).
t.timeit()
2.9035916423318398 # This is the result. Don't forget (like I did in an earlier edit) that this is the result of running the code 1,000,000 times!
A:
For compiled languages such as C and C++, make sure that your compiler flags are set such that the loop isn't optimized away. With optimization switched on I would expect most compilers to detect that nothing is going on in the loop and optimize it away.
A:
in php: (code timer)
$timer = new timer();
$timer->start();
for(i=0;i<1000000;i++)
{
}
$timer->stop();
echo $timer->getTime();
A:
I asked the same question a while back that was specifically for the c++ language.
Heres the answer I ended up using:
#include <omp.h>
// Starting the time measurement
double start = omp_get_wtime();
// Computations to be measured
...
// Measuring the elapsed time
double end = omp_get_wtime();
// Time calculation (in seconds)
A:
The result wont make sense in an empty loop, sine most compilers will optimize it at compiling time, before the runtime.
To compare languages speed, you will need a real algorithm, like "Merge Sort", "Binary Search" or maybe "Dijkstra" if you want something complicated.
Implement the same algorithm in all languages then compare.
Here is a benchmark on a Bio-Informatics algorithm. link text Check the Results page
A:
To the point: just get the current time before doing something (this is the start time) and get the current time after doing something (this is the end time) and then just do the primary school math to get the elapsed time. Every API provides ways to get the current time. In Java for example it's System.currentTimeMillis() and System.nanoTime().
But: especially in Java, the elapsed time isn't always that reliable. There can be microdifferences and it also depends much on how you do the tests. I've seen circumstances where in test2() is faster than test1() because it is executed a bit later and that it become slower when you rearrange the execution to test2() and then test1().
Last but not least, micro-optimization is root of all evil.
A:
For Java, both Apache Commons Lang and the Spring Framework have StopWatch (see the Java doc for Apache's here) classes that you can use as a way to measure execution time. Under the covers though it's just subtracting System.currentTimeMillis() and it doesn't save you that much code to use this utility.
|
How can I measure the execution time of a for loop?
|
I want to measure the execution time of for loops on various platforms like php, c, python, Java, javascript... How can i measure it?
I know these platforms so i am talking about these:
for (i = 0; i < 1000000; i++)
{
}
I don't want to measure anything within the loop.
Little bit modification:
@all Some of the friends of mine are saying compiler will optimize this code making this loop a useless loop. I agree with this. we can add a small statement like some incremental statement, but the fact is I just want to calculate the execution time of per iteration in a loop in various languages. By adding a incremental statement will add up the execution time and that will effect the results, cause on various platforms, execution time for incrementing a value also differ and that will make a result useless.
In short, in better way I should ask:
I WANT TO CALCULATE THE EXECUTION TIME OF PER ITERATION IN A LOOP on Various PLATFORMS..HOW CAN DO THIS???
edit---
I came to know about Python Profilers
Profiler modules ...which evaluate cpu time... absolute time.. Any suggestions???Meanwhile i am working on this...
|
[
"Although an answer has been given for C++, it looks from your description (\"[You] don't want to measure anything within the loop\") like you're trying to measure the time which it takes a program to iterate over an empty loop.\nPlease take care here: not only will it take varying times from different platforms and processors, but many compilers will optimise away such loops, effectively rendering the answer as \"0\" for any loop size.\n",
"javascript\nstart = new Date;\nfor(var i = 0; i < 1000000; i++) {}\ntime = new Date - start;\n\n",
"Note that it also depends on what exactly you want to achieve: do you care about the time your program waits due to it being preempted by the system scheduler? All the solutions above take actual time elapsed into consideration, but that also involves the time when other processes run instead of your own.\nIf you don't care about this, all of the solutions above are good. If you do care, you probably need some profiling software to actually see how long the loop takes. \nI'd start with a program that does nothing but your loop and (in a linux environment at least) do time you-prg-executable. \nThen I'd investigate if there are tools which work like time. Not sure, but I'd look at JRat for java, and gcc's gcov for C and C++. No doubt there are similar tools for the other languages. But, of course, you need to see if they give actual time or not.\n",
"The right way to do it in python is to run timeit from the command line:\n$ python -m timeit \"for i in xrange(100): pass\"\n100000 loops, best of 3: 2.5 usec per loop\n\n",
"Other version in PHP that doesn't require any extra stuff:\n$start = microtime(true);\n\nfor (...) {\n ....\n}\n\n$end = microtime(true);\n\necho ($end - $start).' seconds';\n\n",
"If you're using Python, you can use a module specifically built for timing things. It's called Timeit.\nHere are a couple of references I found (just Googled it):\n\nDive Into Python: Using the Timeit\nModule \nPython Documentation:\nTimeit Module\n\nAnd here's some example code to get you started quickly:\nimport timeit\nt = timeit.Timer(\"for i in range(100): pass\", \"\")\n# Timeit will run the statement 1,000,000 times by default, and return the time it took for all the runs together (it doesn't try to average them out or anything).\nt.timeit()\n2.9035916423318398 # This is the result. Don't forget (like I did in an earlier edit) that this is the result of running the code 1,000,000 times!\n\n",
"For compiled languages such as C and C++, make sure that your compiler flags are set such that the loop isn't optimized away. With optimization switched on I would expect most compilers to detect that nothing is going on in the loop and optimize it away.\n",
"in php: (code timer)\n$timer = new timer();\n\n$timer->start();\n\n for(i=0;i<1000000;i++)\n {\n\n }\n\n$timer->stop();\n\necho $timer->getTime(); \n\n",
"I asked the same question a while back that was specifically for the c++ language.\nHeres the answer I ended up using:\n#include <omp.h>\n\n// Starting the time measurement\ndouble start = omp_get_wtime();\n// Computations to be measured\n...\n// Measuring the elapsed time\ndouble end = omp_get_wtime();\n// Time calculation (in seconds)\n\n",
"The result wont make sense in an empty loop, sine most compilers will optimize it at compiling time, before the runtime.\nTo compare languages speed, you will need a real algorithm, like \"Merge Sort\", \"Binary Search\" or maybe \"Dijkstra\" if you want something complicated.\nImplement the same algorithm in all languages then compare.\nHere is a benchmark on a Bio-Informatics algorithm. link text Check the Results page\n",
"To the point: just get the current time before doing something (this is the start time) and get the current time after doing something (this is the end time) and then just do the primary school math to get the elapsed time. Every API provides ways to get the current time. In Java for example it's System.currentTimeMillis() and System.nanoTime().\nBut: especially in Java, the elapsed time isn't always that reliable. There can be microdifferences and it also depends much on how you do the tests. I've seen circumstances where in test2() is faster than test1() because it is executed a bit later and that it become slower when you rearrange the execution to test2() and then test1().\nLast but not least, micro-optimization is root of all evil.\n",
"For Java, both Apache Commons Lang and the Spring Framework have StopWatch (see the Java doc for Apache's here) classes that you can use as a way to measure execution time. Under the covers though it's just subtracting System.currentTimeMillis() and it doesn't save you that much code to use this utility.\n"
] |
[
5,
2,
2,
2,
1,
1,
1,
0,
0,
0,
0,
0
] |
[] |
[] |
[
"c",
"c++",
"java",
"php",
"python"
] |
stackoverflow_0001721351_c_c++_java_php_python.txt
|
Q:
403 error in Google App Engine with staticdir
For some reason I can't get static_dir to work. In my app.ymal I have:
- url: /ui
static_dir: ui
- url: /dump
static_dir: dump
Loading static files from /ui works (i.e /ui/images/logo.png). But when I try to access something from /dumo I just get:
INFO 2009-11-12 14:03:55,497 dev_appserver.py:3034] "GET /dump/kaxas.zip HTTP/1.1" 403 -
If I change the name of the zip-file to something else it returns a 404 error. So in someway it finds the file.
On the server the files have the same owner and group, and the same rights (chmod 755).
I'm running dev_appserver on a linux server.
Any ideas?
..fredrik
A:
HTTP 403 code is usually returned by GAE for quota problems, read http://code.google.com/appengine/docs/quotas.html
I think your zip file is more than 1 MB, and I have read it doesn't allow such big zip files. Try with a smaller file to make sure dump is working, I think it will work.
|
403 error in Google App Engine with staticdir
|
For some reason I can't get static_dir to work. In my app.ymal I have:
- url: /ui
static_dir: ui
- url: /dump
static_dir: dump
Loading static files from /ui works (i.e /ui/images/logo.png). But when I try to access something from /dumo I just get:
INFO 2009-11-12 14:03:55,497 dev_appserver.py:3034] "GET /dump/kaxas.zip HTTP/1.1" 403 -
If I change the name of the zip-file to something else it returns a 404 error. So in someway it finds the file.
On the server the files have the same owner and group, and the same rights (chmod 755).
I'm running dev_appserver on a linux server.
Any ideas?
..fredrik
|
[
"HTTP 403 code is usually returned by GAE for quota problems, read http://code.google.com/appengine/docs/quotas.html\nI think your zip file is more than 1 MB, and I have read it doesn't allow such big zip files. Try with a smaller file to make sure dump is working, I think it will work.\n"
] |
[
5
] |
[] |
[] |
[
"google_app_engine",
"http_status_code_403",
"http_status_codes",
"linux",
"python"
] |
stackoverflow_0001722441_google_app_engine_http_status_code_403_http_status_codes_linux_python.txt
|
Q:
Is the first entry in sys.path supposed to represent the current working directory?
I had always assumed that the first entry in sys.path by default was the current working directory. But as it turns out, on my system the first entry is the path on which the script resides. So if I'm executing a script that's in /usr/bin from /some/directory, the first entry in sys.path is /usr/bin. Is something misconfigured on my system, or is this the expected behavior?
A:
This is by design:
As initialized upon program startup,
the first item of this list, path[0],
is the directory containing the script
that was used to invoke the Python
interpreter.
source: http://docs.python.org/library/sys.html#sys.path
A:
You can get the current directory with os.getcwd().
|
Is the first entry in sys.path supposed to represent the current working directory?
|
I had always assumed that the first entry in sys.path by default was the current working directory. But as it turns out, on my system the first entry is the path on which the script resides. So if I'm executing a script that's in /usr/bin from /some/directory, the first entry in sys.path is /usr/bin. Is something misconfigured on my system, or is this the expected behavior?
|
[
"This is by design:\n\nAs initialized upon program startup,\n the first item of this list, path[0],\n is the directory containing the script\n that was used to invoke the Python\n interpreter.\n\nsource: http://docs.python.org/library/sys.html#sys.path\n",
"You can get the current directory with os.getcwd().\n"
] |
[
6,
1
] |
[] |
[] |
[
"python",
"pythonpath",
"sys.path"
] |
stackoverflow_0001722901_python_pythonpath_sys.path.txt
|
Q:
Twisted/tkinter program crashes on exit
I am running an app using twisted and tkinter that sends the result to the server, waits for the server to send back a confirmation, and then exits. So, the function I use to exit is this:
def term():
'''To end the program'''
reactor.stop()
root.quit()
root.destroy()
This is then set in the factory and called in the dataReceived function of the protocol. I run it, and the program runs fine and even sends the necessary data and closes, but it also gives me the following error report:
Unhandled error in Deferred:
Traceback (most recent call last):
File "D:\Python25\Lib\site-packages\twisted\internet\base.py", line 1128, in run
self.mainLoop()
File "D:\Python25\Lib\site-packages\twisted\internet\base.py", line 1137, in mainLoop
self.runUntilCurrent()
File "D:\Python25\Lib\site-packages\twisted\internet\base.py", line 757, in runUntilCurrent
call.func(*call.args, **call.kw)
File "D:\Python25\Lib\site-packages\twisted\internet\task.py", line 114, in __call__
d = defer.maybeDeferred(self.f, *self.a, **self.kw)
--- <exception caught here> ---
File "D:\Python25\Lib\site-packages\twisted\internet\defer.py", line 106, in maybeDeferred
result = f(*args, **kw)
File "D:\Python25\lib\lib-tk\Tkinter.py", line 917, in update
self.tk.call('update')
_tkinter.TclError: can't invoke "update" command: application has been destroyed
Does anyone know why?
A:
You only need to call reactor.stop to exit: the root.quit() and root.destroy() calls are superfluous. Consider this short example which runs Twisted and Tk for three seconds and then exits:
import Tkinter
from twisted.internet import tksupport
root = Tkinter.Tk()
tksupport.install(root)
from twisted.internet import reactor
reactor.callLater(3, reactor.stop)
reactor.run()
|
Twisted/tkinter program crashes on exit
|
I am running an app using twisted and tkinter that sends the result to the server, waits for the server to send back a confirmation, and then exits. So, the function I use to exit is this:
def term():
'''To end the program'''
reactor.stop()
root.quit()
root.destroy()
This is then set in the factory and called in the dataReceived function of the protocol. I run it, and the program runs fine and even sends the necessary data and closes, but it also gives me the following error report:
Unhandled error in Deferred:
Traceback (most recent call last):
File "D:\Python25\Lib\site-packages\twisted\internet\base.py", line 1128, in run
self.mainLoop()
File "D:\Python25\Lib\site-packages\twisted\internet\base.py", line 1137, in mainLoop
self.runUntilCurrent()
File "D:\Python25\Lib\site-packages\twisted\internet\base.py", line 757, in runUntilCurrent
call.func(*call.args, **call.kw)
File "D:\Python25\Lib\site-packages\twisted\internet\task.py", line 114, in __call__
d = defer.maybeDeferred(self.f, *self.a, **self.kw)
--- <exception caught here> ---
File "D:\Python25\Lib\site-packages\twisted\internet\defer.py", line 106, in maybeDeferred
result = f(*args, **kw)
File "D:\Python25\lib\lib-tk\Tkinter.py", line 917, in update
self.tk.call('update')
_tkinter.TclError: can't invoke "update" command: application has been destroyed
Does anyone know why?
|
[
"You only need to call reactor.stop to exit: the root.quit() and root.destroy() calls are superfluous. Consider this short example which runs Twisted and Tk for three seconds and then exits:\nimport Tkinter\nfrom twisted.internet import tksupport\n\nroot = Tkinter.Tk()\ntksupport.install(root)\n\nfrom twisted.internet import reactor\nreactor.callLater(3, reactor.stop)\nreactor.run()\n\n"
] |
[
1
] |
[] |
[] |
[
"python",
"tkinter",
"twisted"
] |
stackoverflow_0001722865_python_tkinter_twisted.txt
|
Q:
How to write the output of this code to HTML file?
from HTMLParser import HTMLParser
from urllib import urlopen
class Spider(HTMLParser):
def __init__(self, url):
HTMLParser.__init__(self)
req = urlopen(url)
self.feed(req.read())
def handle_starttag(self, tag, attrs):
if tag == 'a' and attrs:
print "Found link => %s" % attrs[0][1]
Spider('http://stackoverflow.com/questions/tagged/python')
A:
python spider.py > output.html
A:
Put this at the top of your script:
import sys
sys.stdout = file('output.html', 'w')
This will redirect everything your script writes to the standard output (which includes print statements) to the file 'output.html'.
A:
I haven't messed with Spider at all, but is it printing html, or are you just printing the "Found link..." lines? If you are just printing those, you can do something like outfl = open('output.txt')
And then, instead of print, call outfl.write("Found link => %s" % attrs[0][1]).
You can always write out <html><head></head><body> before, and </body></html> after it if you're needing it in HTML format. Also, use outfl = open('output.html') instead of .txt for the filename.
Did I totally miss the question here? If you want better answers, you ought to describe the question a little better.
|
How to write the output of this code to HTML file?
|
from HTMLParser import HTMLParser
from urllib import urlopen
class Spider(HTMLParser):
def __init__(self, url):
HTMLParser.__init__(self)
req = urlopen(url)
self.feed(req.read())
def handle_starttag(self, tag, attrs):
if tag == 'a' and attrs:
print "Found link => %s" % attrs[0][1]
Spider('http://stackoverflow.com/questions/tagged/python')
|
[
"python spider.py > output.html\n\n",
"Put this at the top of your script:\nimport sys\nsys.stdout = file('output.html', 'w')\n\nThis will redirect everything your script writes to the standard output (which includes print statements) to the file 'output.html'.\n",
"I haven't messed with Spider at all, but is it printing html, or are you just printing the \"Found link...\" lines? If you are just printing those, you can do something like outfl = open('output.txt')\nAnd then, instead of print, call outfl.write(\"Found link => %s\" % attrs[0][1]).\nYou can always write out <html><head></head><body> before, and </body></html> after it if you're needing it in HTML format. Also, use outfl = open('output.html') instead of .txt for the filename.\nDid I totally miss the question here? If you want better answers, you ought to describe the question a little better.\n"
] |
[
3,
1,
0
] |
[] |
[] |
[
"python"
] |
stackoverflow_0001722239_python.txt
|
Q:
Multiple programs using the same UDP port? Possible?
I currently have a small Python script that I'm using to spawn multiple executables, (voice chat servers), and in the next version of the software, the servers have the ability to receive heartbeat signals on the UDP port. (There will be possibly thousands of servers on one machine, ranging from ports 7878 and up)
My problem is that these servers might (read: will) be running on the same machine as my Python script and I had planned on opening a UDP port, and just sending the heartbeat, waiting for the reply, and voila...I could restart servers when/if they weren't responding by killing the task and re-loading the server.
Problem is that I cannot open a UDP port that the server is already using. Is there a way around this? The project lead is implementing the heartbeat still, so I'm sure any suggestions in how the heartbeat system could be implemented would be welcome also. -- This is a pretty generic script though that might apply to other programs so my main focus is still communicating on that UDP port.
A:
This isn't possible. What you'll have to do is have one UDP master program that handles all UDP communication over the one port, and communicates with your servers in another way (UDP on different ports, named pipes, ...)
A:
I'm pretty sure this is possible on Linux; I don't know about other UNIXes.
There are two ways to propagate a file descriptor from one process to another:
When a process fork()s, the child inherits all the file descriptors of the parent.
A process can send a file descriptor to another process over a "UNIX Domain Socket". See sendmsg() and recvmsg(). In Python, the _multiprocessing extension module will do this for you; see _multiprocessing.sendfd() and _multiprocessing.recvfd().
I haven't experimented with multiple processes listening on UDP sockets. But for TCP, on Linux, if multiple processes all listen on a single TCP socket, one of them will be randomly chosen when a connection comes in. So I suspect Linux does something sensible when multiple processes are all listening on the same UDP socket.
Try it and let us know!
|
Multiple programs using the same UDP port? Possible?
|
I currently have a small Python script that I'm using to spawn multiple executables, (voice chat servers), and in the next version of the software, the servers have the ability to receive heartbeat signals on the UDP port. (There will be possibly thousands of servers on one machine, ranging from ports 7878 and up)
My problem is that these servers might (read: will) be running on the same machine as my Python script and I had planned on opening a UDP port, and just sending the heartbeat, waiting for the reply, and voila...I could restart servers when/if they weren't responding by killing the task and re-loading the server.
Problem is that I cannot open a UDP port that the server is already using. Is there a way around this? The project lead is implementing the heartbeat still, so I'm sure any suggestions in how the heartbeat system could be implemented would be welcome also. -- This is a pretty generic script though that might apply to other programs so my main focus is still communicating on that UDP port.
|
[
"This isn't possible. What you'll have to do is have one UDP master program that handles all UDP communication over the one port, and communicates with your servers in another way (UDP on different ports, named pipes, ...)\n",
"I'm pretty sure this is possible on Linux; I don't know about other UNIXes.\nThere are two ways to propagate a file descriptor from one process to another:\n\nWhen a process fork()s, the child inherits all the file descriptors of the parent.\nA process can send a file descriptor to another process over a \"UNIX Domain Socket\". See sendmsg() and recvmsg(). In Python, the _multiprocessing extension module will do this for you; see _multiprocessing.sendfd() and _multiprocessing.recvfd().\n\nI haven't experimented with multiple processes listening on UDP sockets. But for TCP, on Linux, if multiple processes all listen on a single TCP socket, one of them will be randomly chosen when a connection comes in. So I suspect Linux does something sensible when multiple processes are all listening on the same UDP socket.\nTry it and let us know!\n"
] |
[
2,
1
] |
[] |
[] |
[
"communication",
"daemon",
"ports",
"python",
"udp"
] |
stackoverflow_0001722993_communication_daemon_ports_python_udp.txt
|
Q:
python function slowing down for no apparent reason
I have a python function defined as follows which i use to delete from list1 the items which are already in list2. I am using python 2.6.2 on windows XP
def compareLists(list1, list2):
curIndex = 0
while curIndex < len(list1):
if list1[curIndex] in list2:
list1.pop(curIndex)
else:
curIndex += 1
Here, list1 and list2 are a list of lists
list1 = [ ['a', 11221, '2232'], ['b', 1321, '22342'] .. ]
# list2 has a similar format.
I tried this function with list1 with 38,000 elements and list2 with 150,000 elements. If i put in a print statement to print the current iteration, I find that the function slows down with each iterations. At first, it processes around 1000 or more items in a second and then after a while it reduces to around 20-50 a second. Why can that be happening?
EDIT: In the case with my data, the curIndex remains 0 or very close to 0 so the pop operation on list1 is almost always on the first item.
If possible, can someone also suggest a better way of doing the same thing in a different way?
A:
Try a more pythonic approach to the filtering, something like
[x for x in list1 if x not in set(list2)]
Converting both lists to sets is unnessescary, and will be very slow and memory hungry on large amounts of data.
Since your data is a list of lists, you need to do something in order to hash it.
Try out
list2_set = set([tuple(x) for x in list2])
diff = [x for x in list1 if tuple(x) not in list2_set]
I tested out your original function, and my approach, using the following test data:
list1 = [[x+1, x*2] for x in range(38000)]
list2 = [[x+1, x*2] for x in range(10000, 160000)]
Timings - not scientific, but still:
#Original function
real 2m16.780s
user 2m16.744s
sys 0m0.017s
#My function
real 0m0.433s
user 0m0.423s
sys 0m0.007s
A:
There are 2 issues that cause your algorithm to scale poorly:
x in list is an O(n) operation.
pop(n) where n is in the middle of the array is an O(n) operation.
Both situations cause it to scale poorly O(n^2) for large amounts of data. gnud's implementation would probably be the best solution since it solves both problems without changing the order of elements or removing potential duplicates.
A:
If we rule the data structure itself out, look at your memory usage next. If you end up asking the OS to swap in for you (i.e., the list takes up more memory than you have), Python's going to sit in iowait waiting on the OS to get the pages from disk, which makes sense given your description.
Is Python sitting in a jacuzzi of iowait when this slowdown happens? Anything else going on in the environment?
(If you're not sure, update with your platform and one of us will tell you how to tell.)
A:
The only reason why the code can become slower is that you have big elements in both lists which share a lot of common elements (so the list1[curIndex] in list2 takes more time).
Here are a couple of ways to fix this:
If you don't care about the order, convert both lists into sets and use set1.difference(set2)
If the order in list1 is important, then at least convert list2 into a set because in is much faster with a set.
Lastly, try a filter: filter(list1, lambda x: x not in set2)
[EDIT] Since set() doesn't work on recursive lists (didn't expect that), try:
result = filter(list1, lambda x: x not in list2)
It should still be much faster than your version. If it isn't, then your last option is to make sure that there can't be duplicate elements in either list. That would allow you to remove items from both lists (and therefore making the compare ever cheaper as you find elements from list2).
A:
EDIT: I've updated my answer to account for lists being unhashable, as well as some other feedback. This one is even tested.
It probably relates to the cost of poping an item out of a middle of a list.
Alternatively have you tried using sets to handle this?
def difference(list1, list2):
return [x for x in list1 if tuple(x) in set(tuple(y) for y in list2)]
You can then set list one to the resulting list if that is your intention by doing
list1 = difference(list1, list2)
A:
The often suggested set wont work here, because the two lists contain lists, which are unhashable. You need to change your data structure first.
You can
convert the sublists into tuples or class instances to make them hashable, then use sets.
Keep both lists sorted, then you just have to compare the lists' heads.
|
python function slowing down for no apparent reason
|
I have a python function defined as follows which i use to delete from list1 the items which are already in list2. I am using python 2.6.2 on windows XP
def compareLists(list1, list2):
curIndex = 0
while curIndex < len(list1):
if list1[curIndex] in list2:
list1.pop(curIndex)
else:
curIndex += 1
Here, list1 and list2 are a list of lists
list1 = [ ['a', 11221, '2232'], ['b', 1321, '22342'] .. ]
# list2 has a similar format.
I tried this function with list1 with 38,000 elements and list2 with 150,000 elements. If i put in a print statement to print the current iteration, I find that the function slows down with each iterations. At first, it processes around 1000 or more items in a second and then after a while it reduces to around 20-50 a second. Why can that be happening?
EDIT: In the case with my data, the curIndex remains 0 or very close to 0 so the pop operation on list1 is almost always on the first item.
If possible, can someone also suggest a better way of doing the same thing in a different way?
|
[
"Try a more pythonic approach to the filtering, something like\n[x for x in list1 if x not in set(list2)]\n\nConverting both lists to sets is unnessescary, and will be very slow and memory hungry on large amounts of data.\nSince your data is a list of lists, you need to do something in order to hash it.\nTry out\nlist2_set = set([tuple(x) for x in list2])\ndiff = [x for x in list1 if tuple(x) not in list2_set]\n\nI tested out your original function, and my approach, using the following test data:\nlist1 = [[x+1, x*2] for x in range(38000)]\nlist2 = [[x+1, x*2] for x in range(10000, 160000)]\n\nTimings - not scientific, but still:\n #Original function\n real 2m16.780s\n user 2m16.744s\n sys 0m0.017s\n\n #My function\n real 0m0.433s\n user 0m0.423s\n sys 0m0.007s\n\n",
"There are 2 issues that cause your algorithm to scale poorly:\n\nx in list is an O(n) operation.\npop(n) where n is in the middle of the array is an O(n) operation.\n\nBoth situations cause it to scale poorly O(n^2) for large amounts of data. gnud's implementation would probably be the best solution since it solves both problems without changing the order of elements or removing potential duplicates.\n",
"If we rule the data structure itself out, look at your memory usage next. If you end up asking the OS to swap in for you (i.e., the list takes up more memory than you have), Python's going to sit in iowait waiting on the OS to get the pages from disk, which makes sense given your description.\nIs Python sitting in a jacuzzi of iowait when this slowdown happens? Anything else going on in the environment?\n(If you're not sure, update with your platform and one of us will tell you how to tell.)\n",
"The only reason why the code can become slower is that you have big elements in both lists which share a lot of common elements (so the list1[curIndex] in list2 takes more time).\nHere are a couple of ways to fix this:\n\nIf you don't care about the order, convert both lists into sets and use set1.difference(set2)\nIf the order in list1 is important, then at least convert list2 into a set because in is much faster with a set.\nLastly, try a filter: filter(list1, lambda x: x not in set2)\n\n[EDIT] Since set() doesn't work on recursive lists (didn't expect that), try:\nresult = filter(list1, lambda x: x not in list2)\n\nIt should still be much faster than your version. If it isn't, then your last option is to make sure that there can't be duplicate elements in either list. That would allow you to remove items from both lists (and therefore making the compare ever cheaper as you find elements from list2).\n",
"EDIT: I've updated my answer to account for lists being unhashable, as well as some other feedback. This one is even tested.\nIt probably relates to the cost of poping an item out of a middle of a list.\nAlternatively have you tried using sets to handle this?\ndef difference(list1, list2):\n return [x for x in list1 if tuple(x) in set(tuple(y) for y in list2)]\n\nYou can then set list one to the resulting list if that is your intention by doing\nlist1 = difference(list1, list2)\n\n",
"The often suggested set wont work here, because the two lists contain lists, which are unhashable. You need to change your data structure first.\nYou can\n\nconvert the sublists into tuples or class instances to make them hashable, then use sets.\nKeep both lists sorted, then you just have to compare the lists' heads.\n\n"
] |
[
12,
3,
2,
2,
1,
0
] |
[] |
[] |
[
"python"
] |
stackoverflow_0001723494_python.txt
|
Q:
Get django-paypal working with pycrypto?
I would like to use the button encryption in django-paypal, but it requires M2Crypto which will not build on webfaction servers. Tech support at Webfaction told me that pycrypto is already installed on the system, but I am too dumb to translate from M2Crypto to pycrypto.
Can anyone tell me how to convert the following to work with pycrypto (if possible)? This is just a small snip showing he encryption, I can post the entire function if needed.
s = SMIME.SMIME()
s.load_key_bio(BIO.openfile(CERT), BIO.openfile(PUB_CERT))
p7 = s.sign(BIO.MemoryBuffer(plaintext), flags=SMIME.PKCS7_BINARY)
x509 = X509.load_cert_bio(BIO.openfile(settings.PAYPAL_CERT))
sk = X509.X509_Stack()
sk.push(x509)
s.set_x509_stack(sk)
s.set_cipher(SMIME.Cipher('des_ede3_cbc'))
tmp = BIO.MemoryBuffer()
p7.write_der(tmp)
p7 = s.encrypt(tmp, flags=SMIME.PKCS7_BINARY)
out = BIO.MemoryBuffer()
p7.write(out)
return out.read()
A:
I was able to get it to build. Here is all you need to do to make it happen:
cat >> ~/.pydistutils.cfg << EOF
[build_ext]
include_dirs=/usr/include/openssl
EOF
easy_install-2.5 --install-dir=$HOME/lib/python2.5 --script-dir=$HOME/bin m2crypto
A:
pycrypto is very incomplete. It does not support the padding schemes and formats that you need. Adding support for those formats is not trivial and will require a lot of time.
A:
You may be able to set up a virtual machine locally and duplicate enough of the webfaction server environment to build it yourself. Then upload to somewhere on your pythonpath
|
Get django-paypal working with pycrypto?
|
I would like to use the button encryption in django-paypal, but it requires M2Crypto which will not build on webfaction servers. Tech support at Webfaction told me that pycrypto is already installed on the system, but I am too dumb to translate from M2Crypto to pycrypto.
Can anyone tell me how to convert the following to work with pycrypto (if possible)? This is just a small snip showing he encryption, I can post the entire function if needed.
s = SMIME.SMIME()
s.load_key_bio(BIO.openfile(CERT), BIO.openfile(PUB_CERT))
p7 = s.sign(BIO.MemoryBuffer(plaintext), flags=SMIME.PKCS7_BINARY)
x509 = X509.load_cert_bio(BIO.openfile(settings.PAYPAL_CERT))
sk = X509.X509_Stack()
sk.push(x509)
s.set_x509_stack(sk)
s.set_cipher(SMIME.Cipher('des_ede3_cbc'))
tmp = BIO.MemoryBuffer()
p7.write_der(tmp)
p7 = s.encrypt(tmp, flags=SMIME.PKCS7_BINARY)
out = BIO.MemoryBuffer()
p7.write(out)
return out.read()
|
[
"I was able to get it to build. Here is all you need to do to make it happen:\ncat >> ~/.pydistutils.cfg << EOF\n[build_ext]\ninclude_dirs=/usr/include/openssl\nEOF\neasy_install-2.5 --install-dir=$HOME/lib/python2.5 --script-dir=$HOME/bin m2crypto\n\n",
"pycrypto is very incomplete. It does not support the padding schemes and formats that you need. Adding support for those formats is not trivial and will require a lot of time.\n",
"You may be able to set up a virtual machine locally and duplicate enough of the webfaction server environment to build it yourself. Then upload to somewhere on your pythonpath\n"
] |
[
2,
1,
0
] |
[] |
[] |
[
"django",
"encryption",
"paypal",
"python"
] |
stackoverflow_0001485903_django_encryption_paypal_python.txt
|
Q:
Django unit testing - Why can't I just run ./tests.py on myApp?
So I'm very familiar with manage.py test myapp. But I can't figure out how to make my tests.py work as an stand-alone executable. You may be wondering why I would want to do this.. Well I'm working (now) in Eclipse and I can't seem to figure out how to set up the tool to simply run this command. Regardless it would be very nice to simply wrap tests.py in a simple manner to just run that.
Here is what my tests.py looks like.
"""
This simply tests myapp
"""
import sys
import logging
from django.test import TestCase
from django.conf import settings
from django.test.utils import get_runner
class ModelTest(TestCase):
def test_model_test1(self):
"""
This is test 1
"""
self.failUnlessEqual(1 + 1, 2)
def test_model_test2(self):
"""
This is test 2
"""
self.failUnlessEqual(1 + 1, 2)
def test_model_test3(self):
"""
This is test 3
"""
self.failUnlessEqual(1 + 1, 2)
def run_tests():
test_runner = get_runner(settings)
failures = test_runner([], verbosity=9, interactive=False)
sys.exit(failures)
if __name__ == '__main__':
# Setup Logging
loglevel = logging.DEBUG
logging.basicConfig(format="%(levelname)-8s %(asctime)s %(name)s %(message)s",
datefmt='%m/%d/%y %H:%M:%S', stream=sys.stdout)
log = logging.getLogger("")
run_tests()
I think the solution is located on this line but I can't seem to figure out what the first argument needs to be in order for it to magically start working..
failures = test_runner([], verbosity=9, interactive=False)
Thanks for helping!!
**** Updates ****
What I am looking to do (Doh!) is to simply run "myApp" tests. The problem is that this works (and chmod is not the problem) but it wants to run the entire test suite. I don't want that. I just want to run the myApp test suite.
Thanks again!
A:
You could create an "External Tool" configuration for your project, such as:
Location: ${project_loc}/src/${project_name}/manage.py
Working Directory: ${project_loc}/src/${project_name}/
Arguments: test ${string_prompt}
This will run manage.py test <whatever name you type in the string prompt>.
The values above assume that you created a pydev project in Eclipse and then housed your Django project in the pydev src directory. It also assumes that you have the project name for pydev be the same name of your Django project. It will use the currently selected project in the package explorer to determine project_loc and project_name.
|
Django unit testing - Why can't I just run ./tests.py on myApp?
|
So I'm very familiar with manage.py test myapp. But I can't figure out how to make my tests.py work as an stand-alone executable. You may be wondering why I would want to do this.. Well I'm working (now) in Eclipse and I can't seem to figure out how to set up the tool to simply run this command. Regardless it would be very nice to simply wrap tests.py in a simple manner to just run that.
Here is what my tests.py looks like.
"""
This simply tests myapp
"""
import sys
import logging
from django.test import TestCase
from django.conf import settings
from django.test.utils import get_runner
class ModelTest(TestCase):
def test_model_test1(self):
"""
This is test 1
"""
self.failUnlessEqual(1 + 1, 2)
def test_model_test2(self):
"""
This is test 2
"""
self.failUnlessEqual(1 + 1, 2)
def test_model_test3(self):
"""
This is test 3
"""
self.failUnlessEqual(1 + 1, 2)
def run_tests():
test_runner = get_runner(settings)
failures = test_runner([], verbosity=9, interactive=False)
sys.exit(failures)
if __name__ == '__main__':
# Setup Logging
loglevel = logging.DEBUG
logging.basicConfig(format="%(levelname)-8s %(asctime)s %(name)s %(message)s",
datefmt='%m/%d/%y %H:%M:%S', stream=sys.stdout)
log = logging.getLogger("")
run_tests()
I think the solution is located on this line but I can't seem to figure out what the first argument needs to be in order for it to magically start working..
failures = test_runner([], verbosity=9, interactive=False)
Thanks for helping!!
**** Updates ****
What I am looking to do (Doh!) is to simply run "myApp" tests. The problem is that this works (and chmod is not the problem) but it wants to run the entire test suite. I don't want that. I just want to run the myApp test suite.
Thanks again!
|
[
"You could create an \"External Tool\" configuration for your project, such as:\nLocation: ${project_loc}/src/${project_name}/manage.py\nWorking Directory: ${project_loc}/src/${project_name}/\nArguments: test ${string_prompt}\n\nThis will run manage.py test <whatever name you type in the string prompt>.\nThe values above assume that you created a pydev project in Eclipse and then housed your Django project in the pydev src directory. It also assumes that you have the project name for pydev be the same name of your Django project. It will use the currently selected project in the package explorer to determine project_loc and project_name.\n"
] |
[
1
] |
[
"a. this should be the first line at your code file (tests.py)\n#!/usr/bin/env python\n\nb. run $ chmod +x tests.py \n"
] |
[
-1
] |
[
"django",
"eclipse",
"pydev",
"python",
"unit_testing"
] |
stackoverflow_0001719883_django_eclipse_pydev_python_unit_testing.txt
|
Q:
aspect-oriented techniques in python?
So I have an interesting problem in Python, that could possibly be solved with aspect-oriented techniques. Here's the situation:
I have a bunch of modules, each of which has a bunch of functions.
I have an executable that calls some set of functions in those modules.
When the executable calls one of those functions, I want a log statement generated with the details of the function call (name & parameters)
When one of the modules calls one of the other modules' functions, I do NOT want any log statement generated.
Is there any convenient way to do this in Python, without sticking logging statements inside every one of the modules' functions?
A:
Modify the behavior of the functions in the executable can be done using a decorator:
#!/usr/bin/env python
from module1 import foo
from module2 import bar
def trace(f):
def tracewrapper(*arg, **kw):
arg_str=','.join(['%r'%a for a in arg]+['%s=%s'%(key,kw[key]) for key in kw])
print "%s(%s)" % (f.__name__, arg_str)
return f(*arg, **kw)
return tracewrapper
verbose_functions=[foo,bar] # add whatever functions you want logged here
for func in verbose_functions:
globals()[func.func_name]=trace(func)
Since you are only modifying the definition of the functions in the executable's namespace, the modules' functions remain untouched. When one module's function calls another module's function, it is undecorated by trace and no log statement is generated.
If you would like to log function calls only when they come directly from main(),
then you could use a trace decorator like this:
import traceback
def trace(f,filename,funcname):
def tracewrapper(*arg, **kw):
stacks=traceback.extract_stack()
(s_filename,s_lineno,s_funcname,s_text)=stacks[-2]
# Alternatively, you can search the entire call stack
# for (s_filename,s_lineno,s_funcname,s_text) in stacks:
if s_filename.endswith(filename) and s_funcname==funcname:
arg_str=','.join(['%r'%a for a in arg]+
['%s=%s'%(key,kw[key]) for key in kw])
print "%s(%s)" % (f.__name__, arg_str)
return f(*arg, **kw)
return tracewrapper
verbose_functions=[foo,bar] # add whatever functions you want logged here
for func in verbose_functions:
# You can pass the module's filename and the function name here
globals()[func.func_name]=trace(func,'test.py','main')
Note that with the above trace
def baz():
foo(3,4)
def main():
foo(1,2,'Hi')
bar(x=3)
baz()
would log the foo(1,2,'Hi') and bar(x=3) calls, but not foo(3,4) since this
call does not come directly from main. However, it does come indirectly from main, since main calls baz. If you'd like to log the foo(3,4) call, then you'd want to
loop through the entire stack:
import traceback
def trace(f,filename,funcname):
def tracewrapper(*arg, **kw):
stacks=traceback.extract_stack()
for (s_filename,s_lineno,s_funcname,s_text) in stacks:
if s_filename.endswith(filename) and s_funcname==funcname:
arg_str=','.join(['%r'%a for a in arg]+
['%s=%s'%(key,kw[key]) for key in kw])
print "%s(%s)" % (f.__name__, arg_str)
return f(*arg, **kw)
return tracewrapper
A:
The simplest and first solution that comes to mind, is using a proxy module.
#fooproxy.py
import foo
import logger #not implemented here - use your imagination :)
def bar(baz):
logger.method("foo.bar")
return foo.bar(baz)
#foo.py
def bar(baz):
print "The real McCoy"
#main.py
import fooproxy as foo
foo.bar()
A:
I don't know the right way to do this in a general case, but what comes to mind is just hacking the executable a little. Something like:
class DebugCallWrapper(object):
def __init__(self, callable):
self.callable = callable
def __call__(*args,**kwargs):
log.debug(str(callable) + str(args) + str(kwargs))
callable(*args,**kwargs)
class Top(object):
def __getattribute__(self, name):
real_object = globals()[name]
if callable(real_object):
return DebugCallWrapper(real_object)
else:
return real_object
top = Top()
import foo
#instead of foo.bar()
top.foo.bar()
This kind of thing could get you into a lot of trouble, and the above probably won't be usable without some tweaking. But maybe it's an idea.
|
aspect-oriented techniques in python?
|
So I have an interesting problem in Python, that could possibly be solved with aspect-oriented techniques. Here's the situation:
I have a bunch of modules, each of which has a bunch of functions.
I have an executable that calls some set of functions in those modules.
When the executable calls one of those functions, I want a log statement generated with the details of the function call (name & parameters)
When one of the modules calls one of the other modules' functions, I do NOT want any log statement generated.
Is there any convenient way to do this in Python, without sticking logging statements inside every one of the modules' functions?
|
[
"Modify the behavior of the functions in the executable can be done using a decorator:\n#!/usr/bin/env python\nfrom module1 import foo\nfrom module2 import bar\n\ndef trace(f):\n def tracewrapper(*arg, **kw):\n arg_str=','.join(['%r'%a for a in arg]+['%s=%s'%(key,kw[key]) for key in kw])\n print \"%s(%s)\" % (f.__name__, arg_str)\n return f(*arg, **kw)\n return tracewrapper\n\nverbose_functions=[foo,bar] # add whatever functions you want logged here\nfor func in verbose_functions:\n globals()[func.func_name]=trace(func)\n\nSince you are only modifying the definition of the functions in the executable's namespace, the modules' functions remain untouched. When one module's function calls another module's function, it is undecorated by trace and no log statement is generated.\nIf you would like to log function calls only when they come directly from main(),\nthen you could use a trace decorator like this:\nimport traceback\ndef trace(f,filename,funcname):\n def tracewrapper(*arg, **kw):\n stacks=traceback.extract_stack()\n (s_filename,s_lineno,s_funcname,s_text)=stacks[-2]\n # Alternatively, you can search the entire call stack\n # for (s_filename,s_lineno,s_funcname,s_text) in stacks:\n if s_filename.endswith(filename) and s_funcname==funcname: \n arg_str=','.join(['%r'%a for a in arg]+\n ['%s=%s'%(key,kw[key]) for key in kw])\n print \"%s(%s)\" % (f.__name__, arg_str) \n return f(*arg, **kw)\n return tracewrapper\nverbose_functions=[foo,bar] # add whatever functions you want logged here\nfor func in verbose_functions:\n # You can pass the module's filename and the function name here\n globals()[func.func_name]=trace(func,'test.py','main')\n\nNote that with the above trace\ndef baz():\n foo(3,4)\ndef main():\n foo(1,2,'Hi')\n bar(x=3)\n baz()\n\nwould log the foo(1,2,'Hi') and bar(x=3) calls, but not foo(3,4) since this\ncall does not come directly from main. However, it does come indirectly from main, since main calls baz. If you'd like to log the foo(3,4) call, then you'd want to \nloop through the entire stack:\nimport traceback\ndef trace(f,filename,funcname):\n def tracewrapper(*arg, **kw):\n stacks=traceback.extract_stack() \n for (s_filename,s_lineno,s_funcname,s_text) in stacks:\n if s_filename.endswith(filename) and s_funcname==funcname: \n arg_str=','.join(['%r'%a for a in arg]+\n ['%s=%s'%(key,kw[key]) for key in kw])\n print \"%s(%s)\" % (f.__name__, arg_str) \n return f(*arg, **kw)\n return tracewrapper\n\n",
"The simplest and first solution that comes to mind, is using a proxy module.\n#fooproxy.py\nimport foo\nimport logger #not implemented here - use your imagination :)\n\ndef bar(baz):\n logger.method(\"foo.bar\")\n return foo.bar(baz)\n\n\n#foo.py\ndef bar(baz):\n print \"The real McCoy\"\n\n#main.py\nimport fooproxy as foo\nfoo.bar()\n\n",
"I don't know the right way to do this in a general case, but what comes to mind is just hacking the executable a little. Something like:\nclass DebugCallWrapper(object):\n def __init__(self, callable):\n self.callable = callable\n\n def __call__(*args,**kwargs):\n log.debug(str(callable) + str(args) + str(kwargs))\n callable(*args,**kwargs)\n\nclass Top(object):\n def __getattribute__(self, name):\n real_object = globals()[name]\n if callable(real_object):\n return DebugCallWrapper(real_object)\n else:\n return real_object\n\ntop = Top()\n\nimport foo\n#instead of foo.bar()\ntop.foo.bar()\n\nThis kind of thing could get you into a lot of trouble, and the above probably won't be usable without some tweaking. But maybe it's an idea.\n"
] |
[
5,
0,
0
] |
[] |
[] |
[
"python"
] |
stackoverflow_0001723849_python.txt
|
Q:
Referencing classes in Python
I'm having a spot of bother with Python (using for app engine). I'm fairly new to it (more used to Java), but I had been enjoying....until now.
The following won't work!
class SomeClass(db.Model):
item = db.ReferenceProperty(AnotherClass)
class AnotherClass(db.Model):
otherItem = db.ReferenceProperty(SomeClass)
As far as I am aware, there seems to be no way of getting this to work. Sorry if this is a stupid question. Hopefully if that is the case, I will get a quick answer.
Thanks in advance.
A:
One way to view the "class" keyword in Python is as simply creating a new named scope during the initial execution of your script. So your code throws a NameError: name 'AnotherClass' is not defined exception because Python hasn't executed the class AnotherClass(db.Model): line yet when it executes the self.item = db.ReferenceProperty(AnotherClass) line.
The most straightforward way to fix this: move the initializations of those values into the class's __init__ method (the Python name for a constructor).
class SomeClass(db.Model):
def __init__(self):
self.item = db.ReferenceProperty(AnotherClass)
class AnotherClass(db.Model):
def __init__(self):
self.otherItem = db.ReferenceProperty(SomeClass)
A:
If you mean it won't work because each class want to reference the other, try this:
class SomeClass(db.Model):
item = None
class AnotherClass(db.Model):
otherItem = db.ReferenceProperty(SomeClass)
SomeClass.item = db.ReferenceProperty(AnotherClass)
It conflicts with some metaclass magic if there is any in place ... worth a try though.
|
Referencing classes in Python
|
I'm having a spot of bother with Python (using for app engine). I'm fairly new to it (more used to Java), but I had been enjoying....until now.
The following won't work!
class SomeClass(db.Model):
item = db.ReferenceProperty(AnotherClass)
class AnotherClass(db.Model):
otherItem = db.ReferenceProperty(SomeClass)
As far as I am aware, there seems to be no way of getting this to work. Sorry if this is a stupid question. Hopefully if that is the case, I will get a quick answer.
Thanks in advance.
|
[
"One way to view the \"class\" keyword in Python is as simply creating a new named scope during the initial execution of your script. So your code throws a NameError: name 'AnotherClass' is not defined exception because Python hasn't executed the class AnotherClass(db.Model): line yet when it executes the self.item = db.ReferenceProperty(AnotherClass) line.\nThe most straightforward way to fix this: move the initializations of those values into the class's __init__ method (the Python name for a constructor).\nclass SomeClass(db.Model):\n def __init__(self):\n self.item = db.ReferenceProperty(AnotherClass)\n\nclass AnotherClass(db.Model):\n def __init__(self):\n self.otherItem = db.ReferenceProperty(SomeClass)\n\n",
"If you mean it won't work because each class want to reference the other, try this:\nclass SomeClass(db.Model):\n item = None\n\nclass AnotherClass(db.Model):\n otherItem = db.ReferenceProperty(SomeClass)\n\nSomeClass.item = db.ReferenceProperty(AnotherClass)\n\nIt conflicts with some metaclass magic if there is any in place ... worth a try though.\n"
] |
[
6,
1
] |
[] |
[] |
[
"class",
"definition",
"google_app_engine",
"python"
] |
stackoverflow_0001724316_class_definition_google_app_engine_python.txt
|
Q:
Trace/BPT trap when calling urllib.urlopen
For some reason I'm getting a Trace/BPT trap error when calling urllib.urlopen. I've tried both urllib and urllib2 with identical results. Here is the code which throws the error:
def get_url(url):
from urllib2 import urlopen
if not url or not url.startswith('http://'): return None
return urlopen(url).read() # FIXME!
I should add that this code is running on a CherryPy webserver with web.py.
Someone requested a traceback. Unfortunately, there is none. Trace/BPT trap is outputted to the terminal and the process terminates. E.g.
dloewenherz@andros project $ sudo ./index.py 80
http://0.0.0.0:80/
# Here I visit the page which contains the get_url(url) method
Trace/BPT trap
dloewenherz@andros project $
Edit: I am running OS X 10.6.2, web.py 0.33, Python 2.6.2, and CherryPy 3.1.2.
A:
Adding the following lines to the top of the main file solved the problem:
import urllib2
urllib2.install_opener(urllib2.build_opener())
In other words, it is not enough to import the urllib2 module but you actually need to create the opener in the main thread.
A:
Are you running this under OS X 10.6? Apparently threads and importing modules for the first time does not play well together there. See if you can't import urllib2 outside of the thread?
There are a few more details in the following thread: Trace/BPT trap with Python threading module
I'd try either moving the import of urllib to the top of the same file or, since it seems to be a problem only with importing a module for the first time in a thread, import it somewhere else as well, like in the same file as your main() function.
Edit: Which versions of OS X, Python, CherryPy and web.py are you running? I'm using OS X 10.5.8, Python 2.6, CherryPy 3.1.2 and web.py 0.33 and can't reproduce your problem using the below code:
import web
urls = (
'/', 'index'
)
app = web.application(urls, globals())
class index:
def GET(self):
from urllib2 import urlopen
return urlopen("http://google.se/").read()
if __name__ == "__main__": app.run()
$ sudo python index.py 80
http://0.0.0.0:80/
127.0.0.1:59601 - - [08/Nov/2009 09:46:40] "HTTP/1.1 GET /" - 200 OK
127.0.0.1:59604 - - [08/Nov/2009 09:46:40] "HTTP/1.1 GET /extern_js/f/CgJzdhICc2UgACswCjhBQB0sKzAOOAksKzAYOAQsKzAlOMmIASwrMCY4BSwrMCc4Aiw/dDWkSd2jmF8.js" - 404 Not Found
127.0.0.1:59601 - - [08/Nov/2009 09:46:40] "HTTP/1.1 GET /logos/elmo-hp.gif" - 404 Not Found
127.0.0.1:59601 - - [08/Nov/2009 09:46:40] "HTTP/1.1 GET /images/nav_logo7.png" - 404 Not Found
Is this code enough to reproduce the problem on your end? If not, I need more information in order to be of help.
|
Trace/BPT trap when calling urllib.urlopen
|
For some reason I'm getting a Trace/BPT trap error when calling urllib.urlopen. I've tried both urllib and urllib2 with identical results. Here is the code which throws the error:
def get_url(url):
from urllib2 import urlopen
if not url or not url.startswith('http://'): return None
return urlopen(url).read() # FIXME!
I should add that this code is running on a CherryPy webserver with web.py.
Someone requested a traceback. Unfortunately, there is none. Trace/BPT trap is outputted to the terminal and the process terminates. E.g.
dloewenherz@andros project $ sudo ./index.py 80
http://0.0.0.0:80/
# Here I visit the page which contains the get_url(url) method
Trace/BPT trap
dloewenherz@andros project $
Edit: I am running OS X 10.6.2, web.py 0.33, Python 2.6.2, and CherryPy 3.1.2.
|
[
"Adding the following lines to the top of the main file solved the problem:\nimport urllib2\nurllib2.install_opener(urllib2.build_opener())\n\nIn other words, it is not enough to import the urllib2 module but you actually need to create the opener in the main thread.\n",
"Are you running this under OS X 10.6? Apparently threads and importing modules for the first time does not play well together there. See if you can't import urllib2 outside of the thread?\nThere are a few more details in the following thread: Trace/BPT trap with Python threading module\nI'd try either moving the import of urllib to the top of the same file or, since it seems to be a problem only with importing a module for the first time in a thread, import it somewhere else as well, like in the same file as your main() function.\nEdit: Which versions of OS X, Python, CherryPy and web.py are you running? I'm using OS X 10.5.8, Python 2.6, CherryPy 3.1.2 and web.py 0.33 and can't reproduce your problem using the below code:\nimport web\n\nurls = (\n '/', 'index'\n)\n\napp = web.application(urls, globals())\n\nclass index:\n def GET(self):\n from urllib2 import urlopen\n return urlopen(\"http://google.se/\").read()\n\nif __name__ == \"__main__\": app.run()\n\n\n$ sudo python index.py 80\nhttp://0.0.0.0:80/\n127.0.0.1:59601 - - [08/Nov/2009 09:46:40] \"HTTP/1.1 GET /\" - 200 OK\n127.0.0.1:59604 - - [08/Nov/2009 09:46:40] \"HTTP/1.1 GET /extern_js/f/CgJzdhICc2UgACswCjhBQB0sKzAOOAksKzAYOAQsKzAlOMmIASwrMCY4BSwrMCc4Aiw/dDWkSd2jmF8.js\" - 404 Not Found\n127.0.0.1:59601 - - [08/Nov/2009 09:46:40] \"HTTP/1.1 GET /logos/elmo-hp.gif\" - 404 Not Found\n127.0.0.1:59601 - - [08/Nov/2009 09:46:40] \"HTTP/1.1 GET /images/nav_logo7.png\" - 404 Not Found\n\nIs this code enough to reproduce the problem on your end? If not, I need more information in order to be of help.\n"
] |
[
3,
2
] |
[] |
[] |
[
"python",
"trace",
"urllib",
"urllib2",
"web.py"
] |
stackoverflow_0001628916_python_trace_urllib_urllib2_web.py.txt
|
Q:
Deleting duplicate dictionaries in a list in python
I have two lists of dictionaries
list1 = [ {..}, {..}, ..]
list2 = [ {..}, {..}, ..]
I want to remove the dictionaries in list1 which are in list2. I had a similar problem where I had a list of lists instead of a dictionary and it is solved here
python function slowing down for no apparent reason
If I use the same code which is,
def removeDups(list1, list2):
list2_set = set([tuple(x) for x in list2])
diff = [x for x in list1 if tuple(x) not in list2_set]
return diff
I do not get correct results since dictionaries like
{key1:'a', key2:'b'} and
{key2:'b', key1:'a'}
which are the same are actually considered as different. How can I change the code or what can I do to remove dictionaries from list1 that appear in list2?
A:
You can't use dicts in sets because they're mutable and don't have stable identities. You can work around that by making a tuple out of their items. Note that simply wrapping a dict in a tuple doesn't get around the fact that distinct dicts will still appear to be distinct objects even if they contain the same items.
To turn two "equivalent" dicts into equal objects, take all of their items, sort the items, and then stuff them into a tuple: tuple(sorted(map.items())). Those tuples will properly compare equal to each other if they contain the same items, no matter the order of the original dict.
def removeDups(list1, list2):
set1 = set(tuple(sorted(x.items())) for x in list1)
set2 = set(tuple(sorted(x.items())) for x in list2)
return set1 - set2
|
Deleting duplicate dictionaries in a list in python
|
I have two lists of dictionaries
list1 = [ {..}, {..}, ..]
list2 = [ {..}, {..}, ..]
I want to remove the dictionaries in list1 which are in list2. I had a similar problem where I had a list of lists instead of a dictionary and it is solved here
python function slowing down for no apparent reason
If I use the same code which is,
def removeDups(list1, list2):
list2_set = set([tuple(x) for x in list2])
diff = [x for x in list1 if tuple(x) not in list2_set]
return diff
I do not get correct results since dictionaries like
{key1:'a', key2:'b'} and
{key2:'b', key1:'a'}
which are the same are actually considered as different. How can I change the code or what can I do to remove dictionaries from list1 that appear in list2?
|
[
"You can't use dicts in sets because they're mutable and don't have stable identities. You can work around that by making a tuple out of their items. Note that simply wrapping a dict in a tuple doesn't get around the fact that distinct dicts will still appear to be distinct objects even if they contain the same items.\nTo turn two \"equivalent\" dicts into equal objects, take all of their items, sort the items, and then stuff them into a tuple: tuple(sorted(map.items())). Those tuples will properly compare equal to each other if they contain the same items, no matter the order of the original dict.\ndef removeDups(list1, list2):\n set1 = set(tuple(sorted(x.items())) for x in list1)\n set2 = set(tuple(sorted(x.items())) for x in list2)\n\n return set1 - set2\n\n"
] |
[
5
] |
[] |
[] |
[
"python"
] |
stackoverflow_0001724588_python.txt
|
Q:
Exclude on a many-to-many relationship through a third table
I have a problem making "exclude" querys on tables which have a many-to-many relationship through a third table. I have a table with projects, a table with people and a relationsship table with the flags "is_green, is_yellow, is_red", like:
class Project(models.Model):
...
class Person(models.Model):
projects = models.ManyToManyField(Project, through='Status')
class Status(models.Model):
person = models.ForeignKey(Person)
project = models.ForeignKey(Project)
is_green = models.BooleanField()
...
Now I want to make a query returning all persons, excluding those which do have the flag "is_red" in a specific project. But the following
Person.objects.exclude(project=p, status__is_red=True)
excludes everyone who is registered at project p but has status=red for any project he is registered. Is there a way to tie the second condition to the first?
My approach was to filter on the Status table directly, which works of course. But then I do have a list of "Status" objects instead of "Person" objects.
A:
Maybe this? (untested)
Person.objects.exclude(id__in=Person.objects.filter(project=p, status__is_red=True).values(id))
A:
If you have a list of Status objects called 'objects', you can use
[s.person for s in objects]
to make it into a list of the corresponding Persons.
|
Exclude on a many-to-many relationship through a third table
|
I have a problem making "exclude" querys on tables which have a many-to-many relationship through a third table. I have a table with projects, a table with people and a relationsship table with the flags "is_green, is_yellow, is_red", like:
class Project(models.Model):
...
class Person(models.Model):
projects = models.ManyToManyField(Project, through='Status')
class Status(models.Model):
person = models.ForeignKey(Person)
project = models.ForeignKey(Project)
is_green = models.BooleanField()
...
Now I want to make a query returning all persons, excluding those which do have the flag "is_red" in a specific project. But the following
Person.objects.exclude(project=p, status__is_red=True)
excludes everyone who is registered at project p but has status=red for any project he is registered. Is there a way to tie the second condition to the first?
My approach was to filter on the Status table directly, which works of course. But then I do have a list of "Status" objects instead of "Person" objects.
|
[
"Maybe this? (untested)\nPerson.objects.exclude(id__in=Person.objects.filter(project=p, status__is_red=True).values(id))\n\n",
"If you have a list of Status objects called 'objects', you can use\n[s.person for s in objects]\n\nto make it into a list of the corresponding Persons.\n"
] |
[
4,
0
] |
[] |
[] |
[
"django",
"many_to_many",
"python"
] |
stackoverflow_0001724317_django_many_to_many_python.txt
|
Q:
How can I use PHP's gettext in conjunction with python's gettext?
I have an app that I'm migrating portions of to Django, but Python and PHP have a different string format, e.g., "Hello %1s" in PHP vs. "Hello {0}" or "Hello {name}" in Python.
We'll be maintaining both apps for a while, but is there a way to use the Python format in PHP or vice versa?
A:
PHP's gettext doesn't expand/substitute %s - this is done by output functions (e.g. printf).
It also appears to be the case in Python.
Most importantly, in Python you can use %s to represent strings, see http://docs.python.org/library/stdtypes.html#string-formatting
So you should be able to use %s-style strings in both.
A:
Would something like this php PECL extension help you?
http://pecl.php.net/package/python
Regards.
|
How can I use PHP's gettext in conjunction with python's gettext?
|
I have an app that I'm migrating portions of to Django, but Python and PHP have a different string format, e.g., "Hello %1s" in PHP vs. "Hello {0}" or "Hello {name}" in Python.
We'll be maintaining both apps for a while, but is there a way to use the Python format in PHP or vice versa?
|
[
"PHP's gettext doesn't expand/substitute %s - this is done by output functions (e.g. printf).\nIt also appears to be the case in Python.\nMost importantly, in Python you can use %s to represent strings, see http://docs.python.org/library/stdtypes.html#string-formatting\nSo you should be able to use %s-style strings in both.\n",
"Would something like this php PECL extension help you?\nhttp://pecl.php.net/package/python\nRegards.\n"
] |
[
0,
0
] |
[] |
[] |
[
"gettext",
"php",
"python"
] |
stackoverflow_0001724629_gettext_php_python.txt
|
Q:
Just curious about result from NumPy function!
I have used NumPy for my Master thesis. I've converted parts of the code from MATLAB code, but I have doubts in NumPy/Python when I reference:
m = numpy.ones((10,2))
m[:,0]
which returns:
array([ 1., 1., 1., 1., 1., 1., 1., 1., 1., 1.])
and when I ref to:
m[:,0:1]
it returns:
array([[ 1.],
[ 1.],
[ 1.],
[ 1.],
[ 1.],
[ 1.],
[ 1.],
[ 1.],
[ 1.],
[ 1.]])
that I think it should be, cause same result with MATLAB!!!
A:
This is because numpy has the concept of 1d arrays which Matlab doesn't have. Coupled with numpys broadcasting this provides a powerful simplification (less worrying about inserting transposes everywhere) but does mean you have to think a little bit about translating from Matlab. In this case, extracting a single column with a scalar Numpy simplifies the result to a 1d array - but with a slice it preserves the original dimensions. If you want to stay closer to Matlab semantics you could try using the Matrix class. See NumPy for matlab users page for details. In this case, you could do either of the following:
m[:,0][:,newaxis] # gives same as matlab
np.matrix(m)[:,0] # gives same as matlab
But remember if you use matrix class * becomes matrix multiplication and you need to use multiply() for elementwise. (This is all covered in NumPy for Matlab Users page). Generally I would recommend trying to get used to using 1d arrays where you would have column or row vector in matlab and generally things just work. You only need to worry about column vs row when reassembling them into a 2d array.
You may be interested in automated matlab to python converters such as OMPC (paper) (I think there are others as well).
A:
I'm still learning Python myself, but I think the way that slicing works is that indices point to in-between locations, therefore 0:1 only gets you the first column. Is this what you were asking about?
This is what the documentation has to say:
One way to remember how slices work is
to think of the indices as pointing
between characters, with the left edge
of the first character numbered 0.
Then the right edge of the last
character of a string of n characters
has index n, for example:
+---+---+---+---+---+
| H | e | l | p | A |
+---+---+---+---+---+
0 1 2 3 4 5
-5 -4 -3 -2 -1
A:
I forget what numpy does, but Matlab indexes vectors from 1, not 0. So array(:,0) is an error in Matlab.
|
Just curious about result from NumPy function!
|
I have used NumPy for my Master thesis. I've converted parts of the code from MATLAB code, but I have doubts in NumPy/Python when I reference:
m = numpy.ones((10,2))
m[:,0]
which returns:
array([ 1., 1., 1., 1., 1., 1., 1., 1., 1., 1.])
and when I ref to:
m[:,0:1]
it returns:
array([[ 1.],
[ 1.],
[ 1.],
[ 1.],
[ 1.],
[ 1.],
[ 1.],
[ 1.],
[ 1.],
[ 1.]])
that I think it should be, cause same result with MATLAB!!!
|
[
"This is because numpy has the concept of 1d arrays which Matlab doesn't have. Coupled with numpys broadcasting this provides a powerful simplification (less worrying about inserting transposes everywhere) but does mean you have to think a little bit about translating from Matlab. In this case, extracting a single column with a scalar Numpy simplifies the result to a 1d array - but with a slice it preserves the original dimensions. If you want to stay closer to Matlab semantics you could try using the Matrix class. See NumPy for matlab users page for details. In this case, you could do either of the following:\nm[:,0][:,newaxis] # gives same as matlab\nnp.matrix(m)[:,0] # gives same as matlab\n\nBut remember if you use matrix class * becomes matrix multiplication and you need to use multiply() for elementwise. (This is all covered in NumPy for Matlab Users page). Generally I would recommend trying to get used to using 1d arrays where you would have column or row vector in matlab and generally things just work. You only need to worry about column vs row when reassembling them into a 2d array.\nYou may be interested in automated matlab to python converters such as OMPC (paper) (I think there are others as well).\n",
"I'm still learning Python myself, but I think the way that slicing works is that indices point to in-between locations, therefore 0:1 only gets you the first column. Is this what you were asking about?\nThis is what the documentation has to say:\n\nOne way to remember how slices work is\n to think of the indices as pointing\n between characters, with the left edge\n of the first character numbered 0.\n Then the right edge of the last\n character of a string of n characters\n has index n, for example:\n\n +---+---+---+---+---+\n | H | e | l | p | A |\n +---+---+---+---+---+\n 0 1 2 3 4 5\n-5 -4 -3 -2 -1\n\n",
"I forget what numpy does, but Matlab indexes vectors from 1, not 0. So array(:,0) is an error in Matlab.\n"
] |
[
5,
3,
0
] |
[] |
[] |
[
"matlab",
"numpy",
"python"
] |
stackoverflow_0001724504_matlab_numpy_python.txt
|
Q:
TypeError when trying to upload Pictures from Google App Engine to Picasa with the GData API
I'm trying to write a small tool to upload Pictures from Google App Engine to Picasa. Fetching the image works, but when i try to upload it i get the error "TypeError: stat() argument 1 must be (encoded string without NULL bytes), not str"
The Code basically looks like this:
def getfile(url):
result = urlfetch.fetch(url)
if result.status_code == 200:
return (result.content)
logging.error ("[-] Error fetching URL: %s" % url)
def uploadpicture(comment,pic):
album_url = '/data/feed/api/user/%s/album/%s' % (username, album)
fname = "image.jpg"
entry = gd_client.InsertPhotoSimple(album_url, fname, comment, pic, content_type='image/jpeg')
picurl = "http://brilliantleap.com/blog/frog.jpg"
pic = getfile(picurl)
comment = "Test"
uploadpicture(comment, pic)
The full Stacktrace is:
Traceback (most recent call last):
File "/home/birt/stuff/google/appengine/ext/webapp/init.py", line 507, in call
handler.get(*groups)
File "/home/birt/stuff/app_picasaupload/main.py", line 124, in get
uploadpicture(comment, pic)
File "/home/birt/stuff/app_picasaupload/main.py", line 104, in uploadpicture
entry = gd_client.InsertPhotoSimple(album_url, fname, comment, pic, content_type='image/jpeg')
File "/home/birt/stuff/app_picasaupload/gdata/photos/service.py", line 469, in InsertPhotoSimple
content_type)
File "/home/birt/stuff/app_picasaupload/gdata/photos/service.py", line 398, in InsertPhoto
os.path.exists(filename_or_handle): # it's a file name
File "/usr/lib/python2.5/posixpath.py", line 171, in exists
st = os.stat(path)
File "/home/birt/stuff/google/appengine/tools/dev_appserver.py", line 1109, in call
if not FakeFile.IsFileAccessible(path):
File "/home/birt/stuff/google/appengine/tools/dev_appserver.py", line 1018, in IsFileAccessible
normcase=normcase)
File "/home/birt/stuff/google/appengine/tools/dev_appserver.py", line 1036, in _IsFileAccessibleNoCache
if os.path.isdir(logical_filename):
File "/usr/lib/python2.5/posixpath.py", line 195, in isdir
st = os.stat(path)
TypeError: stat() argument 1 must be (encoded string without NULL bytes), not str
Any Ideas ? :-)
A:
The Solution to this problem was using StringIO :-)
( http://docs.python.org/library/stringio.html )
adding
pic = StringIO.StringIO(pic)
converts the result.content from urlfetch into a file-like format gdata expects.
|
TypeError when trying to upload Pictures from Google App Engine to Picasa with the GData API
|
I'm trying to write a small tool to upload Pictures from Google App Engine to Picasa. Fetching the image works, but when i try to upload it i get the error "TypeError: stat() argument 1 must be (encoded string without NULL bytes), not str"
The Code basically looks like this:
def getfile(url):
result = urlfetch.fetch(url)
if result.status_code == 200:
return (result.content)
logging.error ("[-] Error fetching URL: %s" % url)
def uploadpicture(comment,pic):
album_url = '/data/feed/api/user/%s/album/%s' % (username, album)
fname = "image.jpg"
entry = gd_client.InsertPhotoSimple(album_url, fname, comment, pic, content_type='image/jpeg')
picurl = "http://brilliantleap.com/blog/frog.jpg"
pic = getfile(picurl)
comment = "Test"
uploadpicture(comment, pic)
The full Stacktrace is:
Traceback (most recent call last):
File "/home/birt/stuff/google/appengine/ext/webapp/init.py", line 507, in call
handler.get(*groups)
File "/home/birt/stuff/app_picasaupload/main.py", line 124, in get
uploadpicture(comment, pic)
File "/home/birt/stuff/app_picasaupload/main.py", line 104, in uploadpicture
entry = gd_client.InsertPhotoSimple(album_url, fname, comment, pic, content_type='image/jpeg')
File "/home/birt/stuff/app_picasaupload/gdata/photos/service.py", line 469, in InsertPhotoSimple
content_type)
File "/home/birt/stuff/app_picasaupload/gdata/photos/service.py", line 398, in InsertPhoto
os.path.exists(filename_or_handle): # it's a file name
File "/usr/lib/python2.5/posixpath.py", line 171, in exists
st = os.stat(path)
File "/home/birt/stuff/google/appengine/tools/dev_appserver.py", line 1109, in call
if not FakeFile.IsFileAccessible(path):
File "/home/birt/stuff/google/appengine/tools/dev_appserver.py", line 1018, in IsFileAccessible
normcase=normcase)
File "/home/birt/stuff/google/appengine/tools/dev_appserver.py", line 1036, in _IsFileAccessibleNoCache
if os.path.isdir(logical_filename):
File "/usr/lib/python2.5/posixpath.py", line 195, in isdir
st = os.stat(path)
TypeError: stat() argument 1 must be (encoded string without NULL bytes), not str
Any Ideas ? :-)
|
[
"The Solution to this problem was using StringIO :-)\n( http://docs.python.org/library/stringio.html )\nadding\npic = StringIO.StringIO(pic)\n\nconverts the result.content from urlfetch into a file-like format gdata expects.\n"
] |
[
5
] |
[] |
[] |
[
"gdata_api",
"google_app_engine",
"picasa",
"python",
"typeerror"
] |
stackoverflow_0001715574_gdata_api_google_app_engine_picasa_python_typeerror.txt
|
Q:
Given a list of slices, how do I split a sequence by them?
Given a list of slices, how do I separate a sequence based on them?
I have long amino-acid strings that I would like to split based on start-stop values in a list. An example is probably the most clear way of explaining it:
str = "MSEPAGDVRQNPCGSKAC"
split_points = [[1,3], [7,10], [12,13]]
output >> ['M', '(SEP)', 'AGD', '(VRQN)', 'P', '(CG)', 'SKAC']
The extra parentheses are to show which elements were selected from the split_points list. I don't expect the start-stop points to ever overlap.
I have a bunch of ideas that would work, but seem terribly inefficient (code-length wise), and it seems like there must be a nice pythonic way of doing this.
A:
Strange way to split strings you have there:
def splitter( s, points ):
c = 0
for x,y in points:
yield s[c:x]
yield "(%s)" % s[x:y+1]
c=y+1
yield s[c:]
print list(splitter(str, split_points))
# => ['M', '(SEP)', 'AGD', '(VRQN)', 'P', '(CG)', 'SKAC']
# if some start and endpoints are the same remove empty strings.
print list(x for x in splitter(str, split_points) if x != '')
A:
Here is a simple solution for you. to grab each of the sets specified by the point.
In[4]: str[p[0]:p[1]+1] for p in split_points]
Out[4]: ['SEP', 'VRQN', 'CG']
To get the parenthesis:
In[5]: ['(' + str[p[0]:p[1]+1] + ')' for p in split_points]
Out[5]: ['(SEP)', '(VRQN)', '(CG)']
Here is the cleaner way of doing it to do the whole deal:
results = []
for i in range(len(split_points)):
start, stop = split_points[i]
stop += 1
last_stop = split_points[i-1][1] + 1 if i > 0 else 0
results.append(string[last_stop:start])
results.append('(' + string[start:stop] + ')')
results.append(string[split_points[-1][1]+1:])
All of the below solutions are bad, and more for fun than anything else, do not use them!
This more of a WTF solution, but I figured I'd post it since it was asked for in comments:
split_points = [(x, y+1) for x, y in split_points]
split_points = [((split_points[i-1][1] if i > 0 else 0, p[0]), p) for i, p in zip(range(len(split_points)), split_points)]
results = [string[n[0]:n[1]] + '\n(' + string[m[0]:m[1]] + ')' for n, m in split_points] + [string[split_points[-1][1][1]:]]
results = '\n'.join(results).split()
still trying to figure out the one liner, here's a two:
split_points = [((split_points[i-1][1]+1 if i > 0 else 0, p[0]), (p[0], p[1]+1)) for i, p in zip(range(len(split_points)), split_points)]
print '\n'.join([string[n[0]:n[1]] + '\n(' + string[m[0]:m[1]] + ')' for n, m in split_points] + [string[split_points[-1][1][1]:]]).split()
And the one liner that should never be used:
print '\n'.join([string[n[0]:n[1]] + '\n(' + string[m[0]:m[1]] + ')' for n, m in (((split_points[i-1][1]+1 if i > 0 else 0, p[0]), (p[0], p[1]+1)) for i, p in zip(range(len(split_points)), split_points))] + [string[split_points[-1][1]:]]).split()
A:
Here's some code that will work.
result = []
last_end = 0
for sp in split_points:
result.append(str[last_end:sp[0]])
result.append('(' + str[sp[0]:sp[1]+1] + ')')
last_end = sp[1]+1
result.append(str[last_end:])
print result
If you just want the parts in the parenthesis it becomes a little simpler:
result = [str[sp[0]:sp[1]+1] for sp in split_points]
A:
Probably not for elegance, but just because I can do it in a oneliner :)
>>> reduce(lambda a,ij:a[:-1]+[str[a[-1]:ij[0]],'('+str[ij[0]:ij[1]+1]+')',
ij[1]], split_points, [0])[:-1] + [str[split_points[-1][-1]+1:]]
['M', '(SEP)', 'PAGD', '(VRQN)', 'NP', '(CG)', 'SKAC']
Maybe you like it. Here some explanation:
In your question you pass one set of slices, and implicitly you want to have the complement set of slices as well (to generate the un-parenthesized [is that English?] slices). So basically, each slice [i,j] lacks the previous j. e.g. [7,10] lacks the 3 and [1,3] lacks the 0.
reduce processes lists and at each step passes the output so far (a) plus the next input element (ij). The trick is that apart from producing the plain output, we add each time an extra variable --- a sort of memory --- which is in the next step retrieved in a[-1]. In this particular example we store the last j value, and hence at all times we have the full information to provide both the unparenthesized and the parenthesized substring.
Finally, the memory is stripped with [:-1] and replaced by the remainder of the original str in [str[split_points[-1][-1]+1:]].
A:
Here's a solution that converts your split_points to regular string slices and then prints out the appropriate slices:
str = "MSEPAGDVRQNPCGSKAC"
split_points = [[1, 3], [7, 10], [12, 13]]
adjust = [s for sp in [[x, y + 1] for x, y in split_points] for s in sp]
zipped = zip([None] + adjust, adjust + [None])
out = [('(%s)' if i % 2 else '%s') % str[x:y] for i, (x, y) in
enumerate(zipped)]
print out
>>> ['M', '(SEP)', 'AGD', '(VRQN)', 'P', '(CG)', 'SKAC']
A:
>>> str = "MSEPAGDVRQNPCGSKAC"
>>> split_points = [[1,3], [7,10], [12,13]]
>>>
>>> all_points = sum(split_points, [0]) + [len(str)-1]
>>> map(lambda i,j: str[i:j+1], all_points[:-1], all_points[1:])
['MS', 'SEP', 'PAGDV', 'VRQN', 'NPC', 'CG', 'GSKAC']
>>>
>>> str_out = map(lambda i,j: str[i:j+1], all_points[:-1:2], all_points[1::2])
>>> str_in = map(lambda i,j: str[i:j+1], all_points[1:-1:2], all_points[2::2])
>>> sum(map(list, zip(['(%s)' % s for s in str_in], str_out[1:])), [str_out[0]])
['MS', '(SEP)', 'PAGDV', '(VRQN)', 'NPC', '(CG)', 'GSKAC']
|
Given a list of slices, how do I split a sequence by them?
|
Given a list of slices, how do I separate a sequence based on them?
I have long amino-acid strings that I would like to split based on start-stop values in a list. An example is probably the most clear way of explaining it:
str = "MSEPAGDVRQNPCGSKAC"
split_points = [[1,3], [7,10], [12,13]]
output >> ['M', '(SEP)', 'AGD', '(VRQN)', 'P', '(CG)', 'SKAC']
The extra parentheses are to show which elements were selected from the split_points list. I don't expect the start-stop points to ever overlap.
I have a bunch of ideas that would work, but seem terribly inefficient (code-length wise), and it seems like there must be a nice pythonic way of doing this.
|
[
"Strange way to split strings you have there:\ndef splitter( s, points ):\n c = 0\n for x,y in points:\n yield s[c:x]\n yield \"(%s)\" % s[x:y+1]\n c=y+1\n yield s[c:]\n\nprint list(splitter(str, split_points))\n# => ['M', '(SEP)', 'AGD', '(VRQN)', 'P', '(CG)', 'SKAC']\n\n# if some start and endpoints are the same remove empty strings.\nprint list(x for x in splitter(str, split_points) if x != '')\n\n",
"Here is a simple solution for you. to grab each of the sets specified by the point. \nIn[4]: str[p[0]:p[1]+1] for p in split_points]\nOut[4]: ['SEP', 'VRQN', 'CG']\n\nTo get the parenthesis:\nIn[5]: ['(' + str[p[0]:p[1]+1] + ')' for p in split_points]\nOut[5]: ['(SEP)', '(VRQN)', '(CG)']\n\nHere is the cleaner way of doing it to do the whole deal:\nresults = []\n\nfor i in range(len(split_points)):\n start, stop = split_points[i]\n stop += 1\n\n last_stop = split_points[i-1][1] + 1 if i > 0 else 0\n\n results.append(string[last_stop:start]) \n results.append('(' + string[start:stop] + ')')\n\nresults.append(string[split_points[-1][1]+1:])\n\nAll of the below solutions are bad, and more for fun than anything else, do not use them!\nThis more of a WTF solution, but I figured I'd post it since it was asked for in comments:\nsplit_points = [(x, y+1) for x, y in split_points]\nsplit_points = [((split_points[i-1][1] if i > 0 else 0, p[0]), p) for i, p in zip(range(len(split_points)), split_points)]\nresults = [string[n[0]:n[1]] + '\\n(' + string[m[0]:m[1]] + ')' for n, m in split_points] + [string[split_points[-1][1][1]:]]\nresults = '\\n'.join(results).split()\n\nstill trying to figure out the one liner, here's a two:\nsplit_points = [((split_points[i-1][1]+1 if i > 0 else 0, p[0]), (p[0], p[1]+1)) for i, p in zip(range(len(split_points)), split_points)]\nprint '\\n'.join([string[n[0]:n[1]] + '\\n(' + string[m[0]:m[1]] + ')' for n, m in split_points] + [string[split_points[-1][1][1]:]]).split()\n\nAnd the one liner that should never be used:\nprint '\\n'.join([string[n[0]:n[1]] + '\\n(' + string[m[0]:m[1]] + ')' for n, m in (((split_points[i-1][1]+1 if i > 0 else 0, p[0]), (p[0], p[1]+1)) for i, p in zip(range(len(split_points)), split_points))] + [string[split_points[-1][1]:]]).split()\n\n",
"Here's some code that will work.\nresult = []\nlast_end = 0\nfor sp in split_points:\n result.append(str[last_end:sp[0]])\n result.append('(' + str[sp[0]:sp[1]+1] + ')')\n last_end = sp[1]+1\nresult.append(str[last_end:])\n\nprint result\n\nIf you just want the parts in the parenthesis it becomes a little simpler:\nresult = [str[sp[0]:sp[1]+1] for sp in split_points]\n\n",
"Probably not for elegance, but just because I can do it in a oneliner :)\n>>> reduce(lambda a,ij:a[:-1]+[str[a[-1]:ij[0]],'('+str[ij[0]:ij[1]+1]+')',\n ij[1]], split_points, [0])[:-1] + [str[split_points[-1][-1]+1:]]\n\n['M', '(SEP)', 'PAGD', '(VRQN)', 'NP', '(CG)', 'SKAC']\n\nMaybe you like it. Here some explanation:\nIn your question you pass one set of slices, and implicitly you want to have the complement set of slices as well (to generate the un-parenthesized [is that English?] slices). So basically, each slice [i,j] lacks the previous j. e.g. [7,10] lacks the 3 and [1,3] lacks the 0.\nreduce processes lists and at each step passes the output so far (a) plus the next input element (ij). The trick is that apart from producing the plain output, we add each time an extra variable --- a sort of memory --- which is in the next step retrieved in a[-1]. In this particular example we store the last j value, and hence at all times we have the full information to provide both the unparenthesized and the parenthesized substring.\nFinally, the memory is stripped with [:-1] and replaced by the remainder of the original str in [str[split_points[-1][-1]+1:]].\n",
"Here's a solution that converts your split_points to regular string slices and then prints out the appropriate slices:\nstr = \"MSEPAGDVRQNPCGSKAC\"\nsplit_points = [[1, 3], [7, 10], [12, 13]]\n\nadjust = [s for sp in [[x, y + 1] for x, y in split_points] for s in sp]\nzipped = zip([None] + adjust, adjust + [None])\n\nout = [('(%s)' if i % 2 else '%s') % str[x:y] for i, (x, y) in\n enumerate(zipped)]\n\nprint out\n\n>>> ['M', '(SEP)', 'AGD', '(VRQN)', 'P', '(CG)', 'SKAC']\n\n",
"\n>>> str = \"MSEPAGDVRQNPCGSKAC\"\n>>> split_points = [[1,3], [7,10], [12,13]]\n>>>\n>>> all_points = sum(split_points, [0]) + [len(str)-1]\n>>> map(lambda i,j: str[i:j+1], all_points[:-1], all_points[1:])\n['MS', 'SEP', 'PAGDV', 'VRQN', 'NPC', 'CG', 'GSKAC']\n>>>\n>>> str_out = map(lambda i,j: str[i:j+1], all_points[:-1:2], all_points[1::2])\n>>> str_in = map(lambda i,j: str[i:j+1], all_points[1:-1:2], all_points[2::2])\n>>> sum(map(list, zip(['(%s)' % s for s in str_in], str_out[1:])), [str_out[0]])\n['MS', '(SEP)', 'PAGDV', '(VRQN)', 'NPC', '(CG)', 'GSKAC']\n\n"
] |
[
9,
2,
0,
0,
0,
0
] |
[] |
[] |
[
"python"
] |
stackoverflow_0001724675_python.txt
|
Q:
Lxml html xpath context
I'm using lxml to parse a HTML file and I'd like to know how can I set the context of xpath search. What I mean I that I have a node element and want to make xpath search only inside this node as if it was the root one. For example, I have a form node and xpath search //input return only inputs of the given form as opposed to all inputs of all forms on the page. How can I do that? I've found some xpath context docs here, but it doesn't seems to be quite what I want.
A:
XPath expression //input will match all input elements, anywhere in your document, while .//input will match all inside current context.
Maybe if you improve your scenario description we can help you further.
|
Lxml html xpath context
|
I'm using lxml to parse a HTML file and I'd like to know how can I set the context of xpath search. What I mean I that I have a node element and want to make xpath search only inside this node as if it was the root one. For example, I have a form node and xpath search //input return only inputs of the given form as opposed to all inputs of all forms on the page. How can I do that? I've found some xpath context docs here, but it doesn't seems to be quite what I want.
|
[
"XPath expression //input will match all input elements, anywhere in your document, while .//input will match all inside current context.\nMaybe if you improve your scenario description we can help you further.\n"
] |
[
12
] |
[] |
[] |
[
"lxml",
"python",
"xpath"
] |
stackoverflow_0001725268_lxml_python_xpath.txt
|
Q:
Python Unit Tests - Am I using SetUp wrong?
What am I doing wrong here?
import unittest
class Test_1(unittest.TestCase):
def SetUp(self):
self.data = []
def test_data(self):
self.assertEqual(len(self.data),0)
if __name__=='__main__':
unittest.main()
When I run it, it says:
Traceback (most recent call last):
File "C:...\break_unit_test.py", line
9 , in test_data
self.assertEqual(len(self.data),0) AttributeError: 'Test_1' object has no
attribute 'data'
I'm trying to follow this example.
A:
It must be named setUp, starting with a lowercase s.
|
Python Unit Tests - Am I using SetUp wrong?
|
What am I doing wrong here?
import unittest
class Test_1(unittest.TestCase):
def SetUp(self):
self.data = []
def test_data(self):
self.assertEqual(len(self.data),0)
if __name__=='__main__':
unittest.main()
When I run it, it says:
Traceback (most recent call last):
File "C:...\break_unit_test.py", line
9 , in test_data
self.assertEqual(len(self.data),0) AttributeError: 'Test_1' object has no
attribute 'data'
I'm trying to follow this example.
|
[
"It must be named setUp, starting with a lowercase s.\n"
] |
[
5
] |
[] |
[] |
[
"python",
"unit_testing"
] |
stackoverflow_0001725366_python_unit_testing.txt
|
Q:
How do I strip a character in Django admin after submission before sending value to dB?
I'm more comfortable with PHP & MySQL, don't know a lick of Python (yet) except for the teeny tiny bit I picked up using the Django admin recently...therefore please excuse this very stupid question that I'm embarrassed to ask. In PHP this would be trivial for me...
I'm using a color picker (farbtastic) w/ Django Admin, it's the only one I like for this purpose. Except...it adds a # symbol prior to the hex value.
When the user hits submit, I'd like to validate the field before sending to the database and just strip off that # symbol.
Thanks in advance for helping this Django newbie :)
UPDATE:
Based on S. Lott's code here's what worked:
def save(self):
if self.hexvalue.startswith("#"):
self.hexvalue= self.hexvalue[1:]
super(Color, self).save()
A:
Usually, you do a customized form to clean the data properly. It seems (at first) like overkill, but it's a very general solution.
You have to (1) define the modified Form, and then (2) bind the modified Form into the Admin interface.
On the other hand, you might be able to do this in the model's save method, which is simpler.
class MyThing( models.Model )
color = models.CharField(...)
def save( self, *args, **kw ):
if self.color.startswith("#"):
self.color= self.color[1:]
super( MyThing, self ).save( *args, **kw )
|
How do I strip a character in Django admin after submission before sending value to dB?
|
I'm more comfortable with PHP & MySQL, don't know a lick of Python (yet) except for the teeny tiny bit I picked up using the Django admin recently...therefore please excuse this very stupid question that I'm embarrassed to ask. In PHP this would be trivial for me...
I'm using a color picker (farbtastic) w/ Django Admin, it's the only one I like for this purpose. Except...it adds a # symbol prior to the hex value.
When the user hits submit, I'd like to validate the field before sending to the database and just strip off that # symbol.
Thanks in advance for helping this Django newbie :)
UPDATE:
Based on S. Lott's code here's what worked:
def save(self):
if self.hexvalue.startswith("#"):
self.hexvalue= self.hexvalue[1:]
super(Color, self).save()
|
[
"Usually, you do a customized form to clean the data properly. It seems (at first) like overkill, but it's a very general solution.\nYou have to (1) define the modified Form, and then (2) bind the modified Form into the Admin interface.\nOn the other hand, you might be able to do this in the model's save method, which is simpler.\nclass MyThing( models.Model )\n color = models.CharField(...)\n def save( self, *args, **kw ):\n if self.color.startswith(\"#\"):\n self.color= self.color[1:]\n super( MyThing, self ).save( *args, **kw )\n\n"
] |
[
1
] |
[] |
[] |
[
"django",
"python"
] |
stackoverflow_0001725175_django_python.txt
|
Q:
How to check if a list is empty in Python?
The API I'm working with can return empty [] lists.
The following conditional statements aren't working as expected:
if myList is not None: #not working
pass
if myList is not []: #not working
pass
What will work?
A:
if not myList:
print "Nothing here"
A:
I like Zarembisty's answer. Although, if you want to be more explicit, you can always do:
if len(my_list) == 0:
print "my_list is empty"
A:
Empty lists evaluate to False in boolean contexts (such as if some_list:).
|
How to check if a list is empty in Python?
|
The API I'm working with can return empty [] lists.
The following conditional statements aren't working as expected:
if myList is not None: #not working
pass
if myList is not []: #not working
pass
What will work?
|
[
"if not myList:\n print \"Nothing here\"\n\n",
"I like Zarembisty's answer. Although, if you want to be more explicit, you can always do:\nif len(my_list) == 0:\n print \"my_list is empty\"\n\n",
"Empty lists evaluate to False in boolean contexts (such as if some_list:).\n"
] |
[
207,
21,
19
] |
[] |
[] |
[
"list",
"python"
] |
stackoverflow_0001725517_list_python.txt
|
Q:
Working with JSON in Python 2.6?
I'm really new to Python, but I've picked a problem that actually pertains to work and I think as I figure out how to do it I'll learn along the way.
I have a directory full of JSON-formatted files. I've gotten as far as importing everything in the directory into a list, and iterating through the list to do a simple print that verifies I got the data.
I'm trying to figure out how to actually work with a given JSON object in Python. In javascript, its as simple as
var x = {'asd':'bob'}
alert( x.asd ) //alerts 'bob'
Accessing the various properties on an object is simple dot notation. What's the equivalent for Python?
So this is my code that is doing the import. I'd like to know how to work with the individual objects stored in the list.
#! /usr/local/bin/python2.6
import os, json
#define path to reports
reportspath = "reports/"
# Gets all json files and imports them
dir = os.listdir(reportspath)
jsonfiles = []
for fname in dir:
with open(reportspath + fname,'r') as f:
jsonfiles.append( json.load(f) )
for i in jsonfiles:
print i #prints the contents of each file stored in jsonfiles
A:
What you get when you json.load a file containing the JSON form of a Javascript object such as {'abc': 'def'} is a Python dictionary (normally and affectionately called a dict) (which in this case happens to have the same textual representation as the Javascript object).
To access a specific item, you use indexing, mydict['abc'], while in Javascript you'd use attribute-access notation, myobj.abc. What you get with attribute-access notation in Python are methods that you can call on your dict, for example mydict.keys() would give ['abc'], a list with all the key values that are present in the dictionary (in this case, only one, and it's a string).
Dictionaries are extremely rich in functionality, with a wealth of methods that will make your head spin plus strong support for many Python language structures (for example, you can loop on a dict, for k in mydict:, and k will step through the dictionary's keys, iteratively and sequentially).
|
Working with JSON in Python 2.6?
|
I'm really new to Python, but I've picked a problem that actually pertains to work and I think as I figure out how to do it I'll learn along the way.
I have a directory full of JSON-formatted files. I've gotten as far as importing everything in the directory into a list, and iterating through the list to do a simple print that verifies I got the data.
I'm trying to figure out how to actually work with a given JSON object in Python. In javascript, its as simple as
var x = {'asd':'bob'}
alert( x.asd ) //alerts 'bob'
Accessing the various properties on an object is simple dot notation. What's the equivalent for Python?
So this is my code that is doing the import. I'd like to know how to work with the individual objects stored in the list.
#! /usr/local/bin/python2.6
import os, json
#define path to reports
reportspath = "reports/"
# Gets all json files and imports them
dir = os.listdir(reportspath)
jsonfiles = []
for fname in dir:
with open(reportspath + fname,'r') as f:
jsonfiles.append( json.load(f) )
for i in jsonfiles:
print i #prints the contents of each file stored in jsonfiles
|
[
"What you get when you json.load a file containing the JSON form of a Javascript object such as {'abc': 'def'} is a Python dictionary (normally and affectionately called a dict) (which in this case happens to have the same textual representation as the Javascript object).\nTo access a specific item, you use indexing, mydict['abc'], while in Javascript you'd use attribute-access notation, myobj.abc. What you get with attribute-access notation in Python are methods that you can call on your dict, for example mydict.keys() would give ['abc'], a list with all the key values that are present in the dictionary (in this case, only one, and it's a string).\nDictionaries are extremely rich in functionality, with a wealth of methods that will make your head spin plus strong support for many Python language structures (for example, you can loop on a dict, for k in mydict:, and k will step through the dictionary's keys, iteratively and sequentially).\n"
] |
[
11
] |
[
"To access all properties, try eval() statement before append a list.\nlike:\nimport os\n\n#define path to reports\nreportspath = \"reports/\"\n\n# Gets all json files and imports them\n\ndir = os.listdir(reportspath)\n\n\nfor fname in dir:\n json = eval(open(fname).read())\n # now, json is a normal python object\n print json\n # list all properties...\n print dir(json)\n\n"
] |
[
-1
] |
[
"json",
"python"
] |
stackoverflow_0001725682_json_python.txt
|
Q:
time.sleep and suspend (ie. standby and hibernate)
For example, if I do time.sleep(100) and immediately hibernate my computer for 99 seconds, will the next statement be executed in 1 second or 100 seconds after waking up?
If the answer is 1 second, how do you "sleep" 100 seconds, regardless of the length of hibernate/standby?
A:
time.sleep(N) attempts to sleep at least N seconds of elapsed, AKA "wall-clock" time - of course there can be no guarantee that the sleep will last exactly N seconds; for example, the thread becomes ready to execute again at that time, but it cannot necessarily preempt whatever other thread is executing at that time -- that's the operating system's decision to make, not any programming language's; on the other hand, sleep may be prematurely interrupted by various kinds of events (such as interrupts).
If you can find on your operating system some clock-like thingy that only advances when the system's state is the one you care about (e.g. "not hybernated", in your case), then of course you can go back to sleep if you wake up again "too early".
For example, on Windows 7, QueryUnbiasedInterruptTime is specifically documented to "not include time the system spends in sleep or hibernation" and to use units of 100 nanoseconds. So if you call that, e.g. through ctypes, you can achieve the effect you want:
def unbiasedsleep(n):
start = kernel32.QueryUnbiasedInterruptTime()
target = start + n * 10 * 1000 * 1000
while True:
timeleft = target - kernel32.QueryUnbiasedInterruptTime()
if timeleft > 0:
time.sleep(timeleft / (10 * 1000 * 1000.0))
I don't know how to get the equivalent of QueryUnbiasedInterruptTime on other releases of Windows or other operating systems, but then, you don't tell us what operating system(s) you're interested in, so it would be pretty pointless anyway to present a long laundry lists of approaches which may work similarly in different environments.
A:
I don't know exactly what you are trying to achieve, but
for i in range(100):sleep(1)
might work, as the hibernate would only use up to 1 seconds worth of the sleep
A:
Clearly, you must sleep according to real, elapsed time.
The alternative (sleeping according to some other clock that "somehow" started and stopped) would be unmanageable. How would your application (which is sleeping) be notified of all this starting and stopping activity? Right, it would have to be woken up to be told that it was not supposed to run because the system was hibernating.
Or, perhaps, some super-sophisticated OS-level scheduler could be used to determine if some time the system was "busy" vs. "hibernating" counted against the schedules of various sleeping processes.
All too complex.
Indeed, if you check carefully, sleep is pretty approximate and any Unix Signal will interrupt it. So it's possible to wake early for lots of reasons. Control-C being the big example.
|
time.sleep and suspend (ie. standby and hibernate)
|
For example, if I do time.sleep(100) and immediately hibernate my computer for 99 seconds, will the next statement be executed in 1 second or 100 seconds after waking up?
If the answer is 1 second, how do you "sleep" 100 seconds, regardless of the length of hibernate/standby?
|
[
"time.sleep(N) attempts to sleep at least N seconds of elapsed, AKA \"wall-clock\" time - of course there can be no guarantee that the sleep will last exactly N seconds; for example, the thread becomes ready to execute again at that time, but it cannot necessarily preempt whatever other thread is executing at that time -- that's the operating system's decision to make, not any programming language's; on the other hand, sleep may be prematurely interrupted by various kinds of events (such as interrupts).\nIf you can find on your operating system some clock-like thingy that only advances when the system's state is the one you care about (e.g. \"not hybernated\", in your case), then of course you can go back to sleep if you wake up again \"too early\".\nFor example, on Windows 7, QueryUnbiasedInterruptTime is specifically documented to \"not include time the system spends in sleep or hibernation\" and to use units of 100 nanoseconds. So if you call that, e.g. through ctypes, you can achieve the effect you want:\ndef unbiasedsleep(n):\n start = kernel32.QueryUnbiasedInterruptTime()\n target = start + n * 10 * 1000 * 1000\n while True:\n timeleft = target - kernel32.QueryUnbiasedInterruptTime()\n if timeleft > 0:\n time.sleep(timeleft / (10 * 1000 * 1000.0))\n\nI don't know how to get the equivalent of QueryUnbiasedInterruptTime on other releases of Windows or other operating systems, but then, you don't tell us what operating system(s) you're interested in, so it would be pretty pointless anyway to present a long laundry lists of approaches which may work similarly in different environments.\n",
"I don't know exactly what you are trying to achieve, but\nfor i in range(100):sleep(1)\n\nmight work, as the hibernate would only use up to 1 seconds worth of the sleep\n",
"Clearly, you must sleep according to real, elapsed time.\nThe alternative (sleeping according to some other clock that \"somehow\" started and stopped) would be unmanageable. How would your application (which is sleeping) be notified of all this starting and stopping activity? Right, it would have to be woken up to be told that it was not supposed to run because the system was hibernating.\nOr, perhaps, some super-sophisticated OS-level scheduler could be used to determine if some time the system was \"busy\" vs. \"hibernating\" counted against the schedules of various sleeping processes.\nAll too complex. \nIndeed, if you check carefully, sleep is pretty approximate and any Unix Signal will interrupt it. So it's possible to wake early for lots of reasons. Control-C being the big example.\n"
] |
[
5,
3,
0
] |
[] |
[] |
[
"python"
] |
stackoverflow_0001725758_python.txt
|
Q:
CherryPy3 and IIS 6.0
I have a small Python web application using the Cherrypy framework. I am by no means an expert in web servers.
I got Cherrypy working with Apache using mod_python on our Ubuntu server. This time, however, I have to use Windows 2003 and IIS 6.0 to host my site.
The site runs perfectly as a stand alone server - I am just so lost when it comes to getting IIS running. I have spent the past day Googling and blindly trying any and everything to get this running.
I have all the various tools installed that websites have told me to (Python 2.6, CherrpyPy 3, ISAPI-WSGI, PyWin32) and have read all the documentation I can. This blog was the most helpful:
http://whatschrisdoing.com/blog/2008/07/10/turbogears-isapi-wsgi-iis/
But I am still lost as to what I need to run my site. I can't find any thorough examples or how-to's to even start with. I hope someone here can help!
Cheers.
A:
I run CherryPy behind my IIS sites. There are several tricks to get it to work.
When running as the IIS Worker Process identity, you won't have the same permissions as you do when you run the site from your user process. Things will break. In particular, anything that wants to write to the file system will probably not work without some tweaking.
If you're using setuptools, you probably want to install your components with the -Z option (unzips all eggs).
Use win32traceutil to track down problems. Be sure that in your hook script that you're importing win32traceutil. Then, when you're attempting to access the web site, if anything goes wrong, make sure it gets printed to standard out, it'll get logged to the trace utility. Use 'python -m win32traceutil' to see the output from the trace.
It's important to understand the basic process to get an ISAPI application running. I suggest first getting a hello-world WSGI application running under ISAPI_WSGI. Here's an early version of a hook script I used to validate that I was getting CherryPy to work with my web server.
#!python
"""
Things to remember:
easy_install munges permissions on zip eggs.
anything that's installed in a user folder (i.e. setup develop) will probably not work.
There may still exist an issue with static files.
"""
import sys
import os
import isapi_wsgi
# change this to '/myapp' to have the site installed to only a virtual
# directory of the site.
site_root = '/'
if hasattr(sys, "isapidllhandle"):
import win32traceutil
appdir = os.path.dirname(__file__)
egg_cache = os.path.join(appdir, 'egg-tmp')
if not os.path.exists(egg_cache):
os.makedirs(egg_cache)
os.environ['PYTHON_EGG_CACHE'] = egg_cache
os.chdir(appdir)
import cherrypy
import traceback
class Root(object):
@cherrypy.expose
def index(self):
return 'Hai Werld'
def setup_application():
print "starting cherrypy application server"
#app_root = os.path.dirname(__file__)
#sys.path.append(app_root)
app = cherrypy.tree.mount(Root(), site_root)
print "successfully set up the application"
return app
def __ExtensionFactory__():
"The entry point for when the ISAPIDLL is triggered"
try:
# import the wsgi app creator
app = setup_application()
return isapi_wsgi.ISAPISimpleHandler(app)
except:
import traceback
traceback.print_exc()
f = open(os.path.join(appdir, 'critical error.txt'), 'w')
traceback.print_exc(file=f)
f.close()
def install_virtual_dir():
import isapi.install
params = isapi.install.ISAPIParameters()
# Setup the virtual directories - this is a list of directories our
# extension uses - in this case only 1.
# Each extension has a "script map" - this is the mapping of ISAPI
# extensions.
sm = [
isapi.install.ScriptMapParams(Extension="*", Flags=0)
]
vd = isapi.install.VirtualDirParameters(
Server="CherryPy Web Server",
Name=site_root,
Description = "CherryPy Application",
ScriptMaps = sm,
ScriptMapUpdate = "end",
)
params.VirtualDirs = [vd]
isapi.install.HandleCommandLine(params)
if __name__=='__main__':
# If run from the command-line, install ourselves.
install_virtual_dir()
This script does several things. It (a) acts as the installer, installing itself into IIS [install_virtual_dir], (b) contains the entry point when IIS loads the DLL [__ExtensionFactory__], and (c) it creates the CherryPy WSGI instance consumed by the ISAPI handler [setup_application].
If you place this in your \inetpub\cherrypy directory and run it, it will attempt to install itself to the root of your IIS web site named "CherryPy Web Server".
You're also welcome to take a look at my production web site code, which has refactored all of this into different modules.
A:
OK, I got it working. Thanks to Jason and all his help. I needed to call
cherrypy.config.update({
'tools.sessions.on': True
})
return cherrypy.tree.mount(Root(), '/', config=path_to_config)
I had this in the config file under [/] but for some reason it did not like that. Now I can get my web app up and running - then I think I will try and work out why it needs that config update and doesn't like the config file I have...
|
CherryPy3 and IIS 6.0
|
I have a small Python web application using the Cherrypy framework. I am by no means an expert in web servers.
I got Cherrypy working with Apache using mod_python on our Ubuntu server. This time, however, I have to use Windows 2003 and IIS 6.0 to host my site.
The site runs perfectly as a stand alone server - I am just so lost when it comes to getting IIS running. I have spent the past day Googling and blindly trying any and everything to get this running.
I have all the various tools installed that websites have told me to (Python 2.6, CherrpyPy 3, ISAPI-WSGI, PyWin32) and have read all the documentation I can. This blog was the most helpful:
http://whatschrisdoing.com/blog/2008/07/10/turbogears-isapi-wsgi-iis/
But I am still lost as to what I need to run my site. I can't find any thorough examples or how-to's to even start with. I hope someone here can help!
Cheers.
|
[
"I run CherryPy behind my IIS sites. There are several tricks to get it to work.\n\nWhen running as the IIS Worker Process identity, you won't have the same permissions as you do when you run the site from your user process. Things will break. In particular, anything that wants to write to the file system will probably not work without some tweaking.\nIf you're using setuptools, you probably want to install your components with the -Z option (unzips all eggs).\nUse win32traceutil to track down problems. Be sure that in your hook script that you're importing win32traceutil. Then, when you're attempting to access the web site, if anything goes wrong, make sure it gets printed to standard out, it'll get logged to the trace utility. Use 'python -m win32traceutil' to see the output from the trace.\n\nIt's important to understand the basic process to get an ISAPI application running. I suggest first getting a hello-world WSGI application running under ISAPI_WSGI. Here's an early version of a hook script I used to validate that I was getting CherryPy to work with my web server.\n#!python\n\n\"\"\"\nThings to remember:\neasy_install munges permissions on zip eggs.\nanything that's installed in a user folder (i.e. setup develop) will probably not work.\nThere may still exist an issue with static files.\n\"\"\"\n\n\nimport sys\nimport os\nimport isapi_wsgi\n\n# change this to '/myapp' to have the site installed to only a virtual\n# directory of the site.\nsite_root = '/'\n\nif hasattr(sys, \"isapidllhandle\"):\n import win32traceutil\n\nappdir = os.path.dirname(__file__)\negg_cache = os.path.join(appdir, 'egg-tmp')\nif not os.path.exists(egg_cache):\n os.makedirs(egg_cache)\nos.environ['PYTHON_EGG_CACHE'] = egg_cache\nos.chdir(appdir)\n\nimport cherrypy\nimport traceback\n\nclass Root(object):\n @cherrypy.expose\n def index(self):\n return 'Hai Werld'\n\ndef setup_application():\n print \"starting cherrypy application server\"\n #app_root = os.path.dirname(__file__)\n #sys.path.append(app_root)\n app = cherrypy.tree.mount(Root(), site_root)\n print \"successfully set up the application\"\n return app\n\ndef __ExtensionFactory__():\n \"The entry point for when the ISAPIDLL is triggered\"\n try:\n # import the wsgi app creator\n app = setup_application()\n return isapi_wsgi.ISAPISimpleHandler(app)\n except:\n import traceback\n traceback.print_exc()\n f = open(os.path.join(appdir, 'critical error.txt'), 'w')\n traceback.print_exc(file=f)\n f.close()\n\ndef install_virtual_dir():\n import isapi.install\n params = isapi.install.ISAPIParameters()\n # Setup the virtual directories - this is a list of directories our\n # extension uses - in this case only 1.\n # Each extension has a \"script map\" - this is the mapping of ISAPI\n # extensions.\n sm = [\n isapi.install.ScriptMapParams(Extension=\"*\", Flags=0)\n ]\n vd = isapi.install.VirtualDirParameters(\n Server=\"CherryPy Web Server\",\n Name=site_root,\n Description = \"CherryPy Application\",\n ScriptMaps = sm,\n ScriptMapUpdate = \"end\",\n )\n params.VirtualDirs = [vd]\n isapi.install.HandleCommandLine(params)\n\nif __name__=='__main__':\n # If run from the command-line, install ourselves.\n install_virtual_dir()\n\nThis script does several things. It (a) acts as the installer, installing itself into IIS [install_virtual_dir], (b) contains the entry point when IIS loads the DLL [__ExtensionFactory__], and (c) it creates the CherryPy WSGI instance consumed by the ISAPI handler [setup_application].\nIf you place this in your \\inetpub\\cherrypy directory and run it, it will attempt to install itself to the root of your IIS web site named \"CherryPy Web Server\".\nYou're also welcome to take a look at my production web site code, which has refactored all of this into different modules.\n",
"OK, I got it working. Thanks to Jason and all his help. I needed to call\ncherrypy.config.update({\n 'tools.sessions.on': True\n})\nreturn cherrypy.tree.mount(Root(), '/', config=path_to_config)\n\nI had this in the config file under [/] but for some reason it did not like that. Now I can get my web app up and running - then I think I will try and work out why it needs that config update and doesn't like the config file I have...\n"
] |
[
10,
2
] |
[] |
[] |
[
"cherrypy",
"iis_6",
"isapi_wsgi",
"python"
] |
stackoverflow_0001677828_cherrypy_iis_6_isapi_wsgi_python.txt
|
Q:
How to connect to a GObject signal in python, without it keeping a reference to the connecter?
The problem is basically this, in python's gobject and gtk bindings. Assume we have a class that binds to a signal when constructed:
class ClipboardMonitor (object):
def __init__(self):
clip = gtk.clipboard_get(gtk.gdk.SELECTION_CLIPBOARD)
clip.connect("owner-change", self._clipboard_changed)
The problem is now that, no instance of ClipboardMonitor will ever die. The gtk clipboard is an application-wide object, and connecting to it keeps a reference to the object, since we use the callback self._clipboard_changed.
I'm debating how to work around this using weak references (weakref module), but I have yet to come up with a plan. Anyone have an idea how to pass a callback to the signal registration, and have it behave like a weak reference (if the signal callback is called when the ClipboardMonitor instance is out of scope, it should be a no-op).
Addition: Phrased independently of GObject or GTK+:
How do you provide a callback method to an opaque object, with weakref semantics? If the connecting object goes out of scope, it should be deleted and the callback should act as a no-op; the connectee should not hold a reference to the connector.
To clarify: I explicitly want to avoid having to call a "destructor/finalizer" method
A:
The standard way is to disconnect the signal. This however needs to have a destructor-like method in your class, called explicitly by code which maintains your object. This is necessary, because otherwise you'll get circular dependency.
class ClipboardMonitor(object):
[...]
def __init__(self):
self.clip = gtk.clipboard_get(gtk.gdk.SELECTION_CLIPBOARD)
self.signal_id = self.clip.connect("owner-change", self._clipboard_changed)
def close(self):
self.clip.disconnect(self.signal_id)
As you pointed out, you need weakrefs if you want to avoid explicite destroying. I would write a weak callback factory, like:
import weakref
class CallbackWrapper(object):
def __init__(self, sender, callback):
self.weak_obj = weakref.ref(callback.im_self)
self.weak_fun = weakref.ref(callback.im_func)
self.sender = sender
self.handle = None
def __call__(self, *things):
obj = self.weak_obj()
fun = self.weak_fun()
if obj is not None and fun is not None:
return fun(obj, *things)
elif self.handle is not None:
self.sender.disconnect(self.handle)
self.handle = None
self.sender = None
def weak_connect(sender, signal, callback):
wrapper = CallbackWrapper(sender, callback)
wrapper.handle = sender.connect(signal, wrapper)
return wrapper
(this is a proof of concept code, works for me -- you should probably adapt this piece to your needs). Few notes:
I am storing callback object and function separatelly. You cannot simply make a weakref of a bound method, because bound methods are very temporary objects. Actually weakref.ref(obj.method) will destroy the bound method object instantly after creating a weakref. I didn't check whether it is needed to store a weakref to the function too... I guess if your code is static, you probably can avoid that.
The object wrapper will remove itself from the signal sender when it notices that the weak reference ceased to exist. This is also necessary to destroy the circular dependence between the CallbackWrapper and the signal sender object.
A:
(This answer tracks my progress)
This second version will disconnect as well; I have a convenience function for gobjects, but I actually need this class for a more general case -- both for D-Bus signal callbacks and GObject callbacks.
Anyway, what can one call the WeakCallback implementation style? It is a very clean encapsulation of the weak callback, but with the gobject/dbus specialization unnoticeably tacked on. Beats writing two subclasses for those two cases.
import weakref
class WeakCallback (object):
"""A Weak Callback object that will keep a reference to
the connecting object with weakref semantics.
This allows to connect to gobject signals without it keeping
the connecting object alive forever.
Will use @gobject_token or @dbus_token if set as follows:
sender.disconnect(gobject_token)
dbus_token.remove()
"""
def __init__(self, obj, attr):
"""Create a new Weak Callback calling the method @obj.@attr"""
self.wref = weakref.ref(obj)
self.callback_attr = attr
self.gobject_token = None
self.dbus_token = None
def __call__(self, *args, **kwargs):
obj = self.wref()
if obj:
attr = getattr(obj, self.callback_attr)
attr(*args, **kwargs)
elif self.gobject_token:
sender = args[0]
sender.disconnect(self.gobject_token)
self.gobject_token = None
elif self.dbus_token:
self.dbus_token.remove()
self.dbus_token = None
def gobject_connect_weakly(sender, signal, connector, attr, *user_args):
"""Connect weakly to GObject @sender's @signal,
with a callback in @connector named @attr.
"""
wc = WeakCallback(connector, attr)
wc.gobject_token = sender.connect(signal, wc, *user_args)
A:
not actually tried it yet, but:
class WeakCallback(object):
"""
Used to wrap bound methods without keeping a ref to the underlying object.
You can also pass in user_data and user_kwargs in the same way as with
rpartial. Note that refs will be kept to everything you pass in other than
the callback, which will have a weakref kept to it.
"""
def __init__(self, callback, *user_data, **user_kwargs):
self.im_self = weakref.proxy(callback.im_self, self._invalidated)
self.im_func = weakref.proxy(callback.im_func)
self.user_data = user_data
self.user_kwargs = user_kwargs
def __call__(self, *args, **kwargs):
kwargs.update(self.user_kwargs)
args += self.user_data
self.im_func(self.im_self, *args, **kwargs)
def _invalidated(self, im_self):
"""Called by the weakref.proxy object."""
cb = getattr(self, 'cancel_callback', None)
if cb is not None:
cb()
def add_cancel_function(self, cancel_callback):
"""
A ref will be kept to cancel_callback. It will be called back without
any args when the underlying object dies.
You can wrap it in WeakCallback if you want, but that's a bit too
self-referrential for me to do by default. Also, that would stop you
being able to use a lambda as the cancel_callback.
"""
self.cancel_callback = cancel_callback
def weak_connect(sender, signal, callback):
"""
API-compatible with the function described in
http://stackoverflow.com/questions/1364923/. Mostly used as an example.
"""
cb = WeakCallback(callback)
handle = sender.connect(signal, cb)
cb.add_cancel_function(WeakCallback(sender.disconnect, handle))
|
How to connect to a GObject signal in python, without it keeping a reference to the connecter?
|
The problem is basically this, in python's gobject and gtk bindings. Assume we have a class that binds to a signal when constructed:
class ClipboardMonitor (object):
def __init__(self):
clip = gtk.clipboard_get(gtk.gdk.SELECTION_CLIPBOARD)
clip.connect("owner-change", self._clipboard_changed)
The problem is now that, no instance of ClipboardMonitor will ever die. The gtk clipboard is an application-wide object, and connecting to it keeps a reference to the object, since we use the callback self._clipboard_changed.
I'm debating how to work around this using weak references (weakref module), but I have yet to come up with a plan. Anyone have an idea how to pass a callback to the signal registration, and have it behave like a weak reference (if the signal callback is called when the ClipboardMonitor instance is out of scope, it should be a no-op).
Addition: Phrased independently of GObject or GTK+:
How do you provide a callback method to an opaque object, with weakref semantics? If the connecting object goes out of scope, it should be deleted and the callback should act as a no-op; the connectee should not hold a reference to the connector.
To clarify: I explicitly want to avoid having to call a "destructor/finalizer" method
|
[
"The standard way is to disconnect the signal. This however needs to have a destructor-like method in your class, called explicitly by code which maintains your object. This is necessary, because otherwise you'll get circular dependency.\nclass ClipboardMonitor(object):\n [...]\n\n def __init__(self):\n self.clip = gtk.clipboard_get(gtk.gdk.SELECTION_CLIPBOARD)\n self.signal_id = self.clip.connect(\"owner-change\", self._clipboard_changed)\n\n def close(self):\n self.clip.disconnect(self.signal_id)\n\nAs you pointed out, you need weakrefs if you want to avoid explicite destroying. I would write a weak callback factory, like:\nimport weakref\n\nclass CallbackWrapper(object):\n def __init__(self, sender, callback):\n self.weak_obj = weakref.ref(callback.im_self)\n self.weak_fun = weakref.ref(callback.im_func)\n self.sender = sender\n self.handle = None\n\n def __call__(self, *things):\n obj = self.weak_obj()\n fun = self.weak_fun()\n if obj is not None and fun is not None:\n return fun(obj, *things)\n elif self.handle is not None:\n self.sender.disconnect(self.handle)\n self.handle = None\n self.sender = None\n\ndef weak_connect(sender, signal, callback):\n wrapper = CallbackWrapper(sender, callback)\n wrapper.handle = sender.connect(signal, wrapper)\n return wrapper\n\n(this is a proof of concept code, works for me -- you should probably adapt this piece to your needs). Few notes:\n\nI am storing callback object and function separatelly. You cannot simply make a weakref of a bound method, because bound methods are very temporary objects. Actually weakref.ref(obj.method) will destroy the bound method object instantly after creating a weakref. I didn't check whether it is needed to store a weakref to the function too... I guess if your code is static, you probably can avoid that.\nThe object wrapper will remove itself from the signal sender when it notices that the weak reference ceased to exist. This is also necessary to destroy the circular dependence between the CallbackWrapper and the signal sender object.\n\n",
"(This answer tracks my progress)\nThis second version will disconnect as well; I have a convenience function for gobjects, but I actually need this class for a more general case -- both for D-Bus signal callbacks and GObject callbacks.\nAnyway, what can one call the WeakCallback implementation style? It is a very clean encapsulation of the weak callback, but with the gobject/dbus specialization unnoticeably tacked on. Beats writing two subclasses for those two cases.\nimport weakref\n\nclass WeakCallback (object):\n \"\"\"A Weak Callback object that will keep a reference to\n the connecting object with weakref semantics.\n\n This allows to connect to gobject signals without it keeping\n the connecting object alive forever.\n\n Will use @gobject_token or @dbus_token if set as follows:\n sender.disconnect(gobject_token)\n dbus_token.remove()\n \"\"\"\n def __init__(self, obj, attr):\n \"\"\"Create a new Weak Callback calling the method @obj.@attr\"\"\"\n self.wref = weakref.ref(obj)\n self.callback_attr = attr\n self.gobject_token = None\n self.dbus_token = None\n\n def __call__(self, *args, **kwargs):\n obj = self.wref()\n if obj:\n attr = getattr(obj, self.callback_attr)\n attr(*args, **kwargs)\n elif self.gobject_token:\n sender = args[0]\n sender.disconnect(self.gobject_token)\n self.gobject_token = None\n elif self.dbus_token:\n self.dbus_token.remove()\n self.dbus_token = None\n\ndef gobject_connect_weakly(sender, signal, connector, attr, *user_args):\n \"\"\"Connect weakly to GObject @sender's @signal,\n with a callback in @connector named @attr.\n \"\"\"\n wc = WeakCallback(connector, attr)\n wc.gobject_token = sender.connect(signal, wc, *user_args)\n\n",
"not actually tried it yet, but:\nclass WeakCallback(object):\n \"\"\"\n Used to wrap bound methods without keeping a ref to the underlying object.\n You can also pass in user_data and user_kwargs in the same way as with\n rpartial. Note that refs will be kept to everything you pass in other than\n the callback, which will have a weakref kept to it.\n \"\"\"\n def __init__(self, callback, *user_data, **user_kwargs):\n self.im_self = weakref.proxy(callback.im_self, self._invalidated)\n self.im_func = weakref.proxy(callback.im_func)\n self.user_data = user_data\n self.user_kwargs = user_kwargs\n\n def __call__(self, *args, **kwargs):\n kwargs.update(self.user_kwargs)\n args += self.user_data\n self.im_func(self.im_self, *args, **kwargs)\n\n def _invalidated(self, im_self):\n \"\"\"Called by the weakref.proxy object.\"\"\"\n cb = getattr(self, 'cancel_callback', None)\n if cb is not None:\n cb()\n\n def add_cancel_function(self, cancel_callback):\n \"\"\"\n A ref will be kept to cancel_callback. It will be called back without\n any args when the underlying object dies.\n You can wrap it in WeakCallback if you want, but that's a bit too\n self-referrential for me to do by default. Also, that would stop you\n being able to use a lambda as the cancel_callback.\n \"\"\"\n self.cancel_callback = cancel_callback\n\ndef weak_connect(sender, signal, callback):\n \"\"\"\n API-compatible with the function described in\n http://stackoverflow.com/questions/1364923/. Mostly used as an example.\n \"\"\"\n cb = WeakCallback(callback)\n handle = sender.connect(signal, cb)\n cb.add_cancel_function(WeakCallback(sender.disconnect, handle))\n\n"
] |
[
10,
1,
1
] |
[] |
[] |
[
"pygobject",
"pygtk",
"python"
] |
stackoverflow_0001364923_pygobject_pygtk_python.txt
|
Q:
Get functions called in a Python expression
I have a database that holds the name of Python functions and a string for their code. I want the user to be able to enter a Python code and see the result. The problem is that I need to know the names of the functions they call in order to retrieve the code from the database. For instance, if they enter cubic_fit(1, 2, get_data()), I need a way to get the function names cubic_fit and get_data. Is there a good way to do this?
A:
The built-in function compile will do that for you exactly:
>>> compile("cubic_fit(1, 2, get_data())", '<string>', 'eval').co_names
('cubic_fit', 'get_data')
And it is safe to run. No code is actually being executed just compiled.
A:
A quick example to you started. Note that you'll be expecting valid python semantics for this to work.
You can extend this to also parse your arguments...
import token, tokenize, StringIO
def extract_names(src):
rawstr = StringIO.StringIO(unicode(src))
tokens = tokenize.generate_tokens(rawstr.readline)
for i, item in enumerate(tokens):
toktype, toktext, (srow,scol), (erow,ecol), line = item
if token.tok_name[toktype] == 'NAME':
print 'name:', toktext
extract_names("cubic_fit(1, 2, get_data())")
# --> output:
# name: cubic_fit
# name: get_data
A:
If you just want the names, then the compile() and co_names method will work best.
You also might take advantage of the capability of eval() to use any mapping object as its locals parameter. You could create a mapping object to look up and compile the objects from your database as needed by eval().
Example:
class LookitUp(object):
def __init__(self):
# simulate some data
self.d = { "foo": "def foo(a):\n return a + 2"}
def __getitem__(self,key):
localdict = {}
c = compile(self.d.get(key,""),"<string>","exec")
eval(c,globals(),localdict)
return localdict[key]
d = LookitUp()
def bar(a):
return a - 1
print "foo from database :",eval("foo(3)",globals(), d)
print "bar from globals():",eval("bar(3)",globals(), d)
print "foo(bar(3)) :",eval("foo(bar(3))",globals(), d)
Result:
foo from database : 5
bar from globals(): 2
foo(bar(3)) : 4
You may need to modify based on what your source in the database looks like, but it's a place to start.
|
Get functions called in a Python expression
|
I have a database that holds the name of Python functions and a string for their code. I want the user to be able to enter a Python code and see the result. The problem is that I need to know the names of the functions they call in order to retrieve the code from the database. For instance, if they enter cubic_fit(1, 2, get_data()), I need a way to get the function names cubic_fit and get_data. Is there a good way to do this?
|
[
"The built-in function compile will do that for you exactly:\n>>> compile(\"cubic_fit(1, 2, get_data())\", '<string>', 'eval').co_names\n('cubic_fit', 'get_data')\n\nAnd it is safe to run. No code is actually being executed just compiled.\n",
"A quick example to you started. Note that you'll be expecting valid python semantics for this to work.\nYou can extend this to also parse your arguments...\nimport token, tokenize, StringIO\n\ndef extract_names(src):\n rawstr = StringIO.StringIO(unicode(src))\n tokens = tokenize.generate_tokens(rawstr.readline)\n for i, item in enumerate(tokens):\n toktype, toktext, (srow,scol), (erow,ecol), line = item\n if token.tok_name[toktype] == 'NAME':\n print 'name:', toktext\n\nextract_names(\"cubic_fit(1, 2, get_data())\")\n\n# --> output:\n# name: cubic_fit\n# name: get_data\n\n",
"If you just want the names, then the compile() and co_names method will work best.\nYou also might take advantage of the capability of eval() to use any mapping object as its locals parameter. You could create a mapping object to look up and compile the objects from your database as needed by eval().\nExample:\nclass LookitUp(object):\n def __init__(self):\n # simulate some data\n self.d = { \"foo\": \"def foo(a):\\n return a + 2\"}\n\n def __getitem__(self,key):\n localdict = {}\n c = compile(self.d.get(key,\"\"),\"<string>\",\"exec\")\n eval(c,globals(),localdict)\n return localdict[key]\n\nd = LookitUp()\n\ndef bar(a): \n return a - 1\n\nprint \"foo from database :\",eval(\"foo(3)\",globals(), d)\nprint \"bar from globals():\",eval(\"bar(3)\",globals(), d)\nprint \"foo(bar(3)) :\",eval(\"foo(bar(3))\",globals(), d)\n\nResult:\nfoo from database : 5\nbar from globals(): 2\nfoo(bar(3)) : 4\n\nYou may need to modify based on what your source in the database looks like, but it's a place to start.\n"
] |
[
11,
2,
0
] |
[] |
[] |
[
"python"
] |
stackoverflow_0001726251_python.txt
|
Q:
python stdin eof
How to pass python eof to stdin
here is my code
p = Popen(commd,stdout=PIPE,stderr=PIPE,stdin=PIPE)
o = p.communicate(inputstring)[0]
when i run the commd in command line after i input the inputstring windows still expecting a Ctrl+Z to finish accepting input.
How can I pass eof or Ctrl+Z in program?
Thanks!
A:
p.stdin.close()
after p.communicate, finishes the input and sends EOF to commd.
|
python stdin eof
|
How to pass python eof to stdin
here is my code
p = Popen(commd,stdout=PIPE,stderr=PIPE,stdin=PIPE)
o = p.communicate(inputstring)[0]
when i run the commd in command line after i input the inputstring windows still expecting a Ctrl+Z to finish accepting input.
How can I pass eof or Ctrl+Z in program?
Thanks!
|
[
"p.stdin.close()\n\nafter p.communicate, finishes the input and sends EOF to commd.\n"
] |
[
9
] |
[] |
[] |
[
"eof",
"python",
"stdin"
] |
stackoverflow_0001726590_eof_python_stdin.txt
|
Q:
programmatically determine if an evaluation of a function is being assigned?
I would like to do this:
def foo():
if <a magical condition>:
return x
else:
poof()
# or...
def foo():
x = <a magical object>
return x
def poof():
print 'poof!'
bar = foo() # bar points to <a magical object> but poof() is not called
foo() # prints 'poof!'
I guess it comes down to what the circumstanses are when the returned object's __del__ method is called. But maybe there is a better way. Like if the function itself knew it's returned value was being assigned. I guess I'm worried about relying on the timing of the garbage collection. Also I don't like that global at_end_of_program flag.
My solution:
class Magic:
def __del__(s):
poof()
def foo():
x = Magic()
return x
def poof():
if not at_end_of_program:
print 'poof!'
bar = foo() # No poof.
foo() # prints 'poof!'
A:
I'm pretty confused by your question, but I think what you are trying to do is run a function when a value is reassigned.
Instead of doing tricky things with a __del__() method function, I suggest you just put your value into a class instance, and then overload __setattr__(). You could also overload __delattr__() to make sure you catch del(object.x) for your value x.
The very purpose of __setattr__() is to give you a hook to catch when something assigns to a member of your class. And you won't need any strange end_of_program flag. At the end of your program, just get rid of your overloaded function for __delattr__() so it doesn't get called for end-of-program cleanup.
A:
A function can't tell what its return value is used for. Your solution will print poof if you re-assign to bar for example.
What's the real problem you are trying to solve?
|
programmatically determine if an evaluation of a function is being assigned?
|
I would like to do this:
def foo():
if <a magical condition>:
return x
else:
poof()
# or...
def foo():
x = <a magical object>
return x
def poof():
print 'poof!'
bar = foo() # bar points to <a magical object> but poof() is not called
foo() # prints 'poof!'
I guess it comes down to what the circumstanses are when the returned object's __del__ method is called. But maybe there is a better way. Like if the function itself knew it's returned value was being assigned. I guess I'm worried about relying on the timing of the garbage collection. Also I don't like that global at_end_of_program flag.
My solution:
class Magic:
def __del__(s):
poof()
def foo():
x = Magic()
return x
def poof():
if not at_end_of_program:
print 'poof!'
bar = foo() # No poof.
foo() # prints 'poof!'
|
[
"I'm pretty confused by your question, but I think what you are trying to do is run a function when a value is reassigned.\nInstead of doing tricky things with a __del__() method function, I suggest you just put your value into a class instance, and then overload __setattr__(). You could also overload __delattr__() to make sure you catch del(object.x) for your value x.\nThe very purpose of __setattr__() is to give you a hook to catch when something assigns to a member of your class. And you won't need any strange end_of_program flag. At the end of your program, just get rid of your overloaded function for __delattr__() so it doesn't get called for end-of-program cleanup.\n",
"A function can't tell what its return value is used for. Your solution will print poof if you re-assign to bar for example.\nWhat's the real problem you are trying to solve?\n"
] |
[
3,
1
] |
[] |
[] |
[
"python"
] |
stackoverflow_0001726655_python.txt
|
Q:
Unzip part of a file using python gzip module
I am trying to unzip a gzipped file in Python using the gzip module. The pre-condition is that, I get 160 bytesof data at a time, and I need to unzip it before I request for the next 160 bytes. Partial unzipping is OK, before requesting the next 160 bytes. The code I have is
import gzip
import time
import StringIO
file = open('input_cp.gz', 'rb')
buf = file.read(160)
sio = StringIO.StringIO(buf)
f = gzip.GzipFile(fileobj=sio)
data = f.read()
print data
The error I am getting is IOError: CRC check failed. I am assuming this is cuz it expects the entire gzipped content to be present in buf, whereas I am reading in only 160 bytes at a time. Is there a workaround this??
Thanks
A:
Create your own class with a read() method (and whatever else GzipFile needs from fileobj, like close and seek) and pass it to GzipFile. Something like:
class MyBuffer(object):
def __init__(self, input_file):
self.input_file = input_file
def read(self, size=-1):
if size < 0:
size = 160
return self.input_file.read(min(160, size))
Then use it like:
file = open('input_cp.gz', 'rb')
mybuf = MyBuffer(file)
f = gzip.GzipFile(fileobj=mybuf)
data = f.read()
|
Unzip part of a file using python gzip module
|
I am trying to unzip a gzipped file in Python using the gzip module. The pre-condition is that, I get 160 bytesof data at a time, and I need to unzip it before I request for the next 160 bytes. Partial unzipping is OK, before requesting the next 160 bytes. The code I have is
import gzip
import time
import StringIO
file = open('input_cp.gz', 'rb')
buf = file.read(160)
sio = StringIO.StringIO(buf)
f = gzip.GzipFile(fileobj=sio)
data = f.read()
print data
The error I am getting is IOError: CRC check failed. I am assuming this is cuz it expects the entire gzipped content to be present in buf, whereas I am reading in only 160 bytes at a time. Is there a workaround this??
Thanks
|
[
"Create your own class with a read() method (and whatever else GzipFile needs from fileobj, like close and seek) and pass it to GzipFile. Something like:\nclass MyBuffer(object):\n def __init__(self, input_file):\n self.input_file = input_file\n\n def read(self, size=-1):\n if size < 0:\n size = 160\n return self.input_file.read(min(160, size))\n\nThen use it like:\nfile = open('input_cp.gz', 'rb')\nmybuf = MyBuffer(file)\nf = gzip.GzipFile(fileobj=mybuf)\ndata = f.read()\n\n"
] |
[
4
] |
[] |
[] |
[
"gzip",
"python",
"unzip"
] |
stackoverflow_0001726696_gzip_python_unzip.txt
|
Q:
How to split the file content by space and end-of-line character?
When I do the following list comprehension I end up with nested lists:
channel_values = [x for x in [ y.split(' ') for y in
open(channel_output_file).readlines() ] if x and not x == '\n']
Basically I have a file composed of this:
7656 7653 7649 7646 7643 7640 7637 7634 7631 7627 7624 7621 7618 7615
8626 8623 8620 8617 8614 8610 8607 8604 8600 8597 8594 8597 8594 4444
<snip several thousand lines>
Where each line of this file is terminated by a new line.
Basically I need to add each number (they are all separated by a single space) into a list.
Is there a better way to do this via list comprehension?
A:
You don't need list comprehensions for this:
channel_values = open(channel_output_file).read().split()
A:
Just do this:
channel_values = open(channel_output_file).read().split()
split() will split according to whitespace that includes ' ' '\t' and '\n'. It will split all the values into one list.
If you want integer values you can do:
channel_values = map(int, open(channel_output_file).read().split())
or with list comprehensions:
channel_values = [int(x) for x in open(channel_output_file).read().split()]
A:
Also, the reason the original list comprehension had nested lists is because you added an extra level of list comprehension with the inner set of square brackets. You meant this:
channel_values = [x for x in y.split(' ') for y in
open(channel_output_file) if x and not x == '\n']
The other answers are still better ways to write the code, but that was the cause of the problem.
A:
Well another problem is that you're leaving the file open. Note that open is an alias for file.
try this:
f = file(channel_output_file)
channel_values = f.read().split()
f.close()
Note they'll be string values so if you want integer ones change the second line to
channel_values = [int(x) for x in f.read().split()]
int(x) will throw a ValueError if you have a non integer value in the file.
A:
If you don't care about dangling file references, and you really must have a list read into memory all at once, the one-liner mentioned in other answers does work:
channel_values = open(channel_output_path).read().split()
In production code, I would probably use a generator, why read all those lines if you don't need them?
def generate_values_for_filename(filename):
with open(filename) as f:
for line in f:
for value in line.split():
yield value
You can always make a list later if you really need to do something other than iterate over values:
channel_values = list(generate_values_for_filename(channel_output_path))
A:
Is there a better way to do this via list comprehension?
Sort of..
Instead of reading each line as an array, with the .readlines() methods, you can just use .read():
channel_values = [x for x in open(channel_output_file).readlines().split(' ')
if x not in [' ', '\n']]
If you need to do anything more complicated, particularly if it involves multiple list-comprehensions, you're almost always better of expanding it into a regular for loop.
out = []
for y in open(channel_output_file).readlines():
for x in y.split(' '):
if x not in [' ', '\n']:
out.append(x)
Or using a for loop and a list-comprehension:
out = []
for y in open(channel_output_file).readlines():
out.extend(
[x for x in y.split(' ')
if x != ' ' and x != '\n'])
Basically, if you can't do something simply with a list comprehension (or need to nest them), list-comprehensions are probably not the best solution.
|
How to split the file content by space and end-of-line character?
|
When I do the following list comprehension I end up with nested lists:
channel_values = [x for x in [ y.split(' ') for y in
open(channel_output_file).readlines() ] if x and not x == '\n']
Basically I have a file composed of this:
7656 7653 7649 7646 7643 7640 7637 7634 7631 7627 7624 7621 7618 7615
8626 8623 8620 8617 8614 8610 8607 8604 8600 8597 8594 8597 8594 4444
<snip several thousand lines>
Where each line of this file is terminated by a new line.
Basically I need to add each number (they are all separated by a single space) into a list.
Is there a better way to do this via list comprehension?
|
[
"You don't need list comprehensions for this:\nchannel_values = open(channel_output_file).read().split()\n\n",
"Just do this:\nchannel_values = open(channel_output_file).read().split()\n\nsplit() will split according to whitespace that includes ' ' '\\t' and '\\n'. It will split all the values into one list.\nIf you want integer values you can do:\nchannel_values = map(int, open(channel_output_file).read().split())\n\nor with list comprehensions:\nchannel_values = [int(x) for x in open(channel_output_file).read().split()]\n\n",
"Also, the reason the original list comprehension had nested lists is because you added an extra level of list comprehension with the inner set of square brackets. You meant this:\nchannel_values = [x for x in y.split(' ') for y in\n open(channel_output_file) if x and not x == '\\n']\n\nThe other answers are still better ways to write the code, but that was the cause of the problem.\n",
"Well another problem is that you're leaving the file open. Note that open is an alias for file.\ntry this:\nf = file(channel_output_file)\nchannel_values = f.read().split()\nf.close()\n\nNote they'll be string values so if you want integer ones change the second line to\nchannel_values = [int(x) for x in f.read().split()]\n\nint(x) will throw a ValueError if you have a non integer value in the file.\n",
"If you don't care about dangling file references, and you really must have a list read into memory all at once, the one-liner mentioned in other answers does work:\nchannel_values = open(channel_output_path).read().split()\n\nIn production code, I would probably use a generator, why read all those lines if you don't need them?\ndef generate_values_for_filename(filename):\n with open(filename) as f:\n for line in f:\n for value in line.split():\n yield value\n\nYou can always make a list later if you really need to do something other than iterate over values:\nchannel_values = list(generate_values_for_filename(channel_output_path))\n\n",
"\nIs there a better way to do this via list comprehension?\n\nSort of..\nInstead of reading each line as an array, with the .readlines() methods, you can just use .read():\nchannel_values = [x for x in open(channel_output_file).readlines().split(' ')\nif x not in [' ', '\\n']]\n\nIf you need to do anything more complicated, particularly if it involves multiple list-comprehensions, you're almost always better of expanding it into a regular for loop.\nout = []\nfor y in open(channel_output_file).readlines():\n for x in y.split(' '):\n if x not in [' ', '\\n']:\n out.append(x)\n\nOr using a for loop and a list-comprehension:\nout = []\nfor y in open(channel_output_file).readlines():\n out.extend(\n [x for x in y.split(' ')\n if x != ' ' and x != '\\n'])\n\nBasically, if you can't do something simply with a list comprehension (or need to nest them), list-comprehensions are probably not the best solution.\n"
] |
[
17,
7,
2,
1,
1,
0
] |
[] |
[] |
[
"list_comprehension",
"python"
] |
stackoverflow_0001724080_list_comprehension_python.txt
|
Q:
How can I use Facebook Connect with Google App Engine without using Django?
I'm developing on the Google App Engine and I would like to integrate Facebook Connect into my site as a means for registering and authenticating. In the past, I relied on Google's Accounts API for user registration. I'm trying to use Google's webapp framework instead of Django but it seems that all the resources regarding Facebook connect and GAE are very Django oriented. I have tried messing around with pyfacebook and miniFB found here at the Facebook docs but I haven't been able to make things work with the webapp framework. I'm having trouble seeing the big picture as far as how I can make this work. What advice can you give me on how to make this work or what I should be considering instead? Should I be focusing on using Javascript instead of client libraries?
Account Linking
How to write a good connect app
A:
It's not Facebook Connect, really, but at least it's webapp FBML handling:
http://github.com/WorldMaker/pyfacebook/.../facebook/webappfb.py
This guy made a post about Facebook Connect on Google AppEngine via webapp framework. (It's stickied in the Connect Authentication forum, with 8515 views.)
Here's an example from May 15: http://myzope.kedai.com.my/blogs/kedai/236
It's based on the Guestbook example webapp, but with Facebook for authentication instead. The author does note that, "there's code duplication (when instantiating pyfacebook) in different classes," and that there should be a better way to do this.
Django sounds like it's better integrated. There's a presentation from 4 months ago on Slideshare called Where Facebook Connects Google App Engine (Robert Mao's talk at Facebook Garage Ireland). It looks like an interesting talk, though no videos of it have been posted at the moment. On slide 13, the following tools are mentioned, including Django: Google App Engine SDK, Eclipse, PyDev, Django, App Engine Patch and pyFacebook. Sample application given: http://github.com/mave99a/fb-guinness/
If you merely want authentication, this Recipe suggests using RPXnow.com for Google, AOL, Yahoo, MySpace, Facebook and OpenID logins with the Webapp Framework. Might be helpful, though doesn't appear at first glance to use Connect, is a contributed howto article on GAE's site for creating a Facebook App with Best Buy Remix.
A:
Most of Facebook Connect (as it was formerly called, now it's "Facebook for Websites") is Javascript. The only serverside thing you really need (assuming you want to integrate it into your own usersystem) is validation of the user's Facebook login. Either minifb or pyfacebook should accomplish this task.
A:
This tutorial might be useful:
http://dollarmani-facebook.blogspot.com/2008/09/facebook-applications.html
|
How can I use Facebook Connect with Google App Engine without using Django?
|
I'm developing on the Google App Engine and I would like to integrate Facebook Connect into my site as a means for registering and authenticating. In the past, I relied on Google's Accounts API for user registration. I'm trying to use Google's webapp framework instead of Django but it seems that all the resources regarding Facebook connect and GAE are very Django oriented. I have tried messing around with pyfacebook and miniFB found here at the Facebook docs but I haven't been able to make things work with the webapp framework. I'm having trouble seeing the big picture as far as how I can make this work. What advice can you give me on how to make this work or what I should be considering instead? Should I be focusing on using Javascript instead of client libraries?
Account Linking
How to write a good connect app
|
[
"It's not Facebook Connect, really, but at least it's webapp FBML handling:\nhttp://github.com/WorldMaker/pyfacebook/.../facebook/webappfb.py\nThis guy made a post about Facebook Connect on Google AppEngine via webapp framework. (It's stickied in the Connect Authentication forum, with 8515 views.)\nHere's an example from May 15: http://myzope.kedai.com.my/blogs/kedai/236\nIt's based on the Guestbook example webapp, but with Facebook for authentication instead. The author does note that, \"there's code duplication (when instantiating pyfacebook) in different classes,\" and that there should be a better way to do this.\nDjango sounds like it's better integrated. There's a presentation from 4 months ago on Slideshare called Where Facebook Connects Google App Engine (Robert Mao's talk at Facebook Garage Ireland). It looks like an interesting talk, though no videos of it have been posted at the moment. On slide 13, the following tools are mentioned, including Django: Google App Engine SDK, Eclipse, PyDev, Django, App Engine Patch and pyFacebook. Sample application given: http://github.com/mave99a/fb-guinness/\nIf you merely want authentication, this Recipe suggests using RPXnow.com for Google, AOL, Yahoo, MySpace, Facebook and OpenID logins with the Webapp Framework. Might be helpful, though doesn't appear at first glance to use Connect, is a contributed howto article on GAE's site for creating a Facebook App with Best Buy Remix.\n",
"Most of Facebook Connect (as it was formerly called, now it's \"Facebook for Websites\") is Javascript. The only serverside thing you really need (assuming you want to integrate it into your own usersystem) is validation of the user's Facebook login. Either minifb or pyfacebook should accomplish this task.\n",
"This tutorial might be useful:\nhttp://dollarmani-facebook.blogspot.com/2008/09/facebook-applications.html\n"
] |
[
10,
4,
1
] |
[] |
[] |
[
"authentication",
"facebook",
"google_app_engine",
"python"
] |
stackoverflow_0001183863_authentication_facebook_google_app_engine_python.txt
|
Q:
Returning array of data mapping values to parameters in python
I have a few functions that return an array of data corresponding to parameters ranges.
Example: for a 2d array a, the a_{ij} value corresponds to the parameter set (param1_i, param2_j). How do I return the result and keep the parameter-value correspondence?
Calling the function for each and every of param1_i, para2_j and returning one value would take ages (far more efficient if you do it in one go)
Break the function into (many) smaller functions and make usage difficult? (the point is to get the values for a range of parameters, 1 value is completely useless)
The best I can come up with is make a new numpy dtype, for example for a 2d array:
tagged2d = np.dtype( [('vals', float, 1), ('params', float, (2,))] )
so that a['vals'][i,j] contains the values and a['params'][i,j] the corresponding parameters.
Any thoughts? Maybe I should just return 2 arrays, one with values, other with parameter tuples?
A:
I recommend your last suggestion... just return two arrays {'values': a, 'params':params}.
There are a few reasons for this.
Primarily, your other solution (using dtype and recarrays) tangles too many things together. For example, what about quantities derived from a that correspond to the same parameters... do you make a new recarray and a new copy of the parameters for that? Even something as simple as 2*a becoming the salient quantity will require that you make difficult decisions.
Recarrays have limitations and this is so easily solved in other ways that it's not worth accepting those limitations.
If you want an easier interrelation between the returned terms, you could put the items in a class. For example, you could have a method that takes a param pair and returns the corresponding result. This way, you wouldn't be limited by the recarray, and you could still construct whatever convenience relationship between the two that you like, and easily make backward-compatible change to behavior, etc.
|
Returning array of data mapping values to parameters in python
|
I have a few functions that return an array of data corresponding to parameters ranges.
Example: for a 2d array a, the a_{ij} value corresponds to the parameter set (param1_i, param2_j). How do I return the result and keep the parameter-value correspondence?
Calling the function for each and every of param1_i, para2_j and returning one value would take ages (far more efficient if you do it in one go)
Break the function into (many) smaller functions and make usage difficult? (the point is to get the values for a range of parameters, 1 value is completely useless)
The best I can come up with is make a new numpy dtype, for example for a 2d array:
tagged2d = np.dtype( [('vals', float, 1), ('params', float, (2,))] )
so that a['vals'][i,j] contains the values and a['params'][i,j] the corresponding parameters.
Any thoughts? Maybe I should just return 2 arrays, one with values, other with parameter tuples?
|
[
"I recommend your last suggestion... just return two arrays {'values': a, 'params':params}.\nThere are a few reasons for this. \n\nPrimarily, your other solution (using dtype and recarrays) tangles too many things together. For example, what about quantities derived from a that correspond to the same parameters... do you make a new recarray and a new copy of the parameters for that? Even something as simple as 2*a becoming the salient quantity will require that you make difficult decisions. \nRecarrays have limitations and this is so easily solved in other ways that it's not worth accepting those limitations.\n\nIf you want an easier interrelation between the returned terms, you could put the items in a class. For example, you could have a method that takes a param pair and returns the corresponding result. This way, you wouldn't be limited by the recarray, and you could still construct whatever convenience relationship between the two that you like, and easily make backward-compatible change to behavior, etc.\n"
] |
[
2
] |
[] |
[] |
[
"arrays",
"numpy",
"python"
] |
stackoverflow_0001726750_arrays_numpy_python.txt
|
Q:
Sorting a 3 parallel list that includes strings and numeric value in Python
how to sort using 3 parallel array lists:
num1 = ['a','b','c,']
num2 = ['apple','pear','grapes']
num3 = [2.5,4.0,.68]
I used 2 for statements followed by a if statement. Sorting by elements the output should be:
a apple 2.5
b pear 4.0
c grapes .68
unfortunately, I am having issues with sorting the 3rd num3 values using the element swapping sort. any ideas
A:
Since you say the lists are parallel, let's group them into tuples, and then sort the list of tuples.
num1 = ['a','b','c']
num2 = ['apple','pear','grapes']
num3 = [2.5,4.0,.68]
lst = zip(num1, num2, num3)
lst.sort()
for x1, x2, x3 in lst:
print x1, x2, x3,
print
The result is:
a apple 2.5 b pear 4.0 c grapes 0.68
A:
From your desired inputs and output it doesn't seem you want any sorting -- just:
num1 = ['a','b','c']
num2 = ['apple','pear','grapes']
num3 = [2.5,4.0,.68]
for item in [x for t in zip(num1, num2, num3) for x in t]:
print item,
print
This does give the output you mention -- is this what you want?
|
Sorting a 3 parallel list that includes strings and numeric value in Python
|
how to sort using 3 parallel array lists:
num1 = ['a','b','c,']
num2 = ['apple','pear','grapes']
num3 = [2.5,4.0,.68]
I used 2 for statements followed by a if statement. Sorting by elements the output should be:
a apple 2.5
b pear 4.0
c grapes .68
unfortunately, I am having issues with sorting the 3rd num3 values using the element swapping sort. any ideas
|
[
"Since you say the lists are parallel, let's group them into tuples, and then sort the list of tuples.\nnum1 = ['a','b','c']\nnum2 = ['apple','pear','grapes']\nnum3 = [2.5,4.0,.68]\n\nlst = zip(num1, num2, num3)\nlst.sort()\n\nfor x1, x2, x3 in lst:\n print x1, x2, x3,\n\nprint\n\nThe result is:\na apple 2.5 b pear 4.0 c grapes 0.68\n",
"From your desired inputs and output it doesn't seem you want any sorting -- just:\nnum1 = ['a','b','c']\nnum2 = ['apple','pear','grapes']\nnum3 = [2.5,4.0,.68]\nfor item in [x for t in zip(num1, num2, num3) for x in t]:\n print item,\nprint\n\nThis does give the output you mention -- is this what you want?\n"
] |
[
2,
1
] |
[] |
[] |
[
"list",
"parallel_processing",
"python",
"sorting"
] |
stackoverflow_0001726865_list_parallel_processing_python_sorting.txt
|
Q:
how to install python-spidermonkey on windows
I'm writing some scripts with python mechanize. One of problems I'm having is it is really hard to find which support javascript supported web client scraping or crawler. I found some such as python-spidermonkey and pykhtml, but most are only supported on Linux.
I want to make my python script with exe file, so definitely I have to install on windows platform.
My question is, is there any method to install python-spidermonkey or pykhtml on Windows?
|
how to install python-spidermonkey on windows
|
I'm writing some scripts with python mechanize. One of problems I'm having is it is really hard to find which support javascript supported web client scraping or crawler. I found some such as python-spidermonkey and pykhtml, but most are only supported on Linux.
I want to make my python script with exe file, so definitely I have to install on windows platform.
My question is, is there any method to install python-spidermonkey or pykhtml on Windows?
|
[] |
[] |
[
"Both these links: http://code.google.com/p/python-spidermonkey/issues/detail?id=5 and http://www.ohloh.net/p/python-spidermonkey say that Spedermonkey is not supported for Windows... yet.\nAs far as I can tell, PyKHTML is not out for Windows yet, but \"support for Windows/Mac should appear in the next few months.\" (http://paul.giannaros.org/pykhtml/)\n"
] |
[
-1
] |
[
"python"
] |
stackoverflow_0001727157_python.txt
|
Q:
Can a python module have a __repr__?
Can a python module have a __repr__? The idea would be to do something like:
import mymodule
print mymodule
EDIT: precision: I mean a user-defined repr!
A:
Short answer: basically the answer is no.
But can't you find the functionality you are looking for using docstrings?
testmodule.py
""" my module test does x and y
"""
class myclass(object):
...
test.py
import testmodule
print testmodule.__doc__
Long answer:
You can define your own __repr__ on a module level (just provide def __repr__(...) but then you'd have to do:
import mymodule
print mymodule.__repr__()
to get the functionality you want.
Have a look at the following python shell session:
>>> import sys # we import the module
>>> sys.__repr__() # works as usual
"<module 'sys' (built-in)>"
>>> sys.__dict__['__repr__'] # but it's not in the modules __dict__ ?
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
KeyError: '__repr__'
>>> sys.__class__.__dict__['__repr__'] # __repr__ is provided on the module type as a slot wrapper
<slot wrapper '__repr__' of 'module' objects>
>>> sys.__class__.__dict__['__repr__'](sys) # which we should feed an instance of the module type
"<module 'sys' (built-in)>"
So I believe the problem lies within these slot wrapper objects which (from what can be read at the link) have the result of bypassing the usual 'python' way of looking up item attributes.
For these class methods CPython returns C pointers to the corresponding methods on these objects (which then get wrapped in the slot wrapper objects to be callable from the python-side).
A:
You can achieve this effect--if you're willing to turn to the Dark Side of the Force.
Add this to mymodule.py:
import sys
class MyReprModule(mymodule.__class__):
def __init__(self, other):
for attr in dir(other):
setattr(self, attr, getattr(other, attr))
def __repr__(self):
return 'ABCDEFGHIJKLMNOQ'
# THIS LINE MUST BE THE LAST LINE IN YOUR MODULE
sys.modules[__name__] = MyReprModule(sys.modules[__name__])
Lo and behold:
>>> import mymodule
>>> print mymodule
ABCDEFGHIJKLMNOQ
I dimly remember, in previous attempts at similarly evil hacks, having trouble setting special attributes like __class__. I didn't have that trouble when testing this. If you run into that problem, just catch the exception and skip that attribute.
A:
Modules can have a __repr__ function, but it isn't invoked when getting the representation of a module.
So no, you can't do what you want.
A:
As a matter of fact, many modules do [have a __repr__]!
>>> import sys
>>> print(sys)
<module 'sys' (built-in)> #read edit, however, this info didn't come from __repr__ !
also try dir(sys) to see __repr__ is there along with __name__ etc..
Edit:
__repr__ seems to be found in modules, in Python 3.0 and up.
As indicated by Ned Batchelder, this methods is not used by Python when it print out the a module. (A quick experiment, where the repr property was re-assigned showed that...)
A:
No, because __repr__ is a special method (I call it a capability), and it is only ever looked up on the class. Your module is just another instance of the module type, so however you would manage to define a __repr__, it would not be called!
|
Can a python module have a __repr__?
|
Can a python module have a __repr__? The idea would be to do something like:
import mymodule
print mymodule
EDIT: precision: I mean a user-defined repr!
|
[
"Short answer: basically the answer is no.\nBut can't you find the functionality you are looking for using docstrings?\ntestmodule.py\n\"\"\" my module test does x and y\n\"\"\"\nclass myclass(object):\n ...\n\ntest.py\nimport testmodule\nprint testmodule.__doc__\n\nLong answer:\nYou can define your own __repr__ on a module level (just provide def __repr__(...) but then you'd have to do:\nimport mymodule\nprint mymodule.__repr__() \n\nto get the functionality you want.\nHave a look at the following python shell session:\n>>> import sys # we import the module\n>>> sys.__repr__() # works as usual\n\"<module 'sys' (built-in)>\"\n>>> sys.__dict__['__repr__'] # but it's not in the modules __dict__ ?\nTraceback (most recent call last):\n File \"<stdin>\", line 1, in <module>\nKeyError: '__repr__'\n>>> sys.__class__.__dict__['__repr__'] # __repr__ is provided on the module type as a slot wrapper\n<slot wrapper '__repr__' of 'module' objects>\n>>> sys.__class__.__dict__['__repr__'](sys) # which we should feed an instance of the module type\n\"<module 'sys' (built-in)>\"\n\nSo I believe the problem lies within these slot wrapper objects which (from what can be read at the link) have the result of bypassing the usual 'python' way of looking up item attributes. \nFor these class methods CPython returns C pointers to the corresponding methods on these objects (which then get wrapped in the slot wrapper objects to be callable from the python-side).\n",
"You can achieve this effect--if you're willing to turn to the Dark Side of the Force.\nAdd this to mymodule.py:\nimport sys\n\nclass MyReprModule(mymodule.__class__):\n def __init__(self, other):\n for attr in dir(other):\n setattr(self, attr, getattr(other, attr))\n\n def __repr__(self):\n return 'ABCDEFGHIJKLMNOQ'\n\n# THIS LINE MUST BE THE LAST LINE IN YOUR MODULE\nsys.modules[__name__] = MyReprModule(sys.modules[__name__])\n\nLo and behold:\n>>> import mymodule\n>>> print mymodule\nABCDEFGHIJKLMNOQ\n\nI dimly remember, in previous attempts at similarly evil hacks, having trouble setting special attributes like __class__. I didn't have that trouble when testing this. If you run into that problem, just catch the exception and skip that attribute.\n",
"Modules can have a __repr__ function, but it isn't invoked when getting the representation of a module. \nSo no, you can't do what you want.\n",
"As a matter of fact, many modules do [have a __repr__]!\n>>> import sys\n>>> print(sys)\n<module 'sys' (built-in)> #read edit, however, this info didn't come from __repr__ !\n\nalso try dir(sys) to see __repr__ is there along with __name__ etc..\nEdit:\n__repr__ seems to be found in modules, in Python 3.0 and up.\nAs indicated by Ned Batchelder, this methods is not used by Python when it print out the a module. (A quick experiment, where the repr property was re-assigned showed that...)\n",
"No, because __repr__ is a special method (I call it a capability), and it is only ever looked up on the class. Your module is just another instance of the module type, so however you would manage to define a __repr__, it would not be called!\n"
] |
[
10,
9,
6,
2,
1
] |
[] |
[] |
[
"module",
"python"
] |
stackoverflow_0001725515_module_python.txt
|
Q:
Log all errors to console or file on Django site
How can I get Django 1.0 to write all errors to the console or a log file when running runserver in debug mode?
I've tried using a middleware class with process_exception function as described in the accepted answer to this question:
How do you log server errors on django sites
The process_exception function is called for some exceptions (eg: assert(False) in views.py) but process_exception is not getting called for other errors like ImportErrors (eg: import thisclassdoesnotexist in urs.py). I'm new to Django/Python. Is this because of some distinction between run-time and compile-time errors? But then I would expect runserver to complain if it was a compile-time error and it doesn't.
I've watched Simon Willison's fantastic presentation on Django debugging (http://simonwillison.net/2008/May/22/debugging/) but I didn't see an option that would work well for me.
In case it's relevant, I'm writing a Facebook app and Facebook masks HTTP 500 errors with their own message rather than showing Django's awesomely informative 500 page. So I need a way for all types of errors to be written to the console or file.
Edit: I guess my expectation is that if Django can return a 500 error page with lots of detail when I have a bad import (ImportError) in urls.py, it should be able to write the same detail to the console or a file without having to add any additional exception handling to the code. I've never seen exception handling around import statements.
Thanks,
Jeff
A:
It's a bit extreme, but for debugging purposes, you can turn on the DEBUG_PROPAGATE_EXCEPTIONS setting. This will allow you to set up your own error handling. The easiest way to set up said error handling would be to override sys.excepthook. This will terminate your application, but it will work. There may be things you can do to make this not kill your app, but this will depend on what platform you're deploying this for. At any rate, never use this in production!
For production, you're pretty much going to have to have extensive error handling in place. One technique I've used is something like this:
>>> def log_error(func):
... def _call_func(*args, **argd):
... try:
... func(*args, **argd)
... except:
... print "error" #substitute your own error handling
... return _call_func
...
>>> @log_error
... def foo(a):
... raise AttributeError
...
>>> foo(1)
error
If you use log_error as a decorator on your view, it will automatically handle whatever errors happened within it.
The process_exception function is called for some exceptions (eg: assert(False) in views.py) but process_exception is not getting called for other errors like ImportErrors (eg: import thisclassdoesnotexist in urs.py). I'm new to Django/Python. Is this because of some distinction between run-time and compile-time errors?
In Python, all errors are run-time errors. The reason why this is causing problems is because these errors occur immediately when the module is imported before your view is ever called. The first method I posted will catch errors like these for debugging. You might be able to figure something out for production, but I'd argue that you have worse problems if you're getting ImportErrors in a production app (and you're not doing any dynamic importing).
A tool like pylint can help you eliminate these kinds of problems though.
A:
The process_exception function is
called for some exceptions (eg:
assert(False) in views.py) but
process_exception is not getting
called for other errors like
ImportErrors (eg: import
thisclassdoesnotexist in urs.py). I'm
new to Django/Python. Is this because
of some distinction between run-time
and compile-time errors?
No, it's just because process_exception middleware is only called if an exception is raised in the view.
I think DEBUG_PROPAGATE_EXCEPTIONS (as mentioned first by Jason Baker) is what you need here, but I don't think you don't need to do anything additional (i.e. sys.excepthook, etc) if you just want the traceback dumped to console.
If you want to do anything more complex with the error (i.e. dump it to file or DB), the simplest approach would be the got_request_exception signal, which Django sends for any request-related exception, whether it was raised in the view or not.
The get_response and handle_uncaught_exception methods of django.core.handlers.BaseHandler are instructive (and brief) reading in this area.
without having to add any additional
exception handling to the code. I've
never seen exception handling around
import statements.
Look around a bit more, you'll see it done (often in cases where you want to handle the absence of a dependency in some particular way). That said, it would of course be quite ugly if you had to go sprinkling additional try-except blocks all over your code to make a global change to how exceptions are handled!
A:
First, there are very few compile-time errors that you'll see through an exception log. If your Python code doesn't have valid syntax, it dies long before logs are opened for writing.
In Django runserver mode, a "print" statement writes to stdout, which you can see. This is not a good long-term solution, however, so don't count on it.
When Django is running under Apache, however, it depends on which plug-in you're using. mod_python isn't easy to deal with. mod_wsgi can be coerced into sending stdout and stderr to a log file.
Your best bet, however, is the logging module. Put an initialization into your top-level urls.py to configure logging. (Or, perhaps, your settings.py)
Be sure that every module has a logger available for writing log messages.
Be sure that every web services call you make has a try/except block around it, and you write the exceptions to your log.
A:
http://groups.google.com/group/django-nashville/browse_thread/thread/b4a258250cfa285a?pli=1
|
Log all errors to console or file on Django site
|
How can I get Django 1.0 to write all errors to the console or a log file when running runserver in debug mode?
I've tried using a middleware class with process_exception function as described in the accepted answer to this question:
How do you log server errors on django sites
The process_exception function is called for some exceptions (eg: assert(False) in views.py) but process_exception is not getting called for other errors like ImportErrors (eg: import thisclassdoesnotexist in urs.py). I'm new to Django/Python. Is this because of some distinction between run-time and compile-time errors? But then I would expect runserver to complain if it was a compile-time error and it doesn't.
I've watched Simon Willison's fantastic presentation on Django debugging (http://simonwillison.net/2008/May/22/debugging/) but I didn't see an option that would work well for me.
In case it's relevant, I'm writing a Facebook app and Facebook masks HTTP 500 errors with their own message rather than showing Django's awesomely informative 500 page. So I need a way for all types of errors to be written to the console or file.
Edit: I guess my expectation is that if Django can return a 500 error page with lots of detail when I have a bad import (ImportError) in urls.py, it should be able to write the same detail to the console or a file without having to add any additional exception handling to the code. I've never seen exception handling around import statements.
Thanks,
Jeff
|
[
"It's a bit extreme, but for debugging purposes, you can turn on the DEBUG_PROPAGATE_EXCEPTIONS setting. This will allow you to set up your own error handling. The easiest way to set up said error handling would be to override sys.excepthook. This will terminate your application, but it will work. There may be things you can do to make this not kill your app, but this will depend on what platform you're deploying this for. At any rate, never use this in production!\nFor production, you're pretty much going to have to have extensive error handling in place. One technique I've used is something like this:\n>>> def log_error(func):\n... def _call_func(*args, **argd):\n... try:\n... func(*args, **argd)\n... except:\n... print \"error\" #substitute your own error handling\n... return _call_func\n...\n>>> @log_error\n... def foo(a):\n... raise AttributeError\n...\n>>> foo(1)\nerror\n\nIf you use log_error as a decorator on your view, it will automatically handle whatever errors happened within it.\n\nThe process_exception function is called for some exceptions (eg: assert(False) in views.py) but process_exception is not getting called for other errors like ImportErrors (eg: import thisclassdoesnotexist in urs.py). I'm new to Django/Python. Is this because of some distinction between run-time and compile-time errors?\n\nIn Python, all errors are run-time errors. The reason why this is causing problems is because these errors occur immediately when the module is imported before your view is ever called. The first method I posted will catch errors like these for debugging. You might be able to figure something out for production, but I'd argue that you have worse problems if you're getting ImportErrors in a production app (and you're not doing any dynamic importing).\nA tool like pylint can help you eliminate these kinds of problems though.\n",
"\nThe process_exception function is\n called for some exceptions (eg:\n assert(False) in views.py) but\n process_exception is not getting\n called for other errors like\n ImportErrors (eg: import\n thisclassdoesnotexist in urs.py). I'm\n new to Django/Python. Is this because\n of some distinction between run-time\n and compile-time errors?\n\nNo, it's just because process_exception middleware is only called if an exception is raised in the view.\nI think DEBUG_PROPAGATE_EXCEPTIONS (as mentioned first by Jason Baker) is what you need here, but I don't think you don't need to do anything additional (i.e. sys.excepthook, etc) if you just want the traceback dumped to console.\nIf you want to do anything more complex with the error (i.e. dump it to file or DB), the simplest approach would be the got_request_exception signal, which Django sends for any request-related exception, whether it was raised in the view or not.\nThe get_response and handle_uncaught_exception methods of django.core.handlers.BaseHandler are instructive (and brief) reading in this area.\n\nwithout having to add any additional\n exception handling to the code. I've\n never seen exception handling around\n import statements.\n\nLook around a bit more, you'll see it done (often in cases where you want to handle the absence of a dependency in some particular way). That said, it would of course be quite ugly if you had to go sprinkling additional try-except blocks all over your code to make a global change to how exceptions are handled!\n",
"First, there are very few compile-time errors that you'll see through an exception log. If your Python code doesn't have valid syntax, it dies long before logs are opened for writing.\nIn Django runserver mode, a \"print\" statement writes to stdout, which you can see. This is not a good long-term solution, however, so don't count on it.\nWhen Django is running under Apache, however, it depends on which plug-in you're using. mod_python isn't easy to deal with. mod_wsgi can be coerced into sending stdout and stderr to a log file.\nYour best bet, however, is the logging module. Put an initialization into your top-level urls.py to configure logging. (Or, perhaps, your settings.py)\nBe sure that every module has a logger available for writing log messages.\nBe sure that every web services call you make has a try/except block around it, and you write the exceptions to your log.\n",
"http://groups.google.com/group/django-nashville/browse_thread/thread/b4a258250cfa285a?pli=1\n"
] |
[
13,
6,
2,
1
] |
[
"If you are on a *nix system you could \nwrite to a log (eg. mylog.txt) in python\nthen run \"tail -f mylog.txt\" in the console\nthis is a handy way to view any kind of log in near real time\n"
] |
[
-1
] |
[
"django",
"facebook",
"python"
] |
stackoverflow_0000690723_django_facebook_python.txt
|
Q:
Implement OpenID in Python
How should I implement OpenID in Python using the OpenID API?
A:
For hassle free installation of openid use the RPX
The installation is quite simple. visit the website for more details. You will be able to understand it very easily.
|
Implement OpenID in Python
|
How should I implement OpenID in Python using the OpenID API?
|
[
"For hassle free installation of openid use the RPX\nThe installation is quite simple. visit the website for more details. You will be able to understand it very easily.\n"
] |
[
3
] |
[] |
[] |
[
"openid",
"python"
] |
stackoverflow_0001727429_openid_python.txt
|
Q:
Finding the correct Python framework with cmake
I am using the macports version of python on a Snow Leopard computer, and using cmake to build a cross-platform extension to it. I search for the python interpreter and libraries on the system using the following commands in CMakeLists.txt
include(FindPythonInterp)
include(FindPythonLibs )
However, while cmake identified the correct interpreter in /opt/local/bin, it tries to link against the wrong framework - namely the system Python framework.
-- Found PythonInterp: /opt/local/bin/python2.6
-- Found PythonLibs: -framework Python
And this causes the following runtime error
Fatal Python error: Interpreter not initialized (version mismatch?)
As soon as I replace -framework Python with /opt/local/Library/Frameworks/Python.framework/Python things seem to work as expected.
How can I make cmake link against the correct Python framework found in
/opt/local/Library/Frameworks/Python.framework/Python
rather than the system one in
/System/Library/Frameworks/Python.framework/Python
?
A:
Adding the following in ~/.bash_profile
export DYLD_FRAMEWORK_PATH=/opt/local/Library/Frameworks
fixes the problem at least temporarily. Apparently, this inconsistency between the python interpreter and the python framework used by cmake is a bug that should be hopefully fixed in the new version.
A:
I am not intimately familiar with CMake, but with the Apple version of gcc/ld, you can pass the -F flag to specify a new framework search path. For example, -F/opt/local/Library/Frameworks will search in MacPorts' frameworks directory. If you can specify such a flag using CMake, it may solve your problem.
|
Finding the correct Python framework with cmake
|
I am using the macports version of python on a Snow Leopard computer, and using cmake to build a cross-platform extension to it. I search for the python interpreter and libraries on the system using the following commands in CMakeLists.txt
include(FindPythonInterp)
include(FindPythonLibs )
However, while cmake identified the correct interpreter in /opt/local/bin, it tries to link against the wrong framework - namely the system Python framework.
-- Found PythonInterp: /opt/local/bin/python2.6
-- Found PythonLibs: -framework Python
And this causes the following runtime error
Fatal Python error: Interpreter not initialized (version mismatch?)
As soon as I replace -framework Python with /opt/local/Library/Frameworks/Python.framework/Python things seem to work as expected.
How can I make cmake link against the correct Python framework found in
/opt/local/Library/Frameworks/Python.framework/Python
rather than the system one in
/System/Library/Frameworks/Python.framework/Python
?
|
[
"Adding the following in ~/.bash_profile\nexport DYLD_FRAMEWORK_PATH=/opt/local/Library/Frameworks\n\nfixes the problem at least temporarily. Apparently, this inconsistency between the python interpreter and the python framework used by cmake is a bug that should be hopefully fixed in the new version.\n",
"I am not intimately familiar with CMake, but with the Apple version of gcc/ld, you can pass the -F flag to specify a new framework search path. For example, -F/opt/local/Library/Frameworks will search in MacPorts' frameworks directory. If you can specify such a flag using CMake, it may solve your problem.\n"
] |
[
5,
1
] |
[] |
[] |
[
"cmake",
"frameworks",
"macos",
"macports",
"python"
] |
stackoverflow_0001718251_cmake_frameworks_macos_macports_python.txt
|
Q:
Classify array of strings based on commonalities
I have huge list (200000) of strings (multi word). I want to group these strings based on comman array of word match among these strings. I cant think of a low computation time algorithm for this
"AB 500"
"Bus AB 500"
"News CA"
"News CA BLAH"
My plan was
a. Tokenize them to words.
b. Create a global array tokens
c. Compare those strings with common tokens.
As you guessed this does not help. Can you suggest an algorithm for this?
I am writing this in python..
A:
200000 is not that much, you can do this
Split each string to get tokens
e.g. "News CA BLAH" -> ["Blah", "CA", "News"]
create a dict entry each length of list e.g. in case of ["Blah", "CA", "News"] all combinations in order
Now just loop thru the dict and see the groups
example code:
data="""AB 500
Bus AB 500
News CA
News CA BLAH"""
def getCombinations(tokens):
count = len(tokens)
for L in range(1,count+1):
for i in range(count-L+1):
yield tuple(tokens[i:i+L])
groupDict = {}
for s in data.split("\n"):
tokens = s.split()
for groupKey in getCombinations(tokens):
if groupKey not in groupDict:
groupDict[groupKey] = [s]
else:
groupDict[groupKey].append(s)
for group, values in groupDict.iteritems():
if len(values) > 1:
print group, "->", values
it outputs:
('News', 'CA') -> ['News CA', 'News CA BLAH']
('AB',) -> ['AB 500', 'Bus AB 500']
('500',) -> ['AB 500', 'Bus AB 500']
('CA',) -> ['News CA', 'News CA BLAH']
('AB', '500') -> ['AB 500', 'Bus AB 500']
('News',) -> ['News CA', 'News CA BLAH']
A:
Do you mean something like this?
>>> from collections import defaultdict
>>> L=["AB 500",
... "Bus AB 500",
... "News CA",
... "News CA BLAH"]
>>> d=defaultdict(list)
>>> for s in L:
... for w in s.split():
... d[w].append(s)
...
>>> print d["News"]
['News CA', 'News CA BLAH']
>>> print d["CA"]
['News CA', 'News CA BLAH']
>>> print d["500"]
['AB 500', 'Bus AB 500']
A:
Unless repetition of words is an important feature for your use case, I suggest sets. I.e.:
thestrings = [
"AB 500",
"Bus AB 500",
"News CA",
"News CA BLAH",
]
thesets = dict((s, set(s.split())) for s in thestrings)
similarities = dict()
for s in thestrings:
for o in thestrings:
if s>=o: continue
sims = len(thesets[s] & thesets[o])
if not sims: continue
similarities[s, o] = sims
for s, o in sorted(similarities, similarities.get, reverse=True):
print "%-16r %-16r %2d" % (s, o, similarities[s, o])
Is this close to what you're looking for? It does classify the 4 strings you give in the way you desire, but that's a very feeble sample, of course, so I'm double checking;-).
A:
What would happen, if the string "AB 500 News CA" is added to your list? Do the two groups of strings have to merge? If not, how to split up the list of strings and why?
A very general workflow for problems like this (if i understood it correctly) goes like this:
Get a list of candidate pairs via an inverted Index/All pairs similarity search/Simhashing
Calc some distance functions for each pair and combine them into a single weight
Each weighted pair ((a, b), weight) represents now an edge in a graph, which you can cluster into the "word-match groups" via hierarchical clustering/power iteration
|
Classify array of strings based on commonalities
|
I have huge list (200000) of strings (multi word). I want to group these strings based on comman array of word match among these strings. I cant think of a low computation time algorithm for this
"AB 500"
"Bus AB 500"
"News CA"
"News CA BLAH"
My plan was
a. Tokenize them to words.
b. Create a global array tokens
c. Compare those strings with common tokens.
As you guessed this does not help. Can you suggest an algorithm for this?
I am writing this in python..
|
[
"200000 is not that much, you can do this\n\nSplit each string to get tokens\ne.g. \"News CA BLAH\" -> [\"Blah\", \"CA\", \"News\"]\ncreate a dict entry each length of list e.g. in case of [\"Blah\", \"CA\", \"News\"] all combinations in order\nNow just loop thru the dict and see the groups\n\nexample code:\ndata=\"\"\"AB 500\nBus AB 500\nNews CA\nNews CA BLAH\"\"\"\n\ndef getCombinations(tokens):\n count = len(tokens)\n for L in range(1,count+1):\n for i in range(count-L+1):\n yield tuple(tokens[i:i+L])\n\ngroupDict = {}\nfor s in data.split(\"\\n\"):\n tokens = s.split()\n for groupKey in getCombinations(tokens):\n if groupKey not in groupDict:\n groupDict[groupKey] = [s]\n else:\n groupDict[groupKey].append(s)\n\nfor group, values in groupDict.iteritems():\n if len(values) > 1:\n print group, \"->\", values\n\nit outputs:\n('News', 'CA') -> ['News CA', 'News CA BLAH']\n('AB',) -> ['AB 500', 'Bus AB 500']\n('500',) -> ['AB 500', 'Bus AB 500']\n('CA',) -> ['News CA', 'News CA BLAH']\n('AB', '500') -> ['AB 500', 'Bus AB 500']\n('News',) -> ['News CA', 'News CA BLAH']\n\n",
"Do you mean something like this?\n>>> from collections import defaultdict\n>>> L=[\"AB 500\",\n... \"Bus AB 500\",\n... \"News CA\",\n... \"News CA BLAH\"]\n>>> d=defaultdict(list)\n>>> for s in L:\n... for w in s.split():\n... d[w].append(s)\n... \n>>> print d[\"News\"]\n['News CA', 'News CA BLAH']\n>>> print d[\"CA\"]\n['News CA', 'News CA BLAH']\n>>> print d[\"500\"]\n['AB 500', 'Bus AB 500']\n\n",
"Unless repetition of words is an important feature for your use case, I suggest sets. I.e.:\nthestrings = [\n\"AB 500\",\n\"Bus AB 500\",\n\"News CA\",\n\"News CA BLAH\",\n]\n\nthesets = dict((s, set(s.split())) for s in thestrings)\n\nsimilarities = dict()\nfor s in thestrings:\n for o in thestrings:\n if s>=o: continue\n sims = len(thesets[s] & thesets[o])\n if not sims: continue\n similarities[s, o] = sims\n\nfor s, o in sorted(similarities, similarities.get, reverse=True):\n print \"%-16r %-16r %2d\" % (s, o, similarities[s, o])\n\nIs this close to what you're looking for? It does classify the 4 strings you give in the way you desire, but that's a very feeble sample, of course, so I'm double checking;-).\n",
"What would happen, if the string \"AB 500 News CA\" is added to your list? Do the two groups of strings have to merge? If not, how to split up the list of strings and why?\nA very general workflow for problems like this (if i understood it correctly) goes like this:\n\nGet a list of candidate pairs via an inverted Index/All pairs similarity search/Simhashing\nCalc some distance functions for each pair and combine them into a single weight\nEach weighted pair ((a, b), weight) represents now an edge in a graph, which you can cluster into the \"word-match groups\" via hierarchical clustering/power iteration\n\n"
] |
[
2,
1,
1,
0
] |
[] |
[] |
[
"algorithm",
"classification",
"python",
"string"
] |
stackoverflow_0001719865_algorithm_classification_python_string.txt
|
Q:
Seeking a High-Level Library for Socket Programming (Java or Python)
In short I'm creating a Flash based multiplayer game and I'm now starting to work on the server-side code. Well I'm the sole developer of the project so I'm seeking a high-level socket library that works well with games to speed up my development time.
I was trying to use the Twisted Framework (for Python) but I'm having some personal issues with it so I'm looking for another solution.
I'm open to either Java or a Python based library. The main thing is that the library is stable enough for multiplayer games and the library needs to be "high-level" (abstract) since I'm new to socket programming for games.
I want to also note that I will be using the raw binary socket for my Flash game (Actionscript 3.0) since I assume it will be faster than the traditional Flash XML socket.
A:
An option for Python is the Concurrence framework. I used it fairly recently, in conjunction with Stackless Python, to simulate an environment in which there were potentially thousands of requests per second, each of which had to be processed in less than 2 seconds. The API is very straightforward and is well documented.
I came very close to implementing in Java using Netty, which is a JBoss project.
A:
High-level on one side and raw binary sockets on the other won't work. Sorry, but you'll need to go low-level on the server side too.
EDIT: in response to the OP's comment. I am not aware of any "high level" interface of the nature that you are talking about for Java. And frankly I don't think it makes a lot of sense. If you are going to talk bytes over Socket streams you really do need to understand the standard JDK Socket / ServerSocket APIs; e.g. timeouts, keep-alive, etc.
A:
See "A Quick Guide to ActionScript 3 and Flash Programming". It has a detailed example of an ActionScript client code using sockets to communicate with a Python server (code included). Not what anyone will call high-level, it makes use of the basic Python socket module for communication.
(Note: the Python server example is not pythonic. After getting the general idea of using sockets in Python, write something simpler and NO from socket import * )
A:
For java there is Apache mina and Grizzly frameworks both of those really simplify work with sockets
|
Seeking a High-Level Library for Socket Programming (Java or Python)
|
In short I'm creating a Flash based multiplayer game and I'm now starting to work on the server-side code. Well I'm the sole developer of the project so I'm seeking a high-level socket library that works well with games to speed up my development time.
I was trying to use the Twisted Framework (for Python) but I'm having some personal issues with it so I'm looking for another solution.
I'm open to either Java or a Python based library. The main thing is that the library is stable enough for multiplayer games and the library needs to be "high-level" (abstract) since I'm new to socket programming for games.
I want to also note that I will be using the raw binary socket for my Flash game (Actionscript 3.0) since I assume it will be faster than the traditional Flash XML socket.
|
[
"An option for Python is the Concurrence framework. I used it fairly recently, in conjunction with Stackless Python, to simulate an environment in which there were potentially thousands of requests per second, each of which had to be processed in less than 2 seconds. The API is very straightforward and is well documented.\nI came very close to implementing in Java using Netty, which is a JBoss project.\n",
"High-level on one side and raw binary sockets on the other won't work. Sorry, but you'll need to go low-level on the server side too.\nEDIT: in response to the OP's comment. I am not aware of any \"high level\" interface of the nature that you are talking about for Java. And frankly I don't think it makes a lot of sense. If you are going to talk bytes over Socket streams you really do need to understand the standard JDK Socket / ServerSocket APIs; e.g. timeouts, keep-alive, etc.\n",
"See \"A Quick Guide to ActionScript 3 and Flash Programming\". It has a detailed example of an ActionScript client code using sockets to communicate with a Python server (code included). Not what anyone will call high-level, it makes use of the basic Python socket module for communication. \n(Note: the Python server example is not pythonic. After getting the general idea of using sockets in Python, write something simpler and NO from socket import * )\n",
"For java there is Apache mina and Grizzly frameworks both of those really simplify work with sockets\n"
] |
[
7,
0,
0,
0
] |
[] |
[] |
[
"java",
"python",
"sockets"
] |
stackoverflow_0001728266_java_python_sockets.txt
|
Q:
Chat server with Twisted framework in python can't receive data from flash client
I've develop a chat server using Twisted framework in Python. It works fine with a Telnet client. But when I use my flash client problem appear...
(the flash client work find with my old php chat server, I rewrote the server in python to gain performance)
The connexion is establish between the flash client and the twisted server: XMLSocket .onConnect return TRUE. So it's not a problem of permission with the policy file.
I'm not able to send any message from Flash clien with XMLSOCket function send(), nothing is receive on th server side. I tried to end those message with '\n' or '\n\0' or '\0' without succes.
You have any clue?
A:
Changing LineOnlyReceiver.delimiter is a pretty bad idea, since that changes the delivery for all instances of LineOnlyReceiver (unless they've changed it themselves on a subclass or on the instance). If you ever happen to use any such code, it will probably break.
You should change delimiter by setting it on your LineOnlyReceiver subclass, since it's your subclass that has this requirement.
A:
I find out that the default delimiter for line, use by Twisted is '\r\n'. It can be overwrite in a your children class with:
LineOnlyReceiver.delimiter = '\n'
|
Chat server with Twisted framework in python can't receive data from flash client
|
I've develop a chat server using Twisted framework in Python. It works fine with a Telnet client. But when I use my flash client problem appear...
(the flash client work find with my old php chat server, I rewrote the server in python to gain performance)
The connexion is establish between the flash client and the twisted server: XMLSocket .onConnect return TRUE. So it's not a problem of permission with the policy file.
I'm not able to send any message from Flash clien with XMLSOCket function send(), nothing is receive on th server side. I tried to end those message with '\n' or '\n\0' or '\0' without succes.
You have any clue?
|
[
"Changing LineOnlyReceiver.delimiter is a pretty bad idea, since that changes the delivery for all instances of LineOnlyReceiver (unless they've changed it themselves on a subclass or on the instance). If you ever happen to use any such code, it will probably break.\nYou should change delimiter by setting it on your LineOnlyReceiver subclass, since it's your subclass that has this requirement.\n",
"I find out that the default delimiter for line, use by Twisted is '\\r\\n'. It can be overwrite in a your children class with:\nLineOnlyReceiver.delimiter = '\\n' \n"
] |
[
1,
0
] |
[] |
[] |
[
"flash",
"python",
"twisted"
] |
stackoverflow_0001489931_flash_python_twisted.txt
|
Q:
How to remove unique, then duplicate dictionaries in a list?
Given the following list that contains some duplicate and some unique dictionaries, what is the best method to remove unique dictionaries first, then reduce the duplicate dictionaries to single instances? I gotta say I only recently started getting into Python but its making this project so much easier. I'm just a bit stumped on this kind of problem.
So my list looks like this:
[{ 'file': u'/file.txt',
'line': u'line 666',
'rule': u'A DUPLICATE RULE'}
{ 'file': u'/file.txt',
'line': u'line 666',
'rule': u'A DUPLICATE RULE'}
{ 'file': u'/uniquefile.txt',
'line': u'line 999',
'rule': u'A UNIQUE RULE'}]
What I'm going for is in the end, the list should look like:
[{ 'file': u'/file.txt',
'line': u'line 666',
'rule': u'A DUPLICATE RULE'}]
A:
One idea is to sort the data. Assume inputdata is your list from above:
from itertools import groupby
from operator import itemgetter
inputdata.sort(key=itemgetter(*inputdata[0])) # ensures order
print [k for k, g in groupby(inputdata) if len(list(g)) > 1]
prints:
[{'line': u'line 666', 'file': u'/file.txt', 'rule': u'A DUPLICATE RULE'}]
A:
I always prefer to work with objects instead of dicts, if the fields are the same for every item.
So, I define a class:
class rule(object):
def __init__(self, file, line, rule):
self.file = file
self.line = line
self.rule = rule
#Not a "magic" method, just a helper for all the methods below :)
def _tuple_(self):
return (self.file, self.line, self.rule)
def __eq__(self, other):
return cmp(self, other) == 0
def __cmp__(self, other):
return cmp(self._tuple_(), rule._tuple_(other))
def __hash__(self):
return hash(self._tuple_())
def __repr__(self):
return repr(self._tuple_())
Now, create a list of these objects, and sort it. ruledict_list can be the example data in your question.
rules = [rule(**r) for r in ruledict_list]
rules.sort()
Loop through the (sorted) list, removing unique objects as we go. Finally, create a set, to remove duplicates. The loop will also remove one of each duplicate object, but that doesn't really matter.
pos = 0
while(pos < len(rules)):
while pos < len(rules)-1 and rules[pos] == rules[pos+1]:
print "Skipping rule %s" % rules[pos]
pos+=1
rules.pop(pos)
rule_set = set(rules)
A:
I'd make another dictionary, using the existing dictionaries as keys and the count of occurrences as values. (Python doesn't allow dictionaries to be used as dictionary keys out of the box, but there are a couple of ways of doing that mentioned in this answer.) Then it's just a matter of iterating over it and selecting the keys where the value is greater than 1.
Of course, using dictionaries as keys relies on their contents not changing over time - at least over the time that you need to use the resulting dictionary. (This is why Python doesn't support it natively.)
A:
Another way is to make a counter for each dict data, based on a frozenset of items:
from operator import itemgetter
from collections import defaultdict
counter = defaultdict(int)
for d in inputdata:
counter[frozenset(d.iteritems())] += 1
result = [dict(item) for item, count in counter.iteritems() if count > 1]
print result
I think that is the best answer so far, because it is very simple to understand and will work linearly.
A:
>>> import itertools
>>> list(a[0] for a in itertools.groupby(sorted(data)) if len(list(a[1])) > 1)
[{'file': u'/file.txt', 'line': u'line 666', 'rule': u'A DUPLICATE RULE'}]
There's probably a more optimal way to check this than len(list(a[1])).
Edit: I added a call to sorted.
A:
This answer is based on Steven Huwig's answer. It's similar to his, but I use sorted() on the list so that groupby() works correctly.
Also, since he said "There's probably a more optimal way to check this than len(list(a[1])).", I decided to use some other way to check for non-unique items. Instead of forcing the whole list, I try to call the .next() method on the iterator, twice. If it works twice, there are at least two items in the iterator, and we are done with it; if we get a StopIteration exception on the first or second call to .next() there was zero or one items in the iterator. (Actually, since we got this iterator from itertools.groupby we know it will have at least one item in it.)
Also, instead of using explicit tuple indexing like a[0] and a[1], I used tuple unpacking, since that's what the cool kids seem to be doing these days.
Finally, instead of using a generator expression to compute the list, and using list() to force it to expand out into a list, I simply used a list comprehension.
data = [
{
'file': u'/file.txt',
'line': u'line 666',
'rule': u'A DUPLICATE RULE'
},
{ 'file': u'/uniquefile.txt',
'line': u'line 999',
'rule': u'A UNIQUE RULE'
},
{ 'file': u'/file.txt',
'line': u'line 666',
'rule': u'A DUPLICATE RULE'
},
]
from itertools import groupby
def notunique(itr):
try:
itr.next()
itr.next()
return True
except StopIteration:
return False
def unique_list(lst):
return [key for key, itr in groupby(sorted(lst)) if notunique(itr)]
print(unique_list(data))
A:
Another option is to create your own data structure instead of using a dict. If you do this, then you can override __cmp__, __eq__ and __hash__. This will give you the ability to then use the 'set' data type in all its glory.
Here's one possible implementation, though I make no promises about the quality of the hash routine I've provided:
class Thing(object):
def __init__(self, file, line, rule):
self.file = file
self.line = line
self.rule = rule
def __cmp__(self, other):
result = cmp(self.file, other.file)
if result == 0:
result = cmp(self.line, other.line)
if result == 0:
result = cmp(self.rule, other.rule)
return result
def __eq__(self, other):
return cmp(self, other) == 0
def __hash__(self):
return hash(self.file) * hash(self.line) * hash(self.rule)
def __str__(self):
return ', '.join([self.file, self.line, self.rule])
things = [ Thing(u'/file.txt', u'line 666', u'A DUPLICATE RULE'),
Thing(u'/file.txt', u'line 666', u'A DUPLICATE RULE'),
Thing(u'/uniquefile.txt', u'line 999', u'A UNIQUE RULE')]
duplicate_things = set()
unique_things = set()
for t in things:
if t in unique_things:
duplicate_things.add(t)
else:
unique_things.add(t)
If you need to get back to a list, just construct one from the resulting set:
unique_things = list(unique_things)
duplicate_things = list(duplicate_things)
It's a bit more code to create your own class like this, but may give you other options down the road if your program grows in complexity.
Edit
OK, my hands are faster than my eyes tonight, but I think this edit solves the problem pointed out by @nosklo
|
How to remove unique, then duplicate dictionaries in a list?
|
Given the following list that contains some duplicate and some unique dictionaries, what is the best method to remove unique dictionaries first, then reduce the duplicate dictionaries to single instances? I gotta say I only recently started getting into Python but its making this project so much easier. I'm just a bit stumped on this kind of problem.
So my list looks like this:
[{ 'file': u'/file.txt',
'line': u'line 666',
'rule': u'A DUPLICATE RULE'}
{ 'file': u'/file.txt',
'line': u'line 666',
'rule': u'A DUPLICATE RULE'}
{ 'file': u'/uniquefile.txt',
'line': u'line 999',
'rule': u'A UNIQUE RULE'}]
What I'm going for is in the end, the list should look like:
[{ 'file': u'/file.txt',
'line': u'line 666',
'rule': u'A DUPLICATE RULE'}]
|
[
"One idea is to sort the data. Assume inputdata is your list from above:\nfrom itertools import groupby\nfrom operator import itemgetter\n\ninputdata.sort(key=itemgetter(*inputdata[0])) # ensures order\nprint [k for k, g in groupby(inputdata) if len(list(g)) > 1]\n\nprints:\n[{'line': u'line 666', 'file': u'/file.txt', 'rule': u'A DUPLICATE RULE'}]\n\n",
"I always prefer to work with objects instead of dicts, if the fields are the same for every item.\nSo, I define a class:\nclass rule(object):\n def __init__(self, file, line, rule):\n self.file = file\n self.line = line\n self.rule = rule\n\n #Not a \"magic\" method, just a helper for all the methods below :)\n def _tuple_(self):\n return (self.file, self.line, self.rule)\n\n def __eq__(self, other):\n return cmp(self, other) == 0\n\n def __cmp__(self, other):\n return cmp(self._tuple_(), rule._tuple_(other))\n\n def __hash__(self):\n return hash(self._tuple_())\n\n def __repr__(self):\n return repr(self._tuple_())\n\nNow, create a list of these objects, and sort it. ruledict_list can be the example data in your question.\nrules = [rule(**r) for r in ruledict_list]\nrules.sort()\n\nLoop through the (sorted) list, removing unique objects as we go. Finally, create a set, to remove duplicates. The loop will also remove one of each duplicate object, but that doesn't really matter.\npos = 0\nwhile(pos < len(rules)):\n while pos < len(rules)-1 and rules[pos] == rules[pos+1]:\n print \"Skipping rule %s\" % rules[pos]\n pos+=1\n rules.pop(pos)\nrule_set = set(rules)\n\n",
"I'd make another dictionary, using the existing dictionaries as keys and the count of occurrences as values. (Python doesn't allow dictionaries to be used as dictionary keys out of the box, but there are a couple of ways of doing that mentioned in this answer.) Then it's just a matter of iterating over it and selecting the keys where the value is greater than 1.\nOf course, using dictionaries as keys relies on their contents not changing over time - at least over the time that you need to use the resulting dictionary. (This is why Python doesn't support it natively.)\n",
"Another way is to make a counter for each dict data, based on a frozenset of items:\nfrom operator import itemgetter\nfrom collections import defaultdict\n\ncounter = defaultdict(int)\nfor d in inputdata:\n counter[frozenset(d.iteritems())] += 1\n\nresult = [dict(item) for item, count in counter.iteritems() if count > 1]\nprint result\n\nI think that is the best answer so far, because it is very simple to understand and will work linearly.\n",
">>> import itertools\n>>> list(a[0] for a in itertools.groupby(sorted(data)) if len(list(a[1])) > 1)\n[{'file': u'/file.txt', 'line': u'line 666', 'rule': u'A DUPLICATE RULE'}]\n\nThere's probably a more optimal way to check this than len(list(a[1])).\nEdit: I added a call to sorted.\n",
"This answer is based on Steven Huwig's answer. It's similar to his, but I use sorted() on the list so that groupby() works correctly.\nAlso, since he said \"There's probably a more optimal way to check this than len(list(a[1])).\", I decided to use some other way to check for non-unique items. Instead of forcing the whole list, I try to call the .next() method on the iterator, twice. If it works twice, there are at least two items in the iterator, and we are done with it; if we get a StopIteration exception on the first or second call to .next() there was zero or one items in the iterator. (Actually, since we got this iterator from itertools.groupby we know it will have at least one item in it.)\nAlso, instead of using explicit tuple indexing like a[0] and a[1], I used tuple unpacking, since that's what the cool kids seem to be doing these days.\nFinally, instead of using a generator expression to compute the list, and using list() to force it to expand out into a list, I simply used a list comprehension.\ndata = [\n {\n 'file': u'/file.txt',\n 'line': u'line 666',\n 'rule': u'A DUPLICATE RULE'\n },\n\n { 'file': u'/uniquefile.txt',\n 'line': u'line 999',\n 'rule': u'A UNIQUE RULE'\n },\n\n { 'file': u'/file.txt',\n 'line': u'line 666',\n 'rule': u'A DUPLICATE RULE'\n },\n\n]\n\nfrom itertools import groupby\n\ndef notunique(itr):\n try:\n itr.next()\n itr.next()\n return True\n except StopIteration:\n return False\n\ndef unique_list(lst):\n return [key for key, itr in groupby(sorted(lst)) if notunique(itr)]\n\nprint(unique_list(data))\n\n",
"Another option is to create your own data structure instead of using a dict. If you do this, then you can override __cmp__, __eq__ and __hash__. This will give you the ability to then use the 'set' data type in all its glory.\nHere's one possible implementation, though I make no promises about the quality of the hash routine I've provided:\nclass Thing(object):\n def __init__(self, file, line, rule):\n self.file = file\n self.line = line\n self.rule = rule\n\n def __cmp__(self, other):\n result = cmp(self.file, other.file)\n if result == 0:\n result = cmp(self.line, other.line)\n if result == 0:\n result = cmp(self.rule, other.rule)\n return result\n\n def __eq__(self, other):\n return cmp(self, other) == 0\n\n def __hash__(self):\n return hash(self.file) * hash(self.line) * hash(self.rule)\n\n def __str__(self):\n return ', '.join([self.file, self.line, self.rule])\n\nthings = [ Thing(u'/file.txt', u'line 666', u'A DUPLICATE RULE'),\n Thing(u'/file.txt', u'line 666', u'A DUPLICATE RULE'),\n Thing(u'/uniquefile.txt', u'line 999', u'A UNIQUE RULE')]\n\nduplicate_things = set()\nunique_things = set()\nfor t in things:\n if t in unique_things:\n duplicate_things.add(t)\n else:\n unique_things.add(t)\n\nIf you need to get back to a list, just construct one from the resulting set:\nunique_things = list(unique_things)\nduplicate_things = list(duplicate_things)\n\nIt's a bit more code to create your own class like this, but may give you other options down the road if your program grows in complexity.\nEdit\nOK, my hands are faster than my eyes tonight, but I think this edit solves the problem pointed out by @nosklo\n"
] |
[
4,
2,
1,
1,
1,
1,
0
] |
[] |
[] |
[
"dictionary",
"list",
"python"
] |
stackoverflow_0001726925_dictionary_list_python.txt
|
Q:
list management python
I have extracted some url list and want to manipulate this list. Following is extracted list sample:
http://help.naver.com/service/svc_index.jsp?selected_nodeId=NODE0000000235
http://www.naver.com/rules/service.html
http://news.naver.com/main/principle.nhn
http://www.naver.com/rules/privacy.html
http://www.naver.com/rules/disclaimer.html
http://help.naver.com/claim_main.asp
http://news.naver.com/main/ombudsman/guidecenter.nhn?mid=omb
http://www.nhncorp.com/
http://www.nhncorp.com/
I want to extract only URLs that start with 'http://www.naver.com', so finally what I want list is following
http://www.naver.com/rules/privacy.html
http://www.naver.com/rules/disclaimer.html
http://www.naver.com/rules/service.html
How can I only extract what I want?
A:
If your old list is contains all urls as strings you can use a list comprehension to filter them.
new = [url for url in old if url.startswith('http://www.naver.com')]
You could write it as a explicit loop, but it adds nothing but lines of code:
new = []
for url in old:
if url.startswith('http://www.naver.com'):
new.append( url )
If you planned on removing items from the original list while looping over it: Don't ever do that, it won't work. You can modify the original list instead with the same LC:
old[:] = [url for url in old if url.startswith('http://www.naver.com')]
A:
You can do this with a List Comprehension. These are a very powerful way to work with lists with Python.
By adding add an if to the list comprehension you can filter the list.
Assuming your URLs are stored in the variable myurls:
filteredurls = [url for url in myurls if url.startswith('http://www.naver.com')]
A:
urlList = [ ... ] # your list of urls
extractedList = [url for url in urlList if url.startswith('http://www.naver.com')]
A:
result = []
for url in myListOfUrls:
if 'http://www.naver.com' in url:
result.append(url)
A:
Someone suggested this alternative answer based on filter() but deleted it, I'll post it here again for completeness:
newList = filter(lambda url: url.startswith('http://www.naver.com'), oldList)
The list comprehension method seems faster though (and in my opinion, more readable):
$ python -m timeit -c "filter(lambda url: url.startswith('1'), map(str, range(100)))"
10000 loops, best of 3: 143 usec per loop
$ python -m timeit -c "[ url for url in map(str, range(100)) if url.startswith('1') ]"
10000 loops, best of 3: 117 usec per loop
|
list management python
|
I have extracted some url list and want to manipulate this list. Following is extracted list sample:
http://help.naver.com/service/svc_index.jsp?selected_nodeId=NODE0000000235
http://www.naver.com/rules/service.html
http://news.naver.com/main/principle.nhn
http://www.naver.com/rules/privacy.html
http://www.naver.com/rules/disclaimer.html
http://help.naver.com/claim_main.asp
http://news.naver.com/main/ombudsman/guidecenter.nhn?mid=omb
http://www.nhncorp.com/
http://www.nhncorp.com/
I want to extract only URLs that start with 'http://www.naver.com', so finally what I want list is following
http://www.naver.com/rules/privacy.html
http://www.naver.com/rules/disclaimer.html
http://www.naver.com/rules/service.html
How can I only extract what I want?
|
[
"If your old list is contains all urls as strings you can use a list comprehension to filter them.\nnew = [url for url in old if url.startswith('http://www.naver.com')]\n\nYou could write it as a explicit loop, but it adds nothing but lines of code:\nnew = []\nfor url in old:\n if url.startswith('http://www.naver.com'):\n new.append( url )\n\nIf you planned on removing items from the original list while looping over it: Don't ever do that, it won't work. You can modify the original list instead with the same LC:\nold[:] = [url for url in old if url.startswith('http://www.naver.com')]\n\n",
"You can do this with a List Comprehension. These are a very powerful way to work with lists with Python.\nBy adding add an if to the list comprehension you can filter the list.\nAssuming your URLs are stored in the variable myurls:\nfilteredurls = [url for url in myurls if url.startswith('http://www.naver.com')]\n\n",
"urlList = [ ... ] # your list of urls\nextractedList = [url for url in urlList if url.startswith('http://www.naver.com')]\n\n",
"result = []\nfor url in myListOfUrls:\n if 'http://www.naver.com' in url:\n result.append(url)\n\n",
"Someone suggested this alternative answer based on filter() but deleted it, I'll post it here again for completeness:\nnewList = filter(lambda url: url.startswith('http://www.naver.com'), oldList)\n\nThe list comprehension method seems faster though (and in my opinion, more readable):\n$ python -m timeit -c \"filter(lambda url: url.startswith('1'), map(str, range(100)))\"\n10000 loops, best of 3: 143 usec per loop\n\n$ python -m timeit -c \"[ url for url in map(str, range(100)) if url.startswith('1') ]\"\n10000 loops, best of 3: 117 usec per loop\n\n"
] |
[
6,
2,
0,
0,
0
] |
[] |
[] |
[
"python"
] |
stackoverflow_0001730261_python.txt
|
Q:
Multiple grids on matplotlib
I'm making plots in Python and matplotlib, which I found huge and flexible, till now.
The only thing I couldn't find how to do, is to make my plot have multiple grids.
I've looked into the documentation, but that's just for line style...
I'm thinking on something like two plots each one with a different grid, which will overlap them.
So, for example I want to make this graph:
Alt text http://img137.imageshack.us/img137/2017/waittimeprobability.png
Have a similar grid marks as this one:
Alt text http://img137.imageshack.us/img137/6122/saucelabssauceloadday.png
And by that, I mean, more frequent grids with lighter color between important points.
A:
How about something like this (adapted from here):
from pylab import *
from matplotlib.ticker import MultipleLocator, FormatStrFormatter
t = arange(0.0, 100.0, 0.1)
s = sin(0.1*pi*t)*exp(-t*0.01)
ax = subplot(111)
plot(t,s)
ax.xaxis.set_major_locator(MultipleLocator(20))
ax.xaxis.set_major_formatter(FormatStrFormatter('%d'))
ax.xaxis.set_minor_locator(MultipleLocator(5))
ax.yaxis.set_major_locator(MultipleLocator(0.5))
ax.yaxis.set_minor_locator(MultipleLocator(0.1))
ax.xaxis.grid(True,'minor')
ax.yaxis.grid(True,'minor')
ax.xaxis.grid(True,'major',linewidth=2)
ax.yaxis.grid(True,'major',linewidth=2)
show()
|
Multiple grids on matplotlib
|
I'm making plots in Python and matplotlib, which I found huge and flexible, till now.
The only thing I couldn't find how to do, is to make my plot have multiple grids.
I've looked into the documentation, but that's just for line style...
I'm thinking on something like two plots each one with a different grid, which will overlap them.
So, for example I want to make this graph:
Alt text http://img137.imageshack.us/img137/2017/waittimeprobability.png
Have a similar grid marks as this one:
Alt text http://img137.imageshack.us/img137/6122/saucelabssauceloadday.png
And by that, I mean, more frequent grids with lighter color between important points.
|
[
"How about something like this (adapted from here):\nfrom pylab import *\nfrom matplotlib.ticker import MultipleLocator, FormatStrFormatter\n\nt = arange(0.0, 100.0, 0.1)\ns = sin(0.1*pi*t)*exp(-t*0.01)\n\nax = subplot(111)\nplot(t,s)\n\nax.xaxis.set_major_locator(MultipleLocator(20))\nax.xaxis.set_major_formatter(FormatStrFormatter('%d'))\nax.xaxis.set_minor_locator(MultipleLocator(5))\n\nax.yaxis.set_major_locator(MultipleLocator(0.5))\nax.yaxis.set_minor_locator(MultipleLocator(0.1))\n\nax.xaxis.grid(True,'minor')\nax.yaxis.grid(True,'minor')\nax.xaxis.grid(True,'major',linewidth=2)\nax.yaxis.grid(True,'major',linewidth=2)\n\nshow()\n\n\n"
] |
[
32
] |
[] |
[] |
[
"matplotlib",
"python"
] |
stackoverflow_0001729995_matplotlib_python.txt
|
Q:
Pack program *and* dynamically loaded files into single executable? (python + pygame, or language agnostic)
There are plenty of great answers to questions about making a standalone executable, but I can't figure out how to pack art assets (or dynamically loaded files) into it as well. Why would I want to do this? Because it would be great to distribute a simple (throw away) game that lives entirely in a single executable with no installer.
As far as I can tell from searching, there are two basic approaches.
1) Avoid art assets in favor of content generation. I could have a program that turns a simple sprite into a RLE pixel-color list that lives in a python script. Since it's a script, it would get bound up into the exe with a packaging tool. Right?
2) Use some kind of self-extracting archive that can dump the directory structure into a temp directory (or maybe into memory?), then automatically run the entry point of the program.
Does what I'm trying to do make sense? The second option seems so much more sensible, but I'm not sure which tools would be used to accomplish it with python and pygame. I've used py2exe, but it only packaged python scripts and imported modules.
EDIT:
This thread makes me think that you can tell the packaging utility to include program data along with the dependencies. Is that true?
A:
Game development is not field of expertise, but if you haven't already checked out py2exe, I would strongly recommend that you do. It seems to me that any and all scripting import statements will be taken care of by py2exe.
Hope this helps
|
Pack program *and* dynamically loaded files into single executable? (python + pygame, or language agnostic)
|
There are plenty of great answers to questions about making a standalone executable, but I can't figure out how to pack art assets (or dynamically loaded files) into it as well. Why would I want to do this? Because it would be great to distribute a simple (throw away) game that lives entirely in a single executable with no installer.
As far as I can tell from searching, there are two basic approaches.
1) Avoid art assets in favor of content generation. I could have a program that turns a simple sprite into a RLE pixel-color list that lives in a python script. Since it's a script, it would get bound up into the exe with a packaging tool. Right?
2) Use some kind of self-extracting archive that can dump the directory structure into a temp directory (or maybe into memory?), then automatically run the entry point of the program.
Does what I'm trying to do make sense? The second option seems so much more sensible, but I'm not sure which tools would be used to accomplish it with python and pygame. I've used py2exe, but it only packaged python scripts and imported modules.
EDIT:
This thread makes me think that you can tell the packaging utility to include program data along with the dependencies. Is that true?
|
[
"Game development is not field of expertise, but if you haven't already checked out py2exe, I would strongly recommend that you do. It seems to me that any and all scripting import statements will be taken care of by py2exe.\nHope this helps\n"
] |
[
2
] |
[] |
[] |
[
"executable",
"packaging",
"pygame",
"python"
] |
stackoverflow_0001730742_executable_packaging_pygame_python.txt
|
Q:
gqlQuery returns object, want list of keys
Is there a way to convert the GqlQuery object to an array of keys, or is there a way to force the query to return an array of keys? For example:
items = db.GqlQuery("SELECT __key__ FROM Items")
returns an object containing the keys:
<google.appengine.ext.db.GqlQuery object at 0x0415E210>
I need to compare it to an array of keys that look like:
[datastore_types.Key.from_path(u'Item', 100L, _app_id_namespace=u'items'),
..., datastore_types.Key.from_path(u'Item', 105L, _app_id_namespace=u'fitems')]
Note: I can get around the problem by querying for the stored objects, and then calling .key(), but this seems wasteful.
items = db.GqlQuery("SELECT * FROM Items")
keyArray = []
for item in items:
keyArray.append(item.key())
A:
Certainly - you can fetch the results by calling .fetch(count) on the GqlQuery object. This is the recommended way, in fact - iterating fetches results in batches, and so is less efficient.
|
gqlQuery returns object, want list of keys
|
Is there a way to convert the GqlQuery object to an array of keys, or is there a way to force the query to return an array of keys? For example:
items = db.GqlQuery("SELECT __key__ FROM Items")
returns an object containing the keys:
<google.appengine.ext.db.GqlQuery object at 0x0415E210>
I need to compare it to an array of keys that look like:
[datastore_types.Key.from_path(u'Item', 100L, _app_id_namespace=u'items'),
..., datastore_types.Key.from_path(u'Item', 105L, _app_id_namespace=u'fitems')]
Note: I can get around the problem by querying for the stored objects, and then calling .key(), but this seems wasteful.
items = db.GqlQuery("SELECT * FROM Items")
keyArray = []
for item in items:
keyArray.append(item.key())
|
[
"Certainly - you can fetch the results by calling .fetch(count) on the GqlQuery object. This is the recommended way, in fact - iterating fetches results in batches, and so is less efficient.\n"
] |
[
3
] |
[] |
[] |
[
"google_app_engine",
"gql",
"python"
] |
stackoverflow_0001730694_google_app_engine_gql_python.txt
|
Q:
A server side component for tracking a large number of RSS & Atom feeds
I am looking for an open source component that can help me track a large number of RSS feeds (>> 10K RSS sources).
I don't care about the programming language, but it should be something with a simple API where I can add or remove RSS feeds and asynchronously receive notifications every time an RSS is updated.
Preferably in Java or Python.
A:
I found this site. Most of these seem to be client apps but some listed APIs. Not sure if there's something here for you. http://java-source.net/open-source/rss-rdf-tools
|
A server side component for tracking a large number of RSS & Atom feeds
|
I am looking for an open source component that can help me track a large number of RSS feeds (>> 10K RSS sources).
I don't care about the programming language, but it should be something with a simple API where I can add or remove RSS feeds and asynchronously receive notifications every time an RSS is updated.
Preferably in Java or Python.
|
[
"I found this site. Most of these seem to be client apps but some listed APIs. Not sure if there's something here for you. http://java-source.net/open-source/rss-rdf-tools\n"
] |
[
0
] |
[] |
[] |
[
"atom_feed",
"java",
"python",
"rss"
] |
stackoverflow_0001710718_atom_feed_java_python_rss.txt
|
Q:
Python code to accept many different formats of US phone numbers?
I'm reading in lots of user entered data that represent phone numbers from files. They are all slightly entered in differently:
5555555555
555-555-5555
555-555/5555
1555-555-5555
etc...
How could I easily parse in all of these phone numbers in Python and produce a canonical output like:
555-555-5555?
A:
Dive into Python has a section on parsing phone numbers
http://www.diveintopython.org/regular_expressions/phone_numbers.html
A:
I'm not american, but this works with russian phone numbers... maybe it applies to american ones too?
Discard all non-number characters
Validate amount of the numbers left
Insert several dashes in appropriate places
A:
take only the numbers with a regex. then find out if they appended the 1 (NO area code starts with 1). if it's there, remove it otherwise, format the 10 digits the way you want.
import re
pnumber = re.sub("[^0-9]", "", input_number)
if pnumber[0] == 1:
pnumber = pnumber[1:] #strip 1st char if 1
#insert the dashes
if len(pnumber) == 10:
pnumber = "%s-%s-%s" % (pnumber[:3],pnumber[3:6],pnumber[6:])
else:
#throw error
A:
After a little preparation with string.maketrans, strings' translate method affords very fast and simple operation. I'm giving Python 2 code for plain strings (Python 3, and Unicode strings in Python 2, are a bit different -- ask if that's what you need):
The preparation (do once and for all, e.g. at module load time):
>>> import string
>>> allchars = string.maketrans('', '')
>>> nondigits = allchars.translate(allchars, string.digits)
The execution (turn any suitable string into the property formatted number):
>>> x='1555-555-5555'
>>> y=(x.translate(allchars, nondigits)).lstrip('1')
>>> assert len(y) == 10
>>> '%s-%s-%s' % (y[:3], y[3:6], y[6:])
'555-555-5555
Of course, you'll need to decide what to do when len(y) does not equal 10 (just raise an exception as I'm doing here, or, what else). But, this would be needed for any other form of processing (regex or whatever) just as well. The translate approach is really really fast and simple!-)
A:
def extractNumber(s):
"""take a string phone number and extract it to the legal string"""
target = ""
for char in s:
try:
target += int(s)
except ValueError:
target += '-'
return target
A:
Decide which formats you want to recognize, then create a regular expression matching each one grouping the different parts of the number (like area code, prefix etc). Finally use a substitution to generate the canonical output you desire.
Example:
to match
xxx-xxx-xxxx -> \d{3}-\d{3}-\d{4}
(xxx) xxx-xxxx -> \(\d{3}\) \d{3}-\d{4}
1-xxx-xxx-xxx -> 1-\d{3}-\d{3}-\d{4}
This ignores rules that restrict prefix and area code (the US doesn't allow area codes or prefixes that being with 0 or 1). You could try and be super smart and create one regular expression that matches everything but you will end up with a jumbled mess that is impossible to modify instead you should OR the patterns together to make them easier to modify in the future.
basic idea:
pattern = re.compile(r'\d{3}-\d{3}-\d{4}|\(\d{3}\) \d{3}-\d{4}|1-\d{3}-\d{3}-\d{4}')
with grouping added for canonical output
pattern = re.compile(r'(\d{3})-(\d{3})-(\d{4})|\((\d{3})\) (\d{3})-(\d{4})|1-(\d{3})-(\d{3})-(\d{4})')
then just run that against your inputs and for each phone number input you will have 3 matching groups, one for the area code, one for the prefix, and one for the suffix which you can output however you want. You need a basic understanding of regular expressions, but it shouldn't be too hard.
|
Python code to accept many different formats of US phone numbers?
|
I'm reading in lots of user entered data that represent phone numbers from files. They are all slightly entered in differently:
5555555555
555-555-5555
555-555/5555
1555-555-5555
etc...
How could I easily parse in all of these phone numbers in Python and produce a canonical output like:
555-555-5555?
|
[
"Dive into Python has a section on parsing phone numbers\nhttp://www.diveintopython.org/regular_expressions/phone_numbers.html\n",
"I'm not american, but this works with russian phone numbers... maybe it applies to american ones too?\n\nDiscard all non-number characters\nValidate amount of the numbers left\nInsert several dashes in appropriate places\n\n",
"take only the numbers with a regex. then find out if they appended the 1 (NO area code starts with 1). if it's there, remove it otherwise, format the 10 digits the way you want. \nimport re\npnumber = re.sub(\"[^0-9]\", \"\", input_number)\nif pnumber[0] == 1:\n pnumber = pnumber[1:] #strip 1st char if 1\n\n#insert the dashes\nif len(pnumber) == 10:\n pnumber = \"%s-%s-%s\" % (pnumber[:3],pnumber[3:6],pnumber[6:])\nelse:\n #throw error\n\n",
"After a little preparation with string.maketrans, strings' translate method affords very fast and simple operation. I'm giving Python 2 code for plain strings (Python 3, and Unicode strings in Python 2, are a bit different -- ask if that's what you need):\nThe preparation (do once and for all, e.g. at module load time):\n>>> import string\n>>> allchars = string.maketrans('', '')\n>>> nondigits = allchars.translate(allchars, string.digits)\n\nThe execution (turn any suitable string into the property formatted number):\n>>> x='1555-555-5555'\n>>> y=(x.translate(allchars, nondigits)).lstrip('1')\n>>> assert len(y) == 10\n>>> '%s-%s-%s' % (y[:3], y[3:6], y[6:])\n'555-555-5555\n\nOf course, you'll need to decide what to do when len(y) does not equal 10 (just raise an exception as I'm doing here, or, what else). But, this would be needed for any other form of processing (regex or whatever) just as well. The translate approach is really really fast and simple!-)\n",
"def extractNumber(s):\n \"\"\"take a string phone number and extract it to the legal string\"\"\"\n\n target = \"\"\n for char in s:\n try:\n target += int(s)\n except ValueError:\n target += '-'\n\n return target\n\n",
"Decide which formats you want to recognize, then create a regular expression matching each one grouping the different parts of the number (like area code, prefix etc). Finally use a substitution to generate the canonical output you desire.\nExample:\nto match\nxxx-xxx-xxxx -> \\d{3}-\\d{3}-\\d{4}\n(xxx) xxx-xxxx -> \\(\\d{3}\\) \\d{3}-\\d{4}\n1-xxx-xxx-xxx -> 1-\\d{3}-\\d{3}-\\d{4}\n\nThis ignores rules that restrict prefix and area code (the US doesn't allow area codes or prefixes that being with 0 or 1). You could try and be super smart and create one regular expression that matches everything but you will end up with a jumbled mess that is impossible to modify instead you should OR the patterns together to make them easier to modify in the future. \nbasic idea: \npattern = re.compile(r'\\d{3}-\\d{3}-\\d{4}|\\(\\d{3}\\) \\d{3}-\\d{4}|1-\\d{3}-\\d{3}-\\d{4}')\n\nwith grouping added for canonical output \npattern = re.compile(r'(\\d{3})-(\\d{3})-(\\d{4})|\\((\\d{3})\\) (\\d{3})-(\\d{4})|1-(\\d{3})-(\\d{3})-(\\d{4})')\n\nthen just run that against your inputs and for each phone number input you will have 3 matching groups, one for the area code, one for the prefix, and one for the suffix which you can output however you want. You need a basic understanding of regular expressions, but it shouldn't be too hard.\n"
] |
[
9,
6,
4,
2,
0,
0
] |
[] |
[] |
[
"python"
] |
stackoverflow_0001731025_python.txt
|
Q:
Is there an existing Python class that can hold any user attributes?
I can use this when I need multiple objects with different attributes:
class struct(object):
def __init__(self,*args,**kwargs):
for key,val in kwargs.items():
setattr(self,key,val)
But I'm wondering if there isn't a built-in already?
A:
Unless I'm not understanding your question, isn't this what we use a dict for? Sure, it's notationally slightly different, but an object's attributes are internally still stored in a dict (namely __dict__). It's a matter of notation.
But, if you insist, then this is one way to do it:
>>> class struct(dict):
... def __getattribute__(self, key):
... return self[key]
...
>>> s = struct(a=5, b=7)
>>> s.a
5
Note I'm using __getattribute__ instead of __getattr__. The reason for this, is that otherwise we cannot store attributes with names such as get and keys, since these are methods defined by dict.
The solution by SilentGhost is probably more efficient and works just as well, without resorting to the use of __getattribute__. The code then becomes:
>>> def struct(**kwargs):
... return type('Struct', (object,), kwargs)
...
>>> s = struct(a=5, b=7)
>>> s.a
5
A:
I'm not certain why you're not using a dictionary for this.
x = {}
x.update([(1, 2), (3, 4), (5, 6)])
print x
result
{1: 2, 3: 4, 5: 6}
or
x.update(a=2, b=4, c=6)
results in
{'a': 2, 'c': 6, 'b': 4}
A:
I have wondered the same thing. I enjoy the convenience of x.foo instead of x["foo"]; a single period is far easier to type (and get correct) than all of [""].
The advantage of a dict is that anything can be a key. (Well, anything hashable.) But when I have a bunch of values I want to just bundle together, the key names I pick are valid identifiers anyway.
Here's the basic version of this idea:
class struct(object):
pass
x = struct()
x.foo = 1
As long as you are going to this much trouble, you might as well add the __init__() that handles kwargs for convenient initialization. But I'm lazy and I was hoping for something built-in.
I tried this, which doesn't work:
x = object()
x.foo = 1 # raises AttributeError exception
I asked about it, and the answer I got was that object is the root of all types in Python; it is as small as possible. If it could act like a class instance, with its own __dict__ attribute, then every object ever created in Python would need an attached __dict__.
I would have liked to see struct added as a built-in for Python 3.x. But I understand why it was not: keeping the language small and clean is a worthy goal, and this feature is trivially easy to code up yourself.
|
Is there an existing Python class that can hold any user attributes?
|
I can use this when I need multiple objects with different attributes:
class struct(object):
def __init__(self,*args,**kwargs):
for key,val in kwargs.items():
setattr(self,key,val)
But I'm wondering if there isn't a built-in already?
|
[
"Unless I'm not understanding your question, isn't this what we use a dict for? Sure, it's notationally slightly different, but an object's attributes are internally still stored in a dict (namely __dict__). It's a matter of notation.\nBut, if you insist, then this is one way to do it:\n>>> class struct(dict):\n... def __getattribute__(self, key):\n... return self[key]\n... \n>>> s = struct(a=5, b=7)\n>>> s.a\n5\n\nNote I'm using __getattribute__ instead of __getattr__. The reason for this, is that otherwise we cannot store attributes with names such as get and keys, since these are methods defined by dict.\nThe solution by SilentGhost is probably more efficient and works just as well, without resorting to the use of __getattribute__. The code then becomes:\n>>> def struct(**kwargs):\n... return type('Struct', (object,), kwargs)\n... \n>>> s = struct(a=5, b=7)\n>>> s.a\n5\n\n",
"I'm not certain why you're not using a dictionary for this.\nx = {}\nx.update([(1, 2), (3, 4), (5, 6)])\nprint x\n\nresult \n{1: 2, 3: 4, 5: 6}\n\nor\nx.update(a=2, b=4, c=6)\n\nresults in\n{'a': 2, 'c': 6, 'b': 4}\n\n",
"I have wondered the same thing. I enjoy the convenience of x.foo instead of x[\"foo\"]; a single period is far easier to type (and get correct) than all of [\"\"].\nThe advantage of a dict is that anything can be a key. (Well, anything hashable.) But when I have a bunch of values I want to just bundle together, the key names I pick are valid identifiers anyway.\nHere's the basic version of this idea:\nclass struct(object):\n pass\n\nx = struct()\nx.foo = 1\n\nAs long as you are going to this much trouble, you might as well add the __init__() that handles kwargs for convenient initialization. But I'm lazy and I was hoping for something built-in.\nI tried this, which doesn't work:\nx = object()\nx.foo = 1 # raises AttributeError exception\n\nI asked about it, and the answer I got was that object is the root of all types in Python; it is as small as possible. If it could act like a class instance, with its own __dict__ attribute, then every object ever created in Python would need an attached __dict__.\nI would have liked to see struct added as a built-in for Python 3.x. But I understand why it was not: keeping the language small and clean is a worthy goal, and this feature is trivially easy to code up yourself.\n"
] |
[
9,
3,
3
] |
[] |
[] |
[
"python",
"struct"
] |
stackoverflow_0001730769_python_struct.txt
|
Q:
How do I check the HTTP status code of an object without downloading it?
>>> a=urllib.urlopen('http://www.domain.com/bigvideo.avi')
>>> a.getcode()
404
>>> a=urllib.urlopen('http://www.google.com/')
>>> a.getcode()
200
My question is...bigvideo.avi is 500MB. Does my script first download the file, then check it? Or, can it immediately check the error code without saving the file?
A:
You want to actually tell the server not to send the full content of the file. HTTP has a mechanism for this called "HEAD" that is an alternative to "GET". It works the same way, but the server only sends you the headers, none of the actual content.
That'll save at least one of you bandwidth, while simply not doing a read() will only not bother getting the full file.
Try this:
import httplib
c = httplib.HTTPConnection(<hostname>)
c.request("HEAD", <url>)
print c.getresponse().status
The status code will be printed. Url should only be a segment, like "/foo" and hostname should be like, "www.example.com".
A:
Yes, it will fetch the file.
I think what you really want to do is send a HTTP HEAD request (which basically asks the server not for the data itself, but for the headers only). you can look here.
A:
i think your code already does that.
you never call the read() method on the response, so you are never actually downloading the file's contents.
better yet... you could send an HTTP HEAD request using httplib instead of doing the HTTP GET that your urllib code does.
|
How do I check the HTTP status code of an object without downloading it?
|
>>> a=urllib.urlopen('http://www.domain.com/bigvideo.avi')
>>> a.getcode()
404
>>> a=urllib.urlopen('http://www.google.com/')
>>> a.getcode()
200
My question is...bigvideo.avi is 500MB. Does my script first download the file, then check it? Or, can it immediately check the error code without saving the file?
|
[
"You want to actually tell the server not to send the full content of the file. HTTP has a mechanism for this called \"HEAD\" that is an alternative to \"GET\". It works the same way, but the server only sends you the headers, none of the actual content.\nThat'll save at least one of you bandwidth, while simply not doing a read() will only not bother getting the full file.\nTry this:\nimport httplib\nc = httplib.HTTPConnection(<hostname>)\nc.request(\"HEAD\", <url>)\nprint c.getresponse().status\n\nThe status code will be printed. Url should only be a segment, like \"/foo\" and hostname should be like, \"www.example.com\".\n",
"Yes, it will fetch the file.\nI think what you really want to do is send a HTTP HEAD request (which basically asks the server not for the data itself, but for the headers only). you can look here.\n",
"i think your code already does that.\nyou never call the read() method on the response, so you are never actually downloading the file's contents.\nbetter yet... you could send an HTTP HEAD request using httplib instead of doing the HTTP GET that your urllib code does.\n"
] |
[
18,
1,
0
] |
[] |
[] |
[
"http",
"python"
] |
stackoverflow_0001731298_http_python.txt
|
Q:
How should unit tests be documented?
I'm trying to improve the number and quality of tests in my Python projects. One of the the difficulties I've encountered as the number of tests increase is knowing what each test does and how it's supposed to help spot problems. I know that part of keeping track of tests is better unit test names (which has been addressed elsewhere), but I'm also interested in understanding how documentation and unit testing go together.
How can unit tests be documented to improve their utility when those tests fail in the future? Specifically, what makes a good unit test docstring?
I'd appreciate both descriptive answers and examples of unit tests with excellent documentation. Though I'm working exclusively with Python, I'm open to practices from other languages.
A:
I document most on my unit tests with the method name exclusively:
testInitializeSetsUpChessBoardCorrectly()
testSuccessfulPromotionAddsCorrectPiece()
For almost 100% of my test cases, this clearly explains what the unit test is validating and that's all I use. However, in a few of the more complicated test cases, I'll add a few comments throughout the method to explain what several lines are doing.
I've seen a tool before (I believe it was for Ruby) that would generate documentation files by parsing the names of all the test cases in a project, but I don't recall the name. If you had test cases for a chess Queen class:
testCanMoveStraightUpWhenNotBlocked()
testCanMoveStraightLeftWhenNotBlocked()
the tool would generate an HTML doc with contents something like this:
Queen requirements:
- can move straight up when not blocked.
- can move straight left when not blocked.
A:
Perhaps the issue isn't in how best to write test docstrings, but how to write the tests themselves? Refactoring tests in such a way that they're self documenting can go a long way, and your docstring won't go stale when the code changes.
There's a few things you can do to make the tests clearer:
clear & descriptive test method names (already mentioned)
test body should be clear and concise (self documenting)
abstract away complicated setup/teardown etc. in methods
more?
For example, if you have a test like this:
def test_widget_run_returns_0():
widget = Widget(param1, param2, "another param")
widget.set_option(true)
widget.set_temp_dir("/tmp/widget_tmp")
widget.destination_ip = "10.10.10.99"
return_value = widget.run()
assert return_value == 0
assert widget.response == "My expected response"
assert widget.errors == None
You might replace the setup statements with a method call:
def test_widget_run_returns_0():
widget = create_basic_widget()
return_value = widget.run()
assert return_value == 0
assert_basic_widget(widget)
def create_basic_widget():
widget = Widget(param1, param2, "another param")
widget.set_option(true)
widget.set_temp_dir("/tmp/widget_tmp")
widget.destination_ip = "10.10.10.99"
return widget
def assert_basic_widget():
assert widget.response == "My expected response"
assert widget.errors == None
Note that your test method is now composed of a series of method calls with intent-revealing names, a sort of DSL specific to your tests. Does a test like that still need documentation?
Another thing to note is that your test method is mainly at one level of abstraction. Someone reading the test method will see the algorithm is:
creating a widget
calling run on the widget
asserting the code did what we expect
Their understanding of the test method is not muddied by the details of setting up the widget, which is one level of abstraction lower than the test method.
The first version of the test method follows the Inline Setup pattern. The second version follows Creation Method and Delegated Setup patterns.
Generally I'm against comments, except where they explain the "why" of the code. Reading Uncle Bob Martin's Clean Code convinced me of this. There is a chapter on comments, and there is a chapter on testing. I recommend it.
For more on automated testing best practices, do check out xUnit Patterns.
A:
The name of the test method should describe exactly what you are testing. The documentation should say what makes the test fail.
A:
You should use a combination of descriptive method names and comments in the doc string. A good way to do it is including a basic procedure and verification steps in the doc string. Then if you run these tests from some kind of testing framework that automates running the tests and collecting results, you can have the framework log the contents of the doc string for each test method along with its stdout+stderr.
Here's a basic example:
class SimpelTestCase(unittest.TestCase):
def testSomething(self):
""" Procedure:
1. Print something
2. Print something else
---------
Verification:
3. Verify no errors occurred
"""
print "something"
print "something else"
Having the procedure with the test makes it much easier to figure out what the test is doing. And if you include the docstring with the test output it makes figuring out what went wrong when going through the results later much easier. The previous place I worked at did something like this and it worked out very well when failures occurred. We ran the unit tests on every checkin automatically, using CruiseControl.
A:
When the test fails (which should be before it ever passes) you should see the error message and be able to tell what's up. That only happens if you plan it that way.
It's entirely a matter of the naming of the test class, the test method, and the assert message. When a test fails, and you can't tell what is up from these three clues, then rename some things or break up some tests classes.
It doesn't happen if the name of the fixture is ClassXTests and the name of the test is TestMethodX and the error message is "expected true, returned false". That's a sign of sloppy test writing.
Most of the time you shouldn't have to read the test or any comments to know what has happened.
|
How should unit tests be documented?
|
I'm trying to improve the number and quality of tests in my Python projects. One of the the difficulties I've encountered as the number of tests increase is knowing what each test does and how it's supposed to help spot problems. I know that part of keeping track of tests is better unit test names (which has been addressed elsewhere), but I'm also interested in understanding how documentation and unit testing go together.
How can unit tests be documented to improve their utility when those tests fail in the future? Specifically, what makes a good unit test docstring?
I'd appreciate both descriptive answers and examples of unit tests with excellent documentation. Though I'm working exclusively with Python, I'm open to practices from other languages.
|
[
"I document most on my unit tests with the method name exclusively:\ntestInitializeSetsUpChessBoardCorrectly()\ntestSuccessfulPromotionAddsCorrectPiece()\n\nFor almost 100% of my test cases, this clearly explains what the unit test is validating and that's all I use. However, in a few of the more complicated test cases, I'll add a few comments throughout the method to explain what several lines are doing.\nI've seen a tool before (I believe it was for Ruby) that would generate documentation files by parsing the names of all the test cases in a project, but I don't recall the name. If you had test cases for a chess Queen class:\ntestCanMoveStraightUpWhenNotBlocked()\ntestCanMoveStraightLeftWhenNotBlocked()\n\nthe tool would generate an HTML doc with contents something like this:\nQueen requirements:\n - can move straight up when not blocked.\n - can move straight left when not blocked.\n\n",
"Perhaps the issue isn't in how best to write test docstrings, but how to write the tests themselves? Refactoring tests in such a way that they're self documenting can go a long way, and your docstring won't go stale when the code changes.\nThere's a few things you can do to make the tests clearer:\n\nclear & descriptive test method names (already mentioned)\ntest body should be clear and concise (self documenting)\nabstract away complicated setup/teardown etc. in methods\nmore?\n\nFor example, if you have a test like this:\ndef test_widget_run_returns_0():\n widget = Widget(param1, param2, \"another param\")\n widget.set_option(true)\n widget.set_temp_dir(\"/tmp/widget_tmp\")\n widget.destination_ip = \"10.10.10.99\"\n\n return_value = widget.run()\n\n assert return_value == 0\n assert widget.response == \"My expected response\"\n assert widget.errors == None\n\nYou might replace the setup statements with a method call:\ndef test_widget_run_returns_0():\n widget = create_basic_widget()\n return_value = widget.run()\n assert return_value == 0\n assert_basic_widget(widget)\n\ndef create_basic_widget():\n widget = Widget(param1, param2, \"another param\")\n widget.set_option(true)\n widget.set_temp_dir(\"/tmp/widget_tmp\")\n widget.destination_ip = \"10.10.10.99\"\n return widget\n\ndef assert_basic_widget():\n assert widget.response == \"My expected response\"\n assert widget.errors == None\n\nNote that your test method is now composed of a series of method calls with intent-revealing names, a sort of DSL specific to your tests. Does a test like that still need documentation?\nAnother thing to note is that your test method is mainly at one level of abstraction. Someone reading the test method will see the algorithm is:\n\ncreating a widget\ncalling run on the widget\nasserting the code did what we expect\n\nTheir understanding of the test method is not muddied by the details of setting up the widget, which is one level of abstraction lower than the test method.\nThe first version of the test method follows the Inline Setup pattern. The second version follows Creation Method and Delegated Setup patterns.\nGenerally I'm against comments, except where they explain the \"why\" of the code. Reading Uncle Bob Martin's Clean Code convinced me of this. There is a chapter on comments, and there is a chapter on testing. I recommend it.\nFor more on automated testing best practices, do check out xUnit Patterns.\n",
"The name of the test method should describe exactly what you are testing. The documentation should say what makes the test fail. \n",
"You should use a combination of descriptive method names and comments in the doc string. A good way to do it is including a basic procedure and verification steps in the doc string. Then if you run these tests from some kind of testing framework that automates running the tests and collecting results, you can have the framework log the contents of the doc string for each test method along with its stdout+stderr.\nHere's a basic example:\nclass SimpelTestCase(unittest.TestCase):\n def testSomething(self):\n \"\"\" Procedure:\n 1. Print something\n 2. Print something else\n ---------\n Verification:\n 3. Verify no errors occurred\n \"\"\"\n print \"something\"\n print \"something else\"\n\nHaving the procedure with the test makes it much easier to figure out what the test is doing. And if you include the docstring with the test output it makes figuring out what went wrong when going through the results later much easier. The previous place I worked at did something like this and it worked out very well when failures occurred. We ran the unit tests on every checkin automatically, using CruiseControl.\n",
"When the test fails (which should be before it ever passes) you should see the error message and be able to tell what's up. That only happens if you plan it that way.\nIt's entirely a matter of the naming of the test class, the test method, and the assert message. When a test fails, and you can't tell what is up from these three clues, then rename some things or break up some tests classes. \nIt doesn't happen if the name of the fixture is ClassXTests and the name of the test is TestMethodX and the error message is \"expected true, returned false\". That's a sign of sloppy test writing.\nMost of the time you shouldn't have to read the test or any comments to know what has happened.\n"
] |
[
17,
15,
4,
0,
0
] |
[] |
[] |
[
"docstring",
"documentation",
"python",
"unit_testing"
] |
stackoverflow_0001726622_docstring_documentation_python_unit_testing.txt
|
Q:
Getting only one dimension of indexes from the getSelectedIndexes function in QT?
I'm working on a small project in QT (well, pyQT4 actually, but it shouldn't matter too much) and I've run into the following problem. I have a QTableView with several rows and columns. I have set the selection mode to be rows only. When I call getSelectedIndexes() on my QTableView, I get an index for every row and column, which in the current setup means that I get an extra 5 Indexes for each selected row, which is less than ideal, since I only need to know the row, not the column. Is there any way to get just one Index per row other than filtering the list that I get from getSelectedIndexes()?
A:
The selection is maintained by QItemSelectionModel, which provides a method called selectedRows() that does what you want. For example:
myTableView->selectionModel()->selectedRows()
|
Getting only one dimension of indexes from the getSelectedIndexes function in QT?
|
I'm working on a small project in QT (well, pyQT4 actually, but it shouldn't matter too much) and I've run into the following problem. I have a QTableView with several rows and columns. I have set the selection mode to be rows only. When I call getSelectedIndexes() on my QTableView, I get an index for every row and column, which in the current setup means that I get an extra 5 Indexes for each selected row, which is less than ideal, since I only need to know the row, not the column. Is there any way to get just one Index per row other than filtering the list that I get from getSelectedIndexes()?
|
[
"The selection is maintained by QItemSelectionModel, which provides a method called selectedRows() that does what you want. For example:\nmyTableView->selectionModel()->selectedRows()\n\n"
] |
[
4
] |
[] |
[] |
[
"indexing",
"pyqt4",
"python",
"qt",
"qt4"
] |
stackoverflow_0001731272_indexing_pyqt4_python_qt_qt4.txt
|
Q:
httplib in Python to get the status code...but it is too tricky?
>>> import httplib
>>> conn = httplib.HTTPConnection("www.google.com")
>>> conn.request("HEAD", "/index.html")
>>> res = conn.getresponse()
>>> print res.status, res.reason
200 OK
This code will get the HTTP status code. However, notice that I split up "google.com" and "/index.html" on 2 lines.
And it's confusing.
What if I want to find the status code of just a general URL???
http://mydomain.com/sunny/boo.avi
http://anotherdomain.com/podcast.mp3
http://anotherdomain.com/rss/fee.xml
Can't I just stick the URL into it, and make it work?
Edit...I cannot use urllib, because I don't want to downlaod the file
A:
Maybe you are better off using the URL library instead?
In Python 2, use urllib2:
>>> import urllib2
>>> url = urllib2.urlopen("http://www.google.com/index.html")
>>> url.getcode()
200
In Python 3, use urllib.request:
>>> import urllib.request
>>> url = urllib.request.urlopen("http://www.google.com/index.html")
>>> url.getcode()
200
A:
Alternatively, if you expect that actually downloading the data is problematic and you really need the HEAD method, you could parse the URL using urlparse:
>>> import httplib
>>> import urlparse
>>> url = "http://www.google.com/index.html"
>>> (scheme, netloc, path, params, query, fragment) = urlparse.urlparse(url)
>>> conn = httplib.HTTPConnection(netloc)
>>> conn.request("HEAD", urlparse.urlunparse(('', '', path, params, query, fragment))
>>> res = conn.getresponse()
>>> print res.status, res.reason
302 Found
And wrap this into a function taking the URL as an argument.
A:
The connect method takes a server argument (with an optional port). You have to split the connection with the resource you actually want.
For a simpler way to download web resources directly, you could go with urllib2 but urllib2 only supports GET or POST methods, no HEAD, so you end up downloading the whole resource.
A:
According to the spec you're supposed to split it up like that, maybe Python could abstract that out for you a bit, they're probably just giving you straight access to the header so you know exactly how it's being formatted, which is really the preference.
A:
I like urllib2, sample code:
import urllib2
res = urllib2.urlopen('http://google.com/index.html')
res.getCode() #contains code
I something went wrong, you'll get an exception you can catch.
EDIT: Thanks, changes res.code to res.getCode() since the second one is documented
A:
Keep in mind that not all web servers support HEAD on each resource so you'll end up retrieving the resource anyway. You should write code accordingly.
|
httplib in Python to get the status code...but it is too tricky?
|
>>> import httplib
>>> conn = httplib.HTTPConnection("www.google.com")
>>> conn.request("HEAD", "/index.html")
>>> res = conn.getresponse()
>>> print res.status, res.reason
200 OK
This code will get the HTTP status code. However, notice that I split up "google.com" and "/index.html" on 2 lines.
And it's confusing.
What if I want to find the status code of just a general URL???
http://mydomain.com/sunny/boo.avi
http://anotherdomain.com/podcast.mp3
http://anotherdomain.com/rss/fee.xml
Can't I just stick the URL into it, and make it work?
Edit...I cannot use urllib, because I don't want to downlaod the file
|
[
"Maybe you are better off using the URL library instead?\nIn Python 2, use urllib2:\n>>> import urllib2\n>>> url = urllib2.urlopen(\"http://www.google.com/index.html\")\n>>> url.getcode()\n200\n\nIn Python 3, use urllib.request:\n>>> import urllib.request\n>>> url = urllib.request.urlopen(\"http://www.google.com/index.html\")\n>>> url.getcode()\n200\n\n",
"Alternatively, if you expect that actually downloading the data is problematic and you really need the HEAD method, you could parse the URL using urlparse:\n>>> import httplib\n>>> import urlparse\n>>> url = \"http://www.google.com/index.html\"\n>>> (scheme, netloc, path, params, query, fragment) = urlparse.urlparse(url)\n>>> conn = httplib.HTTPConnection(netloc)\n>>> conn.request(\"HEAD\", urlparse.urlunparse(('', '', path, params, query, fragment))\n>>> res = conn.getresponse()\n>>> print res.status, res.reason\n302 Found\n\nAnd wrap this into a function taking the URL as an argument.\n",
"The connect method takes a server argument (with an optional port). You have to split the connection with the resource you actually want.\nFor a simpler way to download web resources directly, you could go with urllib2 but urllib2 only supports GET or POST methods, no HEAD, so you end up downloading the whole resource.\n",
"According to the spec you're supposed to split it up like that, maybe Python could abstract that out for you a bit, they're probably just giving you straight access to the header so you know exactly how it's being formatted, which is really the preference.\n",
"I like urllib2, sample code:\nimport urllib2\nres = urllib2.urlopen('http://google.com/index.html')\nres.getCode() #contains code\n\nI something went wrong, you'll get an exception you can catch.\nEDIT: Thanks, changes res.code to res.getCode() since the second one is documented\n",
"Keep in mind that not all web servers support HEAD on each resource so you'll end up retrieving the resource anyway. You should write code accordingly.\n"
] |
[
6,
6,
2,
0,
0,
0
] |
[] |
[] |
[
"http",
"http_headers",
"python",
"regex"
] |
stackoverflow_0001731657_http_http_headers_python_regex.txt
|
Q:
How to play sound till the user hits a key?
First thought of implementing this using threads but python doesnt have a way for killing threads. I have read the other topic on killing threads.
Is there any proper platform independent way of doing this?
A:
Can you be more specific? This could be done in pygame, but you'd need to open a graphical window.
A:
I think you'd better use a Tk timer for ringing periodically, and then stop it when you get the key press.
See http://www.java2s.com/Code/Python/GUI-Tk/Clockevent.htm for an example how to use timer.
Thus you will avoid creating another thread.
|
How to play sound till the user hits a key?
|
First thought of implementing this using threads but python doesnt have a way for killing threads. I have read the other topic on killing threads.
Is there any proper platform independent way of doing this?
|
[
"Can you be more specific? This could be done in pygame, but you'd need to open a graphical window.\n",
"I think you'd better use a Tk timer for ringing periodically, and then stop it when you get the key press.\nSee http://www.java2s.com/Code/Python/GUI-Tk/Clockevent.htm for an example how to use timer.\nThus you will avoid creating another thread.\n"
] |
[
0,
0
] |
[] |
[] |
[
"python",
"tkinter"
] |
stackoverflow_0001731986_python_tkinter.txt
|
Q:
Alternatives to wx.lib.masked.NumCtrl
In a wxPython application I'm developing I need a lot of input fields for numbers (integers and floats), so I tried using wx.lib.masked.NumCtrl, but my users now tell me that it's quite uncomfortable to use (and I agree with them).
Is there an alternative widget implementation I can use, or should I just roll my own, starting from a bare TextCtrl?
(wxPython 2.8.9.1)
Edit
For completeness, here's an example of "uncomfortableness":
given a NumCtrl with selectOnEntry and fractionWidth > 0, when you switch to the decimal part of the field, it gets correctly selected, but pressing numbers doesn't do anything, you have to delete the contents of the field first.
A:
In the usual wxPython distribution there's IntCtrl, and then a few other GUI controls like Slider, Spin, FloatSpin, and KnobCtrl.
There's also the Enthought Traits approach, and the GUI part of this seems to have put a fair amount of focus on numerical entry and display, such as logarithmic sliders, float array editors, etc. Looking at their designs might give some inspiration even if you don't take this path.
Also, it's not really clear why you don't like the masked NumCtrl, but it's very easy to write your own, so if there's some specific thing you want, that's probably the way to go.
|
Alternatives to wx.lib.masked.NumCtrl
|
In a wxPython application I'm developing I need a lot of input fields for numbers (integers and floats), so I tried using wx.lib.masked.NumCtrl, but my users now tell me that it's quite uncomfortable to use (and I agree with them).
Is there an alternative widget implementation I can use, or should I just roll my own, starting from a bare TextCtrl?
(wxPython 2.8.9.1)
Edit
For completeness, here's an example of "uncomfortableness":
given a NumCtrl with selectOnEntry and fractionWidth > 0, when you switch to the decimal part of the field, it gets correctly selected, but pressing numbers doesn't do anything, you have to delete the contents of the field first.
|
[
"In the usual wxPython distribution there's IntCtrl, and then a few other GUI controls like Slider, Spin, FloatSpin, and KnobCtrl.\nThere's also the Enthought Traits approach, and the GUI part of this seems to have put a fair amount of focus on numerical entry and display, such as logarithmic sliders, float array editors, etc. Looking at their designs might give some inspiration even if you don't take this path.\nAlso, it's not really clear why you don't like the masked NumCtrl, but it's very easy to write your own, so if there's some specific thing you want, that's probably the way to go.\n"
] |
[
1
] |
[] |
[] |
[
"python",
"wxpython"
] |
stackoverflow_0001730647_python_wxpython.txt
|
Q:
a better way to do ajax in django
The other day I wrote some AJAX for a Django app that i have been working on.
I come from Ruby on Rails, so I haven't done much in the way of raw JS.
So based on Rails' partials, I something similar to the following in a sort of pseudocode, don't sweat the details:
1) JS function using prototype's Ajax.Updater ('tablediv' being the id of the table i wanted to update Ajaxily, and url pointing to the proper django view)
function updateTable(){
new Ajax.Updater('tablediv',url {params: params....etc
2) django view that got new data to populate the table with:
def ajaxTable
objects = Objects.object.all...
return render_to_response('ajaxtable.html',objects)
3) ajaxtable.html was just a sort of Rails "partial" so basically a table w/o <table> </table> ...:
<th>{{object.data}}</th>
<td>{{object.moredata}}</td>
so to my actual question:
This seemed hacky to me, I sort of threw it together after getting tired of searching online for what i wanted.
Is this the way it's done? It works fine, I just don't know enough to know, you know?
A:
It kinda depends what you want to do I think. Ajax being quite a wide range of scenarios from Google Maps to a simple auto-complete varys greatly in complexity and the best approach.
However, there are some useful things you can do that help.
1) Template level
Make sure you have "django.core.context_processors.request" in your TEMPLATE_CONTEXT_PROCESSORS setting. Then you can do this;
{% if not request.is_ajax %}
<html>
<head>
...
</head>
<body>
...
{% endif %}
actual content
{% if not request.is_ajax %}
</body>
</html>
{% endif %}
Basically then say this page is /test/ you can do a browser request and get the full content or a request via JavaScript and just get the content. There is a blogpost somewhere that explains this in more detail but I can't find it at the moment.
2) In the view
In the template we are just accessing the request object in the template. In the view you can do very similar things.
def my_view(request):
if requst.is_ajax():
# handle for Ajax requests
# otherwise handle 'normal' requests
return HttpResponse('Hello world')
The above methods don't really do it differently than you do but allow you to re-use views and write it bit more concisely. I wouldn't really say what you are doing is wrong or hacky but you could write it to make it more concise and re-use the templates and views.
say for example you could have just one template and if its a Ajax request have it only return the section that will need to be updated. In your case it would be the tables views.
A:
I am quite late, but I want to document how to combine and adapt the solutions presented by d0ugal
in a way, that it will resolve a much cleaner template-code.
I have a model representing contact persons.
The (generic) view to get one ContactPerson looks like this:
def contcactperson_detail_view(request, name):
try:
person = ContactPerson.objects.get(slug=name)
except:
raise Http404
if request.is_ajax():
return contcactperson_detail_view_ajax(request, person)
return list_detail.object_detail(
request,
queryset = ContactPerson.objects.all(),
object_id = person.id,
template_object_name = "contactperson",
)
@render_to('cms/contactperson_detail_ajax.html')
def contcactperson_detail_view_ajax(request, person):
return {'contactperson':person, 'is_ajax':True}
The template to render the view that handles one ContactPerson is called contcactperson_detail_view.html:
{% extends "index.html" %}
{% block textpane %}
<h1 id="mainheader">{{ contactperson.first_name }} {{ contactperson.family_name }} </h1>
<div class="indentation"> </div>
{% include 'cms/contactperson_detail_photo.html' %}
<div id="text_pane">
{% include 'cms/contactperson_detail_textpane.html' %}
</div>
{% endblock %}
It includes two sub-templates
contactperson_detail_textpane.html
<p>{{ contactperson.description }}</p>
<ul>
<li>
<dl>
<dt>Email</dt>
<dd>
{{ contactperson.mail }}
</dd>
</dl>
</li>
<li>
<dl>
<dt>Contact Person for</dt>
<dd>
<ul>
{% for c in contactperson.categories.all %}
<li><a href="{% url category-view c.slug %}">{{ c }}</a></li>
{% endfor %}
</ul>
</dd>
</dl>
</li>
</ul>
and contactperson_detail_photo.html
{% with contactperson.photo.detailphoto as pic %}
{% with pic.url as pic_url %}
<div {% if not is_ajax %}id='imageContainer'{% endif %} style="float: right;padding-right:0.5em;
padding-bottom: 1em; padding-left:0.5em;clear:both;
width:{{ pic.width }}px">
<div style="width:{{ pic.width}}px">
<img style="clear:both" src="{{ pic_url }}" alt="{{ i.name }}"/>
</div>
</div>
{% endwith %}
{% endwith %}
this 3 templates will be used, if the request isn't ajax.
But if the request is ajax, contcactperson_detail_view will return the view contcactperson_detail_view_ajax, that uses the template contactperson_detail_ajax.html for rendering. And this template looks like this:
<h1>{{ contactperson.first_name }} {{ contactperson.family_name }}</h1>
{% include 'cms/contactperson_detail_photo.html' %}
{% include 'cms/contactperson_detail_textpane.html' %}
So it uses the same sub-templates but isn't extending anything, therefore only the needed markup delivered. As the ajax view passes is_ajax = True to the template, it can be used to adjust minor things, like setting correct id-attributes.
No context-processor or additional url-conf needed.
Finally the Javascript code:
$("#contact_person_portlet a").click(function(event){
event.preventDefault();
$.ajax({
type: "GET",
url: event.target.getAttribute('href'),
success: function(msg){
overlay(msg);
}
});
});
Hope that it will be useful for some people. If so, please leave a comment!
A:
No matter what, you're going to need at least two things:
Your javascript code to make the call (you have this)
Server side code to handle the request (this is your view and url-config)
There is absolutely nothing "hacky" about this.
The third thing, your template file, is optional - but is generally good practice. You want to separate your markup from the code, for many reasons.
So I think you've got the right idea. Carry on.
A:
What exactly seems hacky about it? Seems like a perfectly valid way of doing something.
I guess an alternative would be serialising to json and sending it back to a javascript templating snippet.
|
a better way to do ajax in django
|
The other day I wrote some AJAX for a Django app that i have been working on.
I come from Ruby on Rails, so I haven't done much in the way of raw JS.
So based on Rails' partials, I something similar to the following in a sort of pseudocode, don't sweat the details:
1) JS function using prototype's Ajax.Updater ('tablediv' being the id of the table i wanted to update Ajaxily, and url pointing to the proper django view)
function updateTable(){
new Ajax.Updater('tablediv',url {params: params....etc
2) django view that got new data to populate the table with:
def ajaxTable
objects = Objects.object.all...
return render_to_response('ajaxtable.html',objects)
3) ajaxtable.html was just a sort of Rails "partial" so basically a table w/o <table> </table> ...:
<th>{{object.data}}</th>
<td>{{object.moredata}}</td>
so to my actual question:
This seemed hacky to me, I sort of threw it together after getting tired of searching online for what i wanted.
Is this the way it's done? It works fine, I just don't know enough to know, you know?
|
[
"It kinda depends what you want to do I think. Ajax being quite a wide range of scenarios from Google Maps to a simple auto-complete varys greatly in complexity and the best approach.\nHowever, there are some useful things you can do that help.\n1) Template level\nMake sure you have \"django.core.context_processors.request\" in your TEMPLATE_CONTEXT_PROCESSORS setting. Then you can do this;\n{% if not request.is_ajax %}\n<html>\n <head>\n ...\n </head>\n <body>\n ...\n{% endif %}\nactual content\n{% if not request.is_ajax %}\n</body>\n</html>\n{% endif %}\n\nBasically then say this page is /test/ you can do a browser request and get the full content or a request via JavaScript and just get the content. There is a blogpost somewhere that explains this in more detail but I can't find it at the moment.\n2) In the view\nIn the template we are just accessing the request object in the template. In the view you can do very similar things.\ndef my_view(request):\n if requst.is_ajax():\n # handle for Ajax requests\n\n # otherwise handle 'normal' requests\n return HttpResponse('Hello world')\n\nThe above methods don't really do it differently than you do but allow you to re-use views and write it bit more concisely. I wouldn't really say what you are doing is wrong or hacky but you could write it to make it more concise and re-use the templates and views.\nsay for example you could have just one template and if its a Ajax request have it only return the section that will need to be updated. In your case it would be the tables views.\n",
"I am quite late, but I want to document how to combine and adapt the solutions presented by d0ugal\nin a way, that it will resolve a much cleaner template-code.\nI have a model representing contact persons. \nThe (generic) view to get one ContactPerson looks like this:\ndef contcactperson_detail_view(request, name):\n try:\n person = ContactPerson.objects.get(slug=name)\n except:\n raise Http404\n if request.is_ajax():\n return contcactperson_detail_view_ajax(request, person)\n return list_detail.object_detail(\n request,\n queryset = ContactPerson.objects.all(),\n object_id = person.id,\n template_object_name = \"contactperson\",\n )\n\n@render_to('cms/contactperson_detail_ajax.html') \ndef contcactperson_detail_view_ajax(request, person):\n return {'contactperson':person, 'is_ajax':True}\n\nThe template to render the view that handles one ContactPerson is called contcactperson_detail_view.html:\n{% extends \"index.html\" %}\n{% block textpane %}\n\n<h1 id=\"mainheader\">{{ contactperson.first_name }} {{ contactperson.family_name }} </h1>\n<div class=\"indentation\"> </div> \n{% include 'cms/contactperson_detail_photo.html' %} \n<div id=\"text_pane\">\n\n{% include 'cms/contactperson_detail_textpane.html' %}\n</div>\n{% endblock %}\n\nIt includes two sub-templates\ncontactperson_detail_textpane.html\n\n\n<p>{{ contactperson.description }}</p>\n<ul>\n <li>\n <dl>\n <dt>Email</dt>\n <dd>\n {{ contactperson.mail }}\n </dd>\n </dl>\n </li>\n <li>\n <dl>\n <dt>Contact Person for</dt>\n <dd>\n <ul>\n {% for c in contactperson.categories.all %}\n <li><a href=\"{% url category-view c.slug %}\">{{ c }}</a></li>\n {% endfor %}\n </ul>\n </dd>\n </dl>\n </li>\n</ul>\n\nand contactperson_detail_photo.html\n{% with contactperson.photo.detailphoto as pic %} \n {% with pic.url as pic_url %} \n <div {% if not is_ajax %}id='imageContainer'{% endif %} style=\"float: right;padding-right:0.5em; \n padding-bottom: 1em; padding-left:0.5em;clear:both; \n width:{{ pic.width }}px\"> \n <div style=\"width:{{ pic.width}}px\"> \n <img style=\"clear:both\" src=\"{{ pic_url }}\" alt=\"{{ i.name }}\"/> \n </div> \n </div> \n {% endwith %}\n{% endwith %}\n\nthis 3 templates will be used, if the request isn't ajax.\nBut if the request is ajax, contcactperson_detail_view will return the view contcactperson_detail_view_ajax, that uses the template contactperson_detail_ajax.html for rendering. And this template looks like this:\n<h1>{{ contactperson.first_name }} {{ contactperson.family_name }}</h1>\n{% include 'cms/contactperson_detail_photo.html' %} \n{% include 'cms/contactperson_detail_textpane.html' %}\n\nSo it uses the same sub-templates but isn't extending anything, therefore only the needed markup delivered. As the ajax view passes is_ajax = True to the template, it can be used to adjust minor things, like setting correct id-attributes.\nNo context-processor or additional url-conf needed.\nFinally the Javascript code:\n$(\"#contact_person_portlet a\").click(function(event){\n event.preventDefault();\n $.ajax({\n type: \"GET\",\n url: event.target.getAttribute('href'),\n success: function(msg){\n overlay(msg);\n }\n });\n });\n\nHope that it will be useful for some people. If so, please leave a comment!\n",
"No matter what, you're going to need at least two things:\n\nYour javascript code to make the call (you have this)\nServer side code to handle the request (this is your view and url-config)\n\nThere is absolutely nothing \"hacky\" about this.\nThe third thing, your template file, is optional - but is generally good practice. You want to separate your markup from the code, for many reasons.\nSo I think you've got the right idea. Carry on.\n",
"What exactly seems hacky about it? Seems like a perfectly valid way of doing something.\nI guess an alternative would be serialising to json and sending it back to a javascript templating snippet. \n"
] |
[
5,
4,
3,
1
] |
[] |
[] |
[
"ajax",
"django",
"javascript",
"python"
] |
stackoverflow_0001491618_ajax_django_javascript_python.txt
|
Q:
wxPython : Problem updating background color of controls
[EDIT - Reduced and re-posted code, restated question]
I would like to change the background color of a frame (or panel; whichever makes it work).
The problem is that the background color of controls on that frame (or panel) don't have their background color updated until I click on the control (the slider control, specifically).
Any ideas on how to fix this?
Here's some demo code:
import wx
class MyFrame(wx.Frame):
def __init__(self, *args, **kwds):
kwds["style"] = wx.DEFAULT_FRAME_STYLE
wx.Frame.__init__(self, *args, **kwds)
self.panel_1 = wx.Panel(self, -1)
self.sliderDarken = wx.Slider(self.panel_1, -1, 206, 0, 255)
self.label_3 = wx.StaticText(self.panel_1, -1, "This slider should darken the main panel.\n")
self.btnPopup = wx.Button(self.panel_1, -1, "This button will pop up a dialog to dim the panel.")
self.__set_properties()
self.__do_layout()
self.Bind(wx.EVT_COMMAND_SCROLL, self.onDarken, self.sliderDarken)
self.Bind(wx.EVT_BUTTON, self.onDialogPopup, self.btnPopup)
def __set_properties(self):
self.SetTitle("Main Frame")
def __do_layout(self):
sizer_1 = wx.BoxSizer(wx.VERTICAL)
sizer_3 = wx.BoxSizer(wx.HORIZONTAL)
sizer_3.Add(self.sliderDarken, 0, 0, 0)
sizer_3.Add(self.label_3, 0, 0, 0)
sizer_3.Add(self.btnPopup, 0, 0, 0)
self.panel_1.SetSizer(sizer_3)
sizer_1.Add(self.panel_1, 1, wx.EXPAND, 0)
self.SetSizer(sizer_1)
sizer_1.Fit(self)
self.Layout()
def onDarken(self, event):
self.panel_1.SetBackgroundColour(wx.Colour(self.sliderDarken.GetValue(),self.sliderDarken.GetValue(),self.sliderDarken.GetValue()))
self.panel_1.Refresh()
def onDialogPopup(self, event):
dlgPopup=MyDialog1(None)
dlgPopup.Show()
class MyDialog1(wx.Dialog):
def __init__(self, *args, **kwds):
kwds["style"] = wx.DEFAULT_DIALOG_STYLE
wx.Dialog.__init__(self, *args, **kwds)
self.sliderDarkenPopup = wx.Slider(self, -1, 206, 0, 255, style=wx.SL_HORIZONTAL|wx.SL_AUTOTICKS|wx.SL_LABELS)
self.label_2 = wx.StaticText(self, -1, "This slider should darken the panel on the main frame.")
self.__set_properties()
self.__do_layout()
self.Bind(wx.EVT_COMMAND_SCROLL, self.onDarkenPopup, self.sliderDarkenPopup)
def __set_properties(self):
self.SetTitle("Dimmer Pop up")
def __do_layout(self):
sizer_2 = wx.BoxSizer(wx.HORIZONTAL)
sizer_2.Add(self.sliderDarkenPopup, 0, 0, 0)
sizer_2.Add(self.label_2, 0, 0, 0)
self.SetSizer(sizer_2)
sizer_2.Fit(self)
self.Layout()
def onDarkenPopup(self, event):
frame_1.panel_1.SetBackgroundColour(wx.Colour(self.sliderDarkenPopup.GetValue(),self.sliderDarkenPopup.GetValue(),self.sliderDarkenPopup.GetValue()))
frame_1.panel_1.Refresh()
if __name__ == "__main__":
app = wx.PySimpleApp(0)
wx.InitAllImageHandlers()
frame_1 = MyFrame(None, -1, "")
app.SetTopWindow(frame_1)
frame_1.Show()
app.MainLoop()
A:
Try putting a panel in each frame and then putting your controls on the panel. In wxPython, frames don't like to have multiple windows (especially for Windows OS), so it usually helps to have the frame own one panel and the panel to own the other controls.
If this doesn't solve the problem, please to to phrase your question more clearly and reduce your code to the smallest program that displays the problem, and then it will be easier for us (or at least me) to understand.
A:
Try generating and processing a wx.SysColourChangedEvent.
def onDarken(self, event):
self.panel_1.SetBackgroundColour(wx.Colour(self.sliderDarken.GetValue(),self.sliderDarken.GetValue(),self.sliderDarken.GetValue()))
event = wx.SysColourChangedEvent()
self.ProcessEvent(event)
|
wxPython : Problem updating background color of controls
|
[EDIT - Reduced and re-posted code, restated question]
I would like to change the background color of a frame (or panel; whichever makes it work).
The problem is that the background color of controls on that frame (or panel) don't have their background color updated until I click on the control (the slider control, specifically).
Any ideas on how to fix this?
Here's some demo code:
import wx
class MyFrame(wx.Frame):
def __init__(self, *args, **kwds):
kwds["style"] = wx.DEFAULT_FRAME_STYLE
wx.Frame.__init__(self, *args, **kwds)
self.panel_1 = wx.Panel(self, -1)
self.sliderDarken = wx.Slider(self.panel_1, -1, 206, 0, 255)
self.label_3 = wx.StaticText(self.panel_1, -1, "This slider should darken the main panel.\n")
self.btnPopup = wx.Button(self.panel_1, -1, "This button will pop up a dialog to dim the panel.")
self.__set_properties()
self.__do_layout()
self.Bind(wx.EVT_COMMAND_SCROLL, self.onDarken, self.sliderDarken)
self.Bind(wx.EVT_BUTTON, self.onDialogPopup, self.btnPopup)
def __set_properties(self):
self.SetTitle("Main Frame")
def __do_layout(self):
sizer_1 = wx.BoxSizer(wx.VERTICAL)
sizer_3 = wx.BoxSizer(wx.HORIZONTAL)
sizer_3.Add(self.sliderDarken, 0, 0, 0)
sizer_3.Add(self.label_3, 0, 0, 0)
sizer_3.Add(self.btnPopup, 0, 0, 0)
self.panel_1.SetSizer(sizer_3)
sizer_1.Add(self.panel_1, 1, wx.EXPAND, 0)
self.SetSizer(sizer_1)
sizer_1.Fit(self)
self.Layout()
def onDarken(self, event):
self.panel_1.SetBackgroundColour(wx.Colour(self.sliderDarken.GetValue(),self.sliderDarken.GetValue(),self.sliderDarken.GetValue()))
self.panel_1.Refresh()
def onDialogPopup(self, event):
dlgPopup=MyDialog1(None)
dlgPopup.Show()
class MyDialog1(wx.Dialog):
def __init__(self, *args, **kwds):
kwds["style"] = wx.DEFAULT_DIALOG_STYLE
wx.Dialog.__init__(self, *args, **kwds)
self.sliderDarkenPopup = wx.Slider(self, -1, 206, 0, 255, style=wx.SL_HORIZONTAL|wx.SL_AUTOTICKS|wx.SL_LABELS)
self.label_2 = wx.StaticText(self, -1, "This slider should darken the panel on the main frame.")
self.__set_properties()
self.__do_layout()
self.Bind(wx.EVT_COMMAND_SCROLL, self.onDarkenPopup, self.sliderDarkenPopup)
def __set_properties(self):
self.SetTitle("Dimmer Pop up")
def __do_layout(self):
sizer_2 = wx.BoxSizer(wx.HORIZONTAL)
sizer_2.Add(self.sliderDarkenPopup, 0, 0, 0)
sizer_2.Add(self.label_2, 0, 0, 0)
self.SetSizer(sizer_2)
sizer_2.Fit(self)
self.Layout()
def onDarkenPopup(self, event):
frame_1.panel_1.SetBackgroundColour(wx.Colour(self.sliderDarkenPopup.GetValue(),self.sliderDarkenPopup.GetValue(),self.sliderDarkenPopup.GetValue()))
frame_1.panel_1.Refresh()
if __name__ == "__main__":
app = wx.PySimpleApp(0)
wx.InitAllImageHandlers()
frame_1 = MyFrame(None, -1, "")
app.SetTopWindow(frame_1)
frame_1.Show()
app.MainLoop()
|
[
"Try putting a panel in each frame and then putting your controls on the panel. In wxPython, frames don't like to have multiple windows (especially for Windows OS), so it usually helps to have the frame own one panel and the panel to own the other controls.\nIf this doesn't solve the problem, please to to phrase your question more clearly and reduce your code to the smallest program that displays the problem, and then it will be easier for us (or at least me) to understand.\n",
"Try generating and processing a wx.SysColourChangedEvent.\n def onDarken(self, event): \n self.panel_1.SetBackgroundColour(wx.Colour(self.sliderDarken.GetValue(),self.sliderDarken.GetValue(),self.sliderDarken.GetValue()))\n event = wx.SysColourChangedEvent()\n self.ProcessEvent(event)\n\n"
] |
[
1,
1
] |
[] |
[] |
[
"python",
"wxpython"
] |
stackoverflow_0001710724_python_wxpython.txt
|
Q:
The correct case&format of variable and methods and for Python
So I know some languages have expected conventions.
PHP - underscore_case() [for the most part, lolo]
Java - camelCase()
C# - PascalCase()
etc.
What's the "Pythonic" naming convention? I know it doesn't matter in the end but just wondering if there is a "best practice" way that most modules are done in.
A:
Two words: PEP 8.
PEP 8 is the (de facto) Python style guide. Some highlights from this document (I left some stuff out on purpose; go read the original document for the ins and outs):
Package and Module Names: All-lowercase names. Underscores can be used in the module name if it improves readability.
Class Names: Almost without exception, class names use the CapWords convention.*
Global Variable Names: The conventions are about the same as those for functions.
Function Names: Function names should be lowercase, with words separated by underscores as necessary to improve readability. mixedCase is allowed only in contexts where that's already the prevailing style (e.g. threading.py), to retain backwards compatibility.
Method Names and Instance Variables: Lowercase with words separated by underscores as necessary to improve readability. Use one leading underscore only for non-public methods and instance variables.
Constants: Written in all capital letters with underscores separating words. Examples include.
A:
Read PEP 8.
It's a style guide for Python code, written by Python's creator, Guido van Rossum.
Incidentally, the answer to your question is to use underscore_case for variables and function names, and PascalCase for classes.
A:
Seven words: Google Summer of Code Python Style Guide
Note that some naming conventions differ from PEP8 and instead follow the original Google Python Style guide from which this style guide originated.
"Internal" means internal to a module or protected or private within a class.
Prepending a single underscore (_) has some support for protecting module variables and functions (not included with import * from).
Prepending a double underscore (__) to an instance variable or method effectively serves to make the variable or method private to its class (using name mangling).
Place related classes and top-level functions together in a module. Unlike Java, there is no need to limit yourself to one class per module. However, make sure the classes and top-level functions in the same module have high cohesion.
Use CapWords for class names, but lower_with_under.py for module names.
Naming examples
Packages: lower_with_under
Modules: lower_with_under, _lower_with_under
Classes: CapWords, _CapWords
Exceptions: CapWords
Functions: firstLowerCapWords(), _firstLowerCapWords()
Global/Class Constants: CAPS_WITH_UNDER, _CAPS_WITH_UNDER
Global/Class Variables: lower_with_under, _lower_with_under
Instance Variables: lower_with_under, _lower_with_under (protected) or __lower_with_under (private)
Method Names: firstLowerCapWords(), _firstLowerCapWords() (protected) or __firstLowerCapWords() (private)
Function/Method Parameters: lower_with_under
Local Variables: lower_with_under
|
The correct case&format of variable and methods and for Python
|
So I know some languages have expected conventions.
PHP - underscore_case() [for the most part, lolo]
Java - camelCase()
C# - PascalCase()
etc.
What's the "Pythonic" naming convention? I know it doesn't matter in the end but just wondering if there is a "best practice" way that most modules are done in.
|
[
"Two words: PEP 8.\nPEP 8 is the (de facto) Python style guide. Some highlights from this document (I left some stuff out on purpose; go read the original document for the ins and outs): \n\nPackage and Module Names: All-lowercase names. Underscores can be used in the module name if it improves readability.\nClass Names: Almost without exception, class names use the CapWords convention.*\nGlobal Variable Names: The conventions are about the same as those for functions.\nFunction Names: Function names should be lowercase, with words separated by underscores as necessary to improve readability. mixedCase is allowed only in contexts where that's already the prevailing style (e.g. threading.py), to retain backwards compatibility.\nMethod Names and Instance Variables: Lowercase with words separated by underscores as necessary to improve readability. Use one leading underscore only for non-public methods and instance variables.\nConstants: Written in all capital letters with underscores separating words. Examples include.\n\n",
"Read PEP 8.\nIt's a style guide for Python code, written by Python's creator, Guido van Rossum. \nIncidentally, the answer to your question is to use underscore_case for variables and function names, and PascalCase for classes.\n",
"Seven words: Google Summer of Code Python Style Guide\n\nNote that some naming conventions differ from PEP8 and instead follow the original Google Python Style guide from which this style guide originated.\n\n\"Internal\" means internal to a module or protected or private within a class.\n Prepending a single underscore (_) has some support for protecting module variables and functions (not included with import * from).\nPrepending a double underscore (__) to an instance variable or method effectively serves to make the variable or method private to its class (using name mangling).\nPlace related classes and top-level functions together in a module. Unlike Java, there is no need to limit yourself to one class per module. However, make sure the classes and top-level functions in the same module have high cohesion.\nUse CapWords for class names, but lower_with_under.py for module names.\n\nNaming examples\n\nPackages: lower_with_under\nModules: lower_with_under, _lower_with_under\nClasses: CapWords, _CapWords\nExceptions: CapWords \nFunctions: firstLowerCapWords(), _firstLowerCapWords()\nGlobal/Class Constants: CAPS_WITH_UNDER, _CAPS_WITH_UNDER\nGlobal/Class Variables: lower_with_under, _lower_with_under\nInstance Variables: lower_with_under, _lower_with_under (protected) or __lower_with_under (private)\nMethod Names: firstLowerCapWords(), _firstLowerCapWords() (protected) or __firstLowerCapWords() (private)\nFunction/Method Parameters: lower_with_under \nLocal Variables: lower_with_under\n\n\n"
] |
[
8,
5,
1
] |
[] |
[] |
[
"camelcasing",
"pascalcasing",
"python"
] |
stackoverflow_0001732234_camelcasing_pascalcasing_python.txt
|
Q:
Packaging resources with setuptools/distribute
I'm developing an Python egg that has several .txt dependencies (they're templates used to generate files by the egg itself), and I'm struggling to get those dependencies copied to site-packages during setup.py install. According to the distribute documentation...
Filesystem of my package:
setup.py
package
|--- __init__.py
|--- main.py
|--- binary (calls main.py with pkg_resources.load_entry_point)
|--- templates
|--file1.txt
|--file2.txt
In setup.py:
setup(
[...]
eager_resources = ['templates/file1.txt', 'templates/file2.txt']
)
Within my package:
from pkg_resources import resource_string
tpl = resource_string(__name__, 'templates/file1.txt')
...this combination of configuration and filesystem should result in file1.txt and file2.txt being available through pkg_resources.resource_string. Unfortunately, they're not being copied to site-packages during setup.py install. What am I missing?
Thanks!
A:
The information can be found in the setuptools documentation for including package data: https://setuptools.readthedocs.io/en/latest/setuptools.html#including-data-files
Basically, you just need to set include_package_data=True in your setup.py file. If you are using subversion or CVS, all versioned files will be included. If not, you can specify which files to include with a MANIFEST.in file.
I believe distribute supports this as well.
You can then access the files as you would without them being packaged. i.e. in main.py you could have:
import os.path
f = open(os.path.join(os.path.dirname(__file__),'templates','file1.txt'))
print f.read()
f.close()
and this would work in the packaged version as well. One caveat is that you will have to also set zip_safe = False in setup.py so that all the files are unzipped during installation.
|
Packaging resources with setuptools/distribute
|
I'm developing an Python egg that has several .txt dependencies (they're templates used to generate files by the egg itself), and I'm struggling to get those dependencies copied to site-packages during setup.py install. According to the distribute documentation...
Filesystem of my package:
setup.py
package
|--- __init__.py
|--- main.py
|--- binary (calls main.py with pkg_resources.load_entry_point)
|--- templates
|--file1.txt
|--file2.txt
In setup.py:
setup(
[...]
eager_resources = ['templates/file1.txt', 'templates/file2.txt']
)
Within my package:
from pkg_resources import resource_string
tpl = resource_string(__name__, 'templates/file1.txt')
...this combination of configuration and filesystem should result in file1.txt and file2.txt being available through pkg_resources.resource_string. Unfortunately, they're not being copied to site-packages during setup.py install. What am I missing?
Thanks!
|
[
"The information can be found in the setuptools documentation for including package data: https://setuptools.readthedocs.io/en/latest/setuptools.html#including-data-files\nBasically, you just need to set include_package_data=True in your setup.py file. If you are using subversion or CVS, all versioned files will be included. If not, you can specify which files to include with a MANIFEST.in file.\nI believe distribute supports this as well.\nYou can then access the files as you would without them being packaged. i.e. in main.py you could have:\nimport os.path\nf = open(os.path.join(os.path.dirname(__file__),'templates','file1.txt'))\nprint f.read()\nf.close()\n\nand this would work in the packaged version as well. One caveat is that you will have to also set zip_safe = False in setup.py so that all the files are unzipped during installation.\n"
] |
[
5
] |
[] |
[] |
[
"distribute",
"pypi",
"python",
"setuptools"
] |
stackoverflow_0001732619_distribute_pypi_python_setuptools.txt
|
Q:
What is a suitable buffer for Python's struct module
In Python I'm accessing a binary file by reading it into a string and then using struct.unpack(...). Now I want to write to that string using struct.pack_into(...), but I get the error "Cannot use string as modifiable buffer". What would be a suitable buffer for use with the struct module?
A:
As noted in another answer, struct_pack is probably all you need and should use. However, objects of type array support the buffer protocol and can be modified:
>>> import array, struct
>>> a = array.array('c', ' ' * 1000)
>>> c = 'a'; i = 1
>>> struct.pack_into('ci', a, -0, c, i)
>>> a
array('c', 'a\x00\x00\x00\x01\x00\x00\x00 ...
The original buffer protocol was a bit of a hack primarily for C extensions. It has been deprecated and replaced by a new C-level buffer API and memoryview objects in Python 3 (and in the upcoming 2.7).
A:
If you aren't trying to pack it into a specific object, just use struct.pack to return a string.
Otherwise, ctypes.create_string_buffer is one way to obtain a mutable buffer.
|
What is a suitable buffer for Python's struct module
|
In Python I'm accessing a binary file by reading it into a string and then using struct.unpack(...). Now I want to write to that string using struct.pack_into(...), but I get the error "Cannot use string as modifiable buffer". What would be a suitable buffer for use with the struct module?
|
[
"As noted in another answer, struct_pack is probably all you need and should use. However, objects of type array support the buffer protocol and can be modified:\n>>> import array, struct\n>>> a = array.array('c', ' ' * 1000)\n>>> c = 'a'; i = 1\n>>> struct.pack_into('ci', a, -0, c, i)\n>>> a\narray('c', 'a\\x00\\x00\\x00\\x01\\x00\\x00\\x00 ...\n\nThe original buffer protocol was a bit of a hack primarily for C extensions. It has been deprecated and replaced by a new C-level buffer API and memoryview objects in Python 3 (and in the upcoming 2.7).\n",
"If you aren't trying to pack it into a specific object, just use struct.pack to return a string.\nOtherwise, ctypes.create_string_buffer is one way to obtain a mutable buffer.\n"
] |
[
7,
6
] |
[
"Two possibilities leap immediately to mind:\n\nYou can use the Python stringio module to make a read/write buffer with file semantics.\nYou can use the Python array module to get a buffer you can treat like a list, but which will contain just binary bytes.\n\n"
] |
[
-1
] |
[
"binary",
"buffering",
"python"
] |
stackoverflow_0001732660_binary_buffering_python.txt
|
Q:
Lexical Analysis of Python Programming Language
Does anyone know where a FLEX or LEX specification file for Python exists? For example, this is a lex specification for the ANSI C programming language: http://www.quut.com/c/ANSI-C-grammar-l-1998.html
FYI, I am trying to write code highlighting into a Cocoa application. Regex won't do it because I also want grammar parsing to fold code and recognize blocks.
A:
Lex is typically just used for tokenizing, not full parsing. Projects that use flex/lex for tokenizing typically use yacc/bison for the actual parsing.
You may want to take a look at ANTLR, a more "modern" alternative to lexx & yacc.
The ANTLR Project has a Github repo containing many ANTLR 4 grammars including at least one for Python 3.
A:
grammar.txt is the official, complete Python grammar -- not directly lex compatible, but you should be able to massage it into a suitable form.
A:
Have you considered using one of the existing code highlighters, like Pygments?
|
Lexical Analysis of Python Programming Language
|
Does anyone know where a FLEX or LEX specification file for Python exists? For example, this is a lex specification for the ANSI C programming language: http://www.quut.com/c/ANSI-C-grammar-l-1998.html
FYI, I am trying to write code highlighting into a Cocoa application. Regex won't do it because I also want grammar parsing to fold code and recognize blocks.
|
[
"Lex is typically just used for tokenizing, not full parsing. Projects that use flex/lex for tokenizing typically use yacc/bison for the actual parsing.\nYou may want to take a look at ANTLR, a more \"modern\" alternative to lexx & yacc.\nThe ANTLR Project has a Github repo containing many ANTLR 4 grammars including at least one for Python 3.\n",
"grammar.txt is the official, complete Python grammar -- not directly lex compatible, but you should be able to massage it into a suitable form.\n",
"Have you considered using one of the existing code highlighters, like Pygments?\n"
] |
[
6,
3,
0
] |
[] |
[] |
[
"lex",
"lexical_analysis",
"python",
"syntax_highlighting"
] |
stackoverflow_0001732743_lex_lexical_analysis_python_syntax_highlighting.txt
|
Q:
Cannot write a script to "svn export" in Python
I would like to write a script that will tell another server to SVN export a SVN repository.
This is my python script:
import os
# svn export to crawlers
for s in ['work1.main','work2.main']:
cmd = 'ssh %s "cd /home/zes/ ; svn --force export svn+ssh://174.113.224.177/home/svn/dragon-repos"' % s
print cmd
os.system(cmd)
Very simple. It will ssh into work1.main, then cd to a correct directory. Then call SVN export command.
However, when I run this script...
$ python export_to_crawlers.py
ssh work1.main "cd /home/zes/ ; svn --force export svn+ssh://174.113.224.177/home/svn/dragon-repos"
Permission denied, please try again.
Permission denied, please try again.
Permission denied (publickey,gssapi-with-mic,password).
svn: Connection closed unexpectedly
ssh work2.main "cd /home/zes/ ; svn --force export svn+ssh://174.113.224.177/home/svn/dragon-repos"
Host key verification failed.
svn: Connection closed unexpectedly
Why do I get this error and cannot export the directory? I can manually type the commands in the command line and it will work. Why can't it work in the script?
If I change to this...it will not work. and instead, nothing will happen.
cmd = 'ssh %s "cd /home/zes/ ;"' % s
A:
This is a problem with SSH.
Permission denied, please try again.
This means that ssh can't login. Either your ssh agent doesn't have the correct key loaded, you're running the script as a different user or the environment isn't passed on correctly. Check that the variables SSH_AUTH_SOCK and SSH_AGENT_PID are passed to the subprocess of your python script.
Host key verification failed.
This error means that the remote host isn't known to ssh. This means that the host key is not found in the file $HOME/.ssh/known_hosts. Again, make sure that you're checking the home directory of the effective user of the script.
[EDIT] When you run the script, then python will become the "input" of ssh: ssh is no longer connected to a console and will ask python for the password to login. Since python has no idea what ssh wants, it ignores the request. ssh tries three times and dies.
To solve it, run these commands before you run the Python script:
eval $(ssh-agent)
ssh-add path-to-your-private-key
Replace path-to-your-private-key with the path to your private key (the one which you use to login). ssh-add will ask for your password and the ssh-agent will save it in a secure place. It will also modify your environment. So when SSH runs the next time, it will notice that an ssh agent is running and ask it first. Since the ssh-agent knows the password, ssh will login without bothering Python.
To solve the second issue, run the second ssh command manually once. ssh will then add the second host to its files and won't ask again.
[EDIT2] See this howto for a detailed explanation how to login on a remote server via ssh with your private key.
A:
I guess that it is related to ssh. Are you using a public key to automatically connect. I think that your shell knows this key but it is not the case of python.
I am not sure but it's just an idea. I hope it helps
A:
Check out the pxssh module that is part of the pyexpect project:
https://pexpect.readthedocs.org/en/latest/api/pxssh.html
It simplifies dealing with automating ssh-ing into machines.
|
Cannot write a script to "svn export" in Python
|
I would like to write a script that will tell another server to SVN export a SVN repository.
This is my python script:
import os
# svn export to crawlers
for s in ['work1.main','work2.main']:
cmd = 'ssh %s "cd /home/zes/ ; svn --force export svn+ssh://174.113.224.177/home/svn/dragon-repos"' % s
print cmd
os.system(cmd)
Very simple. It will ssh into work1.main, then cd to a correct directory. Then call SVN export command.
However, when I run this script...
$ python export_to_crawlers.py
ssh work1.main "cd /home/zes/ ; svn --force export svn+ssh://174.113.224.177/home/svn/dragon-repos"
Permission denied, please try again.
Permission denied, please try again.
Permission denied (publickey,gssapi-with-mic,password).
svn: Connection closed unexpectedly
ssh work2.main "cd /home/zes/ ; svn --force export svn+ssh://174.113.224.177/home/svn/dragon-repos"
Host key verification failed.
svn: Connection closed unexpectedly
Why do I get this error and cannot export the directory? I can manually type the commands in the command line and it will work. Why can't it work in the script?
If I change to this...it will not work. and instead, nothing will happen.
cmd = 'ssh %s "cd /home/zes/ ;"' % s
|
[
"This is a problem with SSH.\n\nPermission denied, please try again.\n\nThis means that ssh can't login. Either your ssh agent doesn't have the correct key loaded, you're running the script as a different user or the environment isn't passed on correctly. Check that the variables SSH_AUTH_SOCK and SSH_AGENT_PID are passed to the subprocess of your python script.\n\nHost key verification failed.\n\nThis error means that the remote host isn't known to ssh. This means that the host key is not found in the file $HOME/.ssh/known_hosts. Again, make sure that you're checking the home directory of the effective user of the script.\n[EDIT] When you run the script, then python will become the \"input\" of ssh: ssh is no longer connected to a console and will ask python for the password to login. Since python has no idea what ssh wants, it ignores the request. ssh tries three times and dies.\nTo solve it, run these commands before you run the Python script:\neval $(ssh-agent)\nssh-add path-to-your-private-key\n\nReplace path-to-your-private-key with the path to your private key (the one which you use to login). ssh-add will ask for your password and the ssh-agent will save it in a secure place. It will also modify your environment. So when SSH runs the next time, it will notice that an ssh agent is running and ask it first. Since the ssh-agent knows the password, ssh will login without bothering Python.\nTo solve the second issue, run the second ssh command manually once. ssh will then add the second host to its files and won't ask again.\n[EDIT2] See this howto for a detailed explanation how to login on a remote server via ssh with your private key.\n",
"I guess that it is related to ssh. Are you using a public key to automatically connect. I think that your shell knows this key but it is not the case of python.\nI am not sure but it's just an idea. I hope it helps\n",
"Check out the pxssh module that is part of the pyexpect project:\nhttps://pexpect.readthedocs.org/en/latest/api/pxssh.html\nIt simplifies dealing with automating ssh-ing into machines.\n"
] |
[
2,
0,
0
] |
[] |
[] |
[
"linux",
"python",
"svn",
"unix"
] |
stackoverflow_0001720743_linux_python_svn_unix.txt
|
Q:
UnicodeEncodeError on MySQL insert in Python
I used lxml to parse some web page as below:
>>> doc = lxml.html.fromstring(htmldata)
>>> element in doc.cssselect(sometag)[0]
>>> text = element.text_content()
>>> print text
u'Waldenstr\xf6m'
Why it prints u'Waldenstr\xf6m' but not "Waldenström" here?
After that, I tried to add this text to a MySQL table with UTF-8 character set and utf8_general_ci collatio, Users is a Django model:
>>> Users.objects.create(last_name=text)
'ascii' codec can't encode character u'\xf6' in position 9: ordinal not in range(128)
What I was doing wrong here? How can I get the the correct data "Waldenström" and write it to database?
A:
you want text.encode('utf8')
A:
>>> print text
u'Waldenstr\xf6m'
There is a difference between displaying something in the shell (which uses the repr) and printing it (which just spits out the string):
>>> u'Waldenstr\xf6m'
u'Waldenstr\xf6m'
>>> print u'Waldenstr\xf6m'
Waldenström
So, I'm not sure your snippet above is really what happened. If it definitely is, then your XHTML must contain exactly that string:
<div class="something">u'Waldenstr\xf6m'</div>
(maybe it was incorrectly generated by Python using a string's repr() instead of its str()?)
If this is right and intentional, you would need to parse that Python string literal into a simple string. One way of doing that would be:
>>> r= r"u'Waldenstr\xf6m'"
>>> print r[2:-1].decode('unicode-escape')
Waldenström
If the snippet at the top is actually not quite right and you are simply asking why Python's repr escapes all non-ASCII characters, the answer is that printing non-ASCII to the console is unreliable across various environments so the escape is safer. In the above examples you might have received ?s or worse instead of the ö if you were unlucky.
In Python 3 this changes:
>>> 'Waldenstr\xf6m'
'Waldenström'
|
UnicodeEncodeError on MySQL insert in Python
|
I used lxml to parse some web page as below:
>>> doc = lxml.html.fromstring(htmldata)
>>> element in doc.cssselect(sometag)[0]
>>> text = element.text_content()
>>> print text
u'Waldenstr\xf6m'
Why it prints u'Waldenstr\xf6m' but not "Waldenström" here?
After that, I tried to add this text to a MySQL table with UTF-8 character set and utf8_general_ci collatio, Users is a Django model:
>>> Users.objects.create(last_name=text)
'ascii' codec can't encode character u'\xf6' in position 9: ordinal not in range(128)
What I was doing wrong here? How can I get the the correct data "Waldenström" and write it to database?
|
[
"you want text.encode('utf8')\n",
">>> print text\nu'Waldenstr\\xf6m'\n\nThere is a difference between displaying something in the shell (which uses the repr) and printing it (which just spits out the string):\n>>> u'Waldenstr\\xf6m'\nu'Waldenstr\\xf6m'\n\n>>> print u'Waldenstr\\xf6m'\nWaldenström\n\nSo, I'm not sure your snippet above is really what happened. If it definitely is, then your XHTML must contain exactly that string:\n<div class=\"something\">u'Waldenstr\\xf6m'</div>\n\n(maybe it was incorrectly generated by Python using a string's repr() instead of its str()?)\nIf this is right and intentional, you would need to parse that Python string literal into a simple string. One way of doing that would be:\n>>> r= r\"u'Waldenstr\\xf6m'\"\n>>> print r[2:-1].decode('unicode-escape')\nWaldenström\n\nIf the snippet at the top is actually not quite right and you are simply asking why Python's repr escapes all non-ASCII characters, the answer is that printing non-ASCII to the console is unreliable across various environments so the escape is safer. In the above examples you might have received ?s or worse instead of the ö if you were unlucky.\nIn Python 3 this changes:\n>>> 'Waldenstr\\xf6m'\n'Waldenström'\n\n"
] |
[
2,
0
] |
[] |
[] |
[
"mysql",
"python",
"unicode"
] |
stackoverflow_0001732762_mysql_python_unicode.txt
|
Q:
python: how to send packets in multi thread and then the thread kill itself
I have a question. I'd like to send a continuous streams of byte to some host for certain amount of time (let's say 1 minute) using python.
Here is my code so far:
#! /usr/bin/env python
import socket
import thread
import time
IP = "192.168.0.2"
PADDING = "a" * 1000 #assume the MTU is slighly above 1000
DATA = PADDING + "this is sentence number = "
PORT = 14444
killed = False
test_time = 60 #60 seconds of testing
def send_data():
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.connect((IP, PORT))
count = 1
starttime = time.clock()
while elapsed < test_time:
sent = s.send(DATA + str(count) + "\n")
if sent == 0: break # assume that if nothing is sent -> connection died
count = count+1
elapsed = time.clock() - starttime
if killed:
break
s.close()
print str(count) + " has been sent"
print "to quit type quit"
thread.start_new_thread(send_data, ())
while True:
var = raw_input("Enter something: ")
if var == "quit":
killed = True
Few question, is there a better way to let a thread die after 60 seconds other than polling the time.clock every time?
When I run this program, it sends the bytes correctly but when I typed quit the other thread won't die, even though I set the var killed = True. I wonder why is that? the scope of var Killed should reach the other thread right?
Thanks
A:
I recommned using threading module. Even more benefit is to use InterruptableThread for terminating the thread. You do not have to use flag for terminating your thread but exception will occur if you call terminate() on this thread from parent. You can handle exception or not.
import threading, ctypes
class InterruptableThread(threading.Thread):
@classmethod
def _async_raise(cls, tid, excobj):
res = ctypes.pythonapi.PyThreadState_SetAsyncExc(tid, ctypes.py_object(excobj))
if res == 0:
raise ValueError("nonexistent thread id")
elif res > 1:
ctypes.pythonapi.PyThreadState_SetAsyncExc(tid, 0)
raise SystemError("PyThreadState_SetAsyncExc failed")
def raise_exc(self, excobj):
assert self.isAlive(), "thread must be started"
for tid, tobj in threading._active.items():
if tobj is self:
self._async_raise(tid, excobj)
return
def terminate(self):
self.raise_exc(SystemExit)
EDIT:
You can rewrite your code like this using another thread that is waiting 1 minute and then killing your other thread
def send_data:
IP = ...
# other vars
...
s = socket.socket(.....)
# no killed checking
# no time checking
# just do your work here
...
s.close()
my_thread = InterruptableThread(target=send_data)
my_thread.start()
def one_minute_kill(who):
time.sleep(60)
who.terminate()
killer_thread = InterruptableThread(target=one_minute_kill, args=[my_thread])
killer.start()
print "to quit type quit"
while my_thread.isAlive():
if raw_input("Enter something: ") == "quit":
my_thread.terminate()
A:
I don't know how to do this with the "thread" module, but I can do it with the "threading" module. I think this code accomplishes what you want.
For documentation on the threading module:
http://docs.python.org/library/threading.html
#!/usr/bin/python
import time
from threading import Thread
import threading
import sys
test_time = 10
killed = False
class SillyThread( threading.Thread ):
def run(self):
global killed
starttime = time.time()
counter = 0
while (time.time() - starttime) < test_time:
if killed:
break
counter = counter + 1
time.sleep(0.1)
print "I did %d loops" % counter
class ManageThread( threading.Thread ):
def run(self):
global killed
while True:
var = raw_input("Enter something: ")
if var == "quit":
killed = True
break
print "Got var [%s]" % var
silly = SillyThread()
silly.start()
ManageThread().start()
Thread.join(silly)
print "bye bye"
sys.exit(0)
Note that I use time.time() instead of time.clock(). time.clock() gives elapsed processor time on Unix (see http://docs.python.org/library/time.html). I think time.clock() should work everywhere. I set my test_time to 10 seconds because I don't have the patience for a minute.
Here's what happens if I let it run the full 10 seconds:
leif@peacock:~/tmp$ ./test.py
Enter something: I did 100 loops
bye bye
Here's what happens if I type 'quit':
leif@peacock:~/tmp$ ./test.py
Enter something: quit
Got var [quit]
I did 10 loops
bye bye
Hope this helps.
A:
As mentioned above, use the threading module, it is much easier to use and provides several synchronization primitives. It also provides a Timer class that runs after a specified amount of time.
If you just want the program to exit, you can simply make the sending thread a daemon. You do this by calling setDaemon(True) before calling start() (2.6 might use a daemon attribute instead). Python won't exit so long as a non-daemon thread is running.
A:
You can do this pretty easily without threads. For example, using Twisted, you just set up a timed call and a producer:
from twisted.internet.protocol import ClientFactory, Protocol
from twisted.internet import reactor
class Noisy(Protocol):
def __init__(self, delay, data):
self.delay = delay
self.data = data
def stop(self):
self.transport.unregisterProducer()
self.transport.loseConnection()
reactor.stop()
def resumeProducing(self):
self.transport.write(self.data)
def connectionMade(self):
self.transport.registerProducer(self, False)
reactor.callLater(self.delay, self.stop)
factory = ClientFactory()
factory.protocol = lambda: Noisy(60, "hello server")
reactor.connectTCP(host, port, factory)
reactor.run()
This has various advantages over the threaded approach. It doesn't rely on daemon threads, so you can actually clean up the network connection (eg, to send a close message if necessary) rather than relying on the platform to destroy it. It handles all the actual low level networking code for you (your original example is doing the wrong thing in the case of socket.send returning 0; this code will handle that case properly). You also don't have to rely on ctypes or the obscure CPython API for raising an exception in another thread (so it's portable to more versions of Python and can actually interrupt a blocked send immediately, unlike some of the other suggested approaches).
A:
Ensure that the "quit" is working correctly and add a small print to test that the input is working.
if var == "quit":
print "Hey we got quit"
A:
The variable elapsed is not initialized. Set it to zero above the while loop.
A:
It's easy to test the scope of killed:
>>> import thread
>>> killed = False
>>> import time
>>> def test():
... while True:
... time.sleep(1)
... if killed:
... print 'Dead.'
... break
...
>>> thread.start_new_thread(test, ())
25479680
>>> time.sleep(3)
>>> killed = True
>>> Dead.
|
python: how to send packets in multi thread and then the thread kill itself
|
I have a question. I'd like to send a continuous streams of byte to some host for certain amount of time (let's say 1 minute) using python.
Here is my code so far:
#! /usr/bin/env python
import socket
import thread
import time
IP = "192.168.0.2"
PADDING = "a" * 1000 #assume the MTU is slighly above 1000
DATA = PADDING + "this is sentence number = "
PORT = 14444
killed = False
test_time = 60 #60 seconds of testing
def send_data():
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.connect((IP, PORT))
count = 1
starttime = time.clock()
while elapsed < test_time:
sent = s.send(DATA + str(count) + "\n")
if sent == 0: break # assume that if nothing is sent -> connection died
count = count+1
elapsed = time.clock() - starttime
if killed:
break
s.close()
print str(count) + " has been sent"
print "to quit type quit"
thread.start_new_thread(send_data, ())
while True:
var = raw_input("Enter something: ")
if var == "quit":
killed = True
Few question, is there a better way to let a thread die after 60 seconds other than polling the time.clock every time?
When I run this program, it sends the bytes correctly but when I typed quit the other thread won't die, even though I set the var killed = True. I wonder why is that? the scope of var Killed should reach the other thread right?
Thanks
|
[
"I recommned using threading module. Even more benefit is to use InterruptableThread for terminating the thread. You do not have to use flag for terminating your thread but exception will occur if you call terminate() on this thread from parent. You can handle exception or not.\nimport threading, ctypes\n\nclass InterruptableThread(threading.Thread):\n@classmethod\ndef _async_raise(cls, tid, excobj):\n res = ctypes.pythonapi.PyThreadState_SetAsyncExc(tid, ctypes.py_object(excobj))\n if res == 0:\n raise ValueError(\"nonexistent thread id\")\n elif res > 1:\n ctypes.pythonapi.PyThreadState_SetAsyncExc(tid, 0)\n raise SystemError(\"PyThreadState_SetAsyncExc failed\")\n\ndef raise_exc(self, excobj):\n assert self.isAlive(), \"thread must be started\"\n for tid, tobj in threading._active.items():\n if tobj is self:\n self._async_raise(tid, excobj)\n return\n\ndef terminate(self):\n self.raise_exc(SystemExit)\n\nEDIT:\nYou can rewrite your code like this using another thread that is waiting 1 minute and then killing your other thread\ndef send_data:\n IP = ...\n # other vars\n\n ...\n s = socket.socket(.....)\n\n # no killed checking\n # no time checking\n # just do your work here\n ...\n s.close()\n\n\nmy_thread = InterruptableThread(target=send_data)\nmy_thread.start()\n\ndef one_minute_kill(who):\n time.sleep(60)\n who.terminate()\n\nkiller_thread = InterruptableThread(target=one_minute_kill, args=[my_thread])\nkiller.start()\n\nprint \"to quit type quit\"\nwhile my_thread.isAlive():\n if raw_input(\"Enter something: \") == \"quit\":\n my_thread.terminate()\n\n",
"I don't know how to do this with the \"thread\" module, but I can do it with the \"threading\" module. I think this code accomplishes what you want.\nFor documentation on the threading module:\nhttp://docs.python.org/library/threading.html\n#!/usr/bin/python\n\nimport time\nfrom threading import Thread\nimport threading\nimport sys\n\ntest_time = 10\nkilled = False\n\nclass SillyThread( threading.Thread ):\n def run(self):\n global killed\n starttime = time.time()\n counter = 0\n while (time.time() - starttime) < test_time:\n if killed:\n break\n counter = counter + 1\n time.sleep(0.1)\n print \"I did %d loops\" % counter\n\nclass ManageThread( threading.Thread ):\n def run(self):\n global killed\n while True:\n var = raw_input(\"Enter something: \")\n if var == \"quit\":\n killed = True\n break\n print \"Got var [%s]\" % var\n\nsilly = SillyThread()\nsilly.start()\nManageThread().start()\nThread.join(silly)\nprint \"bye bye\"\nsys.exit(0)\n\nNote that I use time.time() instead of time.clock(). time.clock() gives elapsed processor time on Unix (see http://docs.python.org/library/time.html). I think time.clock() should work everywhere. I set my test_time to 10 seconds because I don't have the patience for a minute.\nHere's what happens if I let it run the full 10 seconds:\nleif@peacock:~/tmp$ ./test.py\nEnter something: I did 100 loops\nbye bye\n\nHere's what happens if I type 'quit':\nleif@peacock:~/tmp$ ./test.py\nEnter something: quit\nGot var [quit]\nI did 10 loops\nbye bye\n\nHope this helps.\n",
"As mentioned above, use the threading module, it is much easier to use and provides several synchronization primitives. It also provides a Timer class that runs after a specified amount of time.\nIf you just want the program to exit, you can simply make the sending thread a daemon. You do this by calling setDaemon(True) before calling start() (2.6 might use a daemon attribute instead). Python won't exit so long as a non-daemon thread is running.\n",
"You can do this pretty easily without threads. For example, using Twisted, you just set up a timed call and a producer:\nfrom twisted.internet.protocol import ClientFactory, Protocol\nfrom twisted.internet import reactor\n\nclass Noisy(Protocol):\n def __init__(self, delay, data):\n self.delay = delay\n self.data = data\n\n def stop(self):\n self.transport.unregisterProducer()\n self.transport.loseConnection()\n reactor.stop()\n\n def resumeProducing(self):\n self.transport.write(self.data)\n\n def connectionMade(self):\n self.transport.registerProducer(self, False)\n reactor.callLater(self.delay, self.stop)\n\nfactory = ClientFactory()\nfactory.protocol = lambda: Noisy(60, \"hello server\")\nreactor.connectTCP(host, port, factory)\nreactor.run()\n\nThis has various advantages over the threaded approach. It doesn't rely on daemon threads, so you can actually clean up the network connection (eg, to send a close message if necessary) rather than relying on the platform to destroy it. It handles all the actual low level networking code for you (your original example is doing the wrong thing in the case of socket.send returning 0; this code will handle that case properly). You also don't have to rely on ctypes or the obscure CPython API for raising an exception in another thread (so it's portable to more versions of Python and can actually interrupt a blocked send immediately, unlike some of the other suggested approaches).\n",
"Ensure that the \"quit\" is working correctly and add a small print to test that the input is working.\nif var == \"quit\":\n print \"Hey we got quit\"\n\n",
"The variable elapsed is not initialized. Set it to zero above the while loop.\n",
"It's easy to test the scope of killed:\n>>> import thread\n>>> killed = False\n>>> import time\n>>> def test():\n... while True:\n... time.sleep(1)\n... if killed:\n... print 'Dead.'\n... break\n... \n>>> thread.start_new_thread(test, ())\n25479680\n>>> time.sleep(3)\n>>> killed = True\n>>> Dead.\n\n"
] |
[
5,
2,
1,
1,
0,
0,
0
] |
[] |
[] |
[
"multithreading",
"packet",
"python",
"sockets",
"timer"
] |
stackoverflow_0000605013_multithreading_packet_python_sockets_timer.txt
|
Q:
Python: next() function
I'm learning Python from a book, and I came across this example:
M = [[1,2,3],
[4,5,6],
[7,8,9]]
G = (sum(row) for row in M) # create a generator of row sums
next(G) # Run the iteration protocol
Since I'm an absolute beginner, and the author hasn't provided any explanation of the example or the next() function, I don't understand what the code is doing.
A:
The expression (sum(row) for row in M) creates what's called a generator. This generator will evaluate the expression (sum(row)) once for each row in M. However, the generator doesn't do anything yet, we've just set it up.
The statement next(G) actually runs the generator on M. So, if you run next(G) once, you'll get the sum of the first row. If you run it again, you'll get the sum of the second row, and so on.
>>> M = [[1,2,3],
... [4,5,6],
... [7,8,9]]
>>>
>>> G = (sum(row) for row in M) # create a generator of row sums
>>> next(G) # Run the iteration protocol
6
>>> next(G)
15
>>> next(G)
24
See also:
Documentation on generators
Documentation on yield expressions (with some info about generators)
A:
If you've come that far, then you should already know how a common for-in statement works.
The following statement:
for row in M: print row
would see M as a sequence of 3 rows (sub sequences) consisting of 3 items each, and iterate through M, outputting each row on the matrix:
[1, 2, 3]
[4, 5, 6]
[7, 8, 9]
You knew that, well...
You can see Generators just as some syntactic sugar around for-in loops.
Forget about the sum() call, and type something like this on IDLE:
G = (row for row in M)
print G
for a in G: print a
You see, the Generator cannot be directly represented as text, not just as a sequence can be.
But, you can iterate through a Generator as if it were a sequence.
You'll find some big differences then, but the basics are that you can use a generator not to return just the value of each item in the sequence, but the result of any expression. In the tutorial's example, the expression is sum(row).
Try the following and see what happens:
G = ("("+str(row[2])+";"+str(row[1])+";"+str(row[0])+")" for row in M)
G.next()
G.next()
G.next()
|
Python: next() function
|
I'm learning Python from a book, and I came across this example:
M = [[1,2,3],
[4,5,6],
[7,8,9]]
G = (sum(row) for row in M) # create a generator of row sums
next(G) # Run the iteration protocol
Since I'm an absolute beginner, and the author hasn't provided any explanation of the example or the next() function, I don't understand what the code is doing.
|
[
"The expression (sum(row) for row in M) creates what's called a generator. This generator will evaluate the expression (sum(row)) once for each row in M. However, the generator doesn't do anything yet, we've just set it up.\nThe statement next(G) actually runs the generator on M. So, if you run next(G) once, you'll get the sum of the first row. If you run it again, you'll get the sum of the second row, and so on.\n>>> M = [[1,2,3],\n... [4,5,6],\n... [7,8,9]]\n>>> \n>>> G = (sum(row) for row in M) # create a generator of row sums\n>>> next(G) # Run the iteration protocol\n6\n>>> next(G)\n15\n>>> next(G)\n24\n\nSee also:\n\nDocumentation on generators\nDocumentation on yield expressions (with some info about generators)\n\n",
"If you've come that far, then you should already know how a common for-in statement works.\nThe following statement:\nfor row in M: print row\n\nwould see M as a sequence of 3 rows (sub sequences) consisting of 3 items each, and iterate through M, outputting each row on the matrix:\n[1, 2, 3]\n[4, 5, 6]\n[7, 8, 9]\n\nYou knew that, well...\nYou can see Generators just as some syntactic sugar around for-in loops.\nForget about the sum() call, and type something like this on IDLE:\nG = (row for row in M)\nprint G\nfor a in G: print a\n\nYou see, the Generator cannot be directly represented as text, not just as a sequence can be.\nBut, you can iterate through a Generator as if it were a sequence.\nYou'll find some big differences then, but the basics are that you can use a generator not to return just the value of each item in the sequence, but the result of any expression. In the tutorial's example, the expression is sum(row).\nTry the following and see what happens:\nG = (\"(\"+str(row[2])+\";\"+str(row[1])+\";\"+str(row[0])+\")\" for row in M)\nG.next()\nG.next()\nG.next()\n\n"
] |
[
78,
10
] |
[] |
[] |
[
"next",
"python",
"sum"
] |
stackoverflow_0001733004_next_python_sum.txt
|
Q:
Optimal datafile format loading on a game console
I need to load large models and other structured binary data on an older CD-based game console as efficiently as possible. What's the best way to do it? The data will be exported from a Python application. This is a pretty elaborate hobby project.
Requierements:
no reliance on fully standard compliant STL - i might use uSTL though.
as little overhead as possible. Aim for a solution so good. that it could be used on the original Playstation, and yet as modern and elegant as possible.
no backward/forward compatibility necessary.
no copying of large chunks around - preferably files get loaded into RAM in background, and all large chunks accessed directly from there later.
should not rely on the target having the same endianness and alignment, i.e. a C plugin in Python which dumps its structs to disc would not be a very good idea.
should allow to move the loaded data around, as with individual files 1/3 the RAM size, fragmentation might be an issue. No MMU to abuse.
robustness is a great bonus, as my attention span is very short, i.e. i'd change saving part of the code and forget the loading one or vice versa, so at least a dumb safeguard would be nice.
exchangeability between loaded data and runtime-generated data without runtime overhead and without severe memory management issues would be a nice bonus.
I kind of have a semi-plan of parsing in Python trivial, limited-syntax C headers which would use structs with offsets instead of pointers, and convenience wrapper structs/classes in the main app with getters which would convert offsets to properly typed pointers/references, but i'd like to hear your suggestions.
Clarification: the request is primarily about data loading framework and memory management issues.
A:
On platforms like the Nintendo GameCube and DS, 3D models are usually stored in a very simple custom format:
A brief header, containing a magic number identifying the file, the number of vertices, normals, etc., and optionally a checksum of the data following the header (Adler-32, CRC-16, etc).
A possibly compressed list of 32-bit floating-point 3-tuples for each vector and normal.
A possibly compressed list of edges or faces.
All of the data is in the native endian format of the target platform.
The compression format is often trivial (Huffman), simple (Arithmetic), or standard (gzip). All of these require very little memory or computational power.
You could take formats like that as a cue: it's quite a compact representation.
My suggestion is to use a format most similar to your in-memory data structures, to minimize post-processing and copying. If that means you create the format yourself, so be it. You have extreme needs, so extreme measures are needed.
A:
I note that nowhere in your description do you ask for "ease of programming". :-)
Thus, here's what comes to mind for me as a way of creating this:
The data should be in the same on-disk format as it would be in the target's memory, such that it can simply pull blobs from disk into memory with no reformatting it. Depending on how much freedom you want in putting things into memory, the "blobs" could be the whole file, or could be smaller bits within it; I don't understand your data well enough to suggest how to subdivide it but presumably you can. Because we can't rely on the same endianness and alignment on the host, you'll need to be somewhat clever about translating things when writing the files on the host-side, but at least this way you only need the cleverness on one side of the transfer rather than on both.
In order to provide a bit of assurance that the target-side and host-side code matches, you should write this in a form where you provide a single data description and have some generation code that will generate both the target-side C code and the host-side Python code from it. You could even have your generator generate a small random "version" number in the process, and have the host-side code write this into the file header and the target-side check it, and give you an error if they don't match. (The point of using a random value is that the only information bit you care about is whether they match, and you don't want to have to increment it manually.)
A:
This is a common game development pattern.
The usual approach is to cook the data in an offline pre-process step. The resulting blobs can be streamed in with minimal overhead. The blobs are platform dependent and should contain the proper alignment & endian-ness of the target platform.
At runtime, you can simply cast a pointer to the in-memory blob file. You can deal with nested structures as well. If you keep a table of contents with offsets to all the pointer values within the blob, you can then fix-up the pointers to point to the proper address. This is similar to how dll loading works.
I've been working on a ruby library, bbq, that I use to cook data for my iphone game.
Here's the memory layout I use for the blob header:
// Memory layout
//
// p begining of file in memory.
// p + 0 : num_pointers
// p + 4 : offset 0
// p + 8 : offset 1
// ...
// p + ((num_pointers - 1) * 4) : offset n-1
// p + (num_pointers * 4) : num_pointers // again so we can figure out
// what memory to free.
// p + ((num_pointers + 1) * 4) : start of cooked data
//
Here's how I load binary blob file and fix up pointers:
void* bbq_load(const char* filename)
{
unsigned char* p;
int size = LoadFileToMemory(filename, &p);
if(size <= 0)
return 0;
// get the start of the pointer table
unsigned int* ptr_table = (unsigned int*)p;
unsigned int num_ptrs = *ptr_table;
ptr_table++;
// get the start of the actual data
// the 2 is to skip past both num_pointer values
unsigned char* base = p + ((num_ptrs + 2) * sizeof(unsigned int));
// fix up the pointers
while ((ptr_table + 1) < (unsigned int*)base)
{
unsigned int* ptr = (unsigned int*)(base + *ptr_table);
*ptr = (unsigned int)((unsigned char*)ptr + *ptr);
ptr_table++;
}
return base;
}
My bbq library isn't quite ready for prime time, but it could give you some ideas on how to write one yourself in python.
Good Luck!
A:
Consider storing your data as BLOBs in a SQLite DB. SQLite is extremely portable and lighweight, ANSI C, has both C++ and Python interfaces. This will take care of large files, no fragmentation, variable-length records with fast access, and so on. The rest is just serialization of structs to these BLOBs.
|
Optimal datafile format loading on a game console
|
I need to load large models and other structured binary data on an older CD-based game console as efficiently as possible. What's the best way to do it? The data will be exported from a Python application. This is a pretty elaborate hobby project.
Requierements:
no reliance on fully standard compliant STL - i might use uSTL though.
as little overhead as possible. Aim for a solution so good. that it could be used on the original Playstation, and yet as modern and elegant as possible.
no backward/forward compatibility necessary.
no copying of large chunks around - preferably files get loaded into RAM in background, and all large chunks accessed directly from there later.
should not rely on the target having the same endianness and alignment, i.e. a C plugin in Python which dumps its structs to disc would not be a very good idea.
should allow to move the loaded data around, as with individual files 1/3 the RAM size, fragmentation might be an issue. No MMU to abuse.
robustness is a great bonus, as my attention span is very short, i.e. i'd change saving part of the code and forget the loading one or vice versa, so at least a dumb safeguard would be nice.
exchangeability between loaded data and runtime-generated data without runtime overhead and without severe memory management issues would be a nice bonus.
I kind of have a semi-plan of parsing in Python trivial, limited-syntax C headers which would use structs with offsets instead of pointers, and convenience wrapper structs/classes in the main app with getters which would convert offsets to properly typed pointers/references, but i'd like to hear your suggestions.
Clarification: the request is primarily about data loading framework and memory management issues.
|
[
"On platforms like the Nintendo GameCube and DS, 3D models are usually stored in a very simple custom format:\n\nA brief header, containing a magic number identifying the file, the number of vertices, normals, etc., and optionally a checksum of the data following the header (Adler-32, CRC-16, etc).\nA possibly compressed list of 32-bit floating-point 3-tuples for each vector and normal.\nA possibly compressed list of edges or faces.\nAll of the data is in the native endian format of the target platform.\nThe compression format is often trivial (Huffman), simple (Arithmetic), or standard (gzip). All of these require very little memory or computational power.\n\nYou could take formats like that as a cue: it's quite a compact representation.\nMy suggestion is to use a format most similar to your in-memory data structures, to minimize post-processing and copying. If that means you create the format yourself, so be it. You have extreme needs, so extreme measures are needed.\n",
"I note that nowhere in your description do you ask for \"ease of programming\". :-)\nThus, here's what comes to mind for me as a way of creating this:\n\nThe data should be in the same on-disk format as it would be in the target's memory, such that it can simply pull blobs from disk into memory with no reformatting it. Depending on how much freedom you want in putting things into memory, the \"blobs\" could be the whole file, or could be smaller bits within it; I don't understand your data well enough to suggest how to subdivide it but presumably you can. Because we can't rely on the same endianness and alignment on the host, you'll need to be somewhat clever about translating things when writing the files on the host-side, but at least this way you only need the cleverness on one side of the transfer rather than on both.\nIn order to provide a bit of assurance that the target-side and host-side code matches, you should write this in a form where you provide a single data description and have some generation code that will generate both the target-side C code and the host-side Python code from it. You could even have your generator generate a small random \"version\" number in the process, and have the host-side code write this into the file header and the target-side check it, and give you an error if they don't match. (The point of using a random value is that the only information bit you care about is whether they match, and you don't want to have to increment it manually.)\n\n",
"This is a common game development pattern.\nThe usual approach is to cook the data in an offline pre-process step. The resulting blobs can be streamed in with minimal overhead. The blobs are platform dependent and should contain the proper alignment & endian-ness of the target platform.\nAt runtime, you can simply cast a pointer to the in-memory blob file. You can deal with nested structures as well. If you keep a table of contents with offsets to all the pointer values within the blob, you can then fix-up the pointers to point to the proper address. This is similar to how dll loading works.\nI've been working on a ruby library, bbq, that I use to cook data for my iphone game. \nHere's the memory layout I use for the blob header:\n// Memory layout\n//\n// p begining of file in memory.\n// p + 0 : num_pointers\n// p + 4 : offset 0\n// p + 8 : offset 1\n// ...\n// p + ((num_pointers - 1) * 4) : offset n-1\n// p + (num_pointers * 4) : num_pointers // again so we can figure out \n// what memory to free.\n// p + ((num_pointers + 1) * 4) : start of cooked data\n//\n\nHere's how I load binary blob file and fix up pointers:\nvoid* bbq_load(const char* filename)\n{\n unsigned char* p;\n int size = LoadFileToMemory(filename, &p);\n if(size <= 0)\n return 0;\n\n // get the start of the pointer table\n unsigned int* ptr_table = (unsigned int*)p;\n unsigned int num_ptrs = *ptr_table;\n ptr_table++;\n\n // get the start of the actual data\n // the 2 is to skip past both num_pointer values\n unsigned char* base = p + ((num_ptrs + 2) * sizeof(unsigned int));\n\n // fix up the pointers\n while ((ptr_table + 1) < (unsigned int*)base)\n {\n unsigned int* ptr = (unsigned int*)(base + *ptr_table);\n *ptr = (unsigned int)((unsigned char*)ptr + *ptr);\n ptr_table++;\n }\n\n return base;\n}\n\nMy bbq library isn't quite ready for prime time, but it could give you some ideas on how to write one yourself in python.\nGood Luck!\n",
"Consider storing your data as BLOBs in a SQLite DB. SQLite is extremely portable and lighweight, ANSI C, has both C++ and Python interfaces. This will take care of large files, no fragmentation, variable-length records with fast access, and so on. The rest is just serialization of structs to these BLOBs.\n"
] |
[
4,
3,
3,
0
] |
[] |
[] |
[
"c++",
"embedded",
"playstation",
"python"
] |
stackoverflow_0001727594_c++_embedded_playstation_python.txt
|
Q:
`from QTKit import *` causes a 'FAILED TO establish the default connection to the WindowServer' in PyObjC application
I've been trying out PyObjC and I can't seem to get the QTKit imports to work. If I import QTKit like so: from QTKit import * I get a flood of errors:
[Session started at 2009-11-13 21:03:49 -0600.]
_RegisterApplication(), FAILED TO establish the default connection to the WindowServer, _CGSDefaultConnection() is NULL.
2009-11-13 21:03:50.671 WhyDoesntThisWork[16550:10b] *** -[NSRecursiveLock unlock]: lock (<NSRecursiveLock: 0x1c55c00> '(null)') unlocked when not locked
2009-11-13 21:03:50.673 WhyDoesntThisWork[16550:10b] *** Break on _NSLockError() to debug.
2009-11-13 21:03:50.673 WhyDoesntThisWork[16550:10b] *** -[NSRecursiveLock unlock]: lock (<NSRecursiveLock: 0x1c55c00> '(null)') unlocked when not locked
2009-11-13 21:03:50.674 WhyDoesntThisWork[16550:10b] *** Break on _NSLockError() to debug.
2009-11-13 21:03:50.681 WhyDoesntThisWork[16550:10b] *** -[NSRecursiveLock unlock]: lock (<NSRecursiveLock: 0x1c55c00> '(null)') unlocked when not locked
2009-11-13 21:03:50.682 WhyDoesntThisWork[16550:10b] *** Break on _NSLockError() to debug.
2009-11-13 21:03:50.692 WhyDoesntThisWork[16550:10b] NSInternalInconsistencyException - Error (1002) creating CGSWindow
2009-11-13 21:03:50.704 WhyDoesntThisWork[16550:10b] *** -[NSRecursiveLock unlock]: lock (<NSRecursiveLock: 0x1c55c00> '(null)') unlocked when not locked
2009-11-13 21:03:50.705 WhyDoesntThisWork[16550:10b] *** Break on _NSLockError() to debug.
2009-11-13 21:03:50.712 WhyDoesntThisWork[16550:10b] *** -[NSRecursiveLock unlock]: lock (<NSRecursiveLock: 0x1c55c00> '(null)') unlocked when not locked
2009-11-13 21:03:50.713 WhyDoesntThisWork[16550:10b] *** Break on _NSLockError() to debug.
2009-11-13 21:03:50.721 WhyDoesntThisWork[16550:10b] *** -[NSRecursiveLock unlock]: lock (<NSRecursiveLock: 0x1c55c00> '(null)') unlocked when not locked
2009-11-13 21:03:50.721 WhyDoesntThisWork[16550:10b] *** Break on _NSLockError() to debug.
2009-11-13 21:03:50.722 WhyDoesntThisWork[16550:10b] *** -[NSRecursiveLock unlock]: lock (<NSRecursiveLock: 0x1c55c00> '(null)') unlocked when not locked
2009-11-13 21:03:50.723 WhyDoesntThisWork[16550:10b] *** Break on _NSLockError() to debug.
This happens even with no other code added to the application. For example: I can create a new cocoa/python project, add the Quicktime framework, open the generated delegate and add the line from QTKit import * , build and run and the errors flow. Is there a step I'm missing?
A:
Take a look at this tutorial. Apparently QTKit cannot be imported until after the runloop has been established.
|
`from QTKit import *` causes a 'FAILED TO establish the default connection to the WindowServer' in PyObjC application
|
I've been trying out PyObjC and I can't seem to get the QTKit imports to work. If I import QTKit like so: from QTKit import * I get a flood of errors:
[Session started at 2009-11-13 21:03:49 -0600.]
_RegisterApplication(), FAILED TO establish the default connection to the WindowServer, _CGSDefaultConnection() is NULL.
2009-11-13 21:03:50.671 WhyDoesntThisWork[16550:10b] *** -[NSRecursiveLock unlock]: lock (<NSRecursiveLock: 0x1c55c00> '(null)') unlocked when not locked
2009-11-13 21:03:50.673 WhyDoesntThisWork[16550:10b] *** Break on _NSLockError() to debug.
2009-11-13 21:03:50.673 WhyDoesntThisWork[16550:10b] *** -[NSRecursiveLock unlock]: lock (<NSRecursiveLock: 0x1c55c00> '(null)') unlocked when not locked
2009-11-13 21:03:50.674 WhyDoesntThisWork[16550:10b] *** Break on _NSLockError() to debug.
2009-11-13 21:03:50.681 WhyDoesntThisWork[16550:10b] *** -[NSRecursiveLock unlock]: lock (<NSRecursiveLock: 0x1c55c00> '(null)') unlocked when not locked
2009-11-13 21:03:50.682 WhyDoesntThisWork[16550:10b] *** Break on _NSLockError() to debug.
2009-11-13 21:03:50.692 WhyDoesntThisWork[16550:10b] NSInternalInconsistencyException - Error (1002) creating CGSWindow
2009-11-13 21:03:50.704 WhyDoesntThisWork[16550:10b] *** -[NSRecursiveLock unlock]: lock (<NSRecursiveLock: 0x1c55c00> '(null)') unlocked when not locked
2009-11-13 21:03:50.705 WhyDoesntThisWork[16550:10b] *** Break on _NSLockError() to debug.
2009-11-13 21:03:50.712 WhyDoesntThisWork[16550:10b] *** -[NSRecursiveLock unlock]: lock (<NSRecursiveLock: 0x1c55c00> '(null)') unlocked when not locked
2009-11-13 21:03:50.713 WhyDoesntThisWork[16550:10b] *** Break on _NSLockError() to debug.
2009-11-13 21:03:50.721 WhyDoesntThisWork[16550:10b] *** -[NSRecursiveLock unlock]: lock (<NSRecursiveLock: 0x1c55c00> '(null)') unlocked when not locked
2009-11-13 21:03:50.721 WhyDoesntThisWork[16550:10b] *** Break on _NSLockError() to debug.
2009-11-13 21:03:50.722 WhyDoesntThisWork[16550:10b] *** -[NSRecursiveLock unlock]: lock (<NSRecursiveLock: 0x1c55c00> '(null)') unlocked when not locked
2009-11-13 21:03:50.723 WhyDoesntThisWork[16550:10b] *** Break on _NSLockError() to debug.
This happens even with no other code added to the application. For example: I can create a new cocoa/python project, add the Quicktime framework, open the generated delegate and add the line from QTKit import * , build and run and the errors flow. Is there a step I'm missing?
|
[
"Take a look at this tutorial. Apparently QTKit cannot be imported until after the runloop has been established.\n"
] |
[
1
] |
[] |
[] |
[
"objective_c",
"pyobjc",
"python"
] |
stackoverflow_0001733098_objective_c_pyobjc_python.txt
|
Q:
wxPython: Update wx.ListBox list
I have a wx.ListBox in a python program, and I wan't to change out the list in it on a wx.Timer update. I have the timer working, I just don't know how to change out the list that it displays.
A:
Here's an example for modifying a ListBox.
Generally, it uses the Append and Clear methods of ListBox. You can call those in your timer handler.
Since ListBox derives from ItemContainer, see more item modification methods here.
|
wxPython: Update wx.ListBox list
|
I have a wx.ListBox in a python program, and I wan't to change out the list in it on a wx.Timer update. I have the timer working, I just don't know how to change out the list that it displays.
|
[
"Here's an example for modifying a ListBox.\nGenerally, it uses the Append and Clear methods of ListBox. You can call those in your timer handler.\nSince ListBox derives from ItemContainer, see more item modification methods here.\n"
] |
[
9
] |
[] |
[] |
[
"python",
"wxpython"
] |
stackoverflow_0001733461_python_wxpython.txt
|
Q:
pymedia.audio.sound - How do I get up and running with this module?
Im trying to get my hands on this pymedia.audio.sound module and have attempted to get it several times from python.org, but I think I am doing something wrong like.
Any help greatly appreciated.
Im running Windows XP, Python 2.5 and its running fine, but how do I download and where do I extract the new module to be able to use it?
Apologies for my apparent lack of intelligence.
Cheers
When I execute the file "setup.py" I get the following output:
Using WINDOWS configuration...
Path for OGG not found.
Path for VORBIS not found.
Path for FAAD not found.
Path for MP3LAME not found.
Path for VORBISENC not found.
Path for ALSA not found.
Continue building pymedia ? [Y,n]:
A:
The homepage for pymedia.
Download from here.
Extract the compressed tar file. Then run python setup.py install from the extracted directory.
|
pymedia.audio.sound - How do I get up and running with this module?
|
Im trying to get my hands on this pymedia.audio.sound module and have attempted to get it several times from python.org, but I think I am doing something wrong like.
Any help greatly appreciated.
Im running Windows XP, Python 2.5 and its running fine, but how do I download and where do I extract the new module to be able to use it?
Apologies for my apparent lack of intelligence.
Cheers
When I execute the file "setup.py" I get the following output:
Using WINDOWS configuration...
Path for OGG not found.
Path for VORBIS not found.
Path for FAAD not found.
Path for MP3LAME not found.
Path for VORBISENC not found.
Path for ALSA not found.
Continue building pymedia ? [Y,n]:
|
[
"The homepage for pymedia.\nDownload from here.\nExtract the compressed tar file. Then run python setup.py install from the extracted directory.\n"
] |
[
0
] |
[] |
[] |
[
"python"
] |
stackoverflow_0001733052_python.txt
|
Q:
Making BeautifulSoup ignore contents inside script tags
I have been trying to get BeautifulSoup (3.1.0.1)to parse a html page that has a lot of javascript that generates html inside tags.
One example fragment looks like this :
<html><head><body><div>
<script type='text/javascript'>
if(ii > 0) {
html += '<span id="hoverMenuPosSepId" class="hoverMenuPosSep">|</span>'
}
html +=
'<div class="hoverMenuPos" id="hoverMenuPosId" onMouseOver=\"menuOver_3821();\" ' +
'onMouseOut=\"menuOut_3821();\">';
if (children[ii].uri == location.pathname) {
html += '<a class="hiHover" href="' + children[ii].uri + '" ' + onClick + '>';
} else {
html += '<a class="hover" href="' + children[ii].uri + '" ' + onClick + '>';
}
html += children[ii].name + '</a></div>';
}
}
hp = document.getElementById("hoverpopup_3821");
hp.style.top = (parseInt(hoveritem.offsetTop) + parseInt(hoveritem.offsetHeight)) + "px";
hp.style.visibility = "Visible";
hp.innerHTML = html;
}
return false;
}
function menuOut_3821() {
timeOn_3821 = setTimeout("showSelected_3821()", 1000)
}
var timeOn_3821 = null;
function menuOver_3821() {
clearTimeout(timeOn_3821)
}
function showSelected_3821() {
showChildrenMenu_3821(
document.getElementById("flatMenuItemAnchor" + selectedPageId), selectedPageId);
}
</script>
</body>
</html>
BeautifulSoup doesn't seem to be able to deal with this and is complaning about "malformed start tag" around the onMouseOver=**\"**menuOver_3821();\".
It seems to try parsing the xml that is generated by javascript inside the script block ?!?
Any ideas how to make BeautifulSoup ignores the script tags content ?
I have seen other suggestion of using lxml but can't since it has to run on Google AppEngine.
A:
Reverting to BeautifulSoup 3.0.7a solved this issue and many other html oddities that 3.1.0.1 has choked on.
A:
I've faced this kind of problem before, and what I normally do is replace every occurrence of <script with <!-- and </script> with -->. That way, all the <script></script> tags are commented out.
A:
That would work, but the point of BeautifulSoup is parsing whatever tag soup you throw at it, even if it's horribly ill-formed.
|
Making BeautifulSoup ignore contents inside script tags
|
I have been trying to get BeautifulSoup (3.1.0.1)to parse a html page that has a lot of javascript that generates html inside tags.
One example fragment looks like this :
<html><head><body><div>
<script type='text/javascript'>
if(ii > 0) {
html += '<span id="hoverMenuPosSepId" class="hoverMenuPosSep">|</span>'
}
html +=
'<div class="hoverMenuPos" id="hoverMenuPosId" onMouseOver=\"menuOver_3821();\" ' +
'onMouseOut=\"menuOut_3821();\">';
if (children[ii].uri == location.pathname) {
html += '<a class="hiHover" href="' + children[ii].uri + '" ' + onClick + '>';
} else {
html += '<a class="hover" href="' + children[ii].uri + '" ' + onClick + '>';
}
html += children[ii].name + '</a></div>';
}
}
hp = document.getElementById("hoverpopup_3821");
hp.style.top = (parseInt(hoveritem.offsetTop) + parseInt(hoveritem.offsetHeight)) + "px";
hp.style.visibility = "Visible";
hp.innerHTML = html;
}
return false;
}
function menuOut_3821() {
timeOn_3821 = setTimeout("showSelected_3821()", 1000)
}
var timeOn_3821 = null;
function menuOver_3821() {
clearTimeout(timeOn_3821)
}
function showSelected_3821() {
showChildrenMenu_3821(
document.getElementById("flatMenuItemAnchor" + selectedPageId), selectedPageId);
}
</script>
</body>
</html>
BeautifulSoup doesn't seem to be able to deal with this and is complaning about "malformed start tag" around the onMouseOver=**\"**menuOver_3821();\".
It seems to try parsing the xml that is generated by javascript inside the script block ?!?
Any ideas how to make BeautifulSoup ignores the script tags content ?
I have seen other suggestion of using lxml but can't since it has to run on Google AppEngine.
|
[
"Reverting to BeautifulSoup 3.0.7a solved this issue and many other html oddities that 3.1.0.1 has choked on. \n",
"I've faced this kind of problem before, and what I normally do is replace every occurrence of <script with <!-- and </script> with -->. That way, all the <script></script> tags are commented out.\n",
"That would work, but the point of BeautifulSoup is parsing whatever tag soup you throw at it, even if it's horribly ill-formed.\n"
] |
[
1,
0,
0
] |
[] |
[] |
[
"beautifulsoup",
"html_parsing",
"python"
] |
stackoverflow_0001732956_beautifulsoup_html_parsing_python.txt
|
Q:
More pythonic way of skipping header lines
Is there a shorter (perhaps more pythonic) way of opening a text file and reading past the lines that start with a comment character?
In other words, a neater way of doing this
fin = open("data.txt")
line = fin.readline()
while line.startswith("#"):
line = fin.readline()
A:
At this stage in my arc of learning Python, I find this most Pythonic:
def iscomment(s):
return s.startswith('#')
from itertools import dropwhile
with open(filename, 'r') as f:
for line in dropwhile(iscomment, f):
# do something with line
to skip all of the lines at the top of the file starting with #. To skip all lines starting with #:
from itertools import ifilterfalse
with open(filename, 'r') as f:
for line in ifilterfalse(iscomment, f):
# do something with line
That's almost all about readability for me; functionally there's almost no difference between:
for line in ifilterfalse(iscomment, f))
and
for line in (x for x in f if not x.startswith('#'))
Breaking out the test into its own function makes the intent of the code a little clearer; it also means that if your definition of a comment changes you have one place to change it.
A:
for line in open('data.txt'):
if line.startswith('#'):
continue
# work with line
of course, if your commented lines are only at the beginning of the file, you might use some optimisations.
A:
from itertools import dropwhile
for line in dropwhile(lambda line: line.startswith('#'), file('data.txt')):
pass
A:
If you want to filter out all comment lines (not just those at the start of the file):
for line in file("data.txt"):
if not line.startswith("#"):
# process line
If you only want to skip those at the start then see ephemient's answer using itertools.dropwhile
A:
You could use a generator function
def readlines(filename):
fin = open(filename)
for line in fin:
if not line.startswith("#"):
yield line
and use it like
for line in readlines("data.txt"):
# do things
pass
Depending on exactly where the files come from, you may also want to strip() the lines before the startswith() check. I once had to debug a script like that months after it was written because someone put in a couple of space characters before the '#'
A:
As a practical matter if I knew I was dealing with reasonable sized text files (anything which will comfortably fit in memory) then I'd problem go with something like:
f = open("data.txt")
lines = [ x for x in f.readlines() if x[0] != "#" ]
... to snarf in the whole file and filter out all lines that begin with the octothorpe.
As others have pointed out one might want ignore leading whitespace occurring before the octothorpe like so:
lines = [ x for x in f.readlines() if not x.lstrip().startswith("#") ]
I like this for its brevity.
This assumes that we want to strip out all of the comment lines.
We can also "chop" the last characters (almost always newlines) off the end of each using:
lines = [ x[:-1] for x in ... ]
... assuming that we're not worried about the infamously obscure issue of a missing final newline on the last line of the file. (The only time a line from the .readlines() or related file-like object methods might NOT end in a newline is at EOF).
In reasonably recent versions of Python one can "chomp" (only newlines) off the ends of the lines using a conditional expression like so:
lines = [ x[:-1] if x[-1]=='\n' else x for x in ... ]
... which is about as complicated as I'll go with a list comprehension for legibility's sake.
If we were worried about the possibility of an overly large file (or low memory constraints) impacting our performance or stability, and we're using a version of Python that's recent enough to support generator expressions (which are more recent additions to the language than the list comprehensions I've been using here), then we could use:
for line in (x[:-1] if x[-1]=='\n' else x for x in
f.readlines() if x.lstrip().startswith('#')):
# do stuff with each line
... is at the limits of what I'd expect anyone else to parse in one line a year after the code's been checked in.
If the intent is only to skip "header" lines then I think the best approach would be:
f = open('data.txt')
for line in f:
if line.lstrip().startswith('#'):
continue
... and be done with it.
A:
You could make a generator that loops over the file that skips those lines:
fin = open("data.txt")
fileiter = (l for l in fin if not l.startswith('#'))
for line in fileiter:
...
A:
You could do something like
def drop(n, seq):
for i, x in enumerate(seq):
if i >= n:
yield x
And then say
for line in drop(1, file(filename)):
# whatever
A:
I like @iWerner's generator function idea. One small change to his code and it does what the question asked for.
def readlines(filename):
f = open(filename)
# discard first lines that start with '#'
for line in f:
if not line.lstrip().startswith("#"):
break
yield line
for line in f:
yield line
and use it like
for line in readlines("data.txt"):
# do things
pass
But here is a different approach. This is almost very simple. The idea is that we open the file, and get a file object, which we can use as an iterator. Then we pull the lines we don't want out of the iterator, and just return the iterator. This would be ideal if we always knew how many lines to skip. The problem here is we don't know how many lines we need to skip; we just need to pull lines and look at them. And there is no way to put a line back into the iterator, once we have pulled it.
So: open the iterator, pull lines and count how many have the leading '#' character; then use the .seek() method to rewind the file, pull the correct number again, and return the iterator.
One thing I like about this: you get the actual file object back, with all its methods; you can just use this instead of open() and it will work in all cases. I renamed the function to open_my_text() to reflect this.
def open_my_text(filename):
f = open(filename, "rt")
# count number of lines that start with '#'
count = 0
for line in f:
if not line.lstrip().startswith("#"):
break
count += 1
# rewind file, and discard lines counted above
f.seek(0)
for _ in range(count):
f.readline()
# return file object with comment lines pre-skipped
return f
Instead of f.readline() I could have used f.next() (for Python 2.x) or next(f) (for Python 3.x) but I wanted to write it so it was portable to any Python.
EDIT: Okay, I know nobody cares and I"m not getting any upvotes for this, but I have re-written my answer one last time to make it more elegant.
You can't put a line back into an iterator. But, you can open a file twice, and get two iterators; given the way file caching works, the second iterator is almost free. If we imagine a file with a megabyte of '#' lines at the top, this version would greatly outperform the previous version that calls f.seek(0).
def open_my_text(filename):
# open the same file twice to get two file objects
# (We are opening the file read-only so this is safe.)
ftemp = open(filename, "rt")
f = open(filename, "rt")
# use ftemp to look at lines, then discard from f
for line in ftemp:
if not line.lstrip().startswith("#"):
break
f.readline()
# return file object with comment lines pre-skipped
return f
This version is much better than the previous version, and it still returns a full file object with all its methods.
|
More pythonic way of skipping header lines
|
Is there a shorter (perhaps more pythonic) way of opening a text file and reading past the lines that start with a comment character?
In other words, a neater way of doing this
fin = open("data.txt")
line = fin.readline()
while line.startswith("#"):
line = fin.readline()
|
[
"At this stage in my arc of learning Python, I find this most Pythonic:\ndef iscomment(s):\n return s.startswith('#')\n\nfrom itertools import dropwhile\nwith open(filename, 'r') as f:\n for line in dropwhile(iscomment, f):\n # do something with line\n\nto skip all of the lines at the top of the file starting with #. To skip all lines starting with #:\nfrom itertools import ifilterfalse\nwith open(filename, 'r') as f:\n for line in ifilterfalse(iscomment, f):\n # do something with line\n\nThat's almost all about readability for me; functionally there's almost no difference between:\nfor line in ifilterfalse(iscomment, f))\n\nand\nfor line in (x for x in f if not x.startswith('#'))\n\nBreaking out the test into its own function makes the intent of the code a little clearer; it also means that if your definition of a comment changes you have one place to change it.\n",
"for line in open('data.txt'):\n if line.startswith('#'):\n continue\n # work with line\n\nof course, if your commented lines are only at the beginning of the file, you might use some optimisations.\n",
"from itertools import dropwhile\nfor line in dropwhile(lambda line: line.startswith('#'), file('data.txt')):\n pass\n\n",
"If you want to filter out all comment lines (not just those at the start of the file):\nfor line in file(\"data.txt\"):\n if not line.startswith(\"#\"):\n # process line\n\nIf you only want to skip those at the start then see ephemient's answer using itertools.dropwhile\n",
"You could use a generator function\ndef readlines(filename):\n fin = open(filename)\n for line in fin:\n if not line.startswith(\"#\"):\n yield line\n\nand use it like\nfor line in readlines(\"data.txt\"):\n # do things\n pass\n\nDepending on exactly where the files come from, you may also want to strip() the lines before the startswith() check. I once had to debug a script like that months after it was written because someone put in a couple of space characters before the '#'\n",
"As a practical matter if I knew I was dealing with reasonable sized text files (anything which will comfortably fit in memory) then I'd problem go with something like:\nf = open(\"data.txt\")\nlines = [ x for x in f.readlines() if x[0] != \"#\" ]\n\n... to snarf in the whole file and filter out all lines that begin with the octothorpe.\nAs others have pointed out one might want ignore leading whitespace occurring before the octothorpe like so:\nlines = [ x for x in f.readlines() if not x.lstrip().startswith(\"#\") ]\n\nI like this for its brevity.\nThis assumes that we want to strip out all of the comment lines.\nWe can also \"chop\" the last characters (almost always newlines) off the end of each using:\nlines = [ x[:-1] for x in ... ]\n\n... assuming that we're not worried about the infamously obscure issue of a missing final newline on the last line of the file. (The only time a line from the .readlines() or related file-like object methods might NOT end in a newline is at EOF).\nIn reasonably recent versions of Python one can \"chomp\" (only newlines) off the ends of the lines using a conditional expression like so:\nlines = [ x[:-1] if x[-1]=='\\n' else x for x in ... ]\n\n... which is about as complicated as I'll go with a list comprehension for legibility's sake.\nIf we were worried about the possibility of an overly large file (or low memory constraints) impacting our performance or stability, and we're using a version of Python that's recent enough to support generator expressions (which are more recent additions to the language than the list comprehensions I've been using here), then we could use:\nfor line in (x[:-1] if x[-1]=='\\n' else x for x in\n f.readlines() if x.lstrip().startswith('#')):\n\n # do stuff with each line\n\n... is at the limits of what I'd expect anyone else to parse in one line a year after the code's been checked in.\nIf the intent is only to skip \"header\" lines then I think the best approach would be:\nf = open('data.txt')\nfor line in f:\n if line.lstrip().startswith('#'):\n continue\n\n... and be done with it.\n",
"You could make a generator that loops over the file that skips those lines:\nfin = open(\"data.txt\")\nfileiter = (l for l in fin if not l.startswith('#'))\n\nfor line in fileiter:\n ...\n\n",
"You could do something like\ndef drop(n, seq):\n for i, x in enumerate(seq):\n if i >= n:\n yield x\n\nAnd then say\nfor line in drop(1, file(filename)):\n # whatever\n\n",
"I like @iWerner's generator function idea. One small change to his code and it does what the question asked for. \ndef readlines(filename):\n f = open(filename)\n # discard first lines that start with '#'\n for line in f:\n if not line.lstrip().startswith(\"#\"):\n break\n yield line\n\n for line in f:\n yield line\n\nand use it like\nfor line in readlines(\"data.txt\"):\n # do things\n pass\n\nBut here is a different approach. This is almost very simple. The idea is that we open the file, and get a file object, which we can use as an iterator. Then we pull the lines we don't want out of the iterator, and just return the iterator. This would be ideal if we always knew how many lines to skip. The problem here is we don't know how many lines we need to skip; we just need to pull lines and look at them. And there is no way to put a line back into the iterator, once we have pulled it.\nSo: open the iterator, pull lines and count how many have the leading '#' character; then use the .seek() method to rewind the file, pull the correct number again, and return the iterator.\nOne thing I like about this: you get the actual file object back, with all its methods; you can just use this instead of open() and it will work in all cases. I renamed the function to open_my_text() to reflect this.\ndef open_my_text(filename):\n f = open(filename, \"rt\")\n # count number of lines that start with '#'\n count = 0\n for line in f:\n if not line.lstrip().startswith(\"#\"):\n break\n count += 1\n\n # rewind file, and discard lines counted above\n f.seek(0)\n for _ in range(count):\n f.readline()\n\n # return file object with comment lines pre-skipped\n return f\n\nInstead of f.readline() I could have used f.next() (for Python 2.x) or next(f) (for Python 3.x) but I wanted to write it so it was portable to any Python.\nEDIT: Okay, I know nobody cares and I\"m not getting any upvotes for this, but I have re-written my answer one last time to make it more elegant.\nYou can't put a line back into an iterator. But, you can open a file twice, and get two iterators; given the way file caching works, the second iterator is almost free. If we imagine a file with a megabyte of '#' lines at the top, this version would greatly outperform the previous version that calls f.seek(0).\ndef open_my_text(filename):\n # open the same file twice to get two file objects\n # (We are opening the file read-only so this is safe.)\n ftemp = open(filename, \"rt\")\n f = open(filename, \"rt\")\n\n # use ftemp to look at lines, then discard from f\n for line in ftemp:\n if not line.lstrip().startswith(\"#\"):\n break\n f.readline()\n\n # return file object with comment lines pre-skipped\n return f\n\nThis version is much better than the previous version, and it still returns a full file object with all its methods.\n"
] |
[
16,
14,
10,
6,
5,
5,
4,
2,
2
] |
[] |
[] |
[
"python"
] |
stackoverflow_0001730649_python.txt
|
Q:
run unit tests and coverage in certain python structure
I have some funny noob problem.
I try to run unit tests from commandline:
H:\PRO\pyEstimator>python src\test\python\test_power_estimator.py
Traceback (most recent call last):
File "src\test\python\test_power_estimator.py", line 2, in <module>
import src.main.python.power_estimator as power
ImportError: No module named src.main.python.power_estimator
this same happens when I try to run it in desired folder:
H:\PRO\pyEstimator\src\test\python>python
test_power_estimator.py
My folder structure looks like this.
├───src
│ │ __init__.py
│ │ __init__.pyc
│ │
│ ├───main
│ │ │ __init__.py
│ │ │ __init__.pyc
│ │ │
│ │ └───python
│ │ │ __init__.py
│ │ │ power_estimator.py
│ │ │ __init__.pyc
│ │ │ power_estimator.pyc
│ │ │
│ │ └───GUI
│ │ __init__.py
│ │
│ └───test
│ │ __init__.py
│ │
│ └───python
│ test_power_estimator.py
│ __init__.py
│ covrunner.bat
│ .coverage
│
└───doc
Maybe i don't see something obvious.
I also try to run coverage.
Is this approach good (file structure) ?
A:
The immediate issue you are facing is a misunderstanding of what is "local code" in Python (I am not sure if there is an official terminology, so I am making this one up) and how to import it.
When you run python src\test\python\test_power_estimator.py, the first element in sys.path is set to the directory containing the test_power_estimator.py script, not the current directory. So the statement "import src.main.python.power_estimator as power" looks for the package src in the directory src/test/python, and that fails.
One way to work around the issue is to set the PYTHONPATH environment variable to "H:\PRO\pyEstimator"
But the recommended way to run tests is to use a test runner script. I recommended using nosetest.
In addition, nosetest has support for collecting coverage data while running your tests.
Besides, it sounds like a bad idea to have a python package named "src". You should rename your package to be your project. Maybe "estimator" or "pyestimator" (lowercase, please).
|
run unit tests and coverage in certain python structure
|
I have some funny noob problem.
I try to run unit tests from commandline:
H:\PRO\pyEstimator>python src\test\python\test_power_estimator.py
Traceback (most recent call last):
File "src\test\python\test_power_estimator.py", line 2, in <module>
import src.main.python.power_estimator as power
ImportError: No module named src.main.python.power_estimator
this same happens when I try to run it in desired folder:
H:\PRO\pyEstimator\src\test\python>python
test_power_estimator.py
My folder structure looks like this.
├───src
│ │ __init__.py
│ │ __init__.pyc
│ │
│ ├───main
│ │ │ __init__.py
│ │ │ __init__.pyc
│ │ │
│ │ └───python
│ │ │ __init__.py
│ │ │ power_estimator.py
│ │ │ __init__.pyc
│ │ │ power_estimator.pyc
│ │ │
│ │ └───GUI
│ │ __init__.py
│ │
│ └───test
│ │ __init__.py
│ │
│ └───python
│ test_power_estimator.py
│ __init__.py
│ covrunner.bat
│ .coverage
│
└───doc
Maybe i don't see something obvious.
I also try to run coverage.
Is this approach good (file structure) ?
|
[
"The immediate issue you are facing is a misunderstanding of what is \"local code\" in Python (I am not sure if there is an official terminology, so I am making this one up) and how to import it.\nWhen you run python src\\test\\python\\test_power_estimator.py, the first element in sys.path is set to the directory containing the test_power_estimator.py script, not the current directory. So the statement \"import src.main.python.power_estimator as power\" looks for the package src in the directory src/test/python, and that fails.\nOne way to work around the issue is to set the PYTHONPATH environment variable to \"H:\\PRO\\pyEstimator\"\nBut the recommended way to run tests is to use a test runner script. I recommended using nosetest.\nIn addition, nosetest has support for collecting coverage data while running your tests.\nBesides, it sounds like a bad idea to have a python package named \"src\". You should rename your package to be your project. Maybe \"estimator\" or \"pyestimator\" (lowercase, please).\n"
] |
[
1
] |
[] |
[] |
[
"code_coverage",
"python",
"python_coverage",
"unit_testing"
] |
stackoverflow_0001734001_code_coverage_python_python_coverage_unit_testing.txt
|
Q:
Grokking Timsort
There's a (relatively) new sort on the block called Timsort. It's been used as Python's list.sort, and is now going to be the new Array.sort in Java 7.
There's some documentation and a tiny Wikipedia article describing the high-level properties of the sort and some low-level performance evaluations, but I was curious if anybody can provide some pseudocode to illustrate what Timsort is doing, exactly, and what are the key things that make it zippy. (Esp. with regard to the cited paper, "Optimistic Sorting and Information Theoretic Complexity.")
(See also related StackOverflow post.)
A:
Quoting the relevant portion from a now deleted blog post: Visualising Sorting Algorithms: Python's timsort
The business-end of timsort is a mergesort that operates on runs of pre-sorted elements. A minimum run length minrun is chosen to make sure the final merges are as balanced as possible - for 64 elements, minrun happens to be 32. Before the merges begin, a single pass is made through the data to detect pre-existing runs of sorted elements. Descending runs are handled by simply reversing them in place. If the resultant run length is less than minrun, it is boosted to minrun using insertion sort. On a shuffled array with no significant pre-existing runs, this process looks exactly like our guess above: pre-sorting blocks of minrun elements using insertion sort, before merging with merge sort.
[...]
timsort finds a descending run, and reverses the run in-place. This is done directly on the array of pointers, so seems "instant" from our vantage point.
The run is now boosted to length minrun using insertion sort.
No run is detected at the beginning of the next block, and insertion sort is used to sort the entire block. Note that the sorted elements at the bottom of this block are not treated specially - timsort doesn't detect runs that start in the middle of blocks being boosted to minrun.
Finally, mergesort is used to merge the runs.
A:
This change went through the core-libs mailing list when it went in so there is some discussion and useful links there. Here's the web rev with code review changes and also the original patch.
The comments in the code say:
Implementation note: This implementation is a stable, adaptive,
iterative mergesort that requires far fewer than n lg(n) comparisons
when the input array is partially sorted, while offering the
performance of a traditional mergesort when the input array is
randomly ordered. If the input array is nearly sorted, the
implementation requires approximately n comparisons.
Temporary storage requirements vary from a small constant for nearly sorted
input arrays to n/2 object references for randomly ordered input
arrays.
The implementation takes equal advantage of ascending and
descending order in its input array, and can take advantage of
ascending and descending order in different parts of the the same
input array. It is well-suited to merging two or more sorted arrays:
simply concatenate the arrays and sort the resulting array.
The implementation was adapted from Tim Peters's list sort for Python
TimSort. It uses techiques from Peter McIlroy's "Optimistic
Sorting and Information Theoretic Complexity", in Proceedings of the
Fourth Annual ACM-SIAM Symposium on Discrete Algorithms, pp 467-474,
January 1993.
Buried in there is the very useful link to the Python implementation details, and I think that's a great place to start, followed by the code. To be incredibly high level about it, timsort improves performance by noticing runs of sorted data and taking advantage of that structure during the sort.
|
Grokking Timsort
|
There's a (relatively) new sort on the block called Timsort. It's been used as Python's list.sort, and is now going to be the new Array.sort in Java 7.
There's some documentation and a tiny Wikipedia article describing the high-level properties of the sort and some low-level performance evaluations, but I was curious if anybody can provide some pseudocode to illustrate what Timsort is doing, exactly, and what are the key things that make it zippy. (Esp. with regard to the cited paper, "Optimistic Sorting and Information Theoretic Complexity.")
(See also related StackOverflow post.)
|
[
"Quoting the relevant portion from a now deleted blog post: Visualising Sorting Algorithms: Python's timsort\n\nThe business-end of timsort is a mergesort that operates on runs of pre-sorted elements. A minimum run length minrun is chosen to make sure the final merges are as balanced as possible - for 64 elements, minrun happens to be 32. Before the merges begin, a single pass is made through the data to detect pre-existing runs of sorted elements. Descending runs are handled by simply reversing them in place. If the resultant run length is less than minrun, it is boosted to minrun using insertion sort. On a shuffled array with no significant pre-existing runs, this process looks exactly like our guess above: pre-sorting blocks of minrun elements using insertion sort, before merging with merge sort.\n\n[...]\n\ntimsort finds a descending run, and reverses the run in-place. This is done directly on the array of pointers, so seems \"instant\" from our vantage point.\nThe run is now boosted to length minrun using insertion sort.\nNo run is detected at the beginning of the next block, and insertion sort is used to sort the entire block. Note that the sorted elements at the bottom of this block are not treated specially - timsort doesn't detect runs that start in the middle of blocks being boosted to minrun.\nFinally, mergesort is used to merge the runs.\n\n",
"This change went through the core-libs mailing list when it went in so there is some discussion and useful links there. Here's the web rev with code review changes and also the original patch.\nThe comments in the code say:\n\nImplementation note: This implementation is a stable, adaptive,\niterative mergesort that requires far fewer than n lg(n) comparisons\nwhen the input array is partially sorted, while offering the\nperformance of a traditional mergesort when the input array is\nrandomly ordered. If the input array is nearly sorted, the\nimplementation requires approximately n comparisons.\nTemporary storage requirements vary from a small constant for nearly sorted\ninput arrays to n/2 object references for randomly ordered input\narrays.\nThe implementation takes equal advantage of ascending and\ndescending order in its input array, and can take advantage of\nascending and descending order in different parts of the the same\ninput array. It is well-suited to merging two or more sorted arrays:\nsimply concatenate the arrays and sort the resulting array.\nThe implementation was adapted from Tim Peters's list sort for Python\nTimSort. It uses techiques from Peter McIlroy's \"Optimistic\nSorting and Information Theoretic Complexity\", in Proceedings of the\nFourth Annual ACM-SIAM Symposium on Discrete Algorithms, pp 467-474,\nJanuary 1993.\n\nBuried in there is the very useful link to the Python implementation details, and I think that's a great place to start, followed by the code. To be incredibly high level about it, timsort improves performance by noticing runs of sorted data and taking advantage of that structure during the sort.\n"
] |
[
15,
8
] |
[] |
[] |
[
"algorithm",
"java",
"python",
"sorting",
"timsort"
] |
stackoverflow_0001733073_algorithm_java_python_sorting_timsort.txt
|
Q:
Using keys with spaces
Is there a way to do something like the following in Django templates?
{% for hop in hops%}
<tr>
<td>{{ hop.name }}</td>
<td>{{ hop.mass }}</td>
<td>{{ hop."boil time" }}</td>
</tr>
{% endfor %}
The hop."boil time" doesn't work. The simple solution is rename the key boil_time, but I'm interested in alternatives.
A:
The best way to get at it is to sneak the property name into another variable, like so:
{% for key, value in hop.items %}
{% ifequal key 'boil time' %}
{{ value }}
{% endifequal %}
{% endfor %}
In Django 0.96 (the version used by Google AppEngine) the templating language doesn't support tuple expansion, so it's a bit uglier:
{% for hop in hops %}
<tr>
<td>{{ hop.name }}</td>
<td>{{ hop.mass }}</td>
<td>
{% for item in hop.items %}
{% ifequal item.0 'boil time' %}
{{ item.1 }}
{% endifequal %}
{% endfor %}
</td>
</tr>
{% endfor %}
So, taking your code, we end up with:
{% for hop in hops %}
<tr>
<td>{{ hop.name }}</td>
<td>{{ hop.mass }}</td>
<td>
{% for key, value in hop.items %}
{% ifequal key 'boil time' %}
{{ value }}
{% endifequal %}
{% endfor %}
</td>
</tr>
{% endfor %}
In Django 0.96 (the version on Google AppEnginge), this becomes:
{% for hop in hops %}
<tr>
<td>{{ hop.name }}</td>
<td>{{ hop.mass }}</td>
<td>
{% for item in hop.items %}
{% ifequal item.0 'boil time' %}
{{ item.1 }}
{% endifequal %}
{% endfor %}
</td>
</tr>
{% endfor %}
There's even a wordier way to get at it, using the regroup tag:
{% regroup hop.items by 'boil time' as bt %}
{% for item in bt %}
{% if forloop.first %}
{% for item2 in item.list %}
{% for item3 in item2 %}
{% if not forloop.first %}
{{ item3 }}
{% endif %}
{% endfor %}
{% endfor %}
{% endif %}
{% endfor %}
A:
You could use a get filter from djangosnippets: http://www.djangosnippets.org/snippets/1412/
(Renaming the key is probably better...)
A:
For django 0.96, which is what the Google Appengine uses for templates, the following works:
{% for hop in recipe.get_hops %}
{% for item in hop.items %}
{% ifequal item.0 'boil time' %}
<p>{{ item.1 }}</p>
{% endifequal %}
{% endfor %}
{% endfor %}
item.0 is the key and item.1 is the value. Link.
|
Using keys with spaces
|
Is there a way to do something like the following in Django templates?
{% for hop in hops%}
<tr>
<td>{{ hop.name }}</td>
<td>{{ hop.mass }}</td>
<td>{{ hop."boil time" }}</td>
</tr>
{% endfor %}
The hop."boil time" doesn't work. The simple solution is rename the key boil_time, but I'm interested in alternatives.
|
[
"The best way to get at it is to sneak the property name into another variable, like so:\n{% for key, value in hop.items %}\n {% ifequal key 'boil time' %}\n {{ value }}\n {% endifequal %}\n{% endfor %}\n\nIn Django 0.96 (the version used by Google AppEngine) the templating language doesn't support tuple expansion, so it's a bit uglier:\n{% for hop in hops %}\n <tr>\n <td>{{ hop.name }}</td>\n <td>{{ hop.mass }}</td>\n <td>\n {% for item in hop.items %}\n {% ifequal item.0 'boil time' %}\n {{ item.1 }}\n {% endifequal %}\n {% endfor %}\n </td>\n </tr>\n{% endfor %}\n\nSo, taking your code, we end up with:\n{% for hop in hops %}\n <tr>\n <td>{{ hop.name }}</td>\n <td>{{ hop.mass }}</td>\n <td>\n {% for key, value in hop.items %}\n {% ifequal key 'boil time' %}\n {{ value }}\n {% endifequal %}\n {% endfor %}\n </td>\n </tr>\n{% endfor %}\n\nIn Django 0.96 (the version on Google AppEnginge), this becomes:\n{% for hop in hops %}\n <tr>\n <td>{{ hop.name }}</td>\n <td>{{ hop.mass }}</td>\n <td>\n {% for item in hop.items %}\n {% ifequal item.0 'boil time' %}\n {{ item.1 }}\n {% endifequal %}\n {% endfor %}\n </td>\n </tr>\n{% endfor %}\n\nThere's even a wordier way to get at it, using the regroup tag:\n{% regroup hop.items by 'boil time' as bt %}\n {% for item in bt %}\n {% if forloop.first %}\n {% for item2 in item.list %}\n {% for item3 in item2 %}\n {% if not forloop.first %}\n {{ item3 }}\n {% endif %}\n {% endfor %}\n {% endfor %}\n {% endif %}\n{% endfor %}\n\n",
"You could use a get filter from djangosnippets: http://www.djangosnippets.org/snippets/1412/\n(Renaming the key is probably better...)\n",
"For django 0.96, which is what the Google Appengine uses for templates, the following works:\n{% for hop in recipe.get_hops %}\n {% for item in hop.items %}\n {% ifequal item.0 'boil time' %}\n <p>{{ item.1 }}</p>\n {% endifequal %}\n {% endfor %} \n {% endfor %}\n\nitem.0 is the key and item.1 is the value. Link. \n"
] |
[
1,
1,
0
] |
[] |
[] |
[
"dictionary",
"django",
"django_templates",
"google_app_engine",
"python"
] |
stackoverflow_0001726640_dictionary_django_django_templates_google_app_engine_python.txt
|
Q:
What is more efficient in python new array creation or in place array manipulation?
Say I have an array with a couple hundred elements. I need to iterate of the array and replace one or more items in the array with some other item. Which strategy is more efficient in python in terms of speed (I'm not worried about memory)?
For example: I have an array
my_array = [1,2,3,4,5,6]
I want to replace the first 3 elements with one element with the value 123.
Option 1 (inline):
my_array = [1,2,3,4,5,6]
my_array.remove(0,3)
my_array.insert(0,123)
Option2 (new array creation):
my_array = [1,2,3,4,5,6]
my_array = my_array[3:]
my_array.insert(0,123)
Both of the above will options will give a result of:
>>> [123,4,5,6]
Any comments would be appreciated. Especially if there is options I have missed.
A:
If you want to replace an item or a set of items in a list, you should never use your first option. Removing and adding to a list in the middle is slow (reference). Your second option is also fairly inefficient, since you're doing two operations for a single replacement.
Instead, just do slice assignment, as eiben's answer instructs. This will be significantly faster and more efficient than either of your methods:
>>> my_array = [1,2,3,4,5,6]
>>> my_array[:3] = [123]
>>> my_array
[123, 4, 5, 6]
A:
arr[0] = x
replaces the 0th element with x. You can also replace whole slices.
>>> arr = [1, 2, 3, 4, 5, 6]
>>> arr[0:3] = [8, 9, 99]
>>> arr
[8, 9, 99, 4, 5, 6]
>>>
And generally it's unclear what you're trying to achieve. Please provide more information or an example.
OK, as for your update. The remove method doesn't work (remove needs one argument). But the slicing I presented works for your case too:
>>> arr
[8, 9, 99, 4, 5, 6]
>>> arr[0:3] = [4]
>>> arr
[4, 4, 5, 6]
I would guess it's the fastest method, but do try it with timeit. According to my tests it's twice as fast as your "new array" approach.
A:
If you're looking speed efficience and manipulate series of integers, You should use the standard array module instead:
>>> import array
>>> my_array = array.array('i', [1,2,3,4,5,6])
>>> my_array = my_array[3:]
>>> my_array.insert(0,123)
>>> my_array
array('i', [123, 4, 5, 6])
A:
The key thing is to avoid moving large numbers of list items more than absolutely have to. Slice assignment, as far as i'm aware, still involves moving the items around the slice, which is bad news.
How do you recognise when you have a sequence of items which need to be replaced? I'll assume you have a function like:
def replacement(objects, startIndex):
"returns a pair (numberOfObjectsToReplace, replacementObject), or None if the should be no replacement"
I'd then do:
def replaceAll(objects):
src = 0
dst = 0
while (src < len(objects)):
replacementInfo = replacement(objects, src)
if (replacementInfo != None):
numberOfObjectsToReplace, replacementObject = replacementInfo
else:
numberOfObjectsToReplace = 1
replacementObject = objects[src]
objects[dst] = replacementObject
src = src + numberOfObjectsToReplace
dst = dst + 1
del objects[dst:]
This code still does a few more loads and stores than it absolutely has to, but not many.
|
What is more efficient in python new array creation or in place array manipulation?
|
Say I have an array with a couple hundred elements. I need to iterate of the array and replace one or more items in the array with some other item. Which strategy is more efficient in python in terms of speed (I'm not worried about memory)?
For example: I have an array
my_array = [1,2,3,4,5,6]
I want to replace the first 3 elements with one element with the value 123.
Option 1 (inline):
my_array = [1,2,3,4,5,6]
my_array.remove(0,3)
my_array.insert(0,123)
Option2 (new array creation):
my_array = [1,2,3,4,5,6]
my_array = my_array[3:]
my_array.insert(0,123)
Both of the above will options will give a result of:
>>> [123,4,5,6]
Any comments would be appreciated. Especially if there is options I have missed.
|
[
"If you want to replace an item or a set of items in a list, you should never use your first option. Removing and adding to a list in the middle is slow (reference). Your second option is also fairly inefficient, since you're doing two operations for a single replacement.\nInstead, just do slice assignment, as eiben's answer instructs. This will be significantly faster and more efficient than either of your methods:\n>>> my_array = [1,2,3,4,5,6]\n>>> my_array[:3] = [123]\n>>> my_array\n[123, 4, 5, 6]\n\n",
"arr[0] = x\n\nreplaces the 0th element with x. You can also replace whole slices.\n>>> arr = [1, 2, 3, 4, 5, 6]\n>>> arr[0:3] = [8, 9, 99]\n>>> arr\n[8, 9, 99, 4, 5, 6]\n>>> \n\nAnd generally it's unclear what you're trying to achieve. Please provide more information or an example.\n\nOK, as for your update. The remove method doesn't work (remove needs one argument). But the slicing I presented works for your case too:\n>>> arr\n[8, 9, 99, 4, 5, 6]\n>>> arr[0:3] = [4]\n>>> arr\n[4, 4, 5, 6]\n\nI would guess it's the fastest method, but do try it with timeit. According to my tests it's twice as fast as your \"new array\" approach.\n",
"If you're looking speed efficience and manipulate series of integers, You should use the standard array module instead:\n>>> import array\n>>> my_array = array.array('i', [1,2,3,4,5,6])\n>>> my_array = my_array[3:]\n>>> my_array.insert(0,123)\n>>> my_array\narray('i', [123, 4, 5, 6])\n\n",
"The key thing is to avoid moving large numbers of list items more than absolutely have to. Slice assignment, as far as i'm aware, still involves moving the items around the slice, which is bad news.\nHow do you recognise when you have a sequence of items which need to be replaced? I'll assume you have a function like:\ndef replacement(objects, startIndex):\n \"returns a pair (numberOfObjectsToReplace, replacementObject), or None if the should be no replacement\"\n\nI'd then do:\ndef replaceAll(objects):\n src = 0\n dst = 0\n while (src < len(objects)):\n replacementInfo = replacement(objects, src)\n if (replacementInfo != None):\n numberOfObjectsToReplace, replacementObject = replacementInfo\n else:\n numberOfObjectsToReplace = 1\n replacementObject = objects[src]\n objects[dst] = replacementObject\n src = src + numberOfObjectsToReplace\n dst = dst + 1\n del objects[dst:]\n\nThis code still does a few more loads and stores than it absolutely has to, but not many.\n"
] |
[
6,
3,
0,
0
] |
[] |
[] |
[
"performance",
"python"
] |
stackoverflow_0001733468_performance_python.txt
|
Q:
How to access YQL in Python (Django)?
Hey, I need a simple example for the following task:
Send a query to YQL and receive a response
I am accessing public data from python backend of my Django app.
If I just copy/paste an example from YQL, it says "Please provide valid credentials".
I guess, I need OAuth authorization to do it.
So I got an API key and a shared secret.
Now, what should I do with them?
Should I use python oauth library? This one?
http://oauth.googlecode.com/svn/code/python/oauth/
But what is the code? How I pass my secret/API key along with my yql query?
I guess, many Django programmers would love to know this.
A:
I've just released python-yql also available on pypi. It can do public, two-legged oauth a.k.a signed requests and facilitate 3-legged outh too.
It's brand new so there may be some bugs whilst I work on improving the test coverage but should hopefully do what you need. See the source for some idea on how to use it.
Installing to try it is as follows:
sudo easy_install yql
Bug/Feature requests can be filed here: https://bugs.launchpad.net/python-yql
A:
If you only are accessing public data you can just make a direct rest call from python.
>>> import urllib2
>>> result = urllib2.urlopen("http://query.yahooapis.com/v1/public/yql?q=select%20title%2Cabstract%20from%20search.web%20where%20query%3D%22paul%20tarjan%22&format=json").read()
>>> print result[:100]
{"query":{"count":"10","created":"2009-11-03T04:47:01Z","lang":"en-US","updated":"2009-11-03T04:47:0
And then you can parse the result with simplejson.
>>> import simplejson
>>> data = simplejson.loads(result)
>>> data['query']['results']['result'][0]['title']
u'<b>Paul</b> <b>Tarjan</b> - Silicon Valley, CA | Facebook'
A:
Ok, I sort of resolved the problem.
In YQL console example for data/html the following url was presented as an example:
http://query.yahooapis.com/v1/yql?q=select+*+from+html+where+url%3D%22http%3A%2F%2Ffinance.yahoo.com%2Fq%3Fs%3Dyhoo%22+and%0A++++++xpath%3D%27%2F%2Fdiv%5B%40id%3D%22yfi_headlines%22%5D%2Fdiv%5B2%5D%2Ful%2Fli%2Fa%27
It does not work!
But if you insert "/public" after "v1/" than it magically starts working!
http://query.yahooapis.com/v1/public/yql?q=select+*+from+html+where+url%3D%22http%3A%2F%2Ffinance.yahoo.com%2Fq%3Fs%3Dyhoo%22+and%0A++++++xpath%3D%27%2F%2Fdiv%5B%40id%3D%22yfi_headlines%22%5D%2Fdiv%5B2%5D%2Ful%2Fli%2Fa%27
But the question of how to pass my API key (for v1/yql access) is still open. Any advice?
|
How to access YQL in Python (Django)?
|
Hey, I need a simple example for the following task:
Send a query to YQL and receive a response
I am accessing public data from python backend of my Django app.
If I just copy/paste an example from YQL, it says "Please provide valid credentials".
I guess, I need OAuth authorization to do it.
So I got an API key and a shared secret.
Now, what should I do with them?
Should I use python oauth library? This one?
http://oauth.googlecode.com/svn/code/python/oauth/
But what is the code? How I pass my secret/API key along with my yql query?
I guess, many Django programmers would love to know this.
|
[
"I've just released python-yql also available on pypi. It can do public, two-legged oauth a.k.a signed requests and facilitate 3-legged outh too.\nIt's brand new so there may be some bugs whilst I work on improving the test coverage but should hopefully do what you need. See the source for some idea on how to use it.\nInstalling to try it is as follows:\nsudo easy_install yql\n\nBug/Feature requests can be filed here: https://bugs.launchpad.net/python-yql\n",
"If you only are accessing public data you can just make a direct rest call from python.\n>>> import urllib2\n>>> result = urllib2.urlopen(\"http://query.yahooapis.com/v1/public/yql?q=select%20title%2Cabstract%20from%20search.web%20where%20query%3D%22paul%20tarjan%22&format=json\").read()\n>>> print result[:100]\n{\"query\":{\"count\":\"10\",\"created\":\"2009-11-03T04:47:01Z\",\"lang\":\"en-US\",\"updated\":\"2009-11-03T04:47:0\n\nAnd then you can parse the result with simplejson.\n>>> import simplejson\n>>> data = simplejson.loads(result)\n>>> data['query']['results']['result'][0]['title']\nu'<b>Paul</b> <b>Tarjan</b> - Silicon Valley, CA | Facebook'\n\n",
"Ok, I sort of resolved the problem.\nIn YQL console example for data/html the following url was presented as an example:\nhttp://query.yahooapis.com/v1/yql?q=select+*+from+html+where+url%3D%22http%3A%2F%2Ffinance.yahoo.com%2Fq%3Fs%3Dyhoo%22+and%0A++++++xpath%3D%27%2F%2Fdiv%5B%40id%3D%22yfi_headlines%22%5D%2Fdiv%5B2%5D%2Ful%2Fli%2Fa%27\nIt does not work!\nBut if you insert \"/public\" after \"v1/\" than it magically starts working!\nhttp://query.yahooapis.com/v1/public/yql?q=select+*+from+html+where+url%3D%22http%3A%2F%2Ffinance.yahoo.com%2Fq%3Fs%3Dyhoo%22+and%0A++++++xpath%3D%27%2F%2Fdiv%5B%40id%3D%22yfi_headlines%22%5D%2Fdiv%5B2%5D%2Ful%2Fli%2Fa%27\nBut the question of how to pass my API key (for v1/yql access) is still open. Any advice?\n"
] |
[
3,
2,
0
] |
[] |
[] |
[
"api",
"django",
"oauth",
"python",
"yql"
] |
stackoverflow_0001512926_api_django_oauth_python_yql.txt
|
Q:
Optimal / best pratice to maintain continuos connection between Python and Postgresql using Psycopg2
I'm writing an application in Python with Postgresql 8.3 which runs on several machines on a local network.
All machines
1) fetch huge amount of data from the database server ( lets say database gets 100 different queries from a machine with in 2 seconds time) and there are about 10 or 11 machines doing that.
2) After processing data machines have to update certain tables (about 3 or 4 update/insert queries per machine per 1.5 seconds).
What I have noticed is that database goes down some times by giving server aborted process abnormally or freezes the server machine (requiring a hard reset).
By the way all machines maintain a constant connection to the database at all times i.e. once a connection is made using Psycopg2 (in Python) it remains active until processing finishes (which could last hours).
What's the best / optimal way for handling large number of connections in the application, should they be destroyed after each query ?
Secondly should I increase max_connections ?
Would greatly appreciate any advice on this matter.
A:
This sounds a bit like your DB server might have some problems, especially if your database server literally crashes. I'd start by trying to figure out from logs what is the root cause of the problems. It could be something like running out of memory, but it could also happen because of faulty hardware.
If you're opening all the connections at start and keep them open, max_connections isn't the culprit. The way you're handling the DB connections should be just fine and your server shouldn't do that no matter how it's configured.
A:
The most likely cause indeed sounds like running out of memory. If these are Linux servers, triggering an out-of-memory condition invokes the "OOM-killer", which simply terminates the memory hog processes (hence "server aborted process abnormally"). A low-memory situation often means very high disk swapping/paging load, which makes the server seem unresponsive.
See your kernel log files (or the dmesg command) for anything resembling "Out of Memory: Killed process 1234 (postgres)". This is caused by the default that permits the kernel to overcommit memory. The first thing you should do is disable overcommit, to allow graceful handling of out-of-memory situations:
echo 2 > /proc/sys/vm/overcommit_memory
Plan A:
A likely culprit is the work_mem setting which specifies how much memory each individual operation can allocate. One query may consist of multiple memory-intensive steps, so each backend can allocate a few times the work_mem amount of memory, in addition to the global shared_buffers setting. In addition, you also need some free memory for operating system cache.
For more info see the PostgreSQL manual on resource consumption settings: PostgreSQL 8.3 Documentation, Resource Consumption
Plan B:
It might be that reducing these tunables slows your queries down so much that you will still get no work done. An alternative to this is artificially limiting the number of queries that can run in parallel. Many connection pooling middlewares for PostgreSQL can limit the number of parallel queries, and provide queueing instead. Examples of this software are pgbouncer (simpler) and pgpool-II (more flexible).
EDIT: Answering your questions:
What's the best / optimal way for handling large number of connections in the application, should they be destroyed after each query ?
In general, establishing new connections to PostgreSQL is not fast because PostgreSQL spawns a new process for each backend. However, processes are not cheap in terms of memory, so keeping many idle connections to the database is not a good idea.
The connection pooling middlewares I mentioned in Plan B will take care of keeping a reasonable number of connections to Postgres -- regardless of when or how often you connect or disconnect from the pooler. So if you choose that route, you don't need to worry about manually opening/closing connections.
Secondly should I increase max_connections ?
Unless your database server has large amounts of RAM (over 8GB) I would not go over the default limit of 100 connections.
|
Optimal / best pratice to maintain continuos connection between Python and Postgresql using Psycopg2
|
I'm writing an application in Python with Postgresql 8.3 which runs on several machines on a local network.
All machines
1) fetch huge amount of data from the database server ( lets say database gets 100 different queries from a machine with in 2 seconds time) and there are about 10 or 11 machines doing that.
2) After processing data machines have to update certain tables (about 3 or 4 update/insert queries per machine per 1.5 seconds).
What I have noticed is that database goes down some times by giving server aborted process abnormally or freezes the server machine (requiring a hard reset).
By the way all machines maintain a constant connection to the database at all times i.e. once a connection is made using Psycopg2 (in Python) it remains active until processing finishes (which could last hours).
What's the best / optimal way for handling large number of connections in the application, should they be destroyed after each query ?
Secondly should I increase max_connections ?
Would greatly appreciate any advice on this matter.
|
[
"This sounds a bit like your DB server might have some problems, especially if your database server literally crashes. I'd start by trying to figure out from logs what is the root cause of the problems. It could be something like running out of memory, but it could also happen because of faulty hardware.\nIf you're opening all the connections at start and keep them open, max_connections isn't the culprit. The way you're handling the DB connections should be just fine and your server shouldn't do that no matter how it's configured.\n",
"The most likely cause indeed sounds like running out of memory. If these are Linux servers, triggering an out-of-memory condition invokes the \"OOM-killer\", which simply terminates the memory hog processes (hence \"server aborted process abnormally\"). A low-memory situation often means very high disk swapping/paging load, which makes the server seem unresponsive.\nSee your kernel log files (or the dmesg command) for anything resembling \"Out of Memory: Killed process 1234 (postgres)\". This is caused by the default that permits the kernel to overcommit memory. The first thing you should do is disable overcommit, to allow graceful handling of out-of-memory situations:\necho 2 > /proc/sys/vm/overcommit_memory\n\nPlan A:\nA likely culprit is the work_mem setting which specifies how much memory each individual operation can allocate. One query may consist of multiple memory-intensive steps, so each backend can allocate a few times the work_mem amount of memory, in addition to the global shared_buffers setting. In addition, you also need some free memory for operating system cache.\nFor more info see the PostgreSQL manual on resource consumption settings: PostgreSQL 8.3 Documentation, Resource Consumption\nPlan B:\nIt might be that reducing these tunables slows your queries down so much that you will still get no work done. An alternative to this is artificially limiting the number of queries that can run in parallel. Many connection pooling middlewares for PostgreSQL can limit the number of parallel queries, and provide queueing instead. Examples of this software are pgbouncer (simpler) and pgpool-II (more flexible).\nEDIT: Answering your questions:\n\nWhat's the best / optimal way for handling large number of connections in the application, should they be destroyed after each query ?\n\nIn general, establishing new connections to PostgreSQL is not fast because PostgreSQL spawns a new process for each backend. However, processes are not cheap in terms of memory, so keeping many idle connections to the database is not a good idea.\nThe connection pooling middlewares I mentioned in Plan B will take care of keeping a reasonable number of connections to Postgres -- regardless of when or how often you connect or disconnect from the pooler. So if you choose that route, you don't need to worry about manually opening/closing connections.\n\nSecondly should I increase max_connections ?\n\nUnless your database server has large amounts of RAM (over 8GB) I would not go over the default limit of 100 connections.\n"
] |
[
1,
1
] |
[] |
[] |
[
"linux",
"out_of_memory",
"performance",
"postgresql",
"python"
] |
stackoverflow_0001728350_linux_out_of_memory_performance_postgresql_python.txt
|
Q:
2 mysql instances in MAC
i recently switched to mac. first and foremost i installed xampp.
then for django-python-mysql connectivity, i "somehow" ended up installing a seperate MySQL.
now the seperate mysql installation is active all the time and the Xampp one doesnt switch on unless i kill the other one.
what i wanted to know is it possible to make xampp work with the seperate mysql installation? because that way i wouldnt have to tinker around with the mysqlDB adapter for python?
any help would be appreciated.
A:
You could change the listening port of one of the installations and they shouldn't conflict anymore with each other.
Update: You need to find the mysql configuration file my.cnf of the server which should get a new port (the one from xampp should be somewhere in the xampp folder). Find the line port=3306 in the [mysqld] section. You could change it to something like 3307.
You will also need to specify the new port when connecting to the server from your applications.
|
2 mysql instances in MAC
|
i recently switched to mac. first and foremost i installed xampp.
then for django-python-mysql connectivity, i "somehow" ended up installing a seperate MySQL.
now the seperate mysql installation is active all the time and the Xampp one doesnt switch on unless i kill the other one.
what i wanted to know is it possible to make xampp work with the seperate mysql installation? because that way i wouldnt have to tinker around with the mysqlDB adapter for python?
any help would be appreciated.
|
[
"You could change the listening port of one of the installations and they shouldn't conflict anymore with each other.\nUpdate: You need to find the mysql configuration file my.cnf of the server which should get a new port (the one from xampp should be somewhere in the xampp folder). Find the line port=3306 in the [mysqld] section. You could change it to something like 3307.\nYou will also need to specify the new port when connecting to the server from your applications.\n"
] |
[
1
] |
[] |
[] |
[
"django",
"macos",
"mysql",
"python",
"xampp"
] |
stackoverflow_0001734918_django_macos_mysql_python_xampp.txt
|
Q:
Each looping return a result
I am a beginner and got an issue, really head around now.
Here is the code:
n=3 #time step
#f, v and r are arrays,eg [3,4,5]
#r,v,f all have initial array which is when n=0
def force():
r=position()
f=r*2
return f
def position(n):
v=velocity(n)
for i in range(n): #This part may wrong...
r=v*i #How can I return results when i=0,1...5?
return r
def velocity(n):
f=force
for i in range(n):
v=f*i #Same problem here.....
return v
Another problem is force. It is a function of position which is a function of velocity, and velocity is a function of force. So, it's kind of a logic loop. I can't even
start. Physically it should initially start from force at time=0 then carrying on looping. But I just don't know how to do it in Python.
Also how can I make the row of r,v to be the results with the evolution of the time?
A:
You can use yield.
def velocity(n):
f=force
for i in range(n):
v=f*i
yield(v)
for vel in velocity(n):
//do something
One working example. It will print the output of function test as soon as it yields. So you do not need to wait for the next iteration of the loop.
import time
def test():
for i in range(10):
time.sleep(i)
yield(i)
for k in test():
print k
A:
It looks like you're trying to do an Euler algorithm and getting a bit mixed up in the looping. Here's how I think it should look (and I'll assume this is for a game and not homework... if it is for homework you should state that clearly so we don't give the full answer, like I'm doing here.)
This example is for a ball on a spring, which I think you're aiming for. I'm the example, my initial conditions are to thrown diagonally along the x-z axis, and I've also included gravity (if you didn't intend to you vectors you can just replace all the vector quantities with scalars, e.g. t, x, v = 0., 0., 2.; etc).
from numpy import *
# set the start conditions, etc.
n_timesteps = 100
dt, m, k = .1, 1., 2. # timestep, mass, spring-const (I'll write the equations correctly so the units make sense)
t, x, v = 0., array([0.,0.,0.]), array([2., 0., 2.]) # initial values
gravity = array([0., 0., -9.8]) # to make the problem a little more interesting
result = zeros((4, n_timesteps))
# run the simulation, looping through the timesteps
for n in range(n_timesteps):
# do the calculation
f = -k*x + gravity
a = f/m
v += a*dt
x += v*dt
# store the results
t += dt # just for easy record keeping
result[0,n] = t
result[1:4, n] = x
Note that for loop is looping over the timesteps (and the all looping over the vectors is handles by numpy broadcasting, e.g. f = -k*x+gravity, what could be easier?). Also note that the force is set first, and then we work our way down the chain of integrating the derivatives, then go back to the top and start at the force again. (You're right that this is a bit asymmetric, and really we should update them all at the same time, or something like that, and this is a deficiency of the Euler method, but it works well enough for small timesteps.)
Here's what the plots look like... the ball oscillates as expected
Edit: To clarify your question: Basically, your code's issue is not a question of "starting the functions" as you imply; instead your code is approaching the problem in the wrong way, so you need to fix the approach. It looks like you're trying to iterate your timesteps within each function. This is incorrect! Instead you need to do an enveloping iteration through the timesteps, and for each timestep, update the current state of each variable used in the calculation at that timestep. You can write this update as a separate function or, for example, you can do it inline like I did. But it makes no sense to iterate the timesteps within each variable calculation function. Instead, for your example to make sense, force, velocity, and other functions should have as inputs things at the present timestep and return an update to the state of that variable to be used in the next timestep. See how my example does this: it just cycles through the timesteps and within each timestep cycle it sequentially updates all the variables, basing each updated variable on the variables that were updated just before it in this current timestep.
A:
You could use a list comprehension:
def position(n):
v=velocity(n)
return [v*i for i in range(n)]
Or, since you are using numpy:
v=np.array([1,2,3])
# array([1, 2, 3])
you can use numpy broadcasting to express the entire calculation in one blow:
i=np.arange(5)
# array([0, 1, 2, 3, 4])
v[:]*i[:,np.newaxis]
# array([[ 0, 0, 0],
# [ 1, 2, 3],
# [ 2, 4, 6],
# [ 3, 6, 9],
# [ 4, 8, 12]])
In the above calculation, the scalar values in i (e.g. 0,1,2,3,4) are each multiplied against the array v. The results are collected in a 2-d numpy array. Each row corresponds to a different value of i.
See http://www.scipy.org/EricsBroadcastingDoc for an introduction to numpy broadcasting.
@OP: To address your question regarding a "logic loop":
Typically, what you do is define a "state" of the system. Perhaps in your case a state would consist of a tuple (time,position,velocity). You would then define a function which is given a state-tuple as an input and return a new state-tuple as output.
Given a (time,position,velocity), the force could be computed (mainly from the old position). From the force, you then compute the new velocity. From the velocity, you compute a new position.
Don't write code first.
In this case, sit down with paper and pencil and grind out the calculation by hand with a concrete example. Do enough iterations until you see clearly the pattern of how the calculation is done. What is the order of the steps? What parts get repeated?
Once you see how to do it by hand, it will be much clearer how to write the python code.
A:
You need to use append to add to the list.
def position(n):
v=velocity(n)
r = array()
for i in range(n): #this part may wrong...
r.append(v*i) #how can I return results when i=0,1...5?
return r
|
Each looping return a result
|
I am a beginner and got an issue, really head around now.
Here is the code:
n=3 #time step
#f, v and r are arrays,eg [3,4,5]
#r,v,f all have initial array which is when n=0
def force():
r=position()
f=r*2
return f
def position(n):
v=velocity(n)
for i in range(n): #This part may wrong...
r=v*i #How can I return results when i=0,1...5?
return r
def velocity(n):
f=force
for i in range(n):
v=f*i #Same problem here.....
return v
Another problem is force. It is a function of position which is a function of velocity, and velocity is a function of force. So, it's kind of a logic loop. I can't even
start. Physically it should initially start from force at time=0 then carrying on looping. But I just don't know how to do it in Python.
Also how can I make the row of r,v to be the results with the evolution of the time?
|
[
"You can use yield.\ndef velocity(n):\n f=force\n for i in range(n):\n v=f*i\n yield(v)\nfor vel in velocity(n):\n //do something\n\nOne working example. It will print the output of function test as soon as it yields. So you do not need to wait for the next iteration of the loop.\nimport time\ndef test():\n for i in range(10):\n time.sleep(i)\n yield(i)\nfor k in test():\n print k\n\n",
"It looks like you're trying to do an Euler algorithm and getting a bit mixed up in the looping. Here's how I think it should look (and I'll assume this is for a game and not homework... if it is for homework you should state that clearly so we don't give the full answer, like I'm doing here.)\nThis example is for a ball on a spring, which I think you're aiming for. I'm the example, my initial conditions are to thrown diagonally along the x-z axis, and I've also included gravity (if you didn't intend to you vectors you can just replace all the vector quantities with scalars, e.g. t, x, v = 0., 0., 2.; etc).\nfrom numpy import *\n\n# set the start conditions, etc.\nn_timesteps = 100\ndt, m, k = .1, 1., 2. # timestep, mass, spring-const (I'll write the equations correctly so the units make sense)\nt, x, v = 0., array([0.,0.,0.]), array([2., 0., 2.]) # initial values\ngravity = array([0., 0., -9.8]) # to make the problem a little more interesting\nresult = zeros((4, n_timesteps))\n\n# run the simulation, looping through the timesteps\nfor n in range(n_timesteps):\n # do the calculation\n f = -k*x + gravity\n a = f/m\n v += a*dt\n x += v*dt\n # store the results\n t += dt # just for easy record keeping\n result[0,n] = t\n result[1:4, n] = x\n\nNote that for loop is looping over the timesteps (and the all looping over the vectors is handles by numpy broadcasting, e.g. f = -k*x+gravity, what could be easier?). Also note that the force is set first, and then we work our way down the chain of integrating the derivatives, then go back to the top and start at the force again. (You're right that this is a bit asymmetric, and really we should update them all at the same time, or something like that, and this is a deficiency of the Euler method, but it works well enough for small timesteps.)\nHere's what the plots look like... the ball oscillates as expected\n\n\nEdit: To clarify your question: Basically, your code's issue is not a question of \"starting the functions\" as you imply; instead your code is approaching the problem in the wrong way, so you need to fix the approach. It looks like you're trying to iterate your timesteps within each function. This is incorrect! Instead you need to do an enveloping iteration through the timesteps, and for each timestep, update the current state of each variable used in the calculation at that timestep. You can write this update as a separate function or, for example, you can do it inline like I did. But it makes no sense to iterate the timesteps within each variable calculation function. Instead, for your example to make sense, force, velocity, and other functions should have as inputs things at the present timestep and return an update to the state of that variable to be used in the next timestep. See how my example does this: it just cycles through the timesteps and within each timestep cycle it sequentially updates all the variables, basing each updated variable on the variables that were updated just before it in this current timestep.\n",
"You could use a list comprehension: \ndef position(n):\n v=velocity(n)\n return [v*i for i in range(n)]\n\nOr, since you are using numpy:\nv=np.array([1,2,3])\n# array([1, 2, 3])\n\nyou can use numpy broadcasting to express the entire calculation in one blow:\ni=np.arange(5)\n# array([0, 1, 2, 3, 4])\n\nv[:]*i[:,np.newaxis]\n# array([[ 0, 0, 0],\n# [ 1, 2, 3],\n# [ 2, 4, 6],\n# [ 3, 6, 9],\n# [ 4, 8, 12]])\n\nIn the above calculation, the scalar values in i (e.g. 0,1,2,3,4) are each multiplied against the array v. The results are collected in a 2-d numpy array. Each row corresponds to a different value of i.\nSee http://www.scipy.org/EricsBroadcastingDoc for an introduction to numpy broadcasting.\n@OP: To address your question regarding a \"logic loop\":\nTypically, what you do is define a \"state\" of the system. Perhaps in your case a state would consist of a tuple (time,position,velocity). You would then define a function which is given a state-tuple as an input and return a new state-tuple as output.\nGiven a (time,position,velocity), the force could be computed (mainly from the old position). From the force, you then compute the new velocity. From the velocity, you compute a new position. \nDon't write code first.\nIn this case, sit down with paper and pencil and grind out the calculation by hand with a concrete example. Do enough iterations until you see clearly the pattern of how the calculation is done. What is the order of the steps? What parts get repeated?\nOnce you see how to do it by hand, it will be much clearer how to write the python code.\n",
"You need to use append to add to the list.\ndef position(n):\n v=velocity(n)\n r = array()\n for i in range(n): #this part may wrong...\n r.append(v*i) #how can I return results when i=0,1...5?\n return r\n\n"
] |
[
4,
2,
0,
0
] |
[] |
[] |
[
"arrays",
"numpy",
"python"
] |
stackoverflow_0001734626_arrays_numpy_python.txt
|
Q:
How to keep pyglet from clearing the screen?
I want to draw a scene and sequentially add lines to it. But pyglet keeps updating without control :( , so all I get is blinks
from pyglet.gl import *
window=pyglet.window.Window()
def drawline():
...
@window.event
def on_draw():
drawline()
pyglet.app.run()
should I change the decorator(if there exist options) or what?
Thanks!
A:
You'll need to draw your lines each time the window is redrawn as they won't be retained. You're probably better off using batches of vertex lists and adding to them. See here and here for details.
|
How to keep pyglet from clearing the screen?
|
I want to draw a scene and sequentially add lines to it. But pyglet keeps updating without control :( , so all I get is blinks
from pyglet.gl import *
window=pyglet.window.Window()
def drawline():
...
@window.event
def on_draw():
drawline()
pyglet.app.run()
should I change the decorator(if there exist options) or what?
Thanks!
|
[
"You'll need to draw your lines each time the window is redrawn as they won't be retained. You're probably better off using batches of vertex lists and adding to them. See here and here for details.\n"
] |
[
2
] |
[] |
[] |
[
"pyglet",
"python"
] |
stackoverflow_0001734801_pyglet_python.txt
|
Q:
How do I use the quartz scheduler with Python?
Is there a guide or tutorial on how to use the quartz Scheduler with Python.
Is there an existing API for Python?
A:
Given that Quartz is a Java application/library, the simplest thing to do may be to run it within Jython.
Failing that, and if you simply want to control the configuration of jobs from Python, perhaps the JDBC-JobStore is of use, and you could write jobs into the database via Python. You'll still need an instance of Quartz running in a JVM. However, I'm not sure how well supported that is as a scenario.
Finally, you may be able to talk to a running Quartz instance via JMX. You'll need a JMX client, and consequently you'll need to spawn off a Java JMX client from your Python process.
I think (regrettably) there's a non-trivial mismatch between a Quartz instance (in Java) and your Python code.
|
How do I use the quartz scheduler with Python?
|
Is there a guide or tutorial on how to use the quartz Scheduler with Python.
Is there an existing API for Python?
|
[
"Given that Quartz is a Java application/library, the simplest thing to do may be to run it within Jython.\nFailing that, and if you simply want to control the configuration of jobs from Python, perhaps the JDBC-JobStore is of use, and you could write jobs into the database via Python. You'll still need an instance of Quartz running in a JVM. However, I'm not sure how well supported that is as a scenario. \nFinally, you may be able to talk to a running Quartz instance via JMX. You'll need a JMX client, and consequently you'll need to spawn off a Java JMX client from your Python process.\nI think (regrettably) there's a non-trivial mismatch between a Quartz instance (in Java) and your Python code.\n"
] |
[
0
] |
[] |
[] |
[
"python",
"quartz_scheduler"
] |
stackoverflow_0001735266_python_quartz_scheduler.txt
|
Q:
How to create program startup parameters in python
I'm just beginning to learn python and the program I'm writing requires parameters for it to run with a specific task. For example (programs name is Samtho)
samtho -i Mozilla_Firefox
How can I do that?
A:
Read the documentation on optparse. It is very powerful and will let you lots of parameters and create the help text.
A:
You can use the modules optparse and getopt from the standard library. The former is more flexible and thus recommended.
If you want to write your own parser, then you'll have to inspect the contents of sys.argv. sys.argv[0] contains the name of the program being executed. sys.argv[1:] is a list containing all arguments passed to the program.
This is a minimal example using optparse (I mimicked program execution by manually setting sys.argv):
>>> import sys
>>> sys.argv = 'samtho -i Mozilla_Firefox'.split()
>>>
>>> from optparse import OptionParser
>>> parser = OptionParser()
>>> parser.add_option("-i")
<Option at 0xb7881b4c: -i>
>>> options, args = parser.parse_args()
>>> options
<Values at 0xb788958c: {'i': 'Mozilla_Firefox'}>
>>> options.i
'Mozilla_Firefox'
A:
Use sys.argv to grab input arguments directly (import sys first). There are a bunch of different libraries (optparse and getopt builtin modules are popular) to help parse the arguments but doing raw matching might be easier depending on what complexity you need.
A:
if you don't mind venturing from the standard library, argparse is generally considered best-in-breed for parameter parsing.
A:
I find optfunc the easiest library to use.
import optfunc, sys
def samtho(i=''):
"Usage: %prog -i <option>"
print i
if __name__ == '__main__':
optfunc.run(samtho)
|
How to create program startup parameters in python
|
I'm just beginning to learn python and the program I'm writing requires parameters for it to run with a specific task. For example (programs name is Samtho)
samtho -i Mozilla_Firefox
How can I do that?
|
[
"Read the documentation on optparse. It is very powerful and will let you lots of parameters and create the help text.\n",
"You can use the modules optparse and getopt from the standard library. The former is more flexible and thus recommended.\nIf you want to write your own parser, then you'll have to inspect the contents of sys.argv. sys.argv[0] contains the name of the program being executed. sys.argv[1:] is a list containing all arguments passed to the program.\nThis is a minimal example using optparse (I mimicked program execution by manually setting sys.argv):\n>>> import sys\n>>> sys.argv = 'samtho -i Mozilla_Firefox'.split()\n>>>\n>>> from optparse import OptionParser\n>>> parser = OptionParser()\n>>> parser.add_option(\"-i\")\n<Option at 0xb7881b4c: -i>\n>>> options, args = parser.parse_args()\n>>> options\n<Values at 0xb788958c: {'i': 'Mozilla_Firefox'}>\n>>> options.i\n'Mozilla_Firefox'\n\n",
"Use sys.argv to grab input arguments directly (import sys first). There are a bunch of different libraries (optparse and getopt builtin modules are popular) to help parse the arguments but doing raw matching might be easier depending on what complexity you need.\n",
"if you don't mind venturing from the standard library, argparse is generally considered best-in-breed for parameter parsing.\n",
"I find optfunc the easiest library to use.\nimport optfunc, sys\n\ndef samtho(i=''):\n \"Usage: %prog -i <option>\"\n print i\n\nif __name__ == '__main__':\n optfunc.run(samtho)\n\n"
] |
[
9,
6,
2,
1,
0
] |
[] |
[] |
[
"parameters",
"pydev",
"python",
"startup"
] |
stackoverflow_0001735202_parameters_pydev_python_startup.txt
|
Q:
Understanding Zope internals, from Django eyes
I am a newbie to zope and I previously worked on Django for about 2.5 years. So when I first jumped into Zope(v2) (only because my new company is using it since 7 years), I faced these questions. Please help me in understanding them.
What is the "real" purpose of zodb as such? I know what it does, but tell me one great thing that zodb does and a framework like Django (which doesn't have zodb) misses.
Update: Based on the answers, Zodb replaces the need for ORM. You can directly store the object inside the db(zodb itself).
It is said one of the zope's killer feature is the TTW(Through the Web or Developing using ZMI) philosophy. But I(and any developer) prefers File-System based development(using Version control, using Eclipse, using any favorite tool outside Zope). Then where is this TTW actually used?
This is the big one. What "EXTRA Stuff" does Zope's Acquistion gain when compared to Python/Django Inheritance.
Is it really a good move to come to Zope, from Django ?
Any site like djangosnippets.org for Zope(v2)?
A:
First things first: current zope2 versions include all of zope3, too. And if you look at modern zope2 applications like Plone, you'll see that it uses a lot of "zope 3" (now called the "zope tool kit", ZTK) under the hood.
The real purpose of the ZODB: it is one of the few object databases (as opposed to relational SQL databases) that sees real widespread use. You can "just" store all your python objects in there without needing to use an object-relational mapper. No "select * from xyz" under the hood. And adding a new attribute on a zodb object "just" persists that change. Luxurious! Especially handy when your data cannot be handily mapped to a strict relational database. If you can map it easily: just use such a database, I've used sqlalchemy a few times in zope projects.
TTW: we've come back from that. At least, the zope2 way of TTW indeed has all the drawbacks that you fear. No version control, no outside tools, etc. Plone is experimenting (google for "dexterity") with nice explicit zope 3 ways of doing TTW development that can still be mapped back to the filesystem.
TTW: the zodb makes it easy and cheap to store all sorts of config settings in the database, so you can typically adjust a lot of things through the browser. This doesn't really count as typical TTW development, though.
Acquisition: handy trick, though it leads to a huge namespace polution. Double edged sword. To improve debuggability and maintenance we try to do without in most of the cases. The acquisition happens inside the "object graph", so think "folder structure inside the zope site". A call to "contact_form" three folders down can still find the "contact_form" on the root of the site if it isn't found somewhere in between. Double edged sword!
(And regular python object oriented inheritance happens all over the place of course).
Moving from django to zope: a really good idea for certain problems and nonsensical for other problems :-) Quite a lot of zope2/plone companies have actually done some django projects for specific projects, typically those that have 99% percent of their content in a relatively straightforward SQL database. If you're more into content management, zope (and plone) is probably better.
Additional tip: don't focus only on zope2. Zope3's "component architecture" has lots of functionality for creating bigger applications (also non-web). Look at grok (http://grok.zope.org) for a friendly packaged zope, for instance. The pure component architecture is also usable inside django projects.
A:
On the ZODB:
Another way to ask "What is the real purpose of the ZODB?" is to ask, "Why was the ZODB originally created?"
The answer to that is the project was started very early on, around 1996. This was before the existance of MySQL or PostgreSQL, when miniSQL (a free-to-use but not free software) database was still in common use, or big money databases such as Oracle. Python provided the pickle module to serialize Python objects to disk - but serialization is lower level, it doesn't allow for features such as transactions, concurrent writes, and replication. This is what the ZODB provides.
It's still in use today in Zope because it works well. If you have no existing skillset in realational databases, it's easier to learn to use the ZODB than a relational database. It's also usable simpler use-cases, for example if you have a command-line script that needs to store some configuration information, using a relational database means having to run a database server just to store a little bit of configuraiton. You could use a config file, but the ZODB also works quite nicely because it's an embedable database. That means that the database is running in the same process as the rest of your Python code.
It's also worth noting that the API used to store objects inside containers is different between Zope 2 and Zope 3. In Zope 2, containers are stored as attributes:
root.mycontainer.myattr
In Zope 3, they use the same interface as Python standard dictionary type:
root['mycontainer']myattr
This is another reason why it can be easier to learn to use the ZODB than the Django ORM, since Django has it's own interface for it's ORM which is distinct from Python's existing interfaces.
Through-the-web (TTW):
Again, understanding the reason for TTW goes back when Zope was developed. While it seems silly to break with well known developer tools such Subversion or Mercurial, Zope was developed in the late 90s when the only free version control system was CVS. Zope 2 had it's own simple version control capabilites, and they were as good as CVS (which is to say, "they were limited and sucky."). UNIX workstations cost a lot more money back then, and had far fewer resources, so System Administrators were much more guarded and careful about how servers were managed. TTW allowed people who might not normally be able to upload code to the server with sysadmin intervation a way to do that.
With text editors, emacs and vi have had ftp-modes, and Zope 2 can listen on an FTP port. This would allow you to develop so that code was stored in the ZODB (editable TTW), but it was common to edit this code using a emacs or vi.
Today in Zope, TTW is more rarely used or promoted since it no longer makes sense to do this. Disk space is cheap, servers are (relatively) cheap, and there are lots of developer tools which expect to interact with the standard filesystem.
Acquisition:
It was a mistake. It was a very confusing feature that caused lots of unexpected things to happen. In theory there are some interesting ideas to acquisition, but in practice it's best tossed in the bin and has little practical use.
Moving from Django to Zope:
Work started on Zope 3 in 2001. This fixed a lot of the problems with Zope 2. It's a testament to the Zope community that Zope 2 is still actively and well maintained, but it's hardly state-of-the-art. Zope 2 is really only interesting to learn from a historical perspective.
Zope 3 ended up getting evolved in a few different directions, and so modern incarnations of Zope are best expressed in the form of Grok, BFG or Bobo.
Grok is closest to Zope 3, and as such is a pretty large framework - it can be rather overwhelming at times when delving through it's code base. However, just like Django, or any other full-stack framework you don't need to use every part of Grok, it can be quite easy to learn the basic and create web applications with it. It's convention-over-configuration is second to none, and it's class-based Views give it a much tighter, arguably cleaner code base than a Django web application. It's URL routing system is extremely flexible, but also arguably over-engineered.
BFG is a "pay for only what you eat" framework written by long time Zope developer Chris McDonough. As such, it's closer to Pylons in spirit, where only the parts deemed core or essential to a framework are included. It also plays very well with WSGI. It only uses a few core Zope packages.
Bobo is a "micro-framework". It's just a way to route URLs and serve up an app. It doesn't use any Zope packages, so isn't strictly in the Zope family of web frameworks. But it was written by Zope's creator, Jim Fulton, who originally called the publishing part of Zope, "Bobo". The original Bobo, written in the early 90's, mapped URLs to packages and modules, so if your source code was layed out as:
mypackage.mymodule.MyClass
You could have a URL such as:
/mypackage/mymodule/MyClass
Which was very inflexible, and was replaced with URL Traversel in Zope 2, which is fairly complex. Bobo uses Routes, so it's a middle ground between dead-simple URL resolution and complex URL resolution - about the same in complexity as Django's URL resolution machinery.
A:
I answer without much experience on both, but I had the chance to manipulate both, so I can tell you my opinion on some of your questions.
1)What is the "real" purpose of zodb
as such? Meaning I know what it does,
but tell me one great thing that zodb
does and a framework like django(which
doesn't have zodb) misses
Load distribution via ZEO and search via ZCatalog. Django is very low level on this point of view. To achieve the same, you would have to reimplement a lot of wheels, triangular.
Something I learned quite soon is: don't mess with low level database issues. You will screw them up. It's a can of worms, Dune sized.
So why choose django ORM ? You should also consider if YAGNI. django is easy and self contained, documentation is premium, and when (if) your site will grow that much, you will do the switch to a better ORM (or to a pure OODB, in case of ZODB) later on.
2)It is said one of the zope's killer
feature is the TTW(Through the Web or
Developing using ZMI) philosophy. But
I(and any developer) prefers
File-System based development(using
Version control, using Eclipse, using
any favorite tool outside Zope). Then
where is this TTW actually used?
I cannot answer properly to this question, but I would not say that it's fundamentally bad to develop with such approach. Of course it's a change of mindset, and I tend to prefer filesystem based development as well.
4)Is it really a good move to work on
Zope, from Django ?
Zope 3 is very modular, so you are free to use many of its components from django. I would advise against it though. You can, of course, but what I found most problematic is the lack of help. There are not many people using zope components and django at the same time. Sooner or later, you will have a problem and google won't help. At that point, you will realize that if your life was a videogame, you are definitely playing it at level difficult (maybe extreme, if you will have to put your nose into the zope code).
A:
A very good reference on ZODB is ZODB/ZEO programmer's guide. ZODB is not an ORM. Its a true object database. Python objects are persisted inside the database transparently without any worries about how to transform them into a representation suitable for database. Any pickleable Python object can be saved inside the ZODB. Relational databases are suitable for large amount of flat data (like employee records) while ZODB is best for hierarchical data (typically found in web applications). I personally use Zope 3 for my applications. I never did TTW type of work. Best part of using ZODB was the fact that I never had to worry at all about how I am going to save data and how things would change when I upgrade my software from one version to next one. For example, if I add a new attribute to a Python class, all I have to do is provide a default value as a class attribute. It then becomes automatically available to all objects created with the previous version of the same class. Removing an attribute is a simple del operation on existing objects. BTW, ZODB can be used independently in any kind of Python application and isn't coupled with just ZOPE platform. I love the fact that I don't have to worry about the nitty gritties of SQL while working on Python applications thanx to ZODB. And off course if you need a database server so that you can run multiple copies of your application backed by the same server ZEO comes to your rescue on top of ZODB.
Zope started with the idea of being an Object Publishing Environment. From that perspective mapping the URL directly to the object hierarchy in ZODB was great. The URLs simply reflect the hierarchy of objects. Now so far as figuring out the URL is considered, there is always the Rotterdam debugging interface for help. For development work, I keep the development flags on in the zope configuration and look at the contents of ZODB through the Rotterdam interface. Rotterdam skin provide a great way of introspecting the Python objects stored inside the ZODB and figuring out the URLs is much more interactive. Moreover, for major containers inside my ZODB, I register them as persistent utilities inside the site manager (Zope 3 sites and site managers). Anywhere in my code, whenever I need access to such containers, all I do is getUtility(IMyContainerType). I don't even have to remember the detailed locations of those containers inside the code base. They are once registered with the site manager and going forward available anywhere inside the code base through getUtility() calls.
And the URLs also support namespaces. For example using the ++skin++ namespace, you can anytime change the skin of your web application. Using the ++language++ namespace, you can any time change the preferred language of your user interface. Using the ++attributes++ namespace you can access individual attributes of an object. URLs are simply much more powerful and much more customizable. And you can write traversal adapters, define your own namespaces, to enhance the capabilities of your URLs. To give an example, all pages which are directly accessible from the web interface, are part of my default skin. While all pages which are invoked through background AJAX calls, are under a different skin. This way, one can implement different ways of authentication mechanisms in different skins. In main skin, one is redirected to a different login page in case of authentication failure. For AJAX pages, one could simply receive an HTTP error. This could be centrally done. Zope 3 objects have interfaces and one view can be defined for multiple interfaces. Wherever you have an object which supports the given interface, all associated views become automatically available and all such URLs are automatically valid. If you think about it, its a much more powerful than a single python file or XML file where the URLs are hard-coded. I don't really know much about DJango and J2EE so cannot say if they have equivalent capability.
A:
ZODB is a OO-style database that doesn't need a schema definition. You can simply create (nearly) all kinds of objects, and persist them.
The TTW is sometimes annoying, but you can mount the ZOPE-object-tree using webdav. Then you can edit the templates and scripts using your favorite editor.
ZOPE is especially powerful for creating CMS-like systems, IMHO there it is still unmatched - you'd have to go through a lot to make it work equally well in Django.
And through the TTW, actually non-developers like designers have a good chance of developing e.g. templates and CSS without need for developer interaction.
A:
+1 on Wheat's answer, above: "Zope 2 is really only interesting to learn from a historical perspective". I did Zope dev for a large site for a couple of years, 50% zope 2, 50% zope 3. Even then (this was 2 years ago) we were working to migrate everything off of zope 2. Unless you already have a lot invested in an existing Zope 2 project, there's no reason to use it; there's just not much of future there. And if you do have a big existing zope 2 project, I'd suggest taking a look at a product caled Five (a joke: 2 + 3 = 5) that aims to
allow you to integrate Zope 3
technologies into Zope 2. Among
others, it allows you to use Zope 3
interfaces, ZCML-based configuration,
adapters, browser pages (including
skins, layers, and resources),
automated add and edit forms based on
schemas, object events, as well as
Zope 3-style i18n message catalogs.
When all is said and done, Zope 3 is a very different framework from 2, and IMHO, a much better (albeit more complicated) one. TTW is optional, and not recommended for most cases. Implicit acquisition is gone.
Looks like people here have covered why you might want to use the ZODB, so I thought I'd mention one other thing about Zope 3 (or Zope 2 using Five) that's good. Zope has a very powerful system for wiring together different application components called the Zope Component Architecture (ZCA). It allows you to write components that are more or less autonomous and reusable, and which can be plugged together in a standardized way. I mostly do Django development now and I sometimes find myself missing the ZCA. In Django, the ability to write reusable components is limited and kind of ad-hoc. But, like Reinout says zope.component (like most zope packages, including the ZODB) works outside of the zope framework and could be used in a Django project.
That said, the ZCA has its drawbacks, one of which is the tedious process of registering your components in XML files; it always felt a little Java-esqe to me. One reason I really like Grok http://grok.zope.org/ is that it sits on top of zope.component and does much of that grunt work for you.
So bottom line: Zope 2 is mostly a dead end. If your employer is amenable to it, start looking at Zope 3, or at least Five. I think you'll find Zope 3 has a steep learning curve compared to Django, so it might be a good idea to come at it via Grok, which smooths out a lot of Zope 3's rougher edges. But, I think for a really large or complex web application with lots of moving parts, I'd go for Zope over Django (and I say this as someone who really likes Django a lot). For smaller projects, Django would probably be faster. Quantifying "large" and "small" in this context is hard though, and would probably require a couple of thousand more words. If you really are interested in Zope 3, the book by Philipp von Weitershausen is definitely the place to start.
|
Understanding Zope internals, from Django eyes
|
I am a newbie to zope and I previously worked on Django for about 2.5 years. So when I first jumped into Zope(v2) (only because my new company is using it since 7 years), I faced these questions. Please help me in understanding them.
What is the "real" purpose of zodb as such? I know what it does, but tell me one great thing that zodb does and a framework like Django (which doesn't have zodb) misses.
Update: Based on the answers, Zodb replaces the need for ORM. You can directly store the object inside the db(zodb itself).
It is said one of the zope's killer feature is the TTW(Through the Web or Developing using ZMI) philosophy. But I(and any developer) prefers File-System based development(using Version control, using Eclipse, using any favorite tool outside Zope). Then where is this TTW actually used?
This is the big one. What "EXTRA Stuff" does Zope's Acquistion gain when compared to Python/Django Inheritance.
Is it really a good move to come to Zope, from Django ?
Any site like djangosnippets.org for Zope(v2)?
|
[
"First things first: current zope2 versions include all of zope3, too. And if you look at modern zope2 applications like Plone, you'll see that it uses a lot of \"zope 3\" (now called the \"zope tool kit\", ZTK) under the hood.\nThe real purpose of the ZODB: it is one of the few object databases (as opposed to relational SQL databases) that sees real widespread use. You can \"just\" store all your python objects in there without needing to use an object-relational mapper. No \"select * from xyz\" under the hood. And adding a new attribute on a zodb object \"just\" persists that change. Luxurious! Especially handy when your data cannot be handily mapped to a strict relational database. If you can map it easily: just use such a database, I've used sqlalchemy a few times in zope projects.\nTTW: we've come back from that. At least, the zope2 way of TTW indeed has all the drawbacks that you fear. No version control, no outside tools, etc. Plone is experimenting (google for \"dexterity\") with nice explicit zope 3 ways of doing TTW development that can still be mapped back to the filesystem.\nTTW: the zodb makes it easy and cheap to store all sorts of config settings in the database, so you can typically adjust a lot of things through the browser. This doesn't really count as typical TTW development, though.\nAcquisition: handy trick, though it leads to a huge namespace polution. Double edged sword. To improve debuggability and maintenance we try to do without in most of the cases. The acquisition happens inside the \"object graph\", so think \"folder structure inside the zope site\". A call to \"contact_form\" three folders down can still find the \"contact_form\" on the root of the site if it isn't found somewhere in between. Double edged sword!\n(And regular python object oriented inheritance happens all over the place of course).\nMoving from django to zope: a really good idea for certain problems and nonsensical for other problems :-) Quite a lot of zope2/plone companies have actually done some django projects for specific projects, typically those that have 99% percent of their content in a relatively straightforward SQL database. If you're more into content management, zope (and plone) is probably better.\nAdditional tip: don't focus only on zope2. Zope3's \"component architecture\" has lots of functionality for creating bigger applications (also non-web). Look at grok (http://grok.zope.org) for a friendly packaged zope, for instance. The pure component architecture is also usable inside django projects.\n",
"On the ZODB:\nAnother way to ask \"What is the real purpose of the ZODB?\" is to ask, \"Why was the ZODB originally created?\"\nThe answer to that is the project was started very early on, around 1996. This was before the existance of MySQL or PostgreSQL, when miniSQL (a free-to-use but not free software) database was still in common use, or big money databases such as Oracle. Python provided the pickle module to serialize Python objects to disk - but serialization is lower level, it doesn't allow for features such as transactions, concurrent writes, and replication. This is what the ZODB provides.\nIt's still in use today in Zope because it works well. If you have no existing skillset in realational databases, it's easier to learn to use the ZODB than a relational database. It's also usable simpler use-cases, for example if you have a command-line script that needs to store some configuration information, using a relational database means having to run a database server just to store a little bit of configuraiton. You could use a config file, but the ZODB also works quite nicely because it's an embedable database. That means that the database is running in the same process as the rest of your Python code.\nIt's also worth noting that the API used to store objects inside containers is different between Zope 2 and Zope 3. In Zope 2, containers are stored as attributes:\n root.mycontainer.myattr\n\nIn Zope 3, they use the same interface as Python standard dictionary type:\n root['mycontainer']myattr\n\nThis is another reason why it can be easier to learn to use the ZODB than the Django ORM, since Django has it's own interface for it's ORM which is distinct from Python's existing interfaces.\nThrough-the-web (TTW):\nAgain, understanding the reason for TTW goes back when Zope was developed. While it seems silly to break with well known developer tools such Subversion or Mercurial, Zope was developed in the late 90s when the only free version control system was CVS. Zope 2 had it's own simple version control capabilites, and they were as good as CVS (which is to say, \"they were limited and sucky.\"). UNIX workstations cost a lot more money back then, and had far fewer resources, so System Administrators were much more guarded and careful about how servers were managed. TTW allowed people who might not normally be able to upload code to the server with sysadmin intervation a way to do that.\nWith text editors, emacs and vi have had ftp-modes, and Zope 2 can listen on an FTP port. This would allow you to develop so that code was stored in the ZODB (editable TTW), but it was common to edit this code using a emacs or vi.\nToday in Zope, TTW is more rarely used or promoted since it no longer makes sense to do this. Disk space is cheap, servers are (relatively) cheap, and there are lots of developer tools which expect to interact with the standard filesystem.\nAcquisition:\nIt was a mistake. It was a very confusing feature that caused lots of unexpected things to happen. In theory there are some interesting ideas to acquisition, but in practice it's best tossed in the bin and has little practical use.\nMoving from Django to Zope:\nWork started on Zope 3 in 2001. This fixed a lot of the problems with Zope 2. It's a testament to the Zope community that Zope 2 is still actively and well maintained, but it's hardly state-of-the-art. Zope 2 is really only interesting to learn from a historical perspective.\nZope 3 ended up getting evolved in a few different directions, and so modern incarnations of Zope are best expressed in the form of Grok, BFG or Bobo.\nGrok is closest to Zope 3, and as such is a pretty large framework - it can be rather overwhelming at times when delving through it's code base. However, just like Django, or any other full-stack framework you don't need to use every part of Grok, it can be quite easy to learn the basic and create web applications with it. It's convention-over-configuration is second to none, and it's class-based Views give it a much tighter, arguably cleaner code base than a Django web application. It's URL routing system is extremely flexible, but also arguably over-engineered.\nBFG is a \"pay for only what you eat\" framework written by long time Zope developer Chris McDonough. As such, it's closer to Pylons in spirit, where only the parts deemed core or essential to a framework are included. It also plays very well with WSGI. It only uses a few core Zope packages.\nBobo is a \"micro-framework\". It's just a way to route URLs and serve up an app. It doesn't use any Zope packages, so isn't strictly in the Zope family of web frameworks. But it was written by Zope's creator, Jim Fulton, who originally called the publishing part of Zope, \"Bobo\". The original Bobo, written in the early 90's, mapped URLs to packages and modules, so if your source code was layed out as:\nmypackage.mymodule.MyClass\n\nYou could have a URL such as:\n/mypackage/mymodule/MyClass\n\nWhich was very inflexible, and was replaced with URL Traversel in Zope 2, which is fairly complex. Bobo uses Routes, so it's a middle ground between dead-simple URL resolution and complex URL resolution - about the same in complexity as Django's URL resolution machinery.\n",
"I answer without much experience on both, but I had the chance to manipulate both, so I can tell you my opinion on some of your questions.\n\n1)What is the \"real\" purpose of zodb\n as such? Meaning I know what it does,\n but tell me one great thing that zodb\n does and a framework like django(which\n doesn't have zodb) misses\n\nLoad distribution via ZEO and search via ZCatalog. Django is very low level on this point of view. To achieve the same, you would have to reimplement a lot of wheels, triangular.\nSomething I learned quite soon is: don't mess with low level database issues. You will screw them up. It's a can of worms, Dune sized.\nSo why choose django ORM ? You should also consider if YAGNI. django is easy and self contained, documentation is premium, and when (if) your site will grow that much, you will do the switch to a better ORM (or to a pure OODB, in case of ZODB) later on.\n\n2)It is said one of the zope's killer\n feature is the TTW(Through the Web or\n Developing using ZMI) philosophy. But\n I(and any developer) prefers\n File-System based development(using\n Version control, using Eclipse, using\n any favorite tool outside Zope). Then\n where is this TTW actually used?\n\nI cannot answer properly to this question, but I would not say that it's fundamentally bad to develop with such approach. Of course it's a change of mindset, and I tend to prefer filesystem based development as well.\n\n4)Is it really a good move to work on\n Zope, from Django ?\n\nZope 3 is very modular, so you are free to use many of its components from django. I would advise against it though. You can, of course, but what I found most problematic is the lack of help. There are not many people using zope components and django at the same time. Sooner or later, you will have a problem and google won't help. At that point, you will realize that if your life was a videogame, you are definitely playing it at level difficult (maybe extreme, if you will have to put your nose into the zope code).\n",
"A very good reference on ZODB is ZODB/ZEO programmer's guide. ZODB is not an ORM. Its a true object database. Python objects are persisted inside the database transparently without any worries about how to transform them into a representation suitable for database. Any pickleable Python object can be saved inside the ZODB. Relational databases are suitable for large amount of flat data (like employee records) while ZODB is best for hierarchical data (typically found in web applications). I personally use Zope 3 for my applications. I never did TTW type of work. Best part of using ZODB was the fact that I never had to worry at all about how I am going to save data and how things would change when I upgrade my software from one version to next one. For example, if I add a new attribute to a Python class, all I have to do is provide a default value as a class attribute. It then becomes automatically available to all objects created with the previous version of the same class. Removing an attribute is a simple del operation on existing objects. BTW, ZODB can be used independently in any kind of Python application and isn't coupled with just ZOPE platform. I love the fact that I don't have to worry about the nitty gritties of SQL while working on Python applications thanx to ZODB. And off course if you need a database server so that you can run multiple copies of your application backed by the same server ZEO comes to your rescue on top of ZODB.\nZope started with the idea of being an Object Publishing Environment. From that perspective mapping the URL directly to the object hierarchy in ZODB was great. The URLs simply reflect the hierarchy of objects. Now so far as figuring out the URL is considered, there is always the Rotterdam debugging interface for help. For development work, I keep the development flags on in the zope configuration and look at the contents of ZODB through the Rotterdam interface. Rotterdam skin provide a great way of introspecting the Python objects stored inside the ZODB and figuring out the URLs is much more interactive. Moreover, for major containers inside my ZODB, I register them as persistent utilities inside the site manager (Zope 3 sites and site managers). Anywhere in my code, whenever I need access to such containers, all I do is getUtility(IMyContainerType). I don't even have to remember the detailed locations of those containers inside the code base. They are once registered with the site manager and going forward available anywhere inside the code base through getUtility() calls. \nAnd the URLs also support namespaces. For example using the ++skin++ namespace, you can anytime change the skin of your web application. Using the ++language++ namespace, you can any time change the preferred language of your user interface. Using the ++attributes++ namespace you can access individual attributes of an object. URLs are simply much more powerful and much more customizable. And you can write traversal adapters, define your own namespaces, to enhance the capabilities of your URLs. To give an example, all pages which are directly accessible from the web interface, are part of my default skin. While all pages which are invoked through background AJAX calls, are under a different skin. This way, one can implement different ways of authentication mechanisms in different skins. In main skin, one is redirected to a different login page in case of authentication failure. For AJAX pages, one could simply receive an HTTP error. This could be centrally done. Zope 3 objects have interfaces and one view can be defined for multiple interfaces. Wherever you have an object which supports the given interface, all associated views become automatically available and all such URLs are automatically valid. If you think about it, its a much more powerful than a single python file or XML file where the URLs are hard-coded. I don't really know much about DJango and J2EE so cannot say if they have equivalent capability. \n",
"ZODB is a OO-style database that doesn't need a schema definition. You can simply create (nearly) all kinds of objects, and persist them.\nThe TTW is sometimes annoying, but you can mount the ZOPE-object-tree using webdav. Then you can edit the templates and scripts using your favorite editor.\nZOPE is especially powerful for creating CMS-like systems, IMHO there it is still unmatched - you'd have to go through a lot to make it work equally well in Django.\nAnd through the TTW, actually non-developers like designers have a good chance of developing e.g. templates and CSS without need for developer interaction.\n",
"+1 on Wheat's answer, above: \"Zope 2 is really only interesting to learn from a historical perspective\". I did Zope dev for a large site for a couple of years, 50% zope 2, 50% zope 3. Even then (this was 2 years ago) we were working to migrate everything off of zope 2. Unless you already have a lot invested in an existing Zope 2 project, there's no reason to use it; there's just not much of future there. And if you do have a big existing zope 2 project, I'd suggest taking a look at a product caled Five (a joke: 2 + 3 = 5) that aims to \n\nallow you to integrate Zope 3\n technologies into Zope 2. Among\n others, it allows you to use Zope 3\n interfaces, ZCML-based configuration,\n adapters, browser pages (including\n skins, layers, and resources),\n automated add and edit forms based on\n schemas, object events, as well as\n Zope 3-style i18n message catalogs.\n\nWhen all is said and done, Zope 3 is a very different framework from 2, and IMHO, a much better (albeit more complicated) one. TTW is optional, and not recommended for most cases. Implicit acquisition is gone. \nLooks like people here have covered why you might want to use the ZODB, so I thought I'd mention one other thing about Zope 3 (or Zope 2 using Five) that's good. Zope has a very powerful system for wiring together different application components called the Zope Component Architecture (ZCA). It allows you to write components that are more or less autonomous and reusable, and which can be plugged together in a standardized way. I mostly do Django development now and I sometimes find myself missing the ZCA. In Django, the ability to write reusable components is limited and kind of ad-hoc. But, like Reinout says zope.component (like most zope packages, including the ZODB) works outside of the zope framework and could be used in a Django project. \nThat said, the ZCA has its drawbacks, one of which is the tedious process of registering your components in XML files; it always felt a little Java-esqe to me. One reason I really like Grok http://grok.zope.org/ is that it sits on top of zope.component and does much of that grunt work for you. \nSo bottom line: Zope 2 is mostly a dead end. If your employer is amenable to it, start looking at Zope 3, or at least Five. I think you'll find Zope 3 has a steep learning curve compared to Django, so it might be a good idea to come at it via Grok, which smooths out a lot of Zope 3's rougher edges. But, I think for a really large or complex web application with lots of moving parts, I'd go for Zope over Django (and I say this as someone who really likes Django a lot). For smaller projects, Django would probably be faster. Quantifying \"large\" and \"small\" in this context is hard though, and would probably require a couple of thousand more words. If you really are interested in Zope 3, the book by Philipp von Weitershausen is definitely the place to start. \n"
] |
[
16,
10,
7,
6,
3,
1
] |
[] |
[] |
[
"acquisition",
"django",
"python",
"zodb",
"zope"
] |
stackoverflow_0001706309_acquisition_django_python_zodb_zope.txt
|
Q:
Class-level read-only properties in Python
Is there some way to make a class-level read-only property in Python? For instance, if I have a class Foo, I want to say:
x = Foo.CLASS_PROPERTY
but prevent anyone from saying:
Foo.CLASS_PROPERTY = y
EDIT:
I like the simplicity of Alex Martelli's solution, but not the syntax that it requires. Both his and ~unutbu's answers inspired the following solution, which is closer to the spirit of what I was looking for:
class const_value (object):
def __init__(self, value):
self.__value = value
def make_property(self):
return property(lambda cls: self.__value)
class ROType(type):
def __new__(mcl,classname,bases,classdict):
class UniqeROType (mcl):
pass
for attr, value in classdict.items():
if isinstance(value, const_value):
setattr(UniqeROType, attr, value.make_property())
classdict[attr] = value.make_property()
return type.__new__(UniqeROType,classname,bases,classdict)
class Foo(object):
__metaclass__=ROType
BAR = const_value(1)
BAZ = 2
class Bit(object):
__metaclass__=ROType
BOO = const_value(3)
BAN = 4
Now, I get:
Foo.BAR
# 1
Foo.BAZ
# 2
Foo.BAR=2
# Traceback (most recent call last):
# File "<stdin>", line 1, in <module>
# AttributeError: can't set attribute
Foo.BAZ=3
#
I prefer this solution because:
The members get declared inline instead of after the fact, as with type(X).foo = ...
The members' values are set in the actual class's code as opposed to in the metaclass's code.
It's still not ideal because:
I have to set the __metaclass__ in order for const_value objects to be interpreted correctly.
The const_values don't "behave" like the plain values. For example, I couldn't use it as a default value for a parameter to a method in the class.
A:
The existing solutions are a bit complex -- what about just ensuring that each class in a certain group has a unique metaclass, then setting a normal read-only property on the custom metaclass. Namely:
>>> class Meta(type):
... def __new__(mcl, *a, **k):
... uniquemcl = type('Uniq', (mcl,), {})
... return type.__new__(uniquemcl, *a, **k)
...
>>> class X: __metaclass__ = Meta
...
>>> class Y: __metaclass__ = Meta
...
>>> type(X).foo = property(lambda *_: 23)
>>> type(Y).foo = property(lambda *_: 45)
>>> X.foo
23
>>> Y.foo
45
>>>
this is really much simpler, because it's based on nothing more than the fact that when you get an instance's attribute descriptors are looked up on the class (so of course when you get a class's attribute descriptors are looked on the metaclass), and making class/metaclass unique isn't terribly hard.
Oh, and of course:
>>> X.foo = 67
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
AttributeError: can't set attribute
just to confirm it IS indeed read-only!
A:
The ActiveState solution that Pynt references makes instances of ROClass have read-only attributes. Your question seems to ask if the class itself can have read-only attributes.
Here is one way, based on Raymond Hettinger's comment:
#!/usr/bin/env python
def readonly(value):
return property(lambda self: value)
class ROType(type):
CLASS_PROPERTY = readonly(1)
class Foo(object):
__metaclass__=ROType
print(Foo.CLASS_PROPERTY)
# 1
Foo.CLASS_PROPERTY=2
# AttributeError: can't set attribute
The idea is this: Consider first Raymond Hettinger's solution:
class Bar(object):
CLASS_PROPERTY = property(lambda self: 1)
bar=Bar()
bar.CLASS_PROPERTY=2
It shows a relatively simple way to give bar a read-only property.
Notice that you have to add the CLASS_PROPERTY = property(lambda self: 1)
line to the definition of the class of bar, not to bar itself.
So, if you want the class Foo to have a read-only property, then the parent class of Foo has to have CLASS_PROPERTY = property(lambda self: 1) defined.
The parent class of a class is a metaclass. Hence we define ROType as the metaclass:
class ROType(type):
CLASS_PROPERTY = readonly(1)
Then we make Foo's parent class be ROType:
class Foo(object):
__metaclass__=ROType
A:
Found this on ActiveState:
# simple read only attributes with meta-class programming
# method factory for an attribute get method
def getmethod(attrname):
def _getmethod(self):
return self.__readonly__[attrname]
return _getmethod
class metaClass(type):
def __new__(cls,classname,bases,classdict):
readonly = classdict.get('__readonly__',{})
for name,default in readonly.items():
classdict[name] = property(getmethod(name))
return type.__new__(cls,classname,bases,classdict)
class ROClass(object):
__metaclass__ = metaClass
__readonly__ = {'a':1,'b':'text'}
if __name__ == '__main__':
def test1():
t = ROClass()
print t.a
print t.b
def test2():
t = ROClass()
t.a = 2
test1()
Note that if you try to set a read-only attribute (t.a = 2) python will raise an AttributeError.
|
Class-level read-only properties in Python
|
Is there some way to make a class-level read-only property in Python? For instance, if I have a class Foo, I want to say:
x = Foo.CLASS_PROPERTY
but prevent anyone from saying:
Foo.CLASS_PROPERTY = y
EDIT:
I like the simplicity of Alex Martelli's solution, but not the syntax that it requires. Both his and ~unutbu's answers inspired the following solution, which is closer to the spirit of what I was looking for:
class const_value (object):
def __init__(self, value):
self.__value = value
def make_property(self):
return property(lambda cls: self.__value)
class ROType(type):
def __new__(mcl,classname,bases,classdict):
class UniqeROType (mcl):
pass
for attr, value in classdict.items():
if isinstance(value, const_value):
setattr(UniqeROType, attr, value.make_property())
classdict[attr] = value.make_property()
return type.__new__(UniqeROType,classname,bases,classdict)
class Foo(object):
__metaclass__=ROType
BAR = const_value(1)
BAZ = 2
class Bit(object):
__metaclass__=ROType
BOO = const_value(3)
BAN = 4
Now, I get:
Foo.BAR
# 1
Foo.BAZ
# 2
Foo.BAR=2
# Traceback (most recent call last):
# File "<stdin>", line 1, in <module>
# AttributeError: can't set attribute
Foo.BAZ=3
#
I prefer this solution because:
The members get declared inline instead of after the fact, as with type(X).foo = ...
The members' values are set in the actual class's code as opposed to in the metaclass's code.
It's still not ideal because:
I have to set the __metaclass__ in order for const_value objects to be interpreted correctly.
The const_values don't "behave" like the plain values. For example, I couldn't use it as a default value for a parameter to a method in the class.
|
[
"The existing solutions are a bit complex -- what about just ensuring that each class in a certain group has a unique metaclass, then setting a normal read-only property on the custom metaclass. Namely:\n>>> class Meta(type):\n... def __new__(mcl, *a, **k):\n... uniquemcl = type('Uniq', (mcl,), {})\n... return type.__new__(uniquemcl, *a, **k)\n... \n>>> class X: __metaclass__ = Meta\n... \n>>> class Y: __metaclass__ = Meta\n... \n>>> type(X).foo = property(lambda *_: 23)\n>>> type(Y).foo = property(lambda *_: 45)\n>>> X.foo\n23\n>>> Y.foo\n45\n>>> \n\nthis is really much simpler, because it's based on nothing more than the fact that when you get an instance's attribute descriptors are looked up on the class (so of course when you get a class's attribute descriptors are looked on the metaclass), and making class/metaclass unique isn't terribly hard.\nOh, and of course:\n>>> X.foo = 67\nTraceback (most recent call last):\n File \"<stdin>\", line 1, in <module>\nAttributeError: can't set attribute\n\njust to confirm it IS indeed read-only!\n",
"The ActiveState solution that Pynt references makes instances of ROClass have read-only attributes. Your question seems to ask if the class itself can have read-only attributes.\nHere is one way, based on Raymond Hettinger's comment:\n#!/usr/bin/env python\ndef readonly(value):\n return property(lambda self: value)\n\nclass ROType(type):\n CLASS_PROPERTY = readonly(1)\n\nclass Foo(object):\n __metaclass__=ROType\n\nprint(Foo.CLASS_PROPERTY)\n# 1\n\nFoo.CLASS_PROPERTY=2\n# AttributeError: can't set attribute\n\nThe idea is this: Consider first Raymond Hettinger's solution:\nclass Bar(object):\n CLASS_PROPERTY = property(lambda self: 1)\nbar=Bar()\nbar.CLASS_PROPERTY=2\n\nIt shows a relatively simple way to give bar a read-only property.\nNotice that you have to add the CLASS_PROPERTY = property(lambda self: 1) \nline to the definition of the class of bar, not to bar itself.\nSo, if you want the class Foo to have a read-only property, then the parent class of Foo has to have CLASS_PROPERTY = property(lambda self: 1) defined.\nThe parent class of a class is a metaclass. Hence we define ROType as the metaclass:\nclass ROType(type):\n CLASS_PROPERTY = readonly(1)\n\nThen we make Foo's parent class be ROType:\nclass Foo(object):\n __metaclass__=ROType\n\n",
"Found this on ActiveState:\n# simple read only attributes with meta-class programming\n\n# method factory for an attribute get method\ndef getmethod(attrname):\n def _getmethod(self):\n return self.__readonly__[attrname]\n\n return _getmethod\n\nclass metaClass(type):\n def __new__(cls,classname,bases,classdict):\n readonly = classdict.get('__readonly__',{})\n for name,default in readonly.items():\n classdict[name] = property(getmethod(name))\n\n return type.__new__(cls,classname,bases,classdict)\n\nclass ROClass(object):\n __metaclass__ = metaClass\n __readonly__ = {'a':1,'b':'text'}\n\n\nif __name__ == '__main__':\n def test1():\n t = ROClass()\n print t.a\n print t.b\n\n def test2():\n t = ROClass()\n t.a = 2\n\n test1()\n\nNote that if you try to set a read-only attribute (t.a = 2) python will raise an AttributeError.\n"
] |
[
10,
5,
0
] |
[] |
[] |
[
"python"
] |
stackoverflow_0001735434_python.txt
|
Q:
Why isn't psycopg2 executing any of my SQL functions? (IndexError: tuple index out of range)
I'll take the simplest of the SQL functions as an example:
CREATE OR REPLACE FUNCTION skater_name_match(INTEGER,VARCHAR)
RETURNS BOOL AS
$$
SELECT $1 IN (SELECT skaters_skater.competitor_ptr_id FROM skaters_skater
WHERE name||' '||surname ILIKE '%'||$2||'%'
OR surname||' '||name ILIKE '%'||$2||'%');
$$ LANGUAGE SQL;
If I copy and paste this into psql (PostgreSQL's shell) then it executes without any problems.
If I write a piece of Python code like this (with a real database name and user of course):
import psycopg2
sql_function_above = '''CREATE OR REPLACE FUNCTION skater_name_match(INTEGER,VARCHAR)
RETURNS BOOL AS
$$
SELECT $1 IN (SELECT skaters_skater.competitor_ptr_id FROM skaters_skater
WHERE name||' '||surname ILIKE '%'||$2||'%'
OR surname||' '||name ILIKE '%'||$2||'%');
$$ LANGUAGE SQL;'''
try:
connection = psycopg2.connect("dbname='x' user='x' host='localhost' password='x'");
except:
print "I am unable to connect to the database"
cursor = connection.cursor()
cursor.execute(sql_function_above)
It seems to execute (it doesn't give me an error), but when I look into the database the function is not there.
When I try to execute the code in Django by putting it into an app/sql/model.sql file I get the following error during syncdb:
IndexError: tuple index out of range
When I try to write my own manage.py command that would execute the sql, I get the same error.
What's going on here? Would be very grateful to anyone who could shed some light on this :) I'm still a newbie when it comes to Python and Django, so I may have overlooked something obvious.
A:
By default psycopg2 identifies argument placeholders using the % symbol (usually you'd have %s in the string).
So, if you use cursor.execute('... %s, %s ...', (arg1, arg2)) then those %s get turned into the values of arg1 and arg2 respectively.
But since you call: cursor.execute(sql_function_above), without extra arguments, and your SQL includes % signs the library is trying to find the 2nd argument passed into the function -- which is out of range, hence an IndexError.
Solution: Instead of using %, write %% in your SQL variable. This gets translated into a literal % before it's sent to PostgreSQL.
A:
Looks like you aren't committing the transaction:
Try putting:
cursor.execute("COMMIT")
After the last line and see if that works.
You can also set the isolation level to autocommit like:
connection.set_isolation_level(0)
More info on that in this answer
A:
Index out of range implies you've tried to access (for example) the third element of a tuple which only has two elements. Note that Python's indexes start at 0, so a two-element tuple named myTuple would have elements myTuple[0] and myTuple[1], but no element myTuple[2].
|
Why isn't psycopg2 executing any of my SQL functions? (IndexError: tuple index out of range)
|
I'll take the simplest of the SQL functions as an example:
CREATE OR REPLACE FUNCTION skater_name_match(INTEGER,VARCHAR)
RETURNS BOOL AS
$$
SELECT $1 IN (SELECT skaters_skater.competitor_ptr_id FROM skaters_skater
WHERE name||' '||surname ILIKE '%'||$2||'%'
OR surname||' '||name ILIKE '%'||$2||'%');
$$ LANGUAGE SQL;
If I copy and paste this into psql (PostgreSQL's shell) then it executes without any problems.
If I write a piece of Python code like this (with a real database name and user of course):
import psycopg2
sql_function_above = '''CREATE OR REPLACE FUNCTION skater_name_match(INTEGER,VARCHAR)
RETURNS BOOL AS
$$
SELECT $1 IN (SELECT skaters_skater.competitor_ptr_id FROM skaters_skater
WHERE name||' '||surname ILIKE '%'||$2||'%'
OR surname||' '||name ILIKE '%'||$2||'%');
$$ LANGUAGE SQL;'''
try:
connection = psycopg2.connect("dbname='x' user='x' host='localhost' password='x'");
except:
print "I am unable to connect to the database"
cursor = connection.cursor()
cursor.execute(sql_function_above)
It seems to execute (it doesn't give me an error), but when I look into the database the function is not there.
When I try to execute the code in Django by putting it into an app/sql/model.sql file I get the following error during syncdb:
IndexError: tuple index out of range
When I try to write my own manage.py command that would execute the sql, I get the same error.
What's going on here? Would be very grateful to anyone who could shed some light on this :) I'm still a newbie when it comes to Python and Django, so I may have overlooked something obvious.
|
[
"By default psycopg2 identifies argument placeholders using the % symbol (usually you'd have %s in the string). \nSo, if you use cursor.execute('... %s, %s ...', (arg1, arg2)) then those %s get turned into the values of arg1 and arg2 respectively.\nBut since you call: cursor.execute(sql_function_above), without extra arguments, and your SQL includes % signs the library is trying to find the 2nd argument passed into the function -- which is out of range, hence an IndexError.\nSolution: Instead of using %, write %% in your SQL variable. This gets translated into a literal % before it's sent to PostgreSQL.\n",
"Looks like you aren't committing the transaction:\nTry putting:\n\ncursor.execute(\"COMMIT\")\n\nAfter the last line and see if that works.\nYou can also set the isolation level to autocommit like:\n\nconnection.set_isolation_level(0)\n\nMore info on that in this answer\n",
"Index out of range implies you've tried to access (for example) the third element of a tuple which only has two elements. Note that Python's indexes start at 0, so a two-element tuple named myTuple would have elements myTuple[0] and myTuple[1], but no element myTuple[2].\n"
] |
[
32,
3,
1
] |
[] |
[] |
[
"django",
"postgresql",
"psycopg2",
"python",
"sql"
] |
stackoverflow_0001734814_django_postgresql_psycopg2_python_sql.txt
|
Q:
I set a proxy server on urllib2, and then I can't change it
Like the title says, my code basically does this:
set proxy, test proxy, do some cool stuff
But after the proxy is set the first time, it sticks that way, never changing. This is the failing code:
# Pick proxy
r = random.randint(0, len(proxies) - 1)
proxy = proxies[r]
print proxy
# Setup proxy
l_proxy_support = urllib2.ProxyHandler({"http": "http://{0}:{1}".format(*proxy)})
l_opener = urllib2.build_opener(l_proxy_support)
try:
l_req = l_opener.open(
urllib2.Request('http://[MYIPADDRESSHERE]/ip.php', None, agent)
)
print l_req.read()
except urllib2.URLError:
print "Proxy not functioning, aborting..."
# Do cool stuff here, not really relevant
The output ends up being:
['X.Y.Z.124', '666', 'http']
[Skarlet] Your IP address is: X.Y.Z.124
['X2.Y2.Z2.190', '666', 'http']
[Skarlet] Your IP address is: X.Y.Z.124
['X3.Y3.Z3.41', '666', 'http']
[Skarlet] Your IP address is: X.Y.Z.124
I'm really puzzled right now.
Thanks for your time.
PD: the script that responds from my home IP address is just a PHP echoing $_SERVER['REMOTE_ADDR'].
A:
That does seem strange. I've always found the httplib2 module to be the easiest Python HTTP client to work with. There is an example of using httplib2 with the socks module.
Sorry, I know this isn't a specific answer to your question, but it might be a workaround to try.
|
I set a proxy server on urllib2, and then I can't change it
|
Like the title says, my code basically does this:
set proxy, test proxy, do some cool stuff
But after the proxy is set the first time, it sticks that way, never changing. This is the failing code:
# Pick proxy
r = random.randint(0, len(proxies) - 1)
proxy = proxies[r]
print proxy
# Setup proxy
l_proxy_support = urllib2.ProxyHandler({"http": "http://{0}:{1}".format(*proxy)})
l_opener = urllib2.build_opener(l_proxy_support)
try:
l_req = l_opener.open(
urllib2.Request('http://[MYIPADDRESSHERE]/ip.php', None, agent)
)
print l_req.read()
except urllib2.URLError:
print "Proxy not functioning, aborting..."
# Do cool stuff here, not really relevant
The output ends up being:
['X.Y.Z.124', '666', 'http']
[Skarlet] Your IP address is: X.Y.Z.124
['X2.Y2.Z2.190', '666', 'http']
[Skarlet] Your IP address is: X.Y.Z.124
['X3.Y3.Z3.41', '666', 'http']
[Skarlet] Your IP address is: X.Y.Z.124
I'm really puzzled right now.
Thanks for your time.
PD: the script that responds from my home IP address is just a PHP echoing $_SERVER['REMOTE_ADDR'].
|
[
"That does seem strange. I've always found the httplib2 module to be the easiest Python HTTP client to work with. There is an example of using httplib2 with the socks module.\nSorry, I know this isn't a specific answer to your question, but it might be a workaround to try.\n"
] |
[
1
] |
[] |
[] |
[
"proxy",
"python",
"urllib2"
] |
stackoverflow_0001735852_proxy_python_urllib2.txt
|
Q:
Production quality Python opensocial container and client?
Is there any production quality library for developing opensocial containers and clients in python and django?
A:
Regarding containers, there's GAE-opensocial which can run in App Engine (should also be usable stand-alone); unfortunately it looks like django-opensocial is dormant. For clients, opensocial-python-client.
|
Production quality Python opensocial container and client?
|
Is there any production quality library for developing opensocial containers and clients in python and django?
|
[
"Regarding containers, there's GAE-opensocial which can run in App Engine (should also be usable stand-alone); unfortunately it looks like django-opensocial is dormant. For clients, opensocial-python-client.\n"
] |
[
3
] |
[] |
[] |
[
"django",
"opensocial",
"python"
] |
stackoverflow_0001735180_django_opensocial_python.txt
|
Q:
passing value to other module python
i have two script name is A.py and B.py
i want to know how to send value from A.py to B.py.
for more detail,when run finished A.py script at the end of script ,A.py call B.py.
my question is i have to send some value from A.py to B.py.
anybody some help me how to send value A.py to B.py,so i can use some value in B.py.
"Do I assume correctly that you want to have B.py to use all the variables with values
that exist when A.py finishes?"
this is what i want exactly. i was upload my A.py and B.py to pastebin site.
http://elca.pastebin.com/m618fa852 <- A.py
http://elca.pastebin.com/m50e7d527 <- B.py
i want to use B.py 's xx value, xx value is come from A.py .
sorry my english
A:
Your question isn't quite clear.
import B
B.methodToExecute(argument)
A:
Do I assume correctly that you want to have B.py to use all the variables with values that exist when A.py finishes?
[edit]
Ok, the problem is you cannot easily do this without any variable assignments. What you'd like to achieve is an import statement done backwards. Normally, if you import a module in an other module or script, the importer (in this example, A) can access the importee's (B) variables, methods etc., but not backwards.
In A.py:
a = 2
print "A.a:", a
import B
print "B.b:", B.b
from B import *
print "b in our namespace:", b
In B.py:
b = 3
This will print:
A.a: 2
B.b: 3
b in our namespace: 3
If you are 100% sure you want this (why wouldn't you create some related classes with methods, or just put the methods in one big module?), you can import module A from module B, so if you modify B.py:
In B.py:
b = 3
from A import *
print "a in B's namespace:", a
... and run it again, you'll see some weird output with double lines and the desired a in B's namespace: 2 line (so it's 50% success). The key is that if you are importing simple scripts without functions and/or module/class declaration, whenever Python imports something, the necessary objects and references will be created inside the Python VM and the imported script gets executed, so you can run into troubles with the previously done circular imports. Use modules or classes and you'll be better, because in those only the parts after
if __name__ == "__main__":
...
will be executed on import.
Or, another good idea in this thread is to call a subprocess, but then you need to check for the variables on the command line, not directly in your script's namespace.
A:
Your question might have been phrased too abstractly for me to really know what you need.
Generally, what you would do is after you've done everything in A and are read for B, you will have import A at the top of your module and call a function in A that you what taking in all the values you want to pass. If B is currently using hard-coded globals you want to override, refactor it to use functions.
|
passing value to other module python
|
i have two script name is A.py and B.py
i want to know how to send value from A.py to B.py.
for more detail,when run finished A.py script at the end of script ,A.py call B.py.
my question is i have to send some value from A.py to B.py.
anybody some help me how to send value A.py to B.py,so i can use some value in B.py.
"Do I assume correctly that you want to have B.py to use all the variables with values
that exist when A.py finishes?"
this is what i want exactly. i was upload my A.py and B.py to pastebin site.
http://elca.pastebin.com/m618fa852 <- A.py
http://elca.pastebin.com/m50e7d527 <- B.py
i want to use B.py 's xx value, xx value is come from A.py .
sorry my english
|
[
"Your question isn't quite clear.\nimport B\nB.methodToExecute(argument)\n\n",
"Do I assume correctly that you want to have B.py to use all the variables with values that exist when A.py finishes?\n[edit]\nOk, the problem is you cannot easily do this without any variable assignments. What you'd like to achieve is an import statement done backwards. Normally, if you import a module in an other module or script, the importer (in this example, A) can access the importee's (B) variables, methods etc., but not backwards.\nIn A.py:\na = 2\nprint \"A.a:\", a\nimport B\nprint \"B.b:\", B.b\nfrom B import *\nprint \"b in our namespace:\", b\n\nIn B.py:\nb = 3\n\nThis will print:\nA.a: 2\nB.b: 3\nb in our namespace: 3\n\nIf you are 100% sure you want this (why wouldn't you create some related classes with methods, or just put the methods in one big module?), you can import module A from module B, so if you modify B.py:\nIn B.py:\nb = 3\nfrom A import *\nprint \"a in B's namespace:\", a\n\n... and run it again, you'll see some weird output with double lines and the desired a in B's namespace: 2 line (so it's 50% success). The key is that if you are importing simple scripts without functions and/or module/class declaration, whenever Python imports something, the necessary objects and references will be created inside the Python VM and the imported script gets executed, so you can run into troubles with the previously done circular imports. Use modules or classes and you'll be better, because in those only the parts after\nif __name__ == \"__main__\":\n ...\n\nwill be executed on import.\nOr, another good idea in this thread is to call a subprocess, but then you need to check for the variables on the command line, not directly in your script's namespace.\n",
"Your question might have been phrased too abstractly for me to really know what you need.\nGenerally, what you would do is after you've done everything in A and are read for B, you will have import A at the top of your module and call a function in A that you what taking in all the values you want to pass. If B is currently using hard-coded globals you want to override, refactor it to use functions.\n"
] |
[
2,
1,
0
] |
[] |
[] |
[
"python"
] |
stackoverflow_0001735395_python.txt
|
Q:
How to read data from Game Port with Python?
I like programming with robots and stuff. For this approach, I'm using the LPT port for output and the Gameport for input.
For younger guys: Just some old fashioned USB Ports ;-)
Game Port http://img44.imageshack.us/img44/3650/da15dsubm.png Parallel Port http://img44.imageshack.us/img44/1369/800pxparallelport.jpg
With Python (and the fabulous module pyParallel) the output works very, very well.
Now I'd really like to get data from the Game Port (like photo tubes, temperatur sensors etc.). How can I accomplish this?
Ah, by the way: I'm using Ubuntu for all that stuff.
A:
I cannot really help you much. I don't work with joy/parallel port anymore and I forgot almost everything.
What I can tell you is that under linux, there's a specific driver and device for the joystick port. You find information about it here (google cache, the main doc is down)
http://74.125.153.132/search?q=cache:oKDIwlR1TvYJ:www.infiscape.com/~patrick/vrjuggler-config/2.0/configuring_vr_juggler/apcs05.html+joystick+device&cd=1&hl=en&ct=clnk&client=firefox-a
I am pretty confident the kernel module still exists. Once you modprobe it, you will get access to the /dev/js0 device. You will have to read from that, raw, unless you find a better library solution.
By the way, remember that you can read digital from the parallel port, if I am not mistaken. It's just unusual and hacky, and for your sensors the game port makes more sense (since you have analog input) but if you want to go digital, remember you have the choice to go parallel 100 %.
A:
Have you looked at pygame's joystick package: http://www.pygame.org/docs/ref/joystick.html ?
A:
If your just looking for controller input (USB Joystick, Gamepad, etc) PyGame has an input module that works nicely.
|
How to read data from Game Port with Python?
|
I like programming with robots and stuff. For this approach, I'm using the LPT port for output and the Gameport for input.
For younger guys: Just some old fashioned USB Ports ;-)
Game Port http://img44.imageshack.us/img44/3650/da15dsubm.png Parallel Port http://img44.imageshack.us/img44/1369/800pxparallelport.jpg
With Python (and the fabulous module pyParallel) the output works very, very well.
Now I'd really like to get data from the Game Port (like photo tubes, temperatur sensors etc.). How can I accomplish this?
Ah, by the way: I'm using Ubuntu for all that stuff.
|
[
"I cannot really help you much. I don't work with joy/parallel port anymore and I forgot almost everything.\nWhat I can tell you is that under linux, there's a specific driver and device for the joystick port. You find information about it here (google cache, the main doc is down)\nhttp://74.125.153.132/search?q=cache:oKDIwlR1TvYJ:www.infiscape.com/~patrick/vrjuggler-config/2.0/configuring_vr_juggler/apcs05.html+joystick+device&cd=1&hl=en&ct=clnk&client=firefox-a\nI am pretty confident the kernel module still exists. Once you modprobe it, you will get access to the /dev/js0 device. You will have to read from that, raw, unless you find a better library solution.\nBy the way, remember that you can read digital from the parallel port, if I am not mistaken. It's just unusual and hacky, and for your sensors the game port makes more sense (since you have analog input) but if you want to go digital, remember you have the choice to go parallel 100 %. \n",
"Have you looked at pygame's joystick package: http://www.pygame.org/docs/ref/joystick.html ?\n",
"If your just looking for controller input (USB Joystick, Gamepad, etc) PyGame has an input module that works nicely.\n"
] |
[
2,
1,
1
] |
[] |
[] |
[
"python",
"ubuntu"
] |
stackoverflow_0001734779_python_ubuntu.txt
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.