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:
Generating a List Class in Python
I am having some problems generating a list for a class in Python. I know there is something simple I'm overlooking, but I just can't figure it out.
My basic code so far:
class Test:
def __init__(self,test):
self.__test = test
My problem is that if I enter
t = Test([1,3,5])
things will work just fine, but if I add
t = Test()
I get an error that I didn't enter enough parameters.
I've tried adding
def __init__(self,test=[])
as a default parameter, which sort of works, but then I don't have unique lists.
I've been looking all over and I can't quite figure out what I'm doing wrong. Any help would be greatly appreciated.
A:
I'm not exactly sure what you're looking for, but you probably want to use None as a default:
class Test:
def __init__(self,test=None):
if test is None:
self.__test = []
else:
self.__test = test
A:
You could use the following idiom:
class Test:
def __init__(self,test=None):
self.__test = test if test is not None else []
A:
Default arguments are evaluated once, when the function is defined, so when you do:
def __init__(self, test=[]):
the 'test' list is shared between all calls to __init__ that don't specify the test argument. What you want is commonly expressed so:
def __init__(self, test=None):
if test is None:
test = []
This creates a new list for each invocation where test is not passed an argument (or when it is passed None, obviously.)
|
Generating a List Class in Python
|
I am having some problems generating a list for a class in Python. I know there is something simple I'm overlooking, but I just can't figure it out.
My basic code so far:
class Test:
def __init__(self,test):
self.__test = test
My problem is that if I enter
t = Test([1,3,5])
things will work just fine, but if I add
t = Test()
I get an error that I didn't enter enough parameters.
I've tried adding
def __init__(self,test=[])
as a default parameter, which sort of works, but then I don't have unique lists.
I've been looking all over and I can't quite figure out what I'm doing wrong. Any help would be greatly appreciated.
|
[
"I'm not exactly sure what you're looking for, but you probably want to use None as a default:\nclass Test:\n def __init__(self,test=None):\n if test is None:\n self.__test = []\n else:\n self.__test = test\n\n",
"You could use the following idiom:\nclass Test:\n def __init__(self,test=None):\n self.__test = test if test is not None else []\n\n",
"Default arguments are evaluated once, when the function is defined, so when you do:\ndef __init__(self, test=[]):\n\nthe 'test' list is shared between all calls to __init__ that don't specify the test argument. What you want is commonly expressed so:\ndef __init__(self, test=None):\n if test is None:\n test = []\n\nThis creates a new list for each invocation where test is not passed an argument (or when it is passed None, obviously.)\n"
] |
[
4,
3,
3
] |
[] |
[] |
[
"list",
"python"
] |
stackoverflow_0002675965_list_python.txt
|
Q:
Pushing data once a URL is requested
Given, when a user requests /foo on my server, I send the following HTTP response (not closing the connection):
Content-Type: multipart/x-mixed-replace; boundary=-----------------------
-----------------------
Content-Type: text/html
<a href="/bar">foo</a>
When the user goes to /bar (which will send 204 No Content so the view doesn't change), I want to send the following data in the initial response.
-----------------------
Content-Type: text/html
bar
How would I get the second request to trigger this from the initial response? I'm planning on possibly creating a fancy [engines that support multipart/x-mixed-replace (currently only Gecko)]-only email webapp that does server-push and Ajax effects without any JavaScript, just for fun.
A:
If the problem is to pass some command from /bar application to /foo application and you are using some servlet-like approach (the Python code is loaded once and not for each request as in CGI), you can just change some class property of the /foo application and be ready to react to the change in the /foo instance (by checking the property state).
Obviously the /foo application should not return right after the first request and yield content line by line.
Thought this is just theory, I have not tried that myself.
A:
No complete answer, but:
In your question, you're describing a Comet-style architecture. Regarding support of Comet-style techniques in Python/WSGI, there is a StackOverflow question, which talks about various Python servers with support for long-running requests a la Comet.
Also interesting is this mail thread in the Python Web-SIG: "Could WSGI handle Asynchronous response?". In May 2008, there was a broad discussion in the Web-SIG about the topic of asynchronous requests in WSGI.
A recent development is evserver, a lightweight WSGI server, which implements the Asynchronous WSGI extension proposed by Christopher Stawarz in the Web-SIG in May 2008.
Finally, the Tornado web server supports non-blocking asynchronous requests. It has a chat example application using long polling, which has similarities with your requirements.
A:
I have created some small example (just for fun, you know :))
import threading
num = 0
cond = threading.Condition()
def app(environ, start_response):
global num
cond.acquire()
num += 1
cond.notifyAll()
cond.release()
start_response("200 OK", [("Content-Type", "multipart/x-mixed-replace; boundary=xxx")])
while True:
n = num
s = "--xxx\r\nContent-Type: text/html\r\n\r\n%s\n" % n
yield s
# wait for num change:
cond.acquire()
while num == n:
cond.wait()
cond.release()
from cherrypy.wsgiserver import CherryPyWSGIServer
server = CherryPyWSGIServer(("0.0.0.0", 3000), app)
try:
server.start()
except KeyboardInterrupt:
server.stop()
# Now whenever you visit http://127.0.0.1:3000/, the number increases.
# It also automatically increases in all previously opened windows/tabs.
The idea of a shared variable and thread synchronization (using condition variable object) is based on the fact that WSGI server provided by CherryPyWSGIServer is threaded.
|
Pushing data once a URL is requested
|
Given, when a user requests /foo on my server, I send the following HTTP response (not closing the connection):
Content-Type: multipart/x-mixed-replace; boundary=-----------------------
-----------------------
Content-Type: text/html
<a href="/bar">foo</a>
When the user goes to /bar (which will send 204 No Content so the view doesn't change), I want to send the following data in the initial response.
-----------------------
Content-Type: text/html
bar
How would I get the second request to trigger this from the initial response? I'm planning on possibly creating a fancy [engines that support multipart/x-mixed-replace (currently only Gecko)]-only email webapp that does server-push and Ajax effects without any JavaScript, just for fun.
|
[
"If the problem is to pass some command from /bar application to /foo application and you are using some servlet-like approach (the Python code is loaded once and not for each request as in CGI), you can just change some class property of the /foo application and be ready to react to the change in the /foo instance (by checking the property state).\nObviously the /foo application should not return right after the first request and yield content line by line.\nThought this is just theory, I have not tried that myself.\n",
"No complete answer, but:\nIn your question, you're describing a Comet-style architecture. Regarding support of Comet-style techniques in Python/WSGI, there is a StackOverflow question, which talks about various Python servers with support for long-running requests a la Comet.\nAlso interesting is this mail thread in the Python Web-SIG: \"Could WSGI handle Asynchronous response?\". In May 2008, there was a broad discussion in the Web-SIG about the topic of asynchronous requests in WSGI.\nA recent development is evserver, a lightweight WSGI server, which implements the Asynchronous WSGI extension proposed by Christopher Stawarz in the Web-SIG in May 2008.\nFinally, the Tornado web server supports non-blocking asynchronous requests. It has a chat example application using long polling, which has similarities with your requirements.\n",
"I have created some small example (just for fun, you know :))\nimport threading\n\nnum = 0\ncond = threading.Condition()\n\ndef app(environ, start_response):\n global num\n\n cond.acquire()\n num += 1\n cond.notifyAll()\n cond.release()\n\n start_response(\"200 OK\", [(\"Content-Type\", \"multipart/x-mixed-replace; boundary=xxx\")])\n while True:\n n = num \n s = \"--xxx\\r\\nContent-Type: text/html\\r\\n\\r\\n%s\\n\" % n\n yield s\n # wait for num change:\n cond.acquire()\n while num == n:\n cond.wait()\n cond.release()\n\n\nfrom cherrypy.wsgiserver import CherryPyWSGIServer\nserver = CherryPyWSGIServer((\"0.0.0.0\", 3000), app)\n\ntry:\n server.start()\nexcept KeyboardInterrupt:\n server.stop()\n\n# Now whenever you visit http://127.0.0.1:3000/, the number increases.\n# It also automatically increases in all previously opened windows/tabs.\n\nThe idea of a shared variable and thread synchronization (using condition variable object) is based on the fact that WSGI server provided by CherryPyWSGIServer is threaded.\n"
] |
[
1,
1,
1
] |
[
"Not sure if this is quite what you're looking for, but there is a fairly old way of doing server push using a mime content of multipart/x-mixed-replace \nBasically you compose the response as a mime object with content type multipart/x-mixed-replace, and send the first \"version\" of a document down. The browser will keep the socket open. \nThen as the server decides to push more data, a new \"version\" of the document gets sent from the server, and the browser will intelligently replace (within whatever frame/iframe contains the content) the content. \nThis was an early way of doing webcams, where the server would send down (push) image after image, and the browser would just keep replacing the image in the document over and over. This is also a way of doing a \"Loading...\" message over a single HTTP request.\n"
] |
[
-1
] |
[
"python",
"wsgi"
] |
stackoverflow_0002576715_python_wsgi.txt
|
Q:
In which scenario it is useful to use Disassembly on python?
The dis module can be effectively used to disassemble Python methods, functions and classes into low-level interpreter instructions.
I know that dis information can be used for:
1. Find race condition in programs that use threads
2. Find possible optimizations
From your experience, do you know any other scenarios where Disassembly Python feature could be useful?
A:
dis is useful, for example, when you have different code doing the same thing and you wonder where the performance difference lies in.
Example: list += [item] vs list.append(item)
def f(x): return 2*x
def f1(func, nums):
result = []
for item in nums:
result += [fun(item)]
return result
def f2(func, nums):
result = []
for item in nums:
result.append(fun(item))
return result
timeit.timeit says that f2(f, range(100)) is approximately twice as fast than f1(f, range(100). Why?
(Interestingly f2 is roughly as fast as map(f, range(100)) is.)
f1
You can see the whole output of dis by calling dis.dis(f1), here is line 4.
4 19 LOAD_FAST 2 (result)
22 LOAD_FAST 1 (fun)
25 LOAD_FAST 3 (item)
28 CALL_FUNCTION 1
31 BUILD_LIST 1
34 INPLACE_ADD
35 STORE_FAST 2 (result)
38 JUMP_ABSOLUTE 13
>> 41 POP_BLOCK
f2
Again, here is only line 4:
4 19 LOAD_FAST 2 (result)
22 LOAD_ATTR 0 (append)
25 LOAD_FAST 1 (fun)
28 LOAD_FAST 3 (item)
31 CALL_FUNCTION 1
34 CALL_FUNCTION 1
37 POP_TOP
38 JUMP_ABSOLUTE 13
>> 41 POP_BLOCK
Spot the difference
In f1 we need to:
Call fun on item (opcode 28)
Make a list out of it (opcode 31, expensive!)
Add it to result (opcode 34)
Store the returned value in result (opcode 35)
In f2, instead, we just:
Call fun on item (opcode 31)
Call append on result (opcode 34; C code: fast!)
This explains why the (imho) more expressive list += [value] is much slower than the list.append() method.
Other than that, dis.dis is mainly useful for curiosity and for trying to reconstruct code out of .pyc files you don't have the source of without spending a fortune :)
A:
I see the dis module as being, essentially, a learning tool. Understanding what opcodes a certain snippet of Python code generates is a start to getting more "depth" to your grasp of Python -- rooting the "abstract" understanding of its semantics into a sample of (a bit more) concrete implementation. Sometimes the exact reason a certain Python snippet behaves the way it does may be hard to grasp "top-down" with pure reasoning from the "rules" of Python semantics: in such cases, reinforcing the study with some "bottom-up" verification (based on a possible implementation, of course -- other implementations would also be possible;-) can really help the study's effectiveness.
A:
For day-to-day Python programming, not much. However, it is useful if you want to find out why doing something one way is faster than another way. I've also sometimes used it to figure out exactly how the interpreter handles some obscure bits of code. But really, I come up with a practical use-case for it very infrequently.
On the other hand, if your goal is to understand python rather than just being able to program in it, then it is an invaluable tool. For instance, ever wonder how function definition works? Here you go:
>>> def f():
... def foo(x=[1, 2, 3]):
... y = [4,]
... return x + y
...
>>> dis(f)
2 0 LOAD_CONST 1 (1)
3 LOAD_CONST 2 (2)
6 LOAD_CONST 3 (3)
9 BUILD_LIST 3
12 LOAD_CONST 4 (<code object foo at 0xb7690770, file "<stdin>", line 2>)
15 MAKE_FUNCTION 1
18 STORE_FAST 0 (foo)
21 LOAD_CONST 0 (None)
24 RETURN_VALUE
You can see that this happens by pushing the constants 1, 2, and 3 onto the stack, putting what's in the stack into a list, loading that into a code object, making the code function into an object, and storing it into a variable foo.
|
In which scenario it is useful to use Disassembly on python?
|
The dis module can be effectively used to disassemble Python methods, functions and classes into low-level interpreter instructions.
I know that dis information can be used for:
1. Find race condition in programs that use threads
2. Find possible optimizations
From your experience, do you know any other scenarios where Disassembly Python feature could be useful?
|
[
"dis is useful, for example, when you have different code doing the same thing and you wonder where the performance difference lies in.\nExample: list += [item] vs list.append(item)\ndef f(x): return 2*x\n\ndef f1(func, nums):\n result = []\n for item in nums:\n result += [fun(item)]\n return result\n\ndef f2(func, nums): \n result = []\n for item in nums:\n result.append(fun(item))\n return result\n\ntimeit.timeit says that f2(f, range(100)) is approximately twice as fast than f1(f, range(100). Why?\n(Interestingly f2 is roughly as fast as map(f, range(100)) is.)\nf1\nYou can see the whole output of dis by calling dis.dis(f1), here is line 4.\n 4 19 LOAD_FAST 2 (result)\n 22 LOAD_FAST 1 (fun)\n 25 LOAD_FAST 3 (item)\n 28 CALL_FUNCTION 1 \n 31 BUILD_LIST 1 \n 34 INPLACE_ADD \n 35 STORE_FAST 2 (result) \n 38 JUMP_ABSOLUTE 13 \n >> 41 POP_BLOCK \n\nf2\nAgain, here is only line 4:\n 4 19 LOAD_FAST 2 (result)\n 22 LOAD_ATTR 0 (append)\n 25 LOAD_FAST 1 (fun)\n 28 LOAD_FAST 3 (item)\n 31 CALL_FUNCTION 1 \n 34 CALL_FUNCTION 1 \n 37 POP_TOP \n 38 JUMP_ABSOLUTE 13 \n >> 41 POP_BLOCK \n\nSpot the difference\nIn f1 we need to:\n\nCall fun on item (opcode 28)\nMake a list out of it (opcode 31, expensive!)\nAdd it to result (opcode 34)\nStore the returned value in result (opcode 35)\n\nIn f2, instead, we just:\n\nCall fun on item (opcode 31)\nCall append on result (opcode 34; C code: fast!)\n\nThis explains why the (imho) more expressive list += [value] is much slower than the list.append() method.\n\nOther than that, dis.dis is mainly useful for curiosity and for trying to reconstruct code out of .pyc files you don't have the source of without spending a fortune :)\n",
"I see the dis module as being, essentially, a learning tool. Understanding what opcodes a certain snippet of Python code generates is a start to getting more \"depth\" to your grasp of Python -- rooting the \"abstract\" understanding of its semantics into a sample of (a bit more) concrete implementation. Sometimes the exact reason a certain Python snippet behaves the way it does may be hard to grasp \"top-down\" with pure reasoning from the \"rules\" of Python semantics: in such cases, reinforcing the study with some \"bottom-up\" verification (based on a possible implementation, of course -- other implementations would also be possible;-) can really help the study's effectiveness.\n",
"For day-to-day Python programming, not much. However, it is useful if you want to find out why doing something one way is faster than another way. I've also sometimes used it to figure out exactly how the interpreter handles some obscure bits of code. But really, I come up with a practical use-case for it very infrequently.\nOn the other hand, if your goal is to understand python rather than just being able to program in it, then it is an invaluable tool. For instance, ever wonder how function definition works? Here you go:\n>>> def f():\n... def foo(x=[1, 2, 3]):\n... y = [4,]\n... return x + y\n... \n>>> dis(f)\n 2 0 LOAD_CONST 1 (1)\n 3 LOAD_CONST 2 (2)\n 6 LOAD_CONST 3 (3)\n 9 BUILD_LIST 3\n 12 LOAD_CONST 4 (<code object foo at 0xb7690770, file \"<stdin>\", line 2>)\n 15 MAKE_FUNCTION 1\n 18 STORE_FAST 0 (foo)\n 21 LOAD_CONST 0 (None)\n 24 RETURN_VALUE \n\nYou can see that this happens by pushing the constants 1, 2, and 3 onto the stack, putting what's in the stack into a list, loading that into a code object, making the code function into an object, and storing it into a variable foo.\n"
] |
[
7,
5,
3
] |
[] |
[] |
[
"assembly",
"python"
] |
stackoverflow_0002676154_assembly_python.txt
|
Q:
Objects array with numpy
are there any way to create an object form any class inside a numpy array?. Something like:
a = zeros(4)
for i in range(4):
a[i]=Register()
Thanks
A:
Yes, you can do this:
a = numpy.array([Register() for _ in range(4)])
Here, a.dtype is dtype('object').
Alternatively, if you really need to reserve memory for your array and then build it element by element, you can do:
a = numpy.empty(shape=(4,), dtype=object)
a[0] = Register() # etc.
A:
The items in numpy arrays are statically typed, and when you call zeros you make an array of floats. To store arbitrary Python objects, use code like
numpy.array([Register() for i in range(4)])
which makes an array with dtype=object, which you could also specify manually.
Consider whether you really want numpy in this case. I don't know how close this example is to your use case, but oftentimes a numpy array of dtype object, especially a one-dimensional one, would work at least as well as a list.
|
Objects array with numpy
|
are there any way to create an object form any class inside a numpy array?. Something like:
a = zeros(4)
for i in range(4):
a[i]=Register()
Thanks
|
[
"Yes, you can do this:\na = numpy.array([Register() for _ in range(4)])\n\nHere, a.dtype is dtype('object').\nAlternatively, if you really need to reserve memory for your array and then build it element by element, you can do:\na = numpy.empty(shape=(4,), dtype=object)\na[0] = Register() # etc.\n\n",
"The items in numpy arrays are statically typed, and when you call zeros you make an array of floats. To store arbitrary Python objects, use code like\nnumpy.array([Register() for i in range(4)])\n\nwhich makes an array with dtype=object, which you could also specify manually.\nConsider whether you really want numpy in this case. I don't know how close this example is to your use case, but oftentimes a numpy array of dtype object, especially a one-dimensional one, would work at least as well as a list.\n"
] |
[
17,
5
] |
[] |
[] |
[
"arrays",
"numpy",
"python"
] |
stackoverflow_0002674139_arrays_numpy_python.txt
|
Q:
How do you throw an HTTP error with mod_python
I have a setup where I'm serving simple python pages using the mod_python publisher. At some points I'd like to have the python function raise a standard apache error - for example throwing a 500 error if a required file is missing. How can I throw an apache error from within a mod_python script?
A:
I am not a python expert but from this documentation, it would appear that you can do:
raise apache.SERVER_RETURN, apache.HTTP_INTERNAL_SERVER_ERROR
Here is a quote of the documentation in case of link rot:
A handler function will always be passed a reference to a request
object. (Throughout this manual, the request object is often referred
to by the req variable.)
Every handler can return:
apache.OK, meaning this phase of the request was handled by this
handler and no errors occurred.
apache.DECLINED, meaning this handler has not handled this phase of
the request to completion and Apache needs to look for another handler
in subsequent modules.
apache.HTTP_ERROR, meaning an HTTP error occurred. HTTP_ERROR can be
any of the following:
HTTP_CONTINUE = 100
HTTP_SWITCHING_PROTOCOLS = 101
HTTP_PROCESSING = 102
HTTP_OK = 200
HTTP_CREATED = 201
HTTP_ACCEPTED = 202
HTTP_NON_AUTHORITATIVE = 203
HTTP_NO_CONTENT = 204
HTTP_RESET_CONTENT = 205
HTTP_PARTIAL_CONTENT = 206
HTTP_MULTI_STATUS = 207
HTTP_MULTIPLE_CHOICES = 300
HTTP_MOVED_PERMANENTLY = 301
HTTP_MOVED_TEMPORARILY = 302
HTTP_SEE_OTHER = 303
HTTP_NOT_MODIFIED = 304
HTTP_USE_PROXY = 305
HTTP_TEMPORARY_REDIRECT = 307
HTTP_BAD_REQUEST = 400
HTTP_UNAUTHORIZED = 401
HTTP_PAYMENT_REQUIRED = 402
HTTP_FORBIDDEN = 403
HTTP_NOT_FOUND = 404
HTTP_METHOD_NOT_ALLOWED = 405
HTTP_NOT_ACCEPTABLE = 406
HTTP_PROXY_AUTHENTICATION_REQUIRED= 407
HTTP_REQUEST_TIME_OUT = 408
HTTP_CONFLICT = 409
HTTP_GONE = 410
HTTP_LENGTH_REQUIRED = 411
HTTP_PRECONDITION_FAILED = 412
HTTP_REQUEST_ENTITY_TOO_LARGE = 413
HTTP_REQUEST_URI_TOO_LARGE = 414
HTTP_UNSUPPORTED_MEDIA_TYPE = 415
HTTP_RANGE_NOT_SATISFIABLE = 416
HTTP_EXPECTATION_FAILED = 417
HTTP_UNPROCESSABLE_ENTITY = 422
HTTP_LOCKED = 423
HTTP_FAILED_DEPENDENCY = 424
HTTP_INTERNAL_SERVER_ERROR = 500
HTTP_NOT_IMPLEMENTED = 501
HTTP_BAD_GATEWAY = 502
HTTP_SERVICE_UNAVAILABLE = 503
HTTP_GATEWAY_TIME_OUT = 504
HTTP_VERSION_NOT_SUPPORTED = 505
HTTP_VARIANT_ALSO_VARIES = 506
HTTP_INSUFFICIENT_STORAGE = 507
HTTP_NOT_EXTENDED = 510
As an alternative to returning an HTTP error code, handlers can signal
an error by raising the apache.SERVER_RETURN exception, and providing
an HTTP error code as the exception value, e.g.:
raise apache.SERVER_RETURN, apache.HTTP_FORBIDDEN
A:
I believe it's:
def my_action(req):
# all the status code constants are defined in the apache module
req.status = apache.HTTP_INTERNAL_SERVER_ERROR
req.content_type = some_mime_type
req.write(content)
raise apache.HTTP_SERVER_RETURN, apache.DONE
raising apache.DONE tells Apache not to write out its own error page.
|
How do you throw an HTTP error with mod_python
|
I have a setup where I'm serving simple python pages using the mod_python publisher. At some points I'd like to have the python function raise a standard apache error - for example throwing a 500 error if a required file is missing. How can I throw an apache error from within a mod_python script?
|
[
"I am not a python expert but from this documentation, it would appear that you can do:\nraise apache.SERVER_RETURN, apache.HTTP_INTERNAL_SERVER_ERROR\n\nHere is a quote of the documentation in case of link rot:\n\nA handler function will always be passed a reference to a request\n object. (Throughout this manual, the request object is often referred\n to by the req variable.)\nEvery handler can return:\napache.OK, meaning this phase of the request was handled by this\n handler and no errors occurred.\napache.DECLINED, meaning this handler has not handled this phase of\n the request to completion and Apache needs to look for another handler\n in subsequent modules.\napache.HTTP_ERROR, meaning an HTTP error occurred. HTTP_ERROR can be\n any of the following:\nHTTP_CONTINUE = 100\nHTTP_SWITCHING_PROTOCOLS = 101\nHTTP_PROCESSING = 102\nHTTP_OK = 200\nHTTP_CREATED = 201\nHTTP_ACCEPTED = 202\nHTTP_NON_AUTHORITATIVE = 203\nHTTP_NO_CONTENT = 204\nHTTP_RESET_CONTENT = 205\nHTTP_PARTIAL_CONTENT = 206\nHTTP_MULTI_STATUS = 207\nHTTP_MULTIPLE_CHOICES = 300\nHTTP_MOVED_PERMANENTLY = 301\nHTTP_MOVED_TEMPORARILY = 302\nHTTP_SEE_OTHER = 303\nHTTP_NOT_MODIFIED = 304\nHTTP_USE_PROXY = 305\nHTTP_TEMPORARY_REDIRECT = 307\nHTTP_BAD_REQUEST = 400\nHTTP_UNAUTHORIZED = 401\nHTTP_PAYMENT_REQUIRED = 402\nHTTP_FORBIDDEN = 403\nHTTP_NOT_FOUND = 404\nHTTP_METHOD_NOT_ALLOWED = 405\nHTTP_NOT_ACCEPTABLE = 406\nHTTP_PROXY_AUTHENTICATION_REQUIRED= 407\nHTTP_REQUEST_TIME_OUT = 408\nHTTP_CONFLICT = 409\nHTTP_GONE = 410\nHTTP_LENGTH_REQUIRED = 411\nHTTP_PRECONDITION_FAILED = 412\nHTTP_REQUEST_ENTITY_TOO_LARGE = 413\nHTTP_REQUEST_URI_TOO_LARGE = 414\nHTTP_UNSUPPORTED_MEDIA_TYPE = 415\nHTTP_RANGE_NOT_SATISFIABLE = 416\nHTTP_EXPECTATION_FAILED = 417\nHTTP_UNPROCESSABLE_ENTITY = 422\nHTTP_LOCKED = 423\nHTTP_FAILED_DEPENDENCY = 424\nHTTP_INTERNAL_SERVER_ERROR = 500\nHTTP_NOT_IMPLEMENTED = 501\nHTTP_BAD_GATEWAY = 502\nHTTP_SERVICE_UNAVAILABLE = 503\nHTTP_GATEWAY_TIME_OUT = 504\nHTTP_VERSION_NOT_SUPPORTED = 505\nHTTP_VARIANT_ALSO_VARIES = 506\nHTTP_INSUFFICIENT_STORAGE = 507\nHTTP_NOT_EXTENDED = 510\n\nAs an alternative to returning an HTTP error code, handlers can signal\n an error by raising the apache.SERVER_RETURN exception, and providing\n an HTTP error code as the exception value, e.g.:\nraise apache.SERVER_RETURN, apache.HTTP_FORBIDDEN\n\n\n",
"I believe it's:\ndef my_action(req):\n # all the status code constants are defined in the apache module \n req.status = apache.HTTP_INTERNAL_SERVER_ERROR \n req.content_type = some_mime_type\n req.write(content)\n raise apache.HTTP_SERVER_RETURN, apache.DONE\n\nraising apache.DONE tells Apache not to write out its own error page.\n"
] |
[
2,
1
] |
[] |
[] |
[
"apache",
"http_error",
"mod_python",
"python"
] |
stackoverflow_0002520659_apache_http_error_mod_python_python.txt
|
Q:
Long running, polling, queueing process for Python. What's the best stuff to use?
Feel free to close and/or redirect if this has been asked, but here's my situation:
I've got an application that will require doing a bunch of small units of work (polling a web service until something is done, then parsing about 1MB worth of XML and putting it in a database). I want to have a simple async queueing mechanism that'll poll for work to do in a queue, execute the units of work that need to be done, and have the flexibility to allow for spawning multiple worker processes so these units of work can be done in parallel. (Bonus if there's some kind of event framework that would also me to listen for when work is complete.)
I'm sure there is stuff to do this. Am I describing Twisted? I poked through the documentation, I'm just not sure exactly how my problems maps onto their framework, but I haven't spent much time with it. Should I just look at the multiprocess libraries in Python? Something else?
A:
There's celery.
You could break it down into 2 different Tasks: one to poll the web service and queue the second task, which would be in charge of parsing the XML and persisting it.
A:
This problem sounds like a pretty good candidate for Python's built-in (2.6+ anyway) multiprocessing module: http://docs.python.org/library/multiprocessing.html
A simple solution would be to create a process Pool and use your main program to poll for the XML chunks. Once it has them it can then pass them off to the pool for parsing/persisting.
|
Long running, polling, queueing process for Python. What's the best stuff to use?
|
Feel free to close and/or redirect if this has been asked, but here's my situation:
I've got an application that will require doing a bunch of small units of work (polling a web service until something is done, then parsing about 1MB worth of XML and putting it in a database). I want to have a simple async queueing mechanism that'll poll for work to do in a queue, execute the units of work that need to be done, and have the flexibility to allow for spawning multiple worker processes so these units of work can be done in parallel. (Bonus if there's some kind of event framework that would also me to listen for when work is complete.)
I'm sure there is stuff to do this. Am I describing Twisted? I poked through the documentation, I'm just not sure exactly how my problems maps onto their framework, but I haven't spent much time with it. Should I just look at the multiprocess libraries in Python? Something else?
|
[
"There's celery.\nYou could break it down into 2 different Tasks: one to poll the web service and queue the second task, which would be in charge of parsing the XML and persisting it.\n",
"This problem sounds like a pretty good candidate for Python's built-in (2.6+ anyway) multiprocessing module: http://docs.python.org/library/multiprocessing.html\nA simple solution would be to create a process Pool and use your main program to poll for the XML chunks. Once it has them it can then pass them off to the pool for parsing/persisting.\n"
] |
[
4,
0
] |
[] |
[] |
[
"python"
] |
stackoverflow_0002676057_python.txt
|
Q:
Facebook API non-interactive authorization/login
i'm trying to build a facebook API client using python, code follows:
import os
import urllib2
import urllib
import cookielib
import hashlib
import json
USER = ''
PASS = ''
LOGIN = 'http://www.facebook.com/login.php?login_attempt=1'
HOST = 'http://api.facebook.com/restserver.php'
API_KEY = 'eca5c767f0e5b65942419574374c34a4'
SECRET_KEY = 'e2aab4000e08f4199f3ca6793ab4f02c'
def getSig(params, secret):
sigStr = ''
for k in sorted(params.keys()):
sigStr += k + '=' + params[k]
sigStr += secret
return hashlib.md5(sigStr).hexdigest()
def call(host, params):
basicParams = {'api_key': API_KEY,
'format': 'JSON',
'v': '1.0'}
basicParams.update(params)
basicParams['sig'] = getSig(basicParams, SECRET_KEY)
finalParams = urllib.urlencode(basicParams)
cj = cookielib.LWPCookieJar()
opener = urllib2.build_opener(urllib2.HTTPCookieProcessor(cj), urllib2.HTTPRedirectHandler)
urllib2.install_opener(opener)
request = urllib2.Request(host)
request.add_header('User-Agent', 'Mozilla/5.0 (X11; U; Linux x86_64; en-US; rv:1.9.1.9) Gecko/20100402 Ubuntu/9.10 (karmic) Firefox/3.5.9')
request.add_header('Content-Type', 'application/x-www-form-urlencoded')
h = urllib2.urlopen(request, finalParams)
return h.read()
def getToken():
paramsRaw = {'method': 'Auth.createToken',
'api_key': API_KEY,
}
ret = call(HOST, paramsRaw)
return json.loads(ret)
def login(user, password, token):
# post login form
paramsRaw = {
'auth_token': token,
'email': user,
'pass': password,
}
call(LOGIN, paramsRaw)
def getSession(token):
paramsRaw = {'method': 'Auth.getSession',
'auth_token': token
}
print call(HOST, paramsRaw)
def main():
token = getToken()
login(USER, PASS, token)
getSession(token)
main()
I'm basically receiving a token from Auth.createToken, POSTing it with USER/PASS to facebook.com/login.php and sending the same token to Auth.getSession (as outlined here: http://wiki.developers.facebook.com/index.php/Auth.createToken)
But getSession returns error 100 ("Invalid parameter"), what am i doing wrong? Are there any examples of similar programs on the web?
A:
You also need a call_id parameter which can be based on time.time(), as well as a method parameter.
|
Facebook API non-interactive authorization/login
|
i'm trying to build a facebook API client using python, code follows:
import os
import urllib2
import urllib
import cookielib
import hashlib
import json
USER = ''
PASS = ''
LOGIN = 'http://www.facebook.com/login.php?login_attempt=1'
HOST = 'http://api.facebook.com/restserver.php'
API_KEY = 'eca5c767f0e5b65942419574374c34a4'
SECRET_KEY = 'e2aab4000e08f4199f3ca6793ab4f02c'
def getSig(params, secret):
sigStr = ''
for k in sorted(params.keys()):
sigStr += k + '=' + params[k]
sigStr += secret
return hashlib.md5(sigStr).hexdigest()
def call(host, params):
basicParams = {'api_key': API_KEY,
'format': 'JSON',
'v': '1.0'}
basicParams.update(params)
basicParams['sig'] = getSig(basicParams, SECRET_KEY)
finalParams = urllib.urlencode(basicParams)
cj = cookielib.LWPCookieJar()
opener = urllib2.build_opener(urllib2.HTTPCookieProcessor(cj), urllib2.HTTPRedirectHandler)
urllib2.install_opener(opener)
request = urllib2.Request(host)
request.add_header('User-Agent', 'Mozilla/5.0 (X11; U; Linux x86_64; en-US; rv:1.9.1.9) Gecko/20100402 Ubuntu/9.10 (karmic) Firefox/3.5.9')
request.add_header('Content-Type', 'application/x-www-form-urlencoded')
h = urllib2.urlopen(request, finalParams)
return h.read()
def getToken():
paramsRaw = {'method': 'Auth.createToken',
'api_key': API_KEY,
}
ret = call(HOST, paramsRaw)
return json.loads(ret)
def login(user, password, token):
# post login form
paramsRaw = {
'auth_token': token,
'email': user,
'pass': password,
}
call(LOGIN, paramsRaw)
def getSession(token):
paramsRaw = {'method': 'Auth.getSession',
'auth_token': token
}
print call(HOST, paramsRaw)
def main():
token = getToken()
login(USER, PASS, token)
getSession(token)
main()
I'm basically receiving a token from Auth.createToken, POSTing it with USER/PASS to facebook.com/login.php and sending the same token to Auth.getSession (as outlined here: http://wiki.developers.facebook.com/index.php/Auth.createToken)
But getSession returns error 100 ("Invalid parameter"), what am i doing wrong? Are there any examples of similar programs on the web?
|
[
"You also need a call_id parameter which can be based on time.time(), as well as a method parameter. \n"
] |
[
1
] |
[] |
[] |
[
"facebook",
"python"
] |
stackoverflow_0002674202_facebook_python.txt
|
Q:
Elegant way to collapse or expand sub-sequences of a list in Python?
I want to collapse or expand sub-sequences of a list
e.g. ['A', 'B', 'D', 'E', 'H'] -> ['AB', 'DE', 'H'] and vice versa
EDIT: the example above may cause misunderstanding. the following is better:
e.g. ['foo', 'bar', 'wtf'] <-> ['baz', 'wtf']
currently I wrote some ugly code like:
while True:
for i, x in enumerate(s):
if x == 'foo' and s[i+1] == 'bar':
s[i:i+2] = 'baz'
break
else:
break
For people who asking 'why do that thing':
Actually I'm working on a optimizing compiler and this is the peephole part.
Writing pattern matching is a little annoying.
P.S. I found the following code works, but a bit ridiculous, why enumerate know our modification?
s = ['foo', 'bar', 'wtf', 'foo', 'bar', 'wtf', 'foo', 'bar', 'wtf']
def collapse():
for i, x in enumerate(s):
if s[i] == 'foo' and s[i+1] == 'bar':
s[i:i+2] = ['baz']
def expand():
for i, x in enumerate(s):
if s[i] == 'baz':
s[i:i+1] = ['foo', 'bar']
collapse()
print s
expand()
print s
A:
I wouldn't call this much better but it's a different way to do it, and it also handles the quirk Justin points out. (I was more interested in finding a subsequence from a list, and I couldn't find a good function on Google)
def findsubseq(L, subseq):
if not subseq: return # just die on zero-len input
i = -1
try:
while True:
i = L.index(subseq[0], i+1)
for j in range(1, len(subseq)):
if L[i+j] != subseq[j]:
break
else:
yield i
except ValueError: pass
except IndexError: pass
def replace(target, changethis, tothis):
subseqs = [x for x in findsubseq(target, changethis)]
subseqs.reverse()
for i in subseqs:
target[i:i+len(changethis)] = tothis
def collapse():
global s
replace(s, ['foo', 'bar'], ['baz'])
def expand():
global s
replace(s, ['baz'], ['foo', 'bar'])
s = ['foo', 'bar', 'wtf', 'foo', 'bar', 'wtf',
'foo', 'bar', 'bar', 'bar', 'foo']
print s
collapse()
print s
expand()
print s
C:\Scripts>subseq.py
['foo', 'bar', 'wtf', 'foo', 'bar', 'wtf', 'foo', 'bar', 'bar', 'bar', 'foo']
['baz', 'wtf', 'baz', 'wtf', 'baz', 'bar', 'bar', 'foo']
['foo', 'bar', 'wtf', 'foo', 'bar', 'wtf', 'foo', 'bar', 'bar', 'bar', 'foo']
Edit: generalized it to just a simple replace function
A:
See itertools. Specifically, here's a recipe for more or less what you want (actually, what I thought you wanted after your kind of misleading original post!):
from itertools import tee, izip
def pairwise(iterable):
"s -> (s0,s1), (s1,s2), (s2, s3), ..."
a, b = tee(iterable)
next(b, None)
return izip(a, b)
This will return tuples which you can join().
To undo this, just join() your final sequence and iterate over the individual items (chars).
I will try to come up with an answer to your new/real question.
A:
I think that your way with enumerate is pretty good actually. Enumerate is able to keep track of the modifications because it creates a generator that uses an iterator of the array you input. The problem I see is if you change your array to be:
s = ['foo', 'bar', 'wtf', 'foo', 'bar', 'wtf', 'foo']
then the last 'foo' that doesn't have a 'bar' will give you an exception when your code tries to look at the item beyond the end of the array. I'm not sure how to fix this yet because my attempts haven't been successful.
Edit:
It may not be very elegant, but this code for the collapse() function will work even on the above case:
def collapse():
i = 1
L = len(s)
while i < L:
if s[i-1] == 'foo' and s[i] == 'bar':
s[i-1:i+1] = ['baz']
L -= 1
i += 1
|
Elegant way to collapse or expand sub-sequences of a list in Python?
|
I want to collapse or expand sub-sequences of a list
e.g. ['A', 'B', 'D', 'E', 'H'] -> ['AB', 'DE', 'H'] and vice versa
EDIT: the example above may cause misunderstanding. the following is better:
e.g. ['foo', 'bar', 'wtf'] <-> ['baz', 'wtf']
currently I wrote some ugly code like:
while True:
for i, x in enumerate(s):
if x == 'foo' and s[i+1] == 'bar':
s[i:i+2] = 'baz'
break
else:
break
For people who asking 'why do that thing':
Actually I'm working on a optimizing compiler and this is the peephole part.
Writing pattern matching is a little annoying.
P.S. I found the following code works, but a bit ridiculous, why enumerate know our modification?
s = ['foo', 'bar', 'wtf', 'foo', 'bar', 'wtf', 'foo', 'bar', 'wtf']
def collapse():
for i, x in enumerate(s):
if s[i] == 'foo' and s[i+1] == 'bar':
s[i:i+2] = ['baz']
def expand():
for i, x in enumerate(s):
if s[i] == 'baz':
s[i:i+1] = ['foo', 'bar']
collapse()
print s
expand()
print s
|
[
"I wouldn't call this much better but it's a different way to do it, and it also handles the quirk Justin points out. (I was more interested in finding a subsequence from a list, and I couldn't find a good function on Google)\ndef findsubseq(L, subseq):\n if not subseq: return # just die on zero-len input\n i = -1\n try:\n while True:\n i = L.index(subseq[0], i+1)\n for j in range(1, len(subseq)):\n if L[i+j] != subseq[j]:\n break\n else:\n yield i\n except ValueError: pass\n except IndexError: pass\n\ndef replace(target, changethis, tothis):\n subseqs = [x for x in findsubseq(target, changethis)]\n subseqs.reverse()\n for i in subseqs:\n target[i:i+len(changethis)] = tothis\ndef collapse():\n global s\n replace(s, ['foo', 'bar'], ['baz'])\ndef expand():\n global s\n replace(s, ['baz'], ['foo', 'bar'])\n\ns = ['foo', 'bar', 'wtf', 'foo', 'bar', 'wtf',\n 'foo', 'bar', 'bar', 'bar', 'foo']\nprint s\ncollapse()\nprint s\nexpand()\nprint s\n\n\nC:\\Scripts>subseq.py\n['foo', 'bar', 'wtf', 'foo', 'bar', 'wtf', 'foo', 'bar', 'bar', 'bar', 'foo']\n['baz', 'wtf', 'baz', 'wtf', 'baz', 'bar', 'bar', 'foo']\n['foo', 'bar', 'wtf', 'foo', 'bar', 'wtf', 'foo', 'bar', 'bar', 'bar', 'foo']\n\nEdit: generalized it to just a simple replace function\n",
"See itertools. Specifically, here's a recipe for more or less what you want (actually, what I thought you wanted after your kind of misleading original post!):\nfrom itertools import tee, izip\n\ndef pairwise(iterable):\n \"s -> (s0,s1), (s1,s2), (s2, s3), ...\"\n a, b = tee(iterable)\n next(b, None)\n return izip(a, b)\n\nThis will return tuples which you can join().\nTo undo this, just join() your final sequence and iterate over the individual items (chars).\nI will try to come up with an answer to your new/real question.\n",
"I think that your way with enumerate is pretty good actually. Enumerate is able to keep track of the modifications because it creates a generator that uses an iterator of the array you input. The problem I see is if you change your array to be:\ns = ['foo', 'bar', 'wtf', 'foo', 'bar', 'wtf', 'foo']\n\nthen the last 'foo' that doesn't have a 'bar' will give you an exception when your code tries to look at the item beyond the end of the array. I'm not sure how to fix this yet because my attempts haven't been successful.\nEdit:\nIt may not be very elegant, but this code for the collapse() function will work even on the above case:\ndef collapse():\n i = 1\n L = len(s)\n while i < L:\n if s[i-1] == 'foo' and s[i] == 'bar':\n s[i-1:i+1] = ['baz']\n L -= 1\n i += 1\n\n"
] |
[
2,
1,
0
] |
[] |
[] |
[
"compiler_construction",
"design_patterns",
"list",
"python"
] |
stackoverflow_0002674647_compiler_construction_design_patterns_list_python.txt
|
Q:
Google App Engine: JSON module
I'm using JSON with Google App Engine.
I'm using JSON for comunication, so on the Python side I have:
import json
The error I'm getting is this:
<class 'django.core.exceptions.ViewDoesNotExist'>: Could not import views.ganttapp. Error was: No module named json
In my stand-alone this works great. Is there any problem with JSON on Google App Engine? Or should I use another module?
I don't know if you can open this, but here it goes: http://ganttapp.appspot.com/newgantt. You can find the error here.
A:
Maybe you can import the Django simplejson wrapper:
from django.utils import simplejson
|
Google App Engine: JSON module
|
I'm using JSON with Google App Engine.
I'm using JSON for comunication, so on the Python side I have:
import json
The error I'm getting is this:
<class 'django.core.exceptions.ViewDoesNotExist'>: Could not import views.ganttapp. Error was: No module named json
In my stand-alone this works great. Is there any problem with JSON on Google App Engine? Or should I use another module?
I don't know if you can open this, but here it goes: http://ganttapp.appspot.com/newgantt. You can find the error here.
|
[
"Maybe you can import the Django simplejson wrapper:\nfrom django.utils import simplejson\n\n"
] |
[
17
] |
[] |
[] |
[
"django",
"google_app_engine",
"json",
"python"
] |
stackoverflow_0002676767_django_google_app_engine_json_python.txt
|
Q:
What version of Visual Studio is Python on my computer compiled with?
I am trying to find out the version of Visual Studio that is used to compile the Python on my computer
It says
Python 2.6.2 (r262:71605, Apr 14 2009, 22:40:02) [MSC v.1500 32 bit (Intel)] on win32
What I do not understand is this MSC V.1500 designation. Does it mean it is compiled with Visual Studio 2005? I cannot find this information on http://python.org.
A:
Visual C++ version
_MSC_VER
Visual C++ 4.x
1000
Visual C++ 5
1100
Visual C++ 6
1200
Visual C++ .NET
1300
Visual C++ .NET 2003
1310
Visual C++ 2005 (8.0)
1400
Visual C++ 2008 (9.0)
1500
Visual C++ 2010 (10.0)
1600
Visual C++ 2012 (11.0)
1700
Visual C++ 2013 (12.0)
1800
Visual C++ 2015 (14.0)
1900
Visual C++ 2017 (15.0)
1910
Visual C++ 2017 (15.3)
1911
Visual C++ 2017 (15.5)
1912
Visual C++ 2017 (15.6)
1913
Visual C++ 2017 (15.7)
1914
Visual C++ 2017 (15.8)
1915
Visual C++ 2017 (15.9)
1916
Visual C++ 2019 RTW (16.0)
1920
Visual C++ 2019 (16.1)
1921
Visual C++ 2019 (16.2)
1922
Visual C++ 2019 (16.3)
1923
Visual C++ 2019 (16.4)
1924
Visual C++ 2019 (16.5)
1925
Visual C++ 2019 (16.6)
1926
Visual C++ 2019 (16.7)
1927
Visual C++ 2019 (16.8)
1928
Visual C++ 2019 (16.9)
1928
Visual C++ 2019 (16.10)
1929
Visual C++ 2019 (16.11)
1929
Visual Studio 2022 RTW (17.0)
1930
Source: the documentation for the _MSC_VER predefined macro
A:
MSC v.1500 appears to be Visual C++ 2008 according to this thread on the OpenCobol forums (of all places).
The MSDN page on Predefined Macros indicates 1500 to be the result of the _MSC_VER macro.
This other forum post mentions that
(For reference, Visual Studio 2003 has _MSC_VER = 1310; Visual Studio 2005 has _MSC_VER = 1400; Visual Studio 2008 has _MSC_VER = 1500.)
The above MSDN link said that 1600 indicates VS2010.
Strangely, I wasn't able to find that info about the earlier _MSC_VER values on MSDN.
|
What version of Visual Studio is Python on my computer compiled with?
|
I am trying to find out the version of Visual Studio that is used to compile the Python on my computer
It says
Python 2.6.2 (r262:71605, Apr 14 2009, 22:40:02) [MSC v.1500 32 bit (Intel)] on win32
What I do not understand is this MSC V.1500 designation. Does it mean it is compiled with Visual Studio 2005? I cannot find this information on http://python.org.
|
[
"\n\n\n\nVisual C++ version\n_MSC_VER\n\n\n\n\nVisual C++ 4.x\n1000\n\n\nVisual C++ 5\n1100\n\n\nVisual C++ 6\n1200\n\n\nVisual C++ .NET\n1300\n\n\nVisual C++ .NET 2003\n1310\n\n\nVisual C++ 2005 (8.0)\n1400\n\n\nVisual C++ 2008 (9.0)\n1500\n\n\nVisual C++ 2010 (10.0)\n1600\n\n\nVisual C++ 2012 (11.0)\n1700\n\n\nVisual C++ 2013 (12.0)\n1800\n\n\nVisual C++ 2015 (14.0)\n1900\n\n\nVisual C++ 2017 (15.0)\n1910\n\n\nVisual C++ 2017 (15.3)\n1911\n\n\nVisual C++ 2017 (15.5)\n1912\n\n\nVisual C++ 2017 (15.6)\n1913\n\n\nVisual C++ 2017 (15.7)\n1914\n\n\nVisual C++ 2017 (15.8)\n1915\n\n\nVisual C++ 2017 (15.9)\n1916\n\n\nVisual C++ 2019 RTW (16.0)\n1920\n\n\nVisual C++ 2019 (16.1)\n1921\n\n\nVisual C++ 2019 (16.2)\n1922\n\n\nVisual C++ 2019 (16.3)\n1923\n\n\nVisual C++ 2019 (16.4)\n1924\n\n\nVisual C++ 2019 (16.5)\n1925\n\n\nVisual C++ 2019 (16.6)\n1926\n\n\nVisual C++ 2019 (16.7)\n1927\n\n\nVisual C++ 2019 (16.8)\n1928\n\n\nVisual C++ 2019 (16.9)\n1928\n\n\nVisual C++ 2019 (16.10)\n1929\n\n\nVisual C++ 2019 (16.11)\n1929\n\n\nVisual Studio 2022 RTW (17.0)\n1930\n\n\n\n\nSource: the documentation for the _MSC_VER predefined macro\n",
"MSC v.1500 appears to be Visual C++ 2008 according to this thread on the OpenCobol forums (of all places). \nThe MSDN page on Predefined Macros indicates 1500 to be the result of the _MSC_VER macro.\nThis other forum post mentions that \n\n(For reference, Visual Studio 2003 has _MSC_VER = 1310; Visual Studio 2005 has _MSC_VER = 1400; Visual Studio 2008 has _MSC_VER = 1500.) \n\nThe above MSDN link said that 1600 indicates VS2010.\nStrangely, I wasn't able to find that info about the earlier _MSC_VER values on MSDN.\n"
] |
[
184,
13
] |
[] |
[] |
[
"python",
"visual_c++",
"visual_studio",
"windows"
] |
stackoverflow_0002676763_python_visual_c++_visual_studio_windows.txt
|
Q:
Sorting HTML table (with anchor tags and data in cells) in Python
I have a necessity to sort a given HTML table of the following structure, in Python.
<table>
<tr>
<td><a href="#">ABCD</a></td>
<td>A23BND</td>
<td><a title="ABCD">345345</td>
</tr>
<tr>
<td><a href="#">EFG</a></td>
<td>Add4D</td>
<td><a title="EFG">3432</td>
</tr>
<tr>
<td><a href="#">HG</a></td>
<td>GJJ778</td>
<td><a title="HG">2341333</td>
</tr>
</table>
I am doing something like this:
container = tree.findall("tr")
strOut = ""
data = []
for elem in container:
key = elem.findtext(colName)
data.append((key, elem))
data.sort()
The problem is that it sorts by the text inside the <td>. I want to be able to sort by the anchor value and not href.
What can I do to achieve that? Thanks a lot.
A:
It sorts by the text because that's what you're extracting as the key when you do
key = elem.findtext(colName)
I imagine colName is some tag string, and findtext will just find the text of the first subelement matching that tag. If what you want instead is to use as the key the value of some attribute (e.g. title?) of an <a>,
for ana in elem.findall('a'):
key = ana.get('title')
if key is not None: break
Would do that. Exactly what do you want to use as the key?
A:
The sort method has the valueable key and cmp arguments which you can use for custom sorting. If you augment the data data structure with the extra information you need for sorting, you can use either key or cmp (depending on exact need) in the call to sort to achieve what you want. Here's a simple example:
In [60]: ids = [1, 2, 3]
In [61]: score = {1: 20, 2: 70, 3: 40}
In [62]: ids.sort(key=lambda x: score[x])
In [63]: ids
Out[63]: [1, 3, 2]
Here, I sorted the ids list according to the score of each id taken from the score dictionary.
A:
I know this wasn't your question, but best practice for this sort of thing is to use Javascript. You will get a much better user experience on your website (if that's what you're doing).
This js library is excellent and easy to use:
http://www.kryogenix.org/code/browser/sorttable/
|
Sorting HTML table (with anchor tags and data in cells) in Python
|
I have a necessity to sort a given HTML table of the following structure, in Python.
<table>
<tr>
<td><a href="#">ABCD</a></td>
<td>A23BND</td>
<td><a title="ABCD">345345</td>
</tr>
<tr>
<td><a href="#">EFG</a></td>
<td>Add4D</td>
<td><a title="EFG">3432</td>
</tr>
<tr>
<td><a href="#">HG</a></td>
<td>GJJ778</td>
<td><a title="HG">2341333</td>
</tr>
</table>
I am doing something like this:
container = tree.findall("tr")
strOut = ""
data = []
for elem in container:
key = elem.findtext(colName)
data.append((key, elem))
data.sort()
The problem is that it sorts by the text inside the <td>. I want to be able to sort by the anchor value and not href.
What can I do to achieve that? Thanks a lot.
|
[
"It sorts by the text because that's what you're extracting as the key when you do\nkey = elem.findtext(colName)\n\nI imagine colName is some tag string, and findtext will just find the text of the first subelement matching that tag. If what you want instead is to use as the key the value of some attribute (e.g. title?) of an <a>,\nfor ana in elem.findall('a'):\n key = ana.get('title')\n if key is not None: break\n\nWould do that. Exactly what do you want to use as the key?\n",
"The sort method has the valueable key and cmp arguments which you can use for custom sorting. If you augment the data data structure with the extra information you need for sorting, you can use either key or cmp (depending on exact need) in the call to sort to achieve what you want. Here's a simple example:\nIn [60]: ids = [1, 2, 3]\nIn [61]: score = {1: 20, 2: 70, 3: 40}\nIn [62]: ids.sort(key=lambda x: score[x])\nIn [63]: ids\nOut[63]: [1, 3, 2]\n\nHere, I sorted the ids list according to the score of each id taken from the score dictionary.\n",
"I know this wasn't your question, but best practice for this sort of thing is to use Javascript. You will get a much better user experience on your website (if that's what you're doing).\nThis js library is excellent and easy to use:\n http://www.kryogenix.org/code/browser/sorttable/\n"
] |
[
1,
0,
0
] |
[] |
[] |
[
"html",
"html_table",
"python",
"sorting"
] |
stackoverflow_0002578971_html_html_table_python_sorting.txt
|
Q:
Stealing Cookies with no user input?
I'm creating a static site generator with a dynamic admin backend for one user. The site accepts no user input. Does this mean that I am safe from attackers who are trying to steal my admin cookie?
(there is no user input, so XSS and other methods don't work, right?)
A:
If there's no user input (no links to click that have any effects, etc.), how does the admin backend qualify as "dynamic"?
But basically: No, not unless you're using HTTPS. Even if you're not accepting input, the cookie is transmitted in plaintext and so can be captured (by a man-in-the-middle attack, etc.) and used. (I assume you don't want other people using the cookie to see the admin stuff.)
Or did I completely misunderstand the question? ;-)
A:
The following feature is a point of vulnerability. This could be a vector in which could be accessed in a nefarious means using CSRF. Malicious JavaScript maybe introduced by performing a CSRF->Stored XSS attack.
There is an "admin dashboard" where I
can edit the contents of existing
entries or add in new ones.
The problem being that when you are authenticated to this administrative console a hacker can still access this feature by "riding" on your authenticated session and this is the basis of CSRF. In short, the attacker doesn't need to know your session id because your browser does! By visiting a malicious website an attacker can force your browser into sending an http request to your administrative console. In order to pull off this attack the attacker must know the server, the path to the script, and all of the POST/GET parameters, but he doesn't need your password or cookie. If this is an in-house administrative console that this is an unlikely attack vector. But its easy to defend against. The easiest method would be to check the http referer of an http request that is making this "content modification", Motorola does this for many of their network appliances. A more common approach is to use a "csrf token".
CSRF is still a problem if you are using basic-auth via an .htaccess file or a cookie based auth. No matter what you need to prevent malicious forged requests and protect against sniffing by using HTTPS. This is gone into greater detail in the OWASP Top 10, make sure to read "A3: Broken Authentication and Session Management".
|
Stealing Cookies with no user input?
|
I'm creating a static site generator with a dynamic admin backend for one user. The site accepts no user input. Does this mean that I am safe from attackers who are trying to steal my admin cookie?
(there is no user input, so XSS and other methods don't work, right?)
|
[
"If there's no user input (no links to click that have any effects, etc.), how does the admin backend qualify as \"dynamic\"?\nBut basically: No, not unless you're using HTTPS. Even if you're not accepting input, the cookie is transmitted in plaintext and so can be captured (by a man-in-the-middle attack, etc.) and used. (I assume you don't want other people using the cookie to see the admin stuff.)\nOr did I completely misunderstand the question? ;-)\n",
"The following feature is a point of vulnerability. This could be a vector in which could be accessed in a nefarious means using CSRF. Malicious JavaScript maybe introduced by performing a CSRF->Stored XSS attack.\n\nThere is an \"admin dashboard\" where I\n can edit the contents of existing\n entries or add in new ones.\n\nThe problem being that when you are authenticated to this administrative console a hacker can still access this feature by \"riding\" on your authenticated session and this is the basis of CSRF. In short, the attacker doesn't need to know your session id because your browser does! By visiting a malicious website an attacker can force your browser into sending an http request to your administrative console. In order to pull off this attack the attacker must know the server, the path to the script, and all of the POST/GET parameters, but he doesn't need your password or cookie. If this is an in-house administrative console that this is an unlikely attack vector. But its easy to defend against. The easiest method would be to check the http referer of an http request that is making this \"content modification\", Motorola does this for many of their network appliances. A more common approach is to use a \"csrf token\".\nCSRF is still a problem if you are using basic-auth via an .htaccess file or a cookie based auth. No matter what you need to prevent malicious forged requests and protect against sniffing by using HTTPS. This is gone into greater detail in the OWASP Top 10, make sure to read \"A3: Broken Authentication and Session Management\".\n"
] |
[
1,
0
] |
[] |
[] |
[
"python",
"security",
"xss"
] |
stackoverflow_0002676747_python_security_xss.txt
|
Q:
Explaining Python variable scope
I'm teaching myself Python and I was translating some sample code into this
class Student(object):
def __init__( self, name, a,b,c ):
self.name = name
self.a = a
self.b = b
self.c = c
def average(self):
return ( a+b+c ) / 3.0
Which is pretty much my intended class definition.
Later in the main method I create an instance and call it a:
if __name__ == "__main__" :
a = Student( "Oscar", 10, 10, 10 )
That's how I find out that the variable a declared in main is available to the method average and to make that method work, I have to type self.a + self.b + self.c instead.
What's the rationale for this?
A:
Barenames (like a, b, c) are always scoped as local or global (save for nested functions, which are nowhere around in your code). The rationale is that adding further scopes would needlessly make things more complicated -- e.g, if in your self.a = a the barename a could be scoped to mean what you appear to want (equivalent to self.a) then the assignment itself would be meaningless (assigning a name to itself), so you'd need further complicated rules.
Just using qualified names (like self.a) when you want something different than barenames' simple, straightforward, and optimized behavior, is by far the simplest approach -- perfectly workable, no complicated rules whatsoever, and allows the compiler to optimize things effectively (since e.g. a barename's scope is always lexically determined, not dependent on dynamically varying characteristics of the environment). So, besides perhaps nostalgia for other language with more complicated scoping rules, there's really no rationale for complicating the semantics of barenames.
A:
There are several reasons, though the main one is from the Zen of Python: "Explicit is better than implicit." In a language like C++, a method on the class always has an implicit argument this which is pushed onto the stack every time the method is called. In this case, when an instance variable b exists as well as a global variable b, then the user may just refer to b referring to one without realizing that the other will be used. So Python forces you to be explicit about your scope to avoid confusion.
With that being said, there are other reasons as well. For example, I may define a function outside of a class and then attach it to a class at runtime. For example:
def log(self):
print "some library function requires all objects to have a log method"
print "unfortunately we're using the Student class, which doesn't have one"
print "this class is defined in a separate library, so we can't add the method"
print "fortunately, we can just add the method dynamically at runtime"
Student.log = log
Here the fact that self is explicit makes it trivial for us to define a function outside of a class and then attach it to that class. I don't do this sort of thing incredibly often, but it's EXTREMELY useful when I do.
Here's an even more complex example; suppose we want to define a class inside another class, such as for the purposes of unit testing:
class SomeUnitTests(TestCase):
def test_something(self):
class SomeMockObject(SomeActualObject):
def foo(self2):
self.assertEqual(self2.x, SOME_CONSTANT)
some_lib.do_something_with(SomeMockObject)
Here the presence of an explicit self (which we can call whatever we want, it doesn't have to be self) allows to to distinguish between the self of the inner and outer classes. Again, this isn't something I do frequently, but when I do then it's incredibly useful.
|
Explaining Python variable scope
|
I'm teaching myself Python and I was translating some sample code into this
class Student(object):
def __init__( self, name, a,b,c ):
self.name = name
self.a = a
self.b = b
self.c = c
def average(self):
return ( a+b+c ) / 3.0
Which is pretty much my intended class definition.
Later in the main method I create an instance and call it a:
if __name__ == "__main__" :
a = Student( "Oscar", 10, 10, 10 )
That's how I find out that the variable a declared in main is available to the method average and to make that method work, I have to type self.a + self.b + self.c instead.
What's the rationale for this?
|
[
"Barenames (like a, b, c) are always scoped as local or global (save for nested functions, which are nowhere around in your code). The rationale is that adding further scopes would needlessly make things more complicated -- e.g, if in your self.a = a the barename a could be scoped to mean what you appear to want (equivalent to self.a) then the assignment itself would be meaningless (assigning a name to itself), so you'd need further complicated rules.\nJust using qualified names (like self.a) when you want something different than barenames' simple, straightforward, and optimized behavior, is by far the simplest approach -- perfectly workable, no complicated rules whatsoever, and allows the compiler to optimize things effectively (since e.g. a barename's scope is always lexically determined, not dependent on dynamically varying characteristics of the environment). So, besides perhaps nostalgia for other language with more complicated scoping rules, there's really no rationale for complicating the semantics of barenames.\n",
"There are several reasons, though the main one is from the Zen of Python: \"Explicit is better than implicit.\" In a language like C++, a method on the class always has an implicit argument this which is pushed onto the stack every time the method is called. In this case, when an instance variable b exists as well as a global variable b, then the user may just refer to b referring to one without realizing that the other will be used. So Python forces you to be explicit about your scope to avoid confusion.\nWith that being said, there are other reasons as well. For example, I may define a function outside of a class and then attach it to a class at runtime. For example:\ndef log(self):\n print \"some library function requires all objects to have a log method\"\n print \"unfortunately we're using the Student class, which doesn't have one\"\n print \"this class is defined in a separate library, so we can't add the method\"\n print \"fortunately, we can just add the method dynamically at runtime\"\n\nStudent.log = log\n\nHere the fact that self is explicit makes it trivial for us to define a function outside of a class and then attach it to that class. I don't do this sort of thing incredibly often, but it's EXTREMELY useful when I do.\nHere's an even more complex example; suppose we want to define a class inside another class, such as for the purposes of unit testing:\nclass SomeUnitTests(TestCase):\n def test_something(self):\n class SomeMockObject(SomeActualObject):\n def foo(self2):\n self.assertEqual(self2.x, SOME_CONSTANT)\n\n some_lib.do_something_with(SomeMockObject)\n\nHere the presence of an explicit self (which we can call whatever we want, it doesn't have to be self) allows to to distinguish between the self of the inner and outer classes. Again, this isn't something I do frequently, but when I do then it's incredibly useful.\n"
] |
[
10,
2
] |
[
"All instance variables should be called using self\n"
] |
[
-1
] |
[
"python",
"scope"
] |
stackoverflow_0002677545_python_scope.txt
|
Q:
Why use Python interactive mode?
When I first started reading about Python, all of the tutorials have you use Python's Interactive Mode. It is difficult to save, write long programs, or edit your existing lines (for me at least). It seems like a far more difficult way of writing Python code than opening up a code.py file and running the interpreter on that file.
python code.py
I am coming from a Java background, so I have ingrained expectations of writing and compiling files for programs. I also know that a feature would not be so prominent in Python documentation if it were not somehow useful. So what am I missing?
A:
Let's see:
If you want to know how something works, you can just try it. There is no need to write up a file. I almost always scratch write my programs in the interpreter before coding them. It's not just for things that you don't know how they work in the programming language. I never remember what the correct arguments to range are to create, for example, [-2, -1, 0, 1]. I don't need to. I just have to fire up the interpreter and try stuff until I figure out it is range(-2, 2) (did that just now, actually).
You can use it as a calculator.
Python is a very introspective programming language. If you want to know anything about an object, you can just do dir(object). If you use IPython, you can even do object.<TAB> and it will tab-complete the methods and attributes of that object. That's way faster than looking stuff up in documentation or even in code.
help(anything) for documentation. It's way faster than any web interface.
Again, you have to use IPython (highly recommended), but you can time stuff. %timeit func1() and %timeit func2() is a common idiom to determine what is faster.
How often have you wanted to write a program to use once, and then never again. The fastest way to do this is to just do it in the Python interpreter. Sure, you have to be careful writing loops or functions (they must have the correct syntax the first time), but most stuff is just line by line, and you can play around with it.
Debugging. You don't need to put selective print statements in code to see what variables are when you write it in the interpreter. You just have to type >>> a, and it will show what a is. Nice again to see if you constructed something correctly. The building Python debugger pdb also uses the intrepeter functionality, so you can not only see what a variable is when debugging, but you can also manipulate or even change it without halting debugging.
When people say that Python is faster to develop in, I guarantee that this is a big part of what they are talking about.
Commenters: anything I am forgetting?
A:
REPL Loops (like Python's interactive mode) provide immediate feedback to the programmer. As such, you can rapidly write and test small pieces of code, and assemble those pieces into a larger program.
A:
You're talking about running Python in the console by simply typing "python"? That's just for little tests and for practicing with the language. It's very useful when learning the language and testing out other modules.
Of course any real software project is written in .py files and later executed by the interpreter!
A:
The Python interpreter is a least common denominator: you can run it on multiple platforms, and it acts the same way (modulo platform-specific modules), so it's pretty easy to get a newbie going with.
It's a lot easier to tell a newbie to launch the interpreter and "do this" than to have them open a file, type in some code, save it, make it executable, make sure python is in your PATH, or use a #! line, etc etc. Scrap all of that and just launch the interpreter. For simple examples, you can't beat it. It was never meant for long programs, so if you were using it for that, you probably missed the part of the tutorial that told you "longer scripts go in a file". :)
A:
you use the interactive interpreter to test snippets of your code before you put them into your script.
A:
I find the interactive interpreter very, very good for testing quick code, or to show others the Power of Python. Sometimes I use the interpreter as a handy calculator, too. It's amazing what you can do in a very short amount of time.
Aside from the built-in console, I also have to recommend Pyshell. It has auto-completion, and a decent syntax highlighting. You can also edit multiple lines of code at once. Of course, it's not perfect, but certainly better than the default python console.
A:
As already mentioned, the Python interactive interpreter gives a quick and dirty way to test simple Python functions and/or code snippets.
I personally use the Python shell as a very quick way to perform simple Numerical operations (provided by the math module). I have my environment setup, so that the math module is automatically imported whenever I start a Python shell. In fact, its a good way to "market" Python to non-Pythoniasts. Show them how they can use Python as a neat scientific calculator, and for simple mathematical prototyping.
A:
One thing I use interactive mode for that others haven't mentioned: To see if a module is installed. Just fire up Python and try to import the module; if it dies, then your PYTHONPATH is broke or the module is not installed.
This is a great first step for "Hey, it's not working on my machine" or "Which Python did that get installed in, anyway" bugs.
A:
When coding in Java, you almost always will have the API open in some browser window. However with the python interpreter, you can always import any module that you are thinking about using and check what it offers. You can also test the behavior of new methods that you are unsure of, to eliminate the "Oh! so THAT's how it works" as a source of bugs.
A:
Interactive mode makes it easy to test code snippets before incorporating them into a larger program. If you use IDLE there's syntax highlighting and argument pop-ups to help you out. It's also a quick way of checking that you've figured out how to use a module without having to write a test program.
|
Why use Python interactive mode?
|
When I first started reading about Python, all of the tutorials have you use Python's Interactive Mode. It is difficult to save, write long programs, or edit your existing lines (for me at least). It seems like a far more difficult way of writing Python code than opening up a code.py file and running the interpreter on that file.
python code.py
I am coming from a Java background, so I have ingrained expectations of writing and compiling files for programs. I also know that a feature would not be so prominent in Python documentation if it were not somehow useful. So what am I missing?
|
[
"Let's see:\n\nIf you want to know how something works, you can just try it. There is no need to write up a file. I almost always scratch write my programs in the interpreter before coding them. It's not just for things that you don't know how they work in the programming language. I never remember what the correct arguments to range are to create, for example, [-2, -1, 0, 1]. I don't need to. I just have to fire up the interpreter and try stuff until I figure out it is range(-2, 2) (did that just now, actually).\nYou can use it as a calculator. \nPython is a very introspective programming language. If you want to know anything about an object, you can just do dir(object). If you use IPython, you can even do object.<TAB> and it will tab-complete the methods and attributes of that object. That's way faster than looking stuff up in documentation or even in code.\nhelp(anything) for documentation. It's way faster than any web interface. \nAgain, you have to use IPython (highly recommended), but you can time stuff. %timeit func1() and %timeit func2() is a common idiom to determine what is faster. \nHow often have you wanted to write a program to use once, and then never again. The fastest way to do this is to just do it in the Python interpreter. Sure, you have to be careful writing loops or functions (they must have the correct syntax the first time), but most stuff is just line by line, and you can play around with it.\nDebugging. You don't need to put selective print statements in code to see what variables are when you write it in the interpreter. You just have to type >>> a, and it will show what a is. Nice again to see if you constructed something correctly. The building Python debugger pdb also uses the intrepeter functionality, so you can not only see what a variable is when debugging, but you can also manipulate or even change it without halting debugging. \n\nWhen people say that Python is faster to develop in, I guarantee that this is a big part of what they are talking about.\nCommenters: anything I am forgetting?\n",
"REPL Loops (like Python's interactive mode) provide immediate feedback to the programmer. As such, you can rapidly write and test small pieces of code, and assemble those pieces into a larger program.\n",
"You're talking about running Python in the console by simply typing \"python\"? That's just for little tests and for practicing with the language. It's very useful when learning the language and testing out other modules.\nOf course any real software project is written in .py files and later executed by the interpreter!\n",
"The Python interpreter is a least common denominator: you can run it on multiple platforms, and it acts the same way (modulo platform-specific modules), so it's pretty easy to get a newbie going with. \nIt's a lot easier to tell a newbie to launch the interpreter and \"do this\" than to have them open a file, type in some code, save it, make it executable, make sure python is in your PATH, or use a #! line, etc etc. Scrap all of that and just launch the interpreter. For simple examples, you can't beat it. It was never meant for long programs, so if you were using it for that, you probably missed the part of the tutorial that told you \"longer scripts go in a file\". :) \n",
"you use the interactive interpreter to test snippets of your code before you put them into your script.\n",
"I find the interactive interpreter very, very good for testing quick code, or to show others the Power of Python. Sometimes I use the interpreter as a handy calculator, too. It's amazing what you can do in a very short amount of time.\nAside from the built-in console, I also have to recommend Pyshell. It has auto-completion, and a decent syntax highlighting. You can also edit multiple lines of code at once. Of course, it's not perfect, but certainly better than the default python console.\n",
"As already mentioned, the Python interactive interpreter gives a quick and dirty way to test simple Python functions and/or code snippets. \nI personally use the Python shell as a very quick way to perform simple Numerical operations (provided by the math module). I have my environment setup, so that the math module is automatically imported whenever I start a Python shell. In fact, its a good way to \"market\" Python to non-Pythoniasts. Show them how they can use Python as a neat scientific calculator, and for simple mathematical prototyping.\n",
"One thing I use interactive mode for that others haven't mentioned: To see if a module is installed. Just fire up Python and try to import the module; if it dies, then your PYTHONPATH is broke or the module is not installed.\nThis is a great first step for \"Hey, it's not working on my machine\" or \"Which Python did that get installed in, anyway\" bugs.\n",
"When coding in Java, you almost always will have the API open in some browser window. However with the python interpreter, you can always import any module that you are thinking about using and check what it offers. You can also test the behavior of new methods that you are unsure of, to eliminate the \"Oh! so THAT's how it works\" as a source of bugs.\n",
"Interactive mode makes it easy to test code snippets before incorporating them into a larger program. If you use IDLE there's syntax highlighting and argument pop-ups to help you out. It's also a quick way of checking that you've figured out how to use a module without having to write a test program.\n"
] |
[
39,
14,
5,
2,
2,
2,
2,
2,
1,
0
] |
[] |
[] |
[
"interactive_mode",
"python",
"python_interactive"
] |
stackoverflow_0002664785_interactive_mode_python_python_interactive.txt
|
Q:
How to reload Django models without losing my locals in an interactive session?
I'm doing some research with an interactive shell and using a Django app (shell_plus) for storing data and browsing it using the convenient admin.
Occasionally I add or change some of the app models, and run a syncdb (or South migration when changing a model). The changes to the models don't take effect in my interactive session even if I re-import the app models. Thus I'm forced to restart the shell_plus and lose my precious locals() in the process.
Is there any way to reload the models during a session?
Thanks!!
A:
You can use this snippet to rebuild the AppCache. Do not forget to remove all *.pyc files if any by using something like:
find . -name "*.pyc" -exec rm {} \;
Otherwise the reload() will ignore your changes in your models.py file.
|
How to reload Django models without losing my locals in an interactive session?
|
I'm doing some research with an interactive shell and using a Django app (shell_plus) for storing data and browsing it using the convenient admin.
Occasionally I add or change some of the app models, and run a syncdb (or South migration when changing a model). The changes to the models don't take effect in my interactive session even if I re-import the app models. Thus I'm forced to restart the shell_plus and lose my precious locals() in the process.
Is there any way to reload the models during a session?
Thanks!!
|
[
"You can use this snippet to rebuild the AppCache. Do not forget to remove all *.pyc files if any by using something like:\nfind . -name \"*.pyc\" -exec rm {} \\;\n\nOtherwise the reload() will ignore your changes in your models.py file.\n"
] |
[
1
] |
[] |
[] |
[
"django",
"ipython",
"module",
"python"
] |
stackoverflow_0002677649_django_ipython_module_python.txt
|
Q:
Scraping data from Flash (Games)
I saw this video, and I am really curious how it was performed. Does anyone have any ideas? My intuition is that he scraped pixels from the screen (one per 'box'), and then fed that into some program to determine the next move.
Is scraping pixel-by-pixel the way to do this, or is there a better way? I am looking to do something similar with either Java or Python.
Thanks
A:
Yes, i think he scanned the pixels. Actually it should be very simple because you only need to scan the new shape for each move. With that information you can locally calculate the grid and further use it for your AI calculations.
A:
Probably that's the most reliable way. There are ways to inspect what is happening inside a process - looking directly at its internal state and memory - but they are platform-specific and very prone to misbehaving because your dealing with a slightly different version of something - that includes a different flash version as well as a different version of the app. Those methods are more often used for "trainers" for exe games, where there's typically only one or two versions of the executable to worry about.
Lots of screen shots, comparing, figuring out reliable indicator pixels seems the way to go - plus keeping track of what you expect to happen, of course. When the app is running, it should work from a screenshot at a time (hopefully ensuring a consistent picture, with no half-updated views) and then test the minimum number of pixels needed using (perhaps) a decision tree.
There are ways to automate construction of efficient decision trees, but it's probably easier to do it manually based on comparing screen shots. In this case, since Tetris normally creates all new pieces at the same position, with a 1:1 relationship between colour and shape, you can probably determine the shape and position of a new piece from a single pixel colour - so "decision tree" is probably the wrong term, really, in this case - though there are other things the bot needs to read from the screen.
What's more interesting is the logic to actually make gameplay decisions, since that bot clearly isn't just slotting every piece into the most immediately obvious position, but deliberately aiming to create opportunities to clear 3 or 4 rows at a time.
|
Scraping data from Flash (Games)
|
I saw this video, and I am really curious how it was performed. Does anyone have any ideas? My intuition is that he scraped pixels from the screen (one per 'box'), and then fed that into some program to determine the next move.
Is scraping pixel-by-pixel the way to do this, or is there a better way? I am looking to do something similar with either Java or Python.
Thanks
|
[
"Yes, i think he scanned the pixels. Actually it should be very simple because you only need to scan the new shape for each move. With that information you can locally calculate the grid and further use it for your AI calculations.\n",
"Probably that's the most reliable way. There are ways to inspect what is happening inside a process - looking directly at its internal state and memory - but they are platform-specific and very prone to misbehaving because your dealing with a slightly different version of something - that includes a different flash version as well as a different version of the app. Those methods are more often used for \"trainers\" for exe games, where there's typically only one or two versions of the executable to worry about.\nLots of screen shots, comparing, figuring out reliable indicator pixels seems the way to go - plus keeping track of what you expect to happen, of course. When the app is running, it should work from a screenshot at a time (hopefully ensuring a consistent picture, with no half-updated views) and then test the minimum number of pixels needed using (perhaps) a decision tree.\nThere are ways to automate construction of efficient decision trees, but it's probably easier to do it manually based on comparing screen shots. In this case, since Tetris normally creates all new pieces at the same position, with a 1:1 relationship between colour and shape, you can probably determine the shape and position of a new piece from a single pixel colour - so \"decision tree\" is probably the wrong term, really, in this case - though there are other things the bot needs to read from the screen.\nWhat's more interesting is the logic to actually make gameplay decisions, since that bot clearly isn't just slotting every piece into the most immediately obvious position, but deliberately aiming to create opportunities to clear 3 or 4 rows at a time.\n"
] |
[
2,
2
] |
[] |
[] |
[
"flash",
"java",
"python",
"screen_scraping"
] |
stackoverflow_0002678091_flash_java_python_screen_scraping.txt
|
Q:
Slow XML-RPC in Windows 7 with XML-RPC.NET
I'm considering to use XML-RPC.NET to communicate with a Linux XML-RPC server written in Python. I have tried a sample application (MathApp) from Cook Computing's XML-RPC.NET but it took 30 seconds for the app to add two numbers within the same LAN with server.
I have also tried to run a simple client written in Python on Windows 7 to call the same server and it responded in 5 seconds. The machine has 4 GB of RAM with comparable processing power so this is not an issue.
Then I tried to call the server from a Windows XP system with Java and PHP. Both responses were pretty fast, almost instantly. The server was responding quickly on localhost too, so I don't think the latency arise from server.
My googling returned me some problems regarding Windows' use of IPv6 but our call to server does include IPv4 address (not hostname) in the same subnet. Anyways I turned off IPv6 but nothing changed.
Are there any more ways to check for possible causes of latency?
A:
There is a bug that affects BaseHTTPServer and its subclasses (including SimpleXMLRPCServer). Basically, your server is likely to call socket.getfqdn function for every IP address it is trying to log. This article probably explains it better.
The workaround describes there, for TL;DR:
import BaseHTTPServer
def not_insane_address_string(self):
host, port = self.client_address[:2]
return '%s (no getfqdn)' % host #used to call: socket.getfqdn(host)
BaseHTTPServer.BaseHTTPRequestHandler.address_string = \
not_insane_address_string
A:
Run a packet capture on the client machine, check the network traffic timings versus the time the function is called.
This may help you determine where the latency is in your slow process, e.g. application start-up time, name resolution, etc.
How are you addressing the server from the client? By IP? By FQDN? Is the addressing method the same in each of the applications your using?
If you call the same remote procedure multiple times from the same slow application, does the time taken increase linearly?
|
Slow XML-RPC in Windows 7 with XML-RPC.NET
|
I'm considering to use XML-RPC.NET to communicate with a Linux XML-RPC server written in Python. I have tried a sample application (MathApp) from Cook Computing's XML-RPC.NET but it took 30 seconds for the app to add two numbers within the same LAN with server.
I have also tried to run a simple client written in Python on Windows 7 to call the same server and it responded in 5 seconds. The machine has 4 GB of RAM with comparable processing power so this is not an issue.
Then I tried to call the server from a Windows XP system with Java and PHP. Both responses were pretty fast, almost instantly. The server was responding quickly on localhost too, so I don't think the latency arise from server.
My googling returned me some problems regarding Windows' use of IPv6 but our call to server does include IPv4 address (not hostname) in the same subnet. Anyways I turned off IPv6 but nothing changed.
Are there any more ways to check for possible causes of latency?
|
[
"There is a bug that affects BaseHTTPServer and its subclasses (including SimpleXMLRPCServer). Basically, your server is likely to call socket.getfqdn function for every IP address it is trying to log. This article probably explains it better.\nThe workaround describes there, for TL;DR:\nimport BaseHTTPServer\ndef not_insane_address_string(self):\n host, port = self.client_address[:2]\n return '%s (no getfqdn)' % host #used to call: socket.getfqdn(host)\nBaseHTTPServer.BaseHTTPRequestHandler.address_string = \\\n not_insane_address_string\n\n",
"Run a packet capture on the client machine, check the network traffic timings versus the time the function is called.\nThis may help you determine where the latency is in your slow process, e.g. application start-up time, name resolution, etc.\nHow are you addressing the server from the client? By IP? By FQDN? Is the addressing method the same in each of the applications your using?\nIf you call the same remote procedure multiple times from the same slow application, does the time taken increase linearly?\n"
] |
[
2,
0
] |
[] |
[] |
[
".net",
"c#",
"python",
"windows_7",
"xml_rpc"
] |
stackoverflow_0002235643_.net_c#_python_windows_7_xml_rpc.txt
|
Q:
Building a user subscription application
I'm trying to come up with the best way to handle user subscription and management for our magazine website. What I want to happen is a user purchases a subscription and they are granted online access of a certain membership role for a certain amount of time depending on how many years they subscribed for. I would also like the system to be able to send out emails when a subscription is almost up.
I've seen some third party projects to help accomplish this but I'd prefer to write this from scratch as I want total control over how it works.
Any suggestions would be helpful.
The main thing I can't figure out is how to have an expiring membership. You must keep track of when the user signed up and how long until they should expire.
A:
You just need to keep track of their expiration date, not their join date. If the expiration date is in the future, they're active. Otherwise, they aren't. From that, you could implement a custom decorator similar to @login_required to check for this stuff.
http://code.djangoproject.com/browser/django/trunk/django/contrib/auth/decorators.py#L33
As for emails, you should just create a management command which will look for any user whose expiration date is 3 days from now, and then take that list of users and email them. This management command should be run on a cron job.
|
Building a user subscription application
|
I'm trying to come up with the best way to handle user subscription and management for our magazine website. What I want to happen is a user purchases a subscription and they are granted online access of a certain membership role for a certain amount of time depending on how many years they subscribed for. I would also like the system to be able to send out emails when a subscription is almost up.
I've seen some third party projects to help accomplish this but I'd prefer to write this from scratch as I want total control over how it works.
Any suggestions would be helpful.
The main thing I can't figure out is how to have an expiring membership. You must keep track of when the user signed up and how long until they should expire.
|
[
"You just need to keep track of their expiration date, not their join date. If the expiration date is in the future, they're active. Otherwise, they aren't. From that, you could implement a custom decorator similar to @login_required to check for this stuff. \nhttp://code.djangoproject.com/browser/django/trunk/django/contrib/auth/decorators.py#L33\nAs for emails, you should just create a management command which will look for any user whose expiration date is 3 days from now, and then take that list of users and email them. This management command should be run on a cron job.\n"
] |
[
0
] |
[] |
[] |
[
"django",
"python"
] |
stackoverflow_0002678411_django_python.txt
|
Q:
Share headers amongst files in python?
Is there a way to share headers in python? i import the same things in different controllers in pylons.
A:
Try putting the common code in the __init__.py file. As in here: "The __init__.py file is usually empty, but can be used to export selected portions of the package under more convenient names, hold convenience functions, etc."
A:
You could put the "header" things into a module of their own and then, wherever you need it, do
from myheadermodule import *
|
Share headers amongst files in python?
|
Is there a way to share headers in python? i import the same things in different controllers in pylons.
|
[
"Try putting the common code in the __init__.py file. As in here: \"The __init__.py file is usually empty, but can be used to export selected portions of the package under more convenient names, hold convenience functions, etc.\"\n",
"You could put the \"header\" things into a module of their own and then, wherever you need it, do\nfrom myheadermodule import * \n\n"
] |
[
3,
1
] |
[] |
[] |
[
"import",
"python"
] |
stackoverflow_0002678514_import_python.txt
|
Q:
Speeding up templates in GAE-Py by aggregating RPC calls
Here's my problem:
class City(Model):
name = StringProperty()
class Author(Model):
name = StringProperty()
city = ReferenceProperty(City)
class Post(Model):
author = ReferenceProperty(Author)
content = StringProperty()
The code isn't important... its this django template:
{% for post in posts %}
<div>{{post.content}}</div>
<div>by {{post.author.name}} from {{post.author.city.name}}</div>
{% endfor %}
Now lets say I get the first 100 posts using Post.all().fetch(limit=100), and pass this list to the template - what happens?
It makes 200 more datastore gets - 100 to get each author, 100 to get each author's city.
This is perfectly understandable, actually, since the post only has a reference to the author, and the author only has a reference to the city. The __get__ accessor on the post.author and author.city objects transparently do a get and pull the data back (See this question).
Some ways around this are
Use Post.author.get_value_for_datastore(post) to collect the author keys (see the link above), and then do a batch get to get them all - the trouble here is that we need to re-construct a template data object... something which needs extra code and maintenance for each model and handler.
Write an accessor, say cached_author, that checks memcache for the author first and returns that - the problem here is that post.cached_author is going to be called 100 times, which could probably mean 100 memcache calls.
Hold a static key to object map (and refresh it maybe once in five minutes) if the data doesn't have to be very up to date. The cached_author accessor can then just refer to this map.
All these ideas need extra code and maintenance, and they're not very transparent. What if we could do
@prefetch
def render_template(path, data)
template.render(path, data)
Turns out we can... hooks and Guido's instrumentation module both prove it. If the @prefetch method wraps a template render by capturing which keys are requested we can (atleast to one level of depth) capture which keys are being requested, return mock objects, and do a batch get on them. This could be repeated for all depth levels, till no new keys are being requested. The final render could intercept the gets and return the objects from a map.
This would change a total of 200 gets into 3, transparently and without any extra code. Not to mention greatly cut down the need for memcache and help in situations where memcache can't be used.
Trouble is I don't know how to do it (yet). Before I start trying, has anyone else done this? Or does anyone want to help? Or do you see a massive flaw in the plan?
A:
I have been in a similar situation. Instead of ReferenceProperty, I had parent/child relationships but the basics are the same. My current solution is not polished but at least it is efficient enough for reports and things with 200-1,000 entities, each with several subsequent child entities that require fetching.
You can manually search for data in batches and set it if you want.
# Given the posts, fetches all the data the template will need
# with just 2 key-only loads from the datastore.
posts = get_the_posts()
author_keys = [Post.author.get_value_for_datastore(x) for x in posts]
authors = db.get(author_keys)
city_keys = [Author.city.get_value_for_datastore(x) for x in authors]
cities = db.get(city_keys)
for post, author, city in zip(posts, authors, cities):
post.author = author
author.city = city
Now when you render the template, no additional queries or fetches will be done. It's rough around the edges but I could not live without this pattern I just described.
Also you might consider validating that none of your entities are None because db.get() will return None if the key is bad. That is getting into just basic data validation though. Similarly, you need to retry db.get() if there is a timeout, etc.
(Finally, I don't think memcache will work as a primary solution. Maybe as a secondary layer to speed up datastore calls, but you need to work well if memcache is empty. Also, Memcache has several quotas itself such as memcache calls and total data transferred. Overusing memcache is a great way to kill your app dead.)
A:
Here's some great examples of pre-fetching...
http://blog.notdot.net/2010/01/ReferenceProperty-prefetching-in-App-Engine
|
Speeding up templates in GAE-Py by aggregating RPC calls
|
Here's my problem:
class City(Model):
name = StringProperty()
class Author(Model):
name = StringProperty()
city = ReferenceProperty(City)
class Post(Model):
author = ReferenceProperty(Author)
content = StringProperty()
The code isn't important... its this django template:
{% for post in posts %}
<div>{{post.content}}</div>
<div>by {{post.author.name}} from {{post.author.city.name}}</div>
{% endfor %}
Now lets say I get the first 100 posts using Post.all().fetch(limit=100), and pass this list to the template - what happens?
It makes 200 more datastore gets - 100 to get each author, 100 to get each author's city.
This is perfectly understandable, actually, since the post only has a reference to the author, and the author only has a reference to the city. The __get__ accessor on the post.author and author.city objects transparently do a get and pull the data back (See this question).
Some ways around this are
Use Post.author.get_value_for_datastore(post) to collect the author keys (see the link above), and then do a batch get to get them all - the trouble here is that we need to re-construct a template data object... something which needs extra code and maintenance for each model and handler.
Write an accessor, say cached_author, that checks memcache for the author first and returns that - the problem here is that post.cached_author is going to be called 100 times, which could probably mean 100 memcache calls.
Hold a static key to object map (and refresh it maybe once in five minutes) if the data doesn't have to be very up to date. The cached_author accessor can then just refer to this map.
All these ideas need extra code and maintenance, and they're not very transparent. What if we could do
@prefetch
def render_template(path, data)
template.render(path, data)
Turns out we can... hooks and Guido's instrumentation module both prove it. If the @prefetch method wraps a template render by capturing which keys are requested we can (atleast to one level of depth) capture which keys are being requested, return mock objects, and do a batch get on them. This could be repeated for all depth levels, till no new keys are being requested. The final render could intercept the gets and return the objects from a map.
This would change a total of 200 gets into 3, transparently and without any extra code. Not to mention greatly cut down the need for memcache and help in situations where memcache can't be used.
Trouble is I don't know how to do it (yet). Before I start trying, has anyone else done this? Or does anyone want to help? Or do you see a massive flaw in the plan?
|
[
"I have been in a similar situation. Instead of ReferenceProperty, I had parent/child relationships but the basics are the same. My current solution is not polished but at least it is efficient enough for reports and things with 200-1,000 entities, each with several subsequent child entities that require fetching.\nYou can manually search for data in batches and set it if you want.\n# Given the posts, fetches all the data the template will need\n# with just 2 key-only loads from the datastore.\nposts = get_the_posts()\n\nauthor_keys = [Post.author.get_value_for_datastore(x) for x in posts]\nauthors = db.get(author_keys)\n\ncity_keys = [Author.city.get_value_for_datastore(x) for x in authors]\ncities = db.get(city_keys)\n\nfor post, author, city in zip(posts, authors, cities):\n post.author = author\n author.city = city\n\nNow when you render the template, no additional queries or fetches will be done. It's rough around the edges but I could not live without this pattern I just described.\nAlso you might consider validating that none of your entities are None because db.get() will return None if the key is bad. That is getting into just basic data validation though. Similarly, you need to retry db.get() if there is a timeout, etc.\n(Finally, I don't think memcache will work as a primary solution. Maybe as a secondary layer to speed up datastore calls, but you need to work well if memcache is empty. Also, Memcache has several quotas itself such as memcache calls and total data transferred. Overusing memcache is a great way to kill your app dead.)\n",
"Here's some great examples of pre-fetching...\nhttp://blog.notdot.net/2010/01/ReferenceProperty-prefetching-in-App-Engine\n"
] |
[
1,
0
] |
[] |
[] |
[
"django_templates",
"google_app_engine",
"python"
] |
stackoverflow_0002076470_django_templates_google_app_engine_python.txt
|
Q:
How to workaround Python "WindowsError messages are not properly encoded" problem?
It's a trouble when Python raised a WindowsError, the encoding of message of the exception is always os-native-encoded. For example:
import os
os.remove('does_not_exist.file')
Well, here we get an exception:
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
WindowsError: [Error 2] 系統找不到指定的檔案。: 'does_not_exist.file'
As the language of my Windows7 is Traditional Chinese, the default error message I get is in big5 encoding (as know as CP950).
>>> try:
... os.remove('abc.file')
... except WindowsError, value:
... print value.args
...
(2, '\xa8t\xb2\xce\xa7\xe4\xa4\xa3\xa8\xec\xab\xfc\xa9w\xaa\xba\xc0\xc9\xae\xd7\xa1C')
>>>
As you see here, error message is not Unicode, then I will get another encoding exception when I try to print it out. Here is the issue, it can be found in Python issue list:
http://bugs.python.org/issue1754
The question is, how to workaround this? How to get the native encoding of WindowsError?
The version of Python I use is 2.6.
Thanks.
A:
We have the same problem in Russian version of MS Windows: the code page of the default locale is cp1251, but the default code page of the Windows console is cp866:
>>> import sys
>>> print sys.stdout.encoding
cp866
>>> import locale
>>> print locale.getdefaultlocale()
('ru_RU', 'cp1251')
The solution should be to decode the Windows message with default locale encoding:
>>> try:
... os.remove('abc.file')
... except WindowsError, err:
... print err.args[1].decode(locale.getdefaultlocale()[1])
...
The bad news is that you still can't use exc_info=True in logging.error().
A:
sys.getfilesystemencoding() should help.
import os, sys
try:
os.delete('nosuchfile.txt')
except WindowsError, ex:
enc = sys.getfilesystemencoding()
print (u"%s: %s" % (ex.strerror, ex.filename.decode(enc))).encode(enc)
For other purposes than printing to console you may want to change final encoding to 'utf-8'
A:
That is just the repr() string of the same error message. Since your console already supports cp950, just print the component you want. This works on my system after reconfiguring to use cp950 in my console. I had to explicitly raise the error message since my system is English and not Chinese:
>>> try:
... raise WindowsError(2,'系統找不到指定的檔案。')
... except WindowsError, value:
... print value.args
...
(2, '\xa8t\xb2\xce\xa7\xe4\xa4\xa3\xa8\xec\xab\xfc\xa9w\xaa\xba\xc0\xc9\xae\xd7\xa1C')
>>> try:
... raise WindowsError(2,'系統找不到指定的檔案。')
... except WindowsError, value:
... print value.args[1]
...
系統找不到指定的檔案。
Alternatively, use Python 3.X. It prints repr() using the console encoding. Here's an example:
Python 2.6.5 (r265:79096, Mar 19 2010, 21:48:26) [MSC v.1500 32 bit (Intel)] on win32
Type "help", "copyright", "credits" or "license" for more information.
>>> '系統找不到指定的檔案。'
'\xa8t\xb2\xce\xa7\xe4\xa4\xa3\xa8\xec\xab\xfc\xa9w\xaa\xba\xc0\xc9\xae\xd7\xa1C'
Python 3.1.2 (r312:79149, Mar 21 2010, 00:41:52) [MSC v.1500 32 bit (Intel)] on win32
Type "help", "copyright", "credits" or "license" for more information.
>>> '系統找不到指定的檔案。'
'系統找不到指定的檔案。'
|
How to workaround Python "WindowsError messages are not properly encoded" problem?
|
It's a trouble when Python raised a WindowsError, the encoding of message of the exception is always os-native-encoded. For example:
import os
os.remove('does_not_exist.file')
Well, here we get an exception:
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
WindowsError: [Error 2] 系統找不到指定的檔案。: 'does_not_exist.file'
As the language of my Windows7 is Traditional Chinese, the default error message I get is in big5 encoding (as know as CP950).
>>> try:
... os.remove('abc.file')
... except WindowsError, value:
... print value.args
...
(2, '\xa8t\xb2\xce\xa7\xe4\xa4\xa3\xa8\xec\xab\xfc\xa9w\xaa\xba\xc0\xc9\xae\xd7\xa1C')
>>>
As you see here, error message is not Unicode, then I will get another encoding exception when I try to print it out. Here is the issue, it can be found in Python issue list:
http://bugs.python.org/issue1754
The question is, how to workaround this? How to get the native encoding of WindowsError?
The version of Python I use is 2.6.
Thanks.
|
[
"We have the same problem in Russian version of MS Windows: the code page of the default locale is cp1251, but the default code page of the Windows console is cp866:\n>>> import sys\n>>> print sys.stdout.encoding\ncp866\n>>> import locale\n>>> print locale.getdefaultlocale()\n('ru_RU', 'cp1251')\n\nThe solution should be to decode the Windows message with default locale encoding:\n>>> try:\n... os.remove('abc.file')\n... except WindowsError, err:\n... print err.args[1].decode(locale.getdefaultlocale()[1])\n...\n\nThe bad news is that you still can't use exc_info=True in logging.error(). \n",
"sys.getfilesystemencoding() should help.\nimport os, sys\ntry:\n os.delete('nosuchfile.txt')\nexcept WindowsError, ex:\n enc = sys.getfilesystemencoding()\n print (u\"%s: %s\" % (ex.strerror, ex.filename.decode(enc))).encode(enc)\n\nFor other purposes than printing to console you may want to change final encoding to 'utf-8'\n",
"That is just the repr() string of the same error message. Since your console already supports cp950, just print the component you want. This works on my system after reconfiguring to use cp950 in my console. I had to explicitly raise the error message since my system is English and not Chinese:\n>>> try:\n... raise WindowsError(2,'系統找不到指定的檔案。')\n... except WindowsError, value:\n... print value.args\n...\n(2, '\\xa8t\\xb2\\xce\\xa7\\xe4\\xa4\\xa3\\xa8\\xec\\xab\\xfc\\xa9w\\xaa\\xba\\xc0\\xc9\\xae\\xd7\\xa1C')\n>>> try:\n... raise WindowsError(2,'系統找不到指定的檔案。')\n... except WindowsError, value:\n... print value.args[1]\n...\n系統找不到指定的檔案。\n\nAlternatively, use Python 3.X. It prints repr() using the console encoding. Here's an example:\nPython 2.6.5 (r265:79096, Mar 19 2010, 21:48:26) [MSC v.1500 32 bit (Intel)] on win32\nType \"help\", \"copyright\", \"credits\" or \"license\" for more information.\n>>> '系統找不到指定的檔案。'\n'\\xa8t\\xb2\\xce\\xa7\\xe4\\xa4\\xa3\\xa8\\xec\\xab\\xfc\\xa9w\\xaa\\xba\\xc0\\xc9\\xae\\xd7\\xa1C'\n\nPython 3.1.2 (r312:79149, Mar 21 2010, 00:41:52) [MSC v.1500 32 bit (Intel)] on win32\nType \"help\", \"copyright\", \"credits\" or \"license\" for more information.\n>>> '系統找不到指定的檔案。'\n'系統找不到指定的檔案。'\n\n"
] |
[
4,
0,
0
] |
[] |
[] |
[
"encoding",
"python",
"windowserror"
] |
stackoverflow_0002668319_encoding_python_windowserror.txt
|
Q:
Several numpy arrays with SWIG
I am using SWIG to pass numpy arrays from Python to C++ code:
%include "numpy.i"
%init %{
import_array();
%}
%apply (float* INPLACE_ARRAY1, int DIM1) {(float* data, int n)};
class Class
{
public:
void test(float* data, int n)
{
//...
}
};
and in Python:
c = Class()
a = zeros(5)
c.test(a)
This works, but how can I pass multiple numpy arrays to the same function?
A:
I found out the answer from a collegue of mine:
%apply (float* INPLACE_ARRAY1, int DIM1) {(float* data1, int n1), (float* data2, int n2)};
class Class
{
public:
void test(float* data1, int n1, float* data2, int n2)
{
//...
}
};
Now two numpy arrays are passed to Class::test.
|
Several numpy arrays with SWIG
|
I am using SWIG to pass numpy arrays from Python to C++ code:
%include "numpy.i"
%init %{
import_array();
%}
%apply (float* INPLACE_ARRAY1, int DIM1) {(float* data, int n)};
class Class
{
public:
void test(float* data, int n)
{
//...
}
};
and in Python:
c = Class()
a = zeros(5)
c.test(a)
This works, but how can I pass multiple numpy arrays to the same function?
|
[
"I found out the answer from a collegue of mine:\n%apply (float* INPLACE_ARRAY1, int DIM1) {(float* data1, int n1), (float* data2, int n2)};\n\nclass Class \n{\n public: \n void test(float* data1, int n1, float* data2, int n2)\n {\n //...\n }\n};\n\nNow two numpy arrays are passed to Class::test.\n"
] |
[
9
] |
[] |
[] |
[
"c++",
"numpy",
"python",
"swig"
] |
stackoverflow_0002674046_c++_numpy_python_swig.txt
|
Q:
How do I store values of arbitrary type in a single Django model?
Say I have the unknown number of questions. For example:
Is the sky blue [y/n]
What date were your born on [date]
What is pi [3.14]
What is a large integ [100]
Now each of these questions poses a different but very type specific answer (boolean, date, float, int). Natively django can happily deal with these in a model.
class SkyModel(models.Model):
question = models.CharField("Is the sky blue")
answer = models.BooleanField(default=False)
class BirthModel(models.Model):
question = models.CharField("What date were your born on")
answer = models.DateTimeField(default=today)
class PiModel(models.Model)
question = models.CharField("What is pi")
answer = models.FloatField()
But this has the obvious problem in that each question has a specific model - so if we need to add a question later I have to change the database. Yuck. So now I want to get fancy - How do a set up a model where by the answer type conversion happens automagically?
ANSWER_TYPES = (
('boolean', 'boolean'),
('date', 'date'),
('float', 'float'),
('int', 'int'),
('char', 'char'),
)
class Questions(models.model):
question = models.CharField(()
answer = models.CharField()
answer_type = models.CharField(choices = ANSWER_TYPES)
default = models.CharField()
So in theory this would do the following:
When I build up my views I look at the type of answer and ensure that I
only put in that value.
But when I want to pull that answer back out it will return the data in the format specified by the answer_type. Example 3.14 comes back out as a float not as a str.
How can I perform this sort of automagic transformation? Or can someone suggest a better way to do this?
Thanks much!!
A:
I actually just faced this type of problem regarding extensible user settings. My solution was to store the type on the model in a CharField and use a getter to do the type conversion with a smart use of __builtin__ and getattr. This is my code (adapt for your needs):
VALUE_TYPE_CHOICES = (
("unicode", "Unicode String"),
("int", "Integer"),
("bool", "Boolean"),
)
class Setting(models.Model):
name = models.CharField(max_length=100)
description = models.TextField(blank=True)
type = models.CharField(max_length=50, choices=VALUE_TYPE_CHOICES)
default_value = models.CharField(max_length=127)
def get_setting(user, setting_id):
profile_setting = #get the user's specific setting value here, not relevant
type = getattr(__builtin__, profile_setting.setting.type)
if type is bool:
return type(int(profile_setting.value))
else:
return type(profile_setting.value)
There's one gotcha in there: bool('0') actually returns True, so I chose to typecast to int before typecasting to bool. There are other ways you can accomplish this, like using the ast module's literal_eval method instead. Overall the pattern works, though.
A:
You should be fine just storing the answers as strings. If we're talking about accepting data over the web, you're going to receive your input as a string anyway, so you're not losing precision by storing it in the database as a string.
One possible alternative would be to include one column for each possible data type, allowing them to be null.
class Questions(models.model):
question = models.CharField(()
answer = models.CharField()
answer_type = models.CharField(choices = ANSWER_TYPES)
int_answer = models.IntegerField(null=True)
bool_answer = models.NullBooleanField(null=True)
... etc.
If it were me, I'd stick with a single CharField though.
A:
I would add a custom method to your Questions class:
def get_converted_answer(self):
if self.answer_type == 'int':
return int(self.answer)
if self.answer_type == 'bool':
# ...
|
How do I store values of arbitrary type in a single Django model?
|
Say I have the unknown number of questions. For example:
Is the sky blue [y/n]
What date were your born on [date]
What is pi [3.14]
What is a large integ [100]
Now each of these questions poses a different but very type specific answer (boolean, date, float, int). Natively django can happily deal with these in a model.
class SkyModel(models.Model):
question = models.CharField("Is the sky blue")
answer = models.BooleanField(default=False)
class BirthModel(models.Model):
question = models.CharField("What date were your born on")
answer = models.DateTimeField(default=today)
class PiModel(models.Model)
question = models.CharField("What is pi")
answer = models.FloatField()
But this has the obvious problem in that each question has a specific model - so if we need to add a question later I have to change the database. Yuck. So now I want to get fancy - How do a set up a model where by the answer type conversion happens automagically?
ANSWER_TYPES = (
('boolean', 'boolean'),
('date', 'date'),
('float', 'float'),
('int', 'int'),
('char', 'char'),
)
class Questions(models.model):
question = models.CharField(()
answer = models.CharField()
answer_type = models.CharField(choices = ANSWER_TYPES)
default = models.CharField()
So in theory this would do the following:
When I build up my views I look at the type of answer and ensure that I
only put in that value.
But when I want to pull that answer back out it will return the data in the format specified by the answer_type. Example 3.14 comes back out as a float not as a str.
How can I perform this sort of automagic transformation? Or can someone suggest a better way to do this?
Thanks much!!
|
[
"I actually just faced this type of problem regarding extensible user settings. My solution was to store the type on the model in a CharField and use a getter to do the type conversion with a smart use of __builtin__ and getattr. This is my code (adapt for your needs):\nVALUE_TYPE_CHOICES = (\n (\"unicode\", \"Unicode String\"),\n (\"int\", \"Integer\"),\n (\"bool\", \"Boolean\"),\n)\n\nclass Setting(models.Model):\n name = models.CharField(max_length=100)\n description = models.TextField(blank=True)\n type = models.CharField(max_length=50, choices=VALUE_TYPE_CHOICES)\n default_value = models.CharField(max_length=127)\n\ndef get_setting(user, setting_id):\n profile_setting = #get the user's specific setting value here, not relevant\n type = getattr(__builtin__, profile_setting.setting.type)\n if type is bool:\n return type(int(profile_setting.value))\n else:\n return type(profile_setting.value)\n\nThere's one gotcha in there: bool('0') actually returns True, so I chose to typecast to int before typecasting to bool. There are other ways you can accomplish this, like using the ast module's literal_eval method instead. Overall the pattern works, though.\n",
"You should be fine just storing the answers as strings. If we're talking about accepting data over the web, you're going to receive your input as a string anyway, so you're not losing precision by storing it in the database as a string. \nOne possible alternative would be to include one column for each possible data type, allowing them to be null.\nclass Questions(models.model):\n question = models.CharField(()\n answer = models.CharField()\n answer_type = models.CharField(choices = ANSWER_TYPES)\n int_answer = models.IntegerField(null=True)\n bool_answer = models.NullBooleanField(null=True)\n ... etc. \n\nIf it were me, I'd stick with a single CharField though. \n",
"I would add a custom method to your Questions class:\ndef get_converted_answer(self):\n if self.answer_type == 'int':\n return int(self.answer)\n if self.answer_type == 'bool':\n # ...\n\n"
] |
[
6,
2,
2
] |
[] |
[] |
[
"django",
"django_models",
"python"
] |
stackoverflow_0002678770_django_django_models_python.txt
|
Q:
Changing contents of currently displayed listbox in urwid/python2.6
I'm writing a music player in python, with a cli using urwid. I intend to have the current playlist in a simpleListWalker, wrapped by a listbox, then columns, a pile, and finally a frame.
How do I replace the entire contents of this listbox (or simpleListWalker) with something else?
Relevant code:
class mainDisplay(object):
...
def renderList(self):
songList = db.getListOfSongs()
songDictList = [item for item in songList if item['location'] in
commandSh.currentPlaylists[commandSh.plyr.currentList]]
self.currentSongWidgets = self.createList(songDictList)
self.mainListContent = urwid.SimpleListWalker([urwid.AttrMap(w, None,
'reveal focus') for w in self.currentSongWidgets])
def initFace(self):#this is the init function that creates the interface
#on startup
...
self.scanPlaylists()
self.renderList()
self.mainList = urwid.ListBox(self.mainListContent)
self.columns = urwid.Columns([self.mainList, self.secondaryList])
self.pile = urwid.Pile([self.columns,
("fixed", 1, self.statusDisplayOne),
("fixed", 1, self.statusDisplayTwo),
("fixed", 1, self.cmdShInterface)], 3)
self.topFrame = urwid.Frame(self.pile)
Full code at: http://github.com/ripdog/PyPlayer/tree/cli - Check main.py for interface code.
The code is in a pretty bad state right now, and I've only been programming for two months. Any suggestions on code style, layout, or any other tips you may have are very much appreciated.
A:
self.mainListContent[:] = [new, list, of, widgets]
should replace the whole list of widgets in place.
Next time post your question to the mailing list or the IRC channel if you want a faster response!
|
Changing contents of currently displayed listbox in urwid/python2.6
|
I'm writing a music player in python, with a cli using urwid. I intend to have the current playlist in a simpleListWalker, wrapped by a listbox, then columns, a pile, and finally a frame.
How do I replace the entire contents of this listbox (or simpleListWalker) with something else?
Relevant code:
class mainDisplay(object):
...
def renderList(self):
songList = db.getListOfSongs()
songDictList = [item for item in songList if item['location'] in
commandSh.currentPlaylists[commandSh.plyr.currentList]]
self.currentSongWidgets = self.createList(songDictList)
self.mainListContent = urwid.SimpleListWalker([urwid.AttrMap(w, None,
'reveal focus') for w in self.currentSongWidgets])
def initFace(self):#this is the init function that creates the interface
#on startup
...
self.scanPlaylists()
self.renderList()
self.mainList = urwid.ListBox(self.mainListContent)
self.columns = urwid.Columns([self.mainList, self.secondaryList])
self.pile = urwid.Pile([self.columns,
("fixed", 1, self.statusDisplayOne),
("fixed", 1, self.statusDisplayTwo),
("fixed", 1, self.cmdShInterface)], 3)
self.topFrame = urwid.Frame(self.pile)
Full code at: http://github.com/ripdog/PyPlayer/tree/cli - Check main.py for interface code.
The code is in a pretty bad state right now, and I've only been programming for two months. Any suggestions on code style, layout, or any other tips you may have are very much appreciated.
|
[
"self.mainListContent[:] = [new, list, of, widgets]\n\nshould replace the whole list of widgets in place.\nNext time post your question to the mailing list or the IRC channel if you want a faster response!\n"
] |
[
8
] |
[] |
[] |
[
"python",
"urwid"
] |
stackoverflow_0002137354_python_urwid.txt
|
Q:
Storing processed objects in database with sqlalchemy
i have things that requires processing and rarely changes except with certain events to take advantage of memcached. can i store a serial version of an object in a data field quickly?
A:
Just pickle (or marshal or even JSON) it and throw it in memcached.
|
Storing processed objects in database with sqlalchemy
|
i have things that requires processing and rarely changes except with certain events to take advantage of memcached. can i store a serial version of an object in a data field quickly?
|
[
"Just pickle (or marshal or even JSON) it and throw it in memcached.\n"
] |
[
3
] |
[] |
[] |
[
"python",
"sqlalchemy"
] |
stackoverflow_0002678861_python_sqlalchemy.txt
|
Q:
What is Ruby's analog to Python Metaclasses?
Python has the idea of metaclasses that, if I understand correctly, allow you to modify an object of a class at the moment of construction. You are not modifying the class, but instead the object that is to be created then initialized.
Python (at least as of 3.0 I believe) also has the idea of class decorators. Again if I understand correctly, class decorators allow the modifying of the class definition at the moment it is being declared.
Now I believe there is an equivalent feature or features to the class decorator in Ruby, but I'm currently unaware of something equivalent to metaclasses. I'm sure you can easily pump any Ruby object through some functions and do what you will to it, but is there a feature in the language that sets that up like metaclasses do?
So again, Does Ruby have something similar to Python's metaclasses?
Edit I was off on the metaclasses for Python. A metaclass and a class decorator do very similar things it appears. They both modify the class when it is defined but in different manners. Hopefully a Python guru will come in and explain better on these features in Python.
But a class or the parent of a class can implement a __new__(cls[,..]) function that does customize the construction of the object before it is initialized with __init__(self[,..]).
Edit This question is mostly for discussion and learning about how the two languages compare in these features. I'm familiar with Python but not Ruby and was curious. Hopefully anyone else who has the same question about the two languages will find this post helpful and enlightening.
A:
Ruby doesn't have metaclasses. There are some constructs in Ruby which some people sometimes wrongly call metaclasses but they aren't (which is a source of endless confusion).
However, there's a lot of ways to achieve the same results in Ruby that you would do with metaclasses. But without telling us what exactly you want to do, there's no telling what those mechanisms might be.
In short:
Ruby doesn't have metaclasses
Ruby doesn't have any one construct that corresponds to Python's metaclasses
Everything that Python can do with metaclasses can also be done in Ruby
But there is no single construct, you will use different constructs depending on what exactly you want to do
Any one of those constructs probably has other features as well that do not correspond to metaclasses (although they probably correspond to something else in Python)
While you can do anything in Ruby that you can do with metaclasses in Python, it might not necessarily be straightforward
Although often there will be a more Rubyish solution that is elegant
Last but not least: while you can do anything in Ruby that you can do with metaclasses in Python, doing it might not necessarily be The Ruby Way
So, what are metaclasses exactly? Well, they are classes of classes. So, let's take a step back: what are classes exactly?
Classes …
are factories for objects
define the behavior of objects
define on a metaphysical level what it means to be an instance of the class
For example, the Array class produces array objects, defines the behavior of arrays and defines what "array-ness" means.
Back to metaclasses.
Metaclasses …
are factories for classes
define the behavior of classes
define on a metaphysical level what it means to be a class
In Ruby, those three responsibilities are split across three different places:
the Class class creates classes and defines a little bit of the behavior
the individual class's eigenclass defines a little bit of the behavior of the class
the concept of "classness" is hardwired into the interpreter, which also implements the bulk of the behavior (for example, you cannot inherit from Class to create a new kind of class that looks up methods differently, or something like that – the method lookup algorithm is hardwired into the interpreter)
So, those three things together play the role of metaclasses, but neither one of those is a metaclass (each one only implements a small part of what a metaclass does), nor is the sum of those the metaclass (because they do much more than that).
Unfortunately, some people call eigenclasses of classes metaclasses. (Until recently, I was one of those misguided souls, until I finally saw the light.) Other people call all eigenclasses metaclasses. (Unfortunately, one of those people is the author of one the most popular tutorials on Ruby metaprogramming and the Ruby object model.) Some popular libraries add a metaclass method to Object that returns the object's eigenclass (e.g. ActiveSupport, Facets, metaid). Some people call all virtual classes (i.e. eigenclasses and include classes) metaclasses. Some people call Class the metaclass. Even within the Ruby source code itself, the word "metaclass" is used to refer to things that are not metaclasses.
A:
Your updated question looks quite different now. If I understand you correctly, you want to hook into object allocation and initialization, which has absolutely nothing whatsoever to do with metaclasses. (But you still don't write what it is that you actually want to do, so I might still be off.)
In some object-oriented languages, objects are created by constructors. However, Ruby doesn't have constructors. Constructors are just factory methods (with stupid restrictions); there is no reason to have them in a well-designed language, if you can just use a (more powerful) factory method instead.
Object construction in Ruby works like this: object construction is split into two phases, allocation and initialization. Allocation is done by a public class method called allocate, which is defined as an instance method of class Class and is generally never overriden. (In fact, I don't think you actually can override it.) It just allocates the memory space for the object and sets up a few pointers, however, the object is not really usable at this point.
That's where the initializer comes in: it is an instance method called initialize, which sets up the object's internal state and brings it into a consistent, fully defined state which can be used by other objects.
So, in order to fully create a new object, what you need to do is this:
x = X.allocate
x.initialize
[Note: Objective-C programmers may recognize this.]
However, because it is too easy to forget to call initialize and as a general rule an object should be fully valid after construction, there is a convenience factory method called Class#new, which does all that work for you and looks something like this:
class Class
def new(*args, &block)
obj = allocate
obj.initialize(*args, &block)
return obj
end
end
[Note: actually, initialize is private, so reflection has to be used to circumvent the access restrictions like this: obj.send(:initialize, *args, &block)]
That, by the way, is the reason why to construct an object you call a public class method Foo.new but you implement a private instance method Foo#initialize, which seems to trip up a lot of newcomers.
However, none of this is in any way baked into the language. The fact that the primary factory method for any class is usually called new is just a convention (and sometimes I wish it were different, because it looks similar to constructors in Java, but is completely different). In other languages, the constructor must have a specific name. In Java, it must have the same name as the class, which means that a) there can be only one constructor and b) anonymous classes can't have constructors because they don't have names. In Python, the factory method must be called __new__, which again means there can be only one. (In both Java and Python, you can of course have different factory methods, but calling them looks different from calling the default, while in Ruby (and Smalltalk from whence this pattern originated) it looks just the same.)
In Ruby, there can be as many factory methods as you like, with any name you like, and a factory method can have many different names. (For collection classes, for example, the factory method is often aliased to [], which allows you to write List[1, 2, 3] instead of List.new(1, 2, 3) which ends looking more like an array, thus emphasizing the collection-ish nature of lists.)
In short:
the standardized factory method is Foo.new, but it can be anything
Foo.new calls allocate to allocate memory for an empty object foo
Foo.new then calls foo.initialize, i.e. the Foo#initialize instance method
all three of those are just methods like any other, which you can undefine, redefine, override, wrap, alias and whatnot
well, except allocate which needs to allocate memory inside the Ruby runtime which you can't really do from Ruby
In Python, __new__ roughly corresponds to both new and allocate in Ruby, and __init__ exactly corresponds to initialize in Ruby. The main difference is that in Ruby, new calls initialize whereas in Python, the runtime automatically calls __init__ after __new__.
For example, here is a class which only allows a maximum of 2 instances created:
class Foo
def self.new(*args, &block)
@instances ||= 0
raise 'Too many instances!' if @instances >= 2
obj = allocate
obj.send(:initialize, *args, &block)
@instances += 1
return obj
end
attr_reader :name
def initialize(name)
@name = name
end
end
one = Foo.new('#1')
two = Foo.new('#2')
puts two.name # => #2
three = Foo.new('#3') # => RuntimeError: Too many instances!
|
What is Ruby's analog to Python Metaclasses?
|
Python has the idea of metaclasses that, if I understand correctly, allow you to modify an object of a class at the moment of construction. You are not modifying the class, but instead the object that is to be created then initialized.
Python (at least as of 3.0 I believe) also has the idea of class decorators. Again if I understand correctly, class decorators allow the modifying of the class definition at the moment it is being declared.
Now I believe there is an equivalent feature or features to the class decorator in Ruby, but I'm currently unaware of something equivalent to metaclasses. I'm sure you can easily pump any Ruby object through some functions and do what you will to it, but is there a feature in the language that sets that up like metaclasses do?
So again, Does Ruby have something similar to Python's metaclasses?
Edit I was off on the metaclasses for Python. A metaclass and a class decorator do very similar things it appears. They both modify the class when it is defined but in different manners. Hopefully a Python guru will come in and explain better on these features in Python.
But a class or the parent of a class can implement a __new__(cls[,..]) function that does customize the construction of the object before it is initialized with __init__(self[,..]).
Edit This question is mostly for discussion and learning about how the two languages compare in these features. I'm familiar with Python but not Ruby and was curious. Hopefully anyone else who has the same question about the two languages will find this post helpful and enlightening.
|
[
"Ruby doesn't have metaclasses. There are some constructs in Ruby which some people sometimes wrongly call metaclasses but they aren't (which is a source of endless confusion).\nHowever, there's a lot of ways to achieve the same results in Ruby that you would do with metaclasses. But without telling us what exactly you want to do, there's no telling what those mechanisms might be.\nIn short:\n\nRuby doesn't have metaclasses\nRuby doesn't have any one construct that corresponds to Python's metaclasses\nEverything that Python can do with metaclasses can also be done in Ruby\nBut there is no single construct, you will use different constructs depending on what exactly you want to do\nAny one of those constructs probably has other features as well that do not correspond to metaclasses (although they probably correspond to something else in Python)\nWhile you can do anything in Ruby that you can do with metaclasses in Python, it might not necessarily be straightforward\nAlthough often there will be a more Rubyish solution that is elegant\nLast but not least: while you can do anything in Ruby that you can do with metaclasses in Python, doing it might not necessarily be The Ruby Way\n\nSo, what are metaclasses exactly? Well, they are classes of classes. So, let's take a step back: what are classes exactly?\nClasses …\n\nare factories for objects\ndefine the behavior of objects\ndefine on a metaphysical level what it means to be an instance of the class\n\nFor example, the Array class produces array objects, defines the behavior of arrays and defines what \"array-ness\" means.\nBack to metaclasses.\nMetaclasses …\n\nare factories for classes\ndefine the behavior of classes\ndefine on a metaphysical level what it means to be a class\n\nIn Ruby, those three responsibilities are split across three different places:\n\nthe Class class creates classes and defines a little bit of the behavior\nthe individual class's eigenclass defines a little bit of the behavior of the class\nthe concept of \"classness\" is hardwired into the interpreter, which also implements the bulk of the behavior (for example, you cannot inherit from Class to create a new kind of class that looks up methods differently, or something like that – the method lookup algorithm is hardwired into the interpreter)\n\nSo, those three things together play the role of metaclasses, but neither one of those is a metaclass (each one only implements a small part of what a metaclass does), nor is the sum of those the metaclass (because they do much more than that).\nUnfortunately, some people call eigenclasses of classes metaclasses. (Until recently, I was one of those misguided souls, until I finally saw the light.) Other people call all eigenclasses metaclasses. (Unfortunately, one of those people is the author of one the most popular tutorials on Ruby metaprogramming and the Ruby object model.) Some popular libraries add a metaclass method to Object that returns the object's eigenclass (e.g. ActiveSupport, Facets, metaid). Some people call all virtual classes (i.e. eigenclasses and include classes) metaclasses. Some people call Class the metaclass. Even within the Ruby source code itself, the word \"metaclass\" is used to refer to things that are not metaclasses.\n",
"Your updated question looks quite different now. If I understand you correctly, you want to hook into object allocation and initialization, which has absolutely nothing whatsoever to do with metaclasses. (But you still don't write what it is that you actually want to do, so I might still be off.)\nIn some object-oriented languages, objects are created by constructors. However, Ruby doesn't have constructors. Constructors are just factory methods (with stupid restrictions); there is no reason to have them in a well-designed language, if you can just use a (more powerful) factory method instead.\nObject construction in Ruby works like this: object construction is split into two phases, allocation and initialization. Allocation is done by a public class method called allocate, which is defined as an instance method of class Class and is generally never overriden. (In fact, I don't think you actually can override it.) It just allocates the memory space for the object and sets up a few pointers, however, the object is not really usable at this point.\nThat's where the initializer comes in: it is an instance method called initialize, which sets up the object's internal state and brings it into a consistent, fully defined state which can be used by other objects.\nSo, in order to fully create a new object, what you need to do is this:\nx = X.allocate\nx.initialize\n\n[Note: Objective-C programmers may recognize this.]\nHowever, because it is too easy to forget to call initialize and as a general rule an object should be fully valid after construction, there is a convenience factory method called Class#new, which does all that work for you and looks something like this:\nclass Class\n def new(*args, &block)\n obj = allocate\n obj.initialize(*args, &block)\n\n return obj\n end\nend\n\n[Note: actually, initialize is private, so reflection has to be used to circumvent the access restrictions like this: obj.send(:initialize, *args, &block)]\nThat, by the way, is the reason why to construct an object you call a public class method Foo.new but you implement a private instance method Foo#initialize, which seems to trip up a lot of newcomers.\nHowever, none of this is in any way baked into the language. The fact that the primary factory method for any class is usually called new is just a convention (and sometimes I wish it were different, because it looks similar to constructors in Java, but is completely different). In other languages, the constructor must have a specific name. In Java, it must have the same name as the class, which means that a) there can be only one constructor and b) anonymous classes can't have constructors because they don't have names. In Python, the factory method must be called __new__, which again means there can be only one. (In both Java and Python, you can of course have different factory methods, but calling them looks different from calling the default, while in Ruby (and Smalltalk from whence this pattern originated) it looks just the same.)\nIn Ruby, there can be as many factory methods as you like, with any name you like, and a factory method can have many different names. (For collection classes, for example, the factory method is often aliased to [], which allows you to write List[1, 2, 3] instead of List.new(1, 2, 3) which ends looking more like an array, thus emphasizing the collection-ish nature of lists.)\nIn short:\n\nthe standardized factory method is Foo.new, but it can be anything\nFoo.new calls allocate to allocate memory for an empty object foo\nFoo.new then calls foo.initialize, i.e. the Foo#initialize instance method\nall three of those are just methods like any other, which you can undefine, redefine, override, wrap, alias and whatnot\nwell, except allocate which needs to allocate memory inside the Ruby runtime which you can't really do from Ruby\n\nIn Python, __new__ roughly corresponds to both new and allocate in Ruby, and __init__ exactly corresponds to initialize in Ruby. The main difference is that in Ruby, new calls initialize whereas in Python, the runtime automatically calls __init__ after __new__.\nFor example, here is a class which only allows a maximum of 2 instances created:\nclass Foo\n def self.new(*args, &block)\n @instances ||= 0\n raise 'Too many instances!' if @instances >= 2\n\n obj = allocate\n obj.send(:initialize, *args, &block)\n\n @instances += 1\n\n return obj\n end\n\n attr_reader :name\n\n def initialize(name)\n @name = name\n end\nend\n\none = Foo.new('#1')\ntwo = Foo.new('#2')\nputs two.name # => #2\nthree = Foo.new('#3') # => RuntimeError: Too many instances!\n\n"
] |
[
24,
13
] |
[] |
[] |
[
"metaclass",
"metaprogramming",
"python",
"ruby"
] |
stackoverflow_0002676007_metaclass_metaprogramming_python_ruby.txt
|
Q:
Python - Memory Leak
I'm working on solving a memory leak in my Python application.
Here's the thing - it really only appears to happen on Windows Server 2008 (not R2) but not earlier versions of Windows, and it also doesn't look like it's happening on Linux (although I haven't done nearly as much testing on Linux).
To troubleshoot it, I set up debugging on the garbage collector:
gc.set_debug(gc.DEBUG_UNCOLLECTABLE | gc.DEBUG_INSTANCES | gc.DEBUG_OBJECTS)
Then, periodically, I log the contents of gc.garbage.
Thing is, gc.garbage is always empty, yet my memory usage goes up and up and up.
Very puzzling.
A:
If there's never any garbage in gc.garbage, then I'm not sure what you're trying to do by enabling GC debugging. Sure, it'll tell you which objects are considered for cleanup, but that's not particularly interesting if you end up with no circular references that can't be cleaned up.
If your program is using more and more memory according to the OS, there can generally be four different cases at play:
Your application is storing more and more things, keeping references to each one so they don't get collected.
Your application is creating circular references between objects that can't be cleaned up by the gc module (typically because one of them has a __del__ method.)
Your application is freeing (and re-using) memory, but the OS doesn't want the memory re-used, so it keeps allocating new blocks of memory.
The leak is a real memory leak but in a C/C++ extension module your code is using.
From your description it sounds like it's unlikely to be #1 (as it would behave the same on any OS) and apparently not #2 either (since there's nothing in gc.garbage.) Considering #3, Windows (in general) has a memory allocator that's notoriously bad with fragmented allocations, but Python works around this with its obmalloc frontend for malloc(). It may still be an issue specific in Windows Server 2008 system libraries that make it look like your application is using more and more memory, though. Or it may be a case of #4, a C/C++ extension module, or a DLL used by Python or an extension module, with a memory leak.
A:
In general, the first culprit for memory leaks in python is to be found in C extensions.
Do you use any of them?
Furthermore, you say the issue happens only on 2008; I would then check extensions for any incompatibility, because with Vista and 2008 there were quite a lot of small changes that caused issues on that field.
As and alternative, try to execute your application in Windows compatibility mode, choosing Windows XP - this could help solving the issue, especially if it's related to changes in the security.
|
Python - Memory Leak
|
I'm working on solving a memory leak in my Python application.
Here's the thing - it really only appears to happen on Windows Server 2008 (not R2) but not earlier versions of Windows, and it also doesn't look like it's happening on Linux (although I haven't done nearly as much testing on Linux).
To troubleshoot it, I set up debugging on the garbage collector:
gc.set_debug(gc.DEBUG_UNCOLLECTABLE | gc.DEBUG_INSTANCES | gc.DEBUG_OBJECTS)
Then, periodically, I log the contents of gc.garbage.
Thing is, gc.garbage is always empty, yet my memory usage goes up and up and up.
Very puzzling.
|
[
"If there's never any garbage in gc.garbage, then I'm not sure what you're trying to do by enabling GC debugging. Sure, it'll tell you which objects are considered for cleanup, but that's not particularly interesting if you end up with no circular references that can't be cleaned up.\nIf your program is using more and more memory according to the OS, there can generally be four different cases at play:\n\nYour application is storing more and more things, keeping references to each one so they don't get collected.\nYour application is creating circular references between objects that can't be cleaned up by the gc module (typically because one of them has a __del__ method.)\nYour application is freeing (and re-using) memory, but the OS doesn't want the memory re-used, so it keeps allocating new blocks of memory.\nThe leak is a real memory leak but in a C/C++ extension module your code is using.\n\nFrom your description it sounds like it's unlikely to be #1 (as it would behave the same on any OS) and apparently not #2 either (since there's nothing in gc.garbage.) Considering #3, Windows (in general) has a memory allocator that's notoriously bad with fragmented allocations, but Python works around this with its obmalloc frontend for malloc(). It may still be an issue specific in Windows Server 2008 system libraries that make it look like your application is using more and more memory, though. Or it may be a case of #4, a C/C++ extension module, or a DLL used by Python or an extension module, with a memory leak. \n",
"In general, the first culprit for memory leaks in python is to be found in C extensions.\nDo you use any of them?\nFurthermore, you say the issue happens only on 2008; I would then check extensions for any incompatibility, because with Vista and 2008 there were quite a lot of small changes that caused issues on that field.\nAs and alternative, try to execute your application in Windows compatibility mode, choosing Windows XP - this could help solving the issue, especially if it's related to changes in the security.\n"
] |
[
25,
3
] |
[] |
[] |
[
"memory_leaks",
"python"
] |
stackoverflow_0002678906_memory_leaks_python.txt
|
Q:
Why is Django reverse() failing with unicode?
Here is a django models file that is not working as I would expect.
I would expect the to_url method to do the reverse lookup in the urls.py file, and get a url that would correspond to calling that view with arguments supplied by the Arguments model.
from django.db import models
class Element(models.Model):
viewname = models.CharField(max_length = 200)
arguments = models.ManyToManyField('Argument', null = True, blank = True )
@models.permalink
def to_url(self):
d = dict( self.arguments.values_list('key', 'value') )
return (self.viewname, (), d)
class Argument(models.Model):
key = models.CharField(max_length=200)
value = models.CharField(max_length=200)
The value d ends up as a dictionary from a unicode string to another unicode string, which I believe, should work fine with the reverse() method that would be called by the permalink decorator, however, it results in:
TypeError: reverse() keywords must be strings
A:
In your to_url method, you need to make sure the keys in the d dict are not Unicode strings. This isn't peculiar to Django, it's just how keyword arguments to functions work in Python. Here's a simple example:
>>> def f(**kwargs): print kwargs
...
>>> d1 = { u'foo': u'bar' }
>>> d2 = { 'foo': u'bar' }
>>> f(**d1)
TypeError: f() keywords must be strings
>>> f(**d2)
{'foo': u'bar'}
Changing your
d = dict( self.arguments.values_list('key', 'value') )
into something like
d = dict((str(k), v) for k, v in self.arguments.values_list('key', 'value').iteritems())
should do the trick.
|
Why is Django reverse() failing with unicode?
|
Here is a django models file that is not working as I would expect.
I would expect the to_url method to do the reverse lookup in the urls.py file, and get a url that would correspond to calling that view with arguments supplied by the Arguments model.
from django.db import models
class Element(models.Model):
viewname = models.CharField(max_length = 200)
arguments = models.ManyToManyField('Argument', null = True, blank = True )
@models.permalink
def to_url(self):
d = dict( self.arguments.values_list('key', 'value') )
return (self.viewname, (), d)
class Argument(models.Model):
key = models.CharField(max_length=200)
value = models.CharField(max_length=200)
The value d ends up as a dictionary from a unicode string to another unicode string, which I believe, should work fine with the reverse() method that would be called by the permalink decorator, however, it results in:
TypeError: reverse() keywords must be strings
|
[
"In your to_url method, you need to make sure the keys in the d dict are not Unicode strings. This isn't peculiar to Django, it's just how keyword arguments to functions work in Python. Here's a simple example:\n>>> def f(**kwargs): print kwargs\n... \n>>> d1 = { u'foo': u'bar' }\n>>> d2 = { 'foo': u'bar' }\n>>> f(**d1)\nTypeError: f() keywords must be strings\n>>> f(**d2)\n{'foo': u'bar'}\n\nChanging your\nd = dict( self.arguments.values_list('key', 'value') )\n\ninto something like\nd = dict((str(k), v) for k, v in self.arguments.values_list('key', 'value').iteritems())\n\nshould do the trick.\n"
] |
[
5
] |
[] |
[] |
[
"django",
"python",
"unicode"
] |
stackoverflow_0002679052_django_python_unicode.txt
|
Q:
Django Backend-neutral DictCursor
Is there any way to get a backend-neutral dictionary cursor in Django? This would be a cursor that is a dict rather than a tuple. I am forced to use Oracle for the school project I'm working on.
in Python's MySQLDb module it's called a DictCursor.
With WoLpH's inspiring suggestion I know I am very close..
def dict_cursor(cursor):
for row in cursor:
yield dict(zip(cursor.description, row))
Iterating and printing each row cursor used to result in:
(482072, 602592, 1)
(656680, 820855, 2)
(574968, 718712, 4)
(557532, 696918, 3))
But with dict_cursor I get:
{('NET_SPENT', <type 'cx_Oracle.NUMBER'>, 127, 22, 0, 0, 1): 482072, ('LOT', <type 'cx_Oracle.NUMBER'>, 12, 22, 11, 0, 0): 1, ('NET_COLLECTED', <type 'cx_Oracle.NUMBER'>, 127, 22, 0, 0, 1): 602592}
{('NET_SPENT', <type 'cx_Oracle.NUMBER'>, 127, 22, 0, 0, 1): 656680, ('LOT', <type 'cx_Oracle.NUMBER'>, 12, 22, 11, 0, 0): 2, ('NET_COLLECTED', <type 'cx_Oracle.NUMBER'>, 127, 22, 0, 0, 1): 820855}
{('NET_SPENT', <type 'cx_Oracle.NUMBER'>, 127, 22, 0, 0, 1): 574968, ('LOT', <type 'cx_Oracle.NUMBER'>, 12, 22, 11, 0, 0): 4, ('NET_COLLECTED', <type 'cx_Oracle.NUMBER'>, 127, 22, 0, 0, 1): 718712}
{('NET_SPENT', <type 'cx_Oracle.NUMBER'>, 127, 22, 0, 0, 1): 557532, ('LOT', <type 'cx_Oracle.NUMBER'>, 12, 22, 11, 0, 0): 3, ('NET_COLLECTED', <type 'cx_Oracle.NUMBER'>, 127, 22, 0, 0, 1): 696918}
I only want it to use the key, e.g. 'NET SPENT'.
After refining it a little more, this seems to work:
def dict_cursor(cursor):
for row in cursor:
out = {}
for i,col in enumerate(cursor.description):
out[col[0]] = row[i]
yield out
-
{'NET_COLLECTED': 602592, 'NET_SPENT': 482072, 'LOT': 1}
{'NET_COLLECTED': 820855, 'NET_SPENT': 656680, 'LOT': 2}
{'NET_COLLECTED': 718712, 'NET_SPENT': 574968, 'LOT': 4}
{'NET_COLLECTED': 696918, 'NET_SPENT': 557532, 'LOT': 3}
A:
You could write it in a couple of lines :)
def dict_cursor(cursor):
description = [x[0] for x in cursor.description]
for row in cursor:
yield dict(zip(description, row))
Or if you really want to save space:
simplify_description = lambda cursor: [x[0] for x in cursor.description]
dict_cursor = lambda c, d: dict(zip(d, r) for r in c))
|
Django Backend-neutral DictCursor
|
Is there any way to get a backend-neutral dictionary cursor in Django? This would be a cursor that is a dict rather than a tuple. I am forced to use Oracle for the school project I'm working on.
in Python's MySQLDb module it's called a DictCursor.
With WoLpH's inspiring suggestion I know I am very close..
def dict_cursor(cursor):
for row in cursor:
yield dict(zip(cursor.description, row))
Iterating and printing each row cursor used to result in:
(482072, 602592, 1)
(656680, 820855, 2)
(574968, 718712, 4)
(557532, 696918, 3))
But with dict_cursor I get:
{('NET_SPENT', <type 'cx_Oracle.NUMBER'>, 127, 22, 0, 0, 1): 482072, ('LOT', <type 'cx_Oracle.NUMBER'>, 12, 22, 11, 0, 0): 1, ('NET_COLLECTED', <type 'cx_Oracle.NUMBER'>, 127, 22, 0, 0, 1): 602592}
{('NET_SPENT', <type 'cx_Oracle.NUMBER'>, 127, 22, 0, 0, 1): 656680, ('LOT', <type 'cx_Oracle.NUMBER'>, 12, 22, 11, 0, 0): 2, ('NET_COLLECTED', <type 'cx_Oracle.NUMBER'>, 127, 22, 0, 0, 1): 820855}
{('NET_SPENT', <type 'cx_Oracle.NUMBER'>, 127, 22, 0, 0, 1): 574968, ('LOT', <type 'cx_Oracle.NUMBER'>, 12, 22, 11, 0, 0): 4, ('NET_COLLECTED', <type 'cx_Oracle.NUMBER'>, 127, 22, 0, 0, 1): 718712}
{('NET_SPENT', <type 'cx_Oracle.NUMBER'>, 127, 22, 0, 0, 1): 557532, ('LOT', <type 'cx_Oracle.NUMBER'>, 12, 22, 11, 0, 0): 3, ('NET_COLLECTED', <type 'cx_Oracle.NUMBER'>, 127, 22, 0, 0, 1): 696918}
I only want it to use the key, e.g. 'NET SPENT'.
After refining it a little more, this seems to work:
def dict_cursor(cursor):
for row in cursor:
out = {}
for i,col in enumerate(cursor.description):
out[col[0]] = row[i]
yield out
-
{'NET_COLLECTED': 602592, 'NET_SPENT': 482072, 'LOT': 1}
{'NET_COLLECTED': 820855, 'NET_SPENT': 656680, 'LOT': 2}
{'NET_COLLECTED': 718712, 'NET_SPENT': 574968, 'LOT': 4}
{'NET_COLLECTED': 696918, 'NET_SPENT': 557532, 'LOT': 3}
|
[
"You could write it in a couple of lines :)\ndef dict_cursor(cursor):\n description = [x[0] for x in cursor.description]\n for row in cursor:\n yield dict(zip(description, row))\n\nOr if you really want to save space:\nsimplify_description = lambda cursor: [x[0] for x in cursor.description]\ndict_cursor = lambda c, d: dict(zip(d, r) for r in c))\n\n"
] |
[
7
] |
[] |
[] |
[
"database_cursor",
"dictionary",
"django",
"python"
] |
stackoverflow_0002678991_database_cursor_dictionary_django_python.txt
|
Q:
Regex for finding valid sphinx fields
I'm trying to validate that the fields given to sphinx are valid, but I'm having difficulty.
Imagine that valid fields are cat, mouse, dog, puppy.
Valid searches would then be:
@cat search terms
@(cat) search terms
@(cat, dog) search term
@cat searchterm1 @dog searchterm2
@(cat, dog) searchterm1 @mouse searchterm2
So, I want to use a regular expression to find terms such as cat, dog, mouse in the above examples, and check them against a list of valid terms.
Thus, a query such as:
@(goat)
Would produce an error because goat is not a valid term.
I've gotten so that I can find simple queries such as @cat with this regex: (?:@)([^( ]*)
But I can't figure out how to find the rest.
I'm using python & django, for what that's worth.
A:
To match all allowed fields, the following rather fearful looking regex works:
@((?:cat|mouse|dog|puppy)\b|\((?:(?:cat|mouse|dog|puppy)(?:, *|(?=\))))+\))
It returns these matches, in order: @cat, @(cat), @(cat, dog), @cat, @dog, @(cat, dog), @mouse.
The regex breaks down as follows:
@ # the literal character "@"
( # match group 1
(?:cat|mouse|dog|puppy) # one of your valid search terms (not captured)
\b # a word boundary
| # or...
\( # a literal opening paren
(?: # non-capturing group
(?:cat|mouse|dog|puppy) # one of your valid search terms (not captured)
(?: # non-capturing group
, * # a comma "," plus any number of spaces
| # or...
(?=\)) # a position followed by a closing paren
) # end non-capture group
)+ # end non-capture group, repeat
\) # a literal closing paren
) # end match group one.
Now to identify any invalid search, you would wrap all that in a negative look-ahead:
@(?!(?:cat|mouse|dog|puppy)\b|\((?:(?:cat|mouse|dog|puppy)(?:, *|(?=\))))+\))
--^^
This would identify any @ character after which an invalid search term (or term combination) was attempted. Modifying it so that it also matches the invalid attempt instead of just pointing at it is not that hard anymore.
You would have to prepare (?:cat|mouse|dog|puppy) from your field dynamically and plug it into the static rest of the regex. Should not be too hard to do either.
A:
This pyparsing solution follows a similar logic path as your posted answer. All tags are matched, and then checked against the list of known valid tags, removing them from the reported results. Only those matches that have values left over after removing the valid ones are reported as matches.
from pyparsing import *
# define the pattern of a tag, setting internal results names for easy validation
AT,LPAR,RPAR = map(Suppress,"@()")
term = Word(alphas,alphanums).setResultsName("terms",listAllMatches=True)
sphxTerm = AT + ~White() + ( term | LPAR + delimitedList(term) + RPAR )
# define tags we consider to be valid
valid = set("cat mouse dog".split())
# define a parse action to filter out valid terms, and attach to the sphxTerm
def filterValid(tokens):
tokens = [t for t in tokens.terms if t not in valid]
if not(tokens):
raise ParseException("",0,"")
return tokens
sphxTerm.setParseAction(filterValid)
##### Test out the parser #####
test = """@cat search terms @ house
@(cat) search terms
@(cat, dog) search term @(goat)
@cat searchterm1 @dog searchterm2 @(cat, doggerel)
@(cat, dog) searchterm1 @mouse searchterm2
@caterpillar"""
# scan for invalid terms, and print out the terms and their locations
for t,s,e in sphxTerm.scanString(test):
print "Terms:%s Line: %d Col: %d" % (t, lineno(s, test), col(s, test))
print line(s, test)
print " "*(col(s,test)-1)+"^"
print
With these lovely results:
Terms:['goat'] Line: 3 Col: 29
@(cat, dog) search term @(goat)
^
Terms:['doggerel'] Line: 4 Col: 39
@cat searchterm1 @dog searchterm2 @(cat, doggerel)
^
Terms:['caterpillar'] Line: 6 Col: 5
@caterpillar
^
This last snippet will do all the scanning for you, and just give you the list of found invalid tags:
# print out all of the found invalid terms
print list(set(sum(sphxTerm.searchString(test), ParseResults([]))))
Prints:
['caterpillar', 'goat', 'doggerel']
A:
This should work:
@\((cat|dog|mouse|puppy)\b(,\s*(cat|dog|mouse|puppy)\b)*\)|@(cat|dog|mouse|puppy)\b
It will either match a single @parameter or a parenthesized @(par1, par2) list containing only allowed words (one or more).
It also makes sure that no partial matches are accepted (@caterpillar).
A:
This will match all fields that are cat, dog, mouse, or puppy and combinations thereof.
import re
sphinx_term = "@goat some words to search"
regex = re.compile("@\(?(cat|dog|mouse|puppy)(, ?(cat|dog|mouse|puppy))*\)? ")
if regex.search(sphinx_term):
send the query to sphinx...
A:
Try this:
field_re = re.compile(r"@(?:([^()\s]+)|\([^()]+\))")
A single field name (like cat in @cat) will be captured in group #1, while the names in a parenthesized list like @(cat, dog) will be stored in group #2. In the latter case you'll need to break the list down with split() or something; there's no way to capture the names individually with a Python regex.
A:
I ended up doing this a different way, since none of the above worked. First I found the fields like @cat, with this:
attributes = re.findall('(?:@)([^\( ]*)', query)
Next, I found the more complicated ones, with this:
regex0 = re.compile('''
@ # at sign
(?: # start non-capturing group
\w+ # non-whitespace, one or more
\b # a boundary character (i.e. no more \w)
| # OR
( # capturing group
\( # left paren
[^@(),]+ # not an @(),
(?: # another non-caputing group
, * # a comma, then some spaces
[^@(),]+ # not @(),
)* # some quantity of this non-capturing group
\) # a right paren
) # end of non-capuring group
) # end of non-capturing group
''', re.VERBOSE)
# and this puts them into the attributes list.
groupedAttributes = re.findall(regex0, query)
for item in groupedAttributes:
attributes.extend(item.strip("(").strip(")").split(", "))
Next, I checked if the attributes I found were valid, and added them (uniquely to an array):
# check if the values are valid.
validRegex = re.compile(r'^mice$|^mouse$|^cat$|^dog$')
# if they aren't add them to a new list.
badAttrs = []
for attribute in attributes:
if len(attribute) == 0:
# if it's a zero length attribute, we punt
continue
if validRegex.search(attribute.lower()) == None:
# if the attribute from the search isn't in the valid list
if attribute not in badAttrs:
# and the attribute isn't already in the list
badAttrs.append(attribute)
Thanks all for the help though. I'm very glad to have had it!
|
Regex for finding valid sphinx fields
|
I'm trying to validate that the fields given to sphinx are valid, but I'm having difficulty.
Imagine that valid fields are cat, mouse, dog, puppy.
Valid searches would then be:
@cat search terms
@(cat) search terms
@(cat, dog) search term
@cat searchterm1 @dog searchterm2
@(cat, dog) searchterm1 @mouse searchterm2
So, I want to use a regular expression to find terms such as cat, dog, mouse in the above examples, and check them against a list of valid terms.
Thus, a query such as:
@(goat)
Would produce an error because goat is not a valid term.
I've gotten so that I can find simple queries such as @cat with this regex: (?:@)([^( ]*)
But I can't figure out how to find the rest.
I'm using python & django, for what that's worth.
|
[
"To match all allowed fields, the following rather fearful looking regex works:\n\n@((?:cat|mouse|dog|puppy)\\b|\\((?:(?:cat|mouse|dog|puppy)(?:, *|(?=\\))))+\\))\n\nIt returns these matches, in order: @cat, @(cat), @(cat, dog), @cat, @dog, @(cat, dog), @mouse.\nThe regex breaks down as follows:\n\n@ # the literal character \"@\"\n( # match group 1\n (?:cat|mouse|dog|puppy) # one of your valid search terms (not captured)\n \\b # a word boundary\n | # or...\n \\( # a literal opening paren\n (?: # non-capturing group\n (?:cat|mouse|dog|puppy) # one of your valid search terms (not captured)\n (?: # non-capturing group\n , * # a comma \",\" plus any number of spaces\n | # or...\n (?=\\)) # a position followed by a closing paren\n ) # end non-capture group\n )+ # end non-capture group, repeat\n \\) # a literal closing paren\n) # end match group one.\n\nNow to identify any invalid search, you would wrap all that in a negative look-ahead:\n\n@(?!(?:cat|mouse|dog|puppy)\\b|\\((?:(?:cat|mouse|dog|puppy)(?:, *|(?=\\))))+\\))\n--^^\n\nThis would identify any @ character after which an invalid search term (or term combination) was attempted. Modifying it so that it also matches the invalid attempt instead of just pointing at it is not that hard anymore.\nYou would have to prepare (?:cat|mouse|dog|puppy) from your field dynamically and plug it into the static rest of the regex. Should not be too hard to do either.\n",
"This pyparsing solution follows a similar logic path as your posted answer. All tags are matched, and then checked against the list of known valid tags, removing them from the reported results. Only those matches that have values left over after removing the valid ones are reported as matches.\nfrom pyparsing import *\n\n# define the pattern of a tag, setting internal results names for easy validation\nAT,LPAR,RPAR = map(Suppress,\"@()\")\nterm = Word(alphas,alphanums).setResultsName(\"terms\",listAllMatches=True)\nsphxTerm = AT + ~White() + ( term | LPAR + delimitedList(term) + RPAR )\n\n# define tags we consider to be valid\nvalid = set(\"cat mouse dog\".split())\n\n# define a parse action to filter out valid terms, and attach to the sphxTerm\ndef filterValid(tokens):\n tokens = [t for t in tokens.terms if t not in valid]\n if not(tokens):\n raise ParseException(\"\",0,\"\")\n return tokens\nsphxTerm.setParseAction(filterValid)\n\n\n##### Test out the parser #####\n\ntest = \"\"\"@cat search terms @ house\n @(cat) search terms \n @(cat, dog) search term @(goat)\n @cat searchterm1 @dog searchterm2 @(cat, doggerel)\n @(cat, dog) searchterm1 @mouse searchterm2 \n @caterpillar\"\"\"\n\n# scan for invalid terms, and print out the terms and their locations\nfor t,s,e in sphxTerm.scanString(test):\n print \"Terms:%s Line: %d Col: %d\" % (t, lineno(s, test), col(s, test))\n print line(s, test)\n print \" \"*(col(s,test)-1)+\"^\"\n print\n\nWith these lovely results:\nTerms:['goat'] Line: 3 Col: 29\n @(cat, dog) search term @(goat)\n ^\n\nTerms:['doggerel'] Line: 4 Col: 39\n @cat searchterm1 @dog searchterm2 @(cat, doggerel)\n ^\n\nTerms:['caterpillar'] Line: 6 Col: 5\n @caterpillar\n ^\n\nThis last snippet will do all the scanning for you, and just give you the list of found invalid tags:\n# print out all of the found invalid terms\nprint list(set(sum(sphxTerm.searchString(test), ParseResults([]))))\n\nPrints:\n['caterpillar', 'goat', 'doggerel']\n\n",
"This should work:\n@\\((cat|dog|mouse|puppy)\\b(,\\s*(cat|dog|mouse|puppy)\\b)*\\)|@(cat|dog|mouse|puppy)\\b\n\nIt will either match a single @parameter or a parenthesized @(par1, par2) list containing only allowed words (one or more).\nIt also makes sure that no partial matches are accepted (@caterpillar).\n",
"This will match all fields that are cat, dog, mouse, or puppy and combinations thereof.\nimport re\nsphinx_term = \"@goat some words to search\"\nregex = re.compile(\"@\\(?(cat|dog|mouse|puppy)(, ?(cat|dog|mouse|puppy))*\\)? \")\nif regex.search(sphinx_term):\n send the query to sphinx...\n\n",
"Try this:\nfield_re = re.compile(r\"@(?:([^()\\s]+)|\\([^()]+\\))\")\n\nA single field name (like cat in @cat) will be captured in group #1, while the names in a parenthesized list like @(cat, dog) will be stored in group #2. In the latter case you'll need to break the list down with split() or something; there's no way to capture the names individually with a Python regex.\n",
"I ended up doing this a different way, since none of the above worked. First I found the fields like @cat, with this: \nattributes = re.findall('(?:@)([^\\( ]*)', query)\n\nNext, I found the more complicated ones, with this:\nregex0 = re.compile('''\n @ # at sign\n (?: # start non-capturing group\n \\w+ # non-whitespace, one or more\n \\b # a boundary character (i.e. no more \\w)\n | # OR\n ( # capturing group\n \\( # left paren\n [^@(),]+ # not an @(),\n (?: # another non-caputing group\n , * # a comma, then some spaces\n [^@(),]+ # not @(),\n )* # some quantity of this non-capturing group\n \\) # a right paren\n ) # end of non-capuring group\n ) # end of non-capturing group\n ''', re.VERBOSE)\n\n# and this puts them into the attributes list.\ngroupedAttributes = re.findall(regex0, query)\nfor item in groupedAttributes:\n attributes.extend(item.strip(\"(\").strip(\")\").split(\", \"))\n\nNext, I checked if the attributes I found were valid, and added them (uniquely to an array):\n# check if the values are valid.\nvalidRegex = re.compile(r'^mice$|^mouse$|^cat$|^dog$')\n\n# if they aren't add them to a new list.\nbadAttrs = []\nfor attribute in attributes:\n if len(attribute) == 0:\n # if it's a zero length attribute, we punt\n continue\n if validRegex.search(attribute.lower()) == None:\n # if the attribute from the search isn't in the valid list\n if attribute not in badAttrs:\n # and the attribute isn't already in the list\n badAttrs.append(attribute)\n\nThanks all for the help though. I'm very glad to have had it!\n"
] |
[
3,
2,
1,
0,
0,
0
] |
[] |
[] |
[
"django",
"python",
"regex",
"sphinx"
] |
stackoverflow_0002677713_django_python_regex_sphinx.txt
|
Q:
how to read specific number of floats from file in python?
I am reading a text file from the web. The file starts with some header lines containing the number of data points, followed the actual vertices (3 coordinates each). The file looks like:
# comment
HEADER TEXT
POINTS 6 float
1.1 2.2 3.3 4.4 5.5 6.6 7.7 8.8 9.9
1.1 2.2 3.3 4.4 5.5 6.6 7.7 8.8 9.9
POLYGONS
the line starting with the word POINTS contains the number of vertices (in this case we have 3 vertices per line, but that could change)
This is how I am reading it right now:
ur=urlopen("http://.../file.dat")
j=0
contents = []
while 1:
line = ur.readline()
if not line:
break
else:
line=line.lower()
if 'points' in line :
myline=line.strip()
word=myline.split()
node_number=int(word[1])
node_type=word[2]
while 'polygons' not in line :
line = ur.readline()
line=line.lower()
myline=line.split()
i=0
while(i<len(myline)):
contents[j]=float(myline[i])
i=i+1
j=j+1
How can I read a specified number of floats instead of reading line by line as strings and converting to floating numbers?
Instead of ur.readline() I want to read the specified number of elements in the file
Any suggestion is welcome..
A:
I'm not entirely sure what your goal is from your explanation.
For the record, here is code that does basically the same thing as yours seems to be trying to that uses some techniques I would employ over the ones you have chosen. It's usually a sign that you're doing something wrong if you're using while loops and indices and indeed your code does not work because contents[j] = ... will be an IndexError.
lines = (line.strip().lower() for line in your_web_page)
points_line = next(line for line in lines if 'points' in line)
_, node_number, node_type = points_line.split()
node_number = int(node_number)
def get_contents(lines):
for line in lines:
if 'polygons' in line:
break
for number in line.split():
yield float(number)
contents = list(get_contents(lines))
If you are more explicit about the new thing it is you want to do, maybe someone can provide a better answer for your ultimate goal.
A:
Here is a no-fuss cleanup of your code that should make the looping over the contents much faster.
ur=urlopen("http://.../file.dat")
contents = []
node_number = 0
node_type = None
while 1:
line = ur.readline()
if not line:
break
line = line.lower()
if 'points' in line :
word = line.split()
node_number = int(word[1])
node_type = word[2]
while 1:
pieces = ur.readline().split()
if not pieces: continue # or break or issue error message
if pieces[0].lower() == 'polygons': break
contents.extend(map(float, pieces))
assert len(contents) == node_number * 3
If you wrap the code in a function and call that, it will run even faster (because you will be accessing local variables instead of global ones).
Note that the most significant changes are near/at the end of the script.
HOWEVER: stand back and think about this for a few seconds: how much of the time is taken up by the ur.readline() and how much by unpacking the lines?
|
how to read specific number of floats from file in python?
|
I am reading a text file from the web. The file starts with some header lines containing the number of data points, followed the actual vertices (3 coordinates each). The file looks like:
# comment
HEADER TEXT
POINTS 6 float
1.1 2.2 3.3 4.4 5.5 6.6 7.7 8.8 9.9
1.1 2.2 3.3 4.4 5.5 6.6 7.7 8.8 9.9
POLYGONS
the line starting with the word POINTS contains the number of vertices (in this case we have 3 vertices per line, but that could change)
This is how I am reading it right now:
ur=urlopen("http://.../file.dat")
j=0
contents = []
while 1:
line = ur.readline()
if not line:
break
else:
line=line.lower()
if 'points' in line :
myline=line.strip()
word=myline.split()
node_number=int(word[1])
node_type=word[2]
while 'polygons' not in line :
line = ur.readline()
line=line.lower()
myline=line.split()
i=0
while(i<len(myline)):
contents[j]=float(myline[i])
i=i+1
j=j+1
How can I read a specified number of floats instead of reading line by line as strings and converting to floating numbers?
Instead of ur.readline() I want to read the specified number of elements in the file
Any suggestion is welcome..
|
[
"I'm not entirely sure what your goal is from your explanation. \nFor the record, here is code that does basically the same thing as yours seems to be trying to that uses some techniques I would employ over the ones you have chosen. It's usually a sign that you're doing something wrong if you're using while loops and indices and indeed your code does not work because contents[j] = ... will be an IndexError.\nlines = (line.strip().lower() for line in your_web_page)\n\npoints_line = next(line for line in lines if 'points' in line)\n_, node_number, node_type = points_line.split()\nnode_number = int(node_number)\n\ndef get_contents(lines):\n for line in lines:\n if 'polygons' in line:\n break\n\n for number in line.split():\n yield float(number)\n\ncontents = list(get_contents(lines))\n\nIf you are more explicit about the new thing it is you want to do, maybe someone can provide a better answer for your ultimate goal. \n",
"Here is a no-fuss cleanup of your code that should make the looping over the contents much faster.\nur=urlopen(\"http://.../file.dat\")\ncontents = []\nnode_number = 0\nnode_type = None\nwhile 1:\n line = ur.readline()\n if not line:\n break\n line = line.lower() \n if 'points' in line :\n word = line.split()\n node_number = int(word[1])\n node_type = word[2]\n while 1:\n pieces = ur.readline().split()\n if not pieces: continue # or break or issue error message\n if pieces[0].lower() == 'polygons': break\n contents.extend(map(float, pieces))\nassert len(contents) == node_number * 3\n\nIf you wrap the code in a function and call that, it will run even faster (because you will be accessing local variables instead of global ones).\nNote that the most significant changes are near/at the end of the script.\nHOWEVER: stand back and think about this for a few seconds: how much of the time is taken up by the ur.readline() and how much by unpacking the lines? \n"
] |
[
3,
0
] |
[] |
[] |
[
"python",
"readfile"
] |
stackoverflow_0002679290_python_readfile.txt
|
Q:
Keep PyGTK Button from Resizing on Label Change
I'm working on a PyGTK app with some Buttons that, when clicked, give a text entry dialog, then set the text on the button to whatever was entered in the box. The problem is that if the text is longer than the button can show, the button changes size to accomodate. How do I keep GTK Buttons from resizing when the text changes?
A:
Have you tried set_size_request?
http://library.gnome.org/devel/pygtk/stable/class-gtkwidget.html#method-gtkwidget--set-size-request
button = gtk.Button("text on button")
button.set_size_request(width=30, height=20)
See:
http://www.pygtk.org/docs/pygtk/class-gtkwidget.html#method-gtkwidget--set-size-request
In glade, you can set "Width request" in the "Common" tab.
|
Keep PyGTK Button from Resizing on Label Change
|
I'm working on a PyGTK app with some Buttons that, when clicked, give a text entry dialog, then set the text on the button to whatever was entered in the box. The problem is that if the text is longer than the button can show, the button changes size to accomodate. How do I keep GTK Buttons from resizing when the text changes?
|
[
"Have you tried set_size_request?\nhttp://library.gnome.org/devel/pygtk/stable/class-gtkwidget.html#method-gtkwidget--set-size-request\nbutton = gtk.Button(\"text on button\")\nbutton.set_size_request(width=30, height=20)\n\nSee:\nhttp://www.pygtk.org/docs/pygtk/class-gtkwidget.html#method-gtkwidget--set-size-request\nIn glade, you can set \"Width request\" in the \"Common\" tab.\n"
] |
[
1
] |
[] |
[] |
[
"button",
"pygtk",
"python",
"user_interface"
] |
stackoverflow_0002679500_button_pygtk_python_user_interface.txt
|
Q:
jQuery as a replacement for Django or Web2Py
I was planning to write a new webapp, I figured out two options for my backend - web2py or django.
I recently came across jQuery and found it to be very cool.
Could I just use jQuery as a replacement for django and web2py and finish this webapp.
Some features that I'm going to implement - user profiles, users can add content to the website, etc.
Is it possible to do solely in jQuery ?
A:
It's definitely possible to do all of the front-end in Javascript on the client's browser (unless you have to support JS-less or very old browser), reducing the server's role to that of offering a REST-ish interface for the client's AJAX calls (as well of course as serving static files of various sort;).
This approach is known as thin-server architecture and jQuery (just as much as, say, Dojo or Closure) is suitable for implementing the client-side part of it. If you can restrict yourself to advanced browsers with HTML5 goodies, you can do even more client-side, further lightening the load on your server and enhancing scalability (how much you can demand of the browser varies widely with your app, of course -- if it targets iPhone, Android or other advanced mobile phones specifically, or if it's an enterprise-internal web app where the users can be made to use Chrome or Safari, say, you can be far more demanding than if you want millions of random users out on the open web;-).
For the server-side part I'd suggest an ultralight microframework on top of Werkzeug and WSGI, such as Flask or (if the server uses App Engine) tipfy (there are others, esp. for GAE -- see here for a list).
I would not place on the client-side anything that needs "security", though - since all of your Javascript code, jQuery or not, can be examined and hacked easily, anything you want to be "safe" should live server-side.
A:
No. jQuery is a client side technology as opposed to the 2 server side frameworks you mentioned.
A:
No. jQuery is for client-side interfaces. web2py and Django are for server-side. You need both. In fact web2py contains jQuery and has many plugins that combine client-side and server-side functionality and are based on jQuery (http://web2py.com/plugins). jQuery is agnostic on which server-side framework you use (web2py, Django or other) and server-side frameworks are also agnostic on which client library you use (jQuery, prototype, etc.). In the web2py world we tend to prefer jQuery.
EDIT: you can move a lot (if not all) of the presentation from the server to the client but you still need centralized storage which requires the serverside part.
|
jQuery as a replacement for Django or Web2Py
|
I was planning to write a new webapp, I figured out two options for my backend - web2py or django.
I recently came across jQuery and found it to be very cool.
Could I just use jQuery as a replacement for django and web2py and finish this webapp.
Some features that I'm going to implement - user profiles, users can add content to the website, etc.
Is it possible to do solely in jQuery ?
|
[
"It's definitely possible to do all of the front-end in Javascript on the client's browser (unless you have to support JS-less or very old browser), reducing the server's role to that of offering a REST-ish interface for the client's AJAX calls (as well of course as serving static files of various sort;).\nThis approach is known as thin-server architecture and jQuery (just as much as, say, Dojo or Closure) is suitable for implementing the client-side part of it. If you can restrict yourself to advanced browsers with HTML5 goodies, you can do even more client-side, further lightening the load on your server and enhancing scalability (how much you can demand of the browser varies widely with your app, of course -- if it targets iPhone, Android or other advanced mobile phones specifically, or if it's an enterprise-internal web app where the users can be made to use Chrome or Safari, say, you can be far more demanding than if you want millions of random users out on the open web;-).\nFor the server-side part I'd suggest an ultralight microframework on top of Werkzeug and WSGI, such as Flask or (if the server uses App Engine) tipfy (there are others, esp. for GAE -- see here for a list).\nI would not place on the client-side anything that needs \"security\", though - since all of your Javascript code, jQuery or not, can be examined and hacked easily, anything you want to be \"safe\" should live server-side.\n",
"No. jQuery is a client side technology as opposed to the 2 server side frameworks you mentioned.\n",
"No. jQuery is for client-side interfaces. web2py and Django are for server-side. You need both. In fact web2py contains jQuery and has many plugins that combine client-side and server-side functionality and are based on jQuery (http://web2py.com/plugins). jQuery is agnostic on which server-side framework you use (web2py, Django or other) and server-side frameworks are also agnostic on which client library you use (jQuery, prototype, etc.). In the web2py world we tend to prefer jQuery.\nEDIT: you can move a lot (if not all) of the presentation from the server to the client but you still need centralized storage which requires the serverside part. \n"
] |
[
8,
4,
3
] |
[] |
[] |
[
"django",
"jquery",
"python",
"web2py"
] |
stackoverflow_0002677117_django_jquery_python_web2py.txt
|
Q:
How to get the coordinates of an object in a tkinter canvas?
I can't seem to figure out how to retrieve the x,y position of an oval created on a Tkinter canvas using Python via
c.create_oval(x0, y0, x1, y2)
I understand that Tkinter creates the oval inside the box specified by x0,y0,x1,y2 and if I can get those coordinates that would also work.
I need the coordinates to move the oval by an offset equal to the mouse coords and the actual oval.
A:
Assign the results of c.create_oval to x -- that's the "object ID" of the oval. Then,
c.coords(x)
gives you the (x1, y1, x2, y2) tuple of the oval's coordinates (you call coords with new coordinates following the x to move the oval).
|
How to get the coordinates of an object in a tkinter canvas?
|
I can't seem to figure out how to retrieve the x,y position of an oval created on a Tkinter canvas using Python via
c.create_oval(x0, y0, x1, y2)
I understand that Tkinter creates the oval inside the box specified by x0,y0,x1,y2 and if I can get those coordinates that would also work.
I need the coordinates to move the oval by an offset equal to the mouse coords and the actual oval.
|
[
"Assign the results of c.create_oval to x -- that's the \"object ID\" of the oval. Then,\nc.coords(x)\n\ngives you the (x1, y1, x2, y2) tuple of the oval's coordinates (you call coords with new coordinates following the x to move the oval).\n"
] |
[
45
] |
[] |
[] |
[
"python",
"tkinter"
] |
stackoverflow_0002679418_python_tkinter.txt
|
Q:
python gio waiting for async operations to be done
I have to mount a WebDav location and wait for the operation to be finished before to proceed (it's a script).
So I'm using the library in this way:
location = gio.File("dav://server.bb")
location.mount_enclosing_volume(*args,**kw) # The setup is not much relevant
location.get_path() # Returns None because it's not yet mounted since the call is async
How to wait until the device is mounted?
A:
To wait for termination, you need to call mount_enclosing_volume_finished with the async-result object returned by mount_enclosing_volume (alternatively, you could pass the latter a callback, if you want to operate asynchronously, but it looks like you want sync-like operations here).
|
python gio waiting for async operations to be done
|
I have to mount a WebDav location and wait for the operation to be finished before to proceed (it's a script).
So I'm using the library in this way:
location = gio.File("dav://server.bb")
location.mount_enclosing_volume(*args,**kw) # The setup is not much relevant
location.get_path() # Returns None because it's not yet mounted since the call is async
How to wait until the device is mounted?
|
[
"To wait for termination, you need to call mount_enclosing_volume_finished with the async-result object returned by mount_enclosing_volume (alternatively, you could pass the latter a callback, if you want to operate asynchronously, but it looks like you want sync-like operations here).\n"
] |
[
1
] |
[] |
[] |
[
"asynchronous",
"file_io",
"pygtk",
"python"
] |
stackoverflow_0002676951_asynchronous_file_io_pygtk_python.txt
|
Q:
Serializing Python bytestrings to JSON, preserving ordinal character values
I have some binary data produced as base-256 bytestrings in Python (2.x). I need to read these into JavaScript, preserving the ordinal value of each byte (char) in the string. If you'll allow me to mix languages, I want to encode a string s in Python such that ord(s[i]) == s.charCodeAt(i) after I've read it back into JavaScript.
The cleanest way to do this seems to be to serialize my Python strings to JSON. However, json.dump doesn't like my bytestrings, despite fiddling with the ensure_ascii and encoding parameters. Is there a way to encode bytestrings to Unicode strings that preserves ordinal character values? Otherwise I think I need to encode the characters above the ASCII range into JSON-style \u1234 escapes; but a codec like this does not seem to be among Python's codecs.
Is there an easy way to serialize Python bytestrings to JSON, preserving char values, or do I need to write my own encoder?
A:
Is there a way to encode bytestrings
to Unicode strings that preserves
ordinal character values?
The byte -> unicode transformation is called decode, not encode. But yes, decoding with a codec such as iso-8859-1 should indeed "preserve ordinal character values" as you wish.
A:
Could you just use Base64? (Python base64 module, Javascript has several implementations, one of which is here.)
No reason to use escaped ASCII or UTF-8 unless your data is almost all text.
|
Serializing Python bytestrings to JSON, preserving ordinal character values
|
I have some binary data produced as base-256 bytestrings in Python (2.x). I need to read these into JavaScript, preserving the ordinal value of each byte (char) in the string. If you'll allow me to mix languages, I want to encode a string s in Python such that ord(s[i]) == s.charCodeAt(i) after I've read it back into JavaScript.
The cleanest way to do this seems to be to serialize my Python strings to JSON. However, json.dump doesn't like my bytestrings, despite fiddling with the ensure_ascii and encoding parameters. Is there a way to encode bytestrings to Unicode strings that preserves ordinal character values? Otherwise I think I need to encode the characters above the ASCII range into JSON-style \u1234 escapes; but a codec like this does not seem to be among Python's codecs.
Is there an easy way to serialize Python bytestrings to JSON, preserving char values, or do I need to write my own encoder?
|
[
"\nIs there a way to encode bytestrings\n to Unicode strings that preserves\n ordinal character values?\n\nThe byte -> unicode transformation is called decode, not encode. But yes, decoding with a codec such as iso-8859-1 should indeed \"preserve ordinal character values\" as you wish.\n",
"Could you just use Base64? (Python base64 module, Javascript has several implementations, one of which is here.)\nNo reason to use escaped ASCII or UTF-8 unless your data is almost all text.\n"
] |
[
5,
3
] |
[] |
[] |
[
"json",
"python"
] |
stackoverflow_0002679936_json_python.txt
|
Q:
Swig - wrapping C struct
I am trying to write Python wrap for C code which uses struct.
modules.c:
struct foo
{
int a;
};
struct foo bar;
modulues.i
%module nepal
%{
struct foo
{
int a;
}
%}
extern struct foo bar;
But during compiling I am given error:
In function ‘Swig_var_bar_set’:
error: ‘bar’ undeclared (first use in this function)
Could you be so kind to help me how to correctly define export struct variable ?
A:
Try this:
%module nepal
%{
struct foo
{
int a;
};
extern struct foo bar;
%}
struct foo
{
int a;
};
extern struct foo bar;
The code in %{ %} is inserted in the wrapper, and the code below it is parsed to create the wrapper. It's easier to put this all in a header file so it is not so repetitive:
modules.h
struct foo
{
int a;
};
extern struct foo bar;
modules.c
#include "modules.h"
struct foo bar;
modules.i
%module nepal
%{
#include "modules.h"
%}
%include "modules.h"
|
Swig - wrapping C struct
|
I am trying to write Python wrap for C code which uses struct.
modules.c:
struct foo
{
int a;
};
struct foo bar;
modulues.i
%module nepal
%{
struct foo
{
int a;
}
%}
extern struct foo bar;
But during compiling I am given error:
In function ‘Swig_var_bar_set’:
error: ‘bar’ undeclared (first use in this function)
Could you be so kind to help me how to correctly define export struct variable ?
|
[
"Try this:\n%module nepal\n%{\n struct foo\n {\n int a;\n };\n\n extern struct foo bar;\n%}\n\nstruct foo\n{\n int a;\n};\n\nextern struct foo bar;\n\nThe code in %{ %} is inserted in the wrapper, and the code below it is parsed to create the wrapper. It's easier to put this all in a header file so it is not so repetitive:\nmodules.h\nstruct foo\n{\n int a;\n};\n\nextern struct foo bar;\n\nmodules.c\n#include \"modules.h\"\nstruct foo bar;\n\nmodules.i\n%module nepal\n%{\n #include \"modules.h\"\n%}\n\n%include \"modules.h\"\n\n"
] |
[
2
] |
[] |
[] |
[
"c",
"python",
"struct",
"swig"
] |
stackoverflow_0002676453_c_python_struct_swig.txt
|
Q:
exceptions with python unicode encode/decode functions (why doesn't errors=ignore actually ignore them??)
Does anyone know why the string conversion functions throw exceptions when errors="ignore" is passed? How can I convert from regular Python string objects to unicode without errors being thrown? Thanks very much!
python -c "import codecs; codecs.open('tmp', 'wb', encoding='utf8', errors='ignore').write('кошка')"
returns
Traceback (most recent call last):
File "", line 1, in
File "/usr/lib/python2.6/codecs.py", line 686, in write
return self.writer.write(data)
File "/usr/lib/python2.6/codecs.py", line 351, in write
data, consumed = self.encode(object, self.errors)
UnicodeDecodeError: 'ascii' codec can't decode byte 0xd0 in position 0: ordinal not in range(128)
EDIT -- thanks for the responses, but does anyone know how to convert the literal above, not using the "u" prefix? The reason being is that you could, of course, be dealing with something that wasn't a constant :)
A:
The write method (in Python 2) takes a unicode object, and you're passing it a str -- so the encode call in codecs.py line 351 is first trying to build a unicode object (with the default codec, 'ascii'). Fix is easy: change the write call to
write(u'кошка')
The u prefix tells Python you're using a Unicode object, and it should be fine.
A:
In Python 2.x use write('кошка'.decode('utf-8') instead of write('кошка').
You can use other encoding too instead of 'utf-8'.
Hopefully it will not throw any error ...
A:
a non-solution (from question author) I just found out: use python3
python3 -c "import codecs; codecs.open('tmp', 'wb', encoding='utf8', errors='ignore').write('кошка')"
A:
problem is here ===>>>> write('кошка')
You are writing a str object, the recipient is expecting a unicode object, so it tries to convert it to unicode using the default encoding (ascii), which of course (?) produces the well-known (?) UnicodeDecodeError: 'ascii' codec can't decode byte 0xXX in position 0: ordinal not in range(128)
The whole point of using the codecs module like that is to get it to convert your unicode objects to utf8-encoded on the fly -- so feed it unicode
Update How to convert the literal or non-literal:
unicode_object = literal_or_whatever.decode("UNKNOWN_ENCODING")
Do you know how your literal is encoded? Would you like to tell us what you are trying to accomplish? A one liner with python -c isn't much help ;-)
|
exceptions with python unicode encode/decode functions (why doesn't errors=ignore actually ignore them??)
|
Does anyone know why the string conversion functions throw exceptions when errors="ignore" is passed? How can I convert from regular Python string objects to unicode without errors being thrown? Thanks very much!
python -c "import codecs; codecs.open('tmp', 'wb', encoding='utf8', errors='ignore').write('кошка')"
returns
Traceback (most recent call last):
File "", line 1, in
File "/usr/lib/python2.6/codecs.py", line 686, in write
return self.writer.write(data)
File "/usr/lib/python2.6/codecs.py", line 351, in write
data, consumed = self.encode(object, self.errors)
UnicodeDecodeError: 'ascii' codec can't decode byte 0xd0 in position 0: ordinal not in range(128)
EDIT -- thanks for the responses, but does anyone know how to convert the literal above, not using the "u" prefix? The reason being is that you could, of course, be dealing with something that wasn't a constant :)
|
[
"The write method (in Python 2) takes a unicode object, and you're passing it a str -- so the encode call in codecs.py line 351 is first trying to build a unicode object (with the default codec, 'ascii'). Fix is easy: change the write call to \nwrite(u'кошка')\n\nThe u prefix tells Python you're using a Unicode object, and it should be fine.\n",
"In Python 2.x use write('кошка'.decode('utf-8') instead of write('кошка').\nYou can use other encoding too instead of 'utf-8'.\nHopefully it will not throw any error ...\n",
"a non-solution (from question author) I just found out: use python3\npython3 -c \"import codecs; codecs.open('tmp', 'wb', encoding='utf8', errors='ignore').write('кошка')\"\n\n",
"problem is here ===>>>> write('кошка')\nYou are writing a str object, the recipient is expecting a unicode object, so it tries to convert it to unicode using the default encoding (ascii), which of course (?) produces the well-known (?) UnicodeDecodeError: 'ascii' codec can't decode byte 0xXX in position 0: ordinal not in range(128)\nThe whole point of using the codecs module like that is to get it to convert your unicode objects to utf8-encoded on the fly -- so feed it unicode\nUpdate How to convert the literal or non-literal: \nunicode_object = literal_or_whatever.decode(\"UNKNOWN_ENCODING\")\nDo you know how your literal is encoded? Would you like to tell us what you are trying to accomplish? A one liner with python -c isn't much help ;-)\n"
] |
[
3,
3,
2,
1
] |
[] |
[] |
[
"python",
"unicode"
] |
stackoverflow_0002679930_python_unicode.txt
|
Q:
maya2008 win32api 64 bit python
How is it possible to run import win32api successfully on a 64bit maya version 2008?
The following error occurs:
Error: No module named win32api
Traceback (most recent call last):
File "", line 1, in
ImportError: No module named win32api
I need to get mouse cursor position in python so that I can place window exactly in that position. Is there any other way to get it?
Best regards,
kNish
A:
Maya uses its own Python installation. You need to add the path where pywin32 is installed by one way or another ... you can create a .pth file in
C:\Program
Files\Autodesk\Maya2009\Python\Lib\site-packages\
Also, like Adam pointed out, make sure you have the 64 bit pywin32 installed.
Here's an article talking about this subject:
http://www.rtrowbridge.com/blog/2008/11/27/maya-python-import-scripts/
Edit:
Yeah indeed I think they don't provide PyWin32 for Python25 x64:
Available for AMD64 versions of
Windows for Python 2.6 and later
(support for Python 2.5 is just too
hard, sorry). Lots of help from
Roger, Steve Yin and Sidnei da
Silva.
http://sourceforge.net/project/shownotes.php?release_id=603349
|
maya2008 win32api 64 bit python
|
How is it possible to run import win32api successfully on a 64bit maya version 2008?
The following error occurs:
Error: No module named win32api
Traceback (most recent call last):
File "", line 1, in
ImportError: No module named win32api
I need to get mouse cursor position in python so that I can place window exactly in that position. Is there any other way to get it?
Best regards,
kNish
|
[
"Maya uses its own Python installation. You need to add the path where pywin32 is installed by one way or another ... you can create a .pth file in \n\nC:\\Program\n Files\\Autodesk\\Maya2009\\Python\\Lib\\site-packages\\\n\nAlso, like Adam pointed out, make sure you have the 64 bit pywin32 installed.\nHere's an article talking about this subject: \nhttp://www.rtrowbridge.com/blog/2008/11/27/maya-python-import-scripts/\nEdit:\nYeah indeed I think they don't provide PyWin32 for Python25 x64:\n\nAvailable for AMD64 versions of\n Windows for Python 2.6 and later\n (support for Python 2.5 is just too\n hard, sorry). Lots of help from\n Roger, Steve Yin and Sidnei da\n Silva.\n\nhttp://sourceforge.net/project/shownotes.php?release_id=603349\n"
] |
[
1
] |
[] |
[] |
[
"maya",
"python"
] |
stackoverflow_0002680589_maya_python.txt
|
Q:
Right clicking on QHeaderView inside of QTreeView
I've written a descendant of QTreeView with multiple columns. I want to create a popup menu that appears whe nthe user right-clicks over the column headers. I have tried catching signals from QTreeView for this, but QTreeView doesn't seem to emit signals on the headers. QTreeView.header() does. I therefore believe I must either:
1: connect one of QHeaderView's signals to a popup function - I have been unable to find a signal that is triggered on a single right click - I have tried sectionClicked, sectionHandleDoubleClicked, sectionDoubleClicked, sectionPressed (not surprised the double click functions didn't catch a single right click - but they do catch a double right click)
self.header().sectionClicked.connect(self.headerMenu)
self.header().sectionHandleDoubleClicked.connect(self.headerMenu)
self.header().sectionDoubleClicked.connect(self.headerMenu)
self.header().sectionPressed.connect(self.headerMenu)
or,
2: write a descendant of QHeaderView with my own MousePressEvent function, and use that for my headers. I have so far been unsuccessful in connecting the new header class to the QTreeView descendant. I keep getting a Segmentation Fault on runtime, with no more explanation.
#in DiceView's init, where DiceHeaders is the QHeaderView descendant
self.setHeader(DiceHeaders())
Any ideas?
A:
I discovered the setContextMenuPolicy function:
self.header().setContextMenuPolicy(QtCore.Qt.CustomContextMenu)
self.header().customContextMenuRequested.connect(self.headerMenu)
Then, in headerMenu:
def headerMenu(self, pos):
globalPos = self.mapToGlobal(pos)
menu = QMenu()
menu.addAction("test item")
selectedItem = menu.exec_(globalPos)
if selectedItem:
print "selected: ", selectedItem
A:
I'd go for solution n°2 : Write your own class inheriting QHeaderView.
Your segmentation fault may be coming from a python/pyqt glitch ?
You should make sure that you DiceHeaders object exists by keeping a reference to it.
|
Right clicking on QHeaderView inside of QTreeView
|
I've written a descendant of QTreeView with multiple columns. I want to create a popup menu that appears whe nthe user right-clicks over the column headers. I have tried catching signals from QTreeView for this, but QTreeView doesn't seem to emit signals on the headers. QTreeView.header() does. I therefore believe I must either:
1: connect one of QHeaderView's signals to a popup function - I have been unable to find a signal that is triggered on a single right click - I have tried sectionClicked, sectionHandleDoubleClicked, sectionDoubleClicked, sectionPressed (not surprised the double click functions didn't catch a single right click - but they do catch a double right click)
self.header().sectionClicked.connect(self.headerMenu)
self.header().sectionHandleDoubleClicked.connect(self.headerMenu)
self.header().sectionDoubleClicked.connect(self.headerMenu)
self.header().sectionPressed.connect(self.headerMenu)
or,
2: write a descendant of QHeaderView with my own MousePressEvent function, and use that for my headers. I have so far been unsuccessful in connecting the new header class to the QTreeView descendant. I keep getting a Segmentation Fault on runtime, with no more explanation.
#in DiceView's init, where DiceHeaders is the QHeaderView descendant
self.setHeader(DiceHeaders())
Any ideas?
|
[
"I discovered the setContextMenuPolicy function:\nself.header().setContextMenuPolicy(QtCore.Qt.CustomContextMenu)\nself.header().customContextMenuRequested.connect(self.headerMenu)\n\nThen, in headerMenu: \ndef headerMenu(self, pos):\n globalPos = self.mapToGlobal(pos)\n menu = QMenu()\n menu.addAction(\"test item\")\n selectedItem = menu.exec_(globalPos)\n if selectedItem:\n print \"selected: \", selectedItem\n\n",
"I'd go for solution n°2 : Write your own class inheriting QHeaderView.\nYour segmentation fault may be coming from a python/pyqt glitch ?\nYou should make sure that you DiceHeaders object exists by keeping a reference to it.\n"
] |
[
5,
0
] |
[] |
[] |
[
"pyqt",
"python",
"qheaderview",
"qt",
"qtreeview"
] |
stackoverflow_0002673326_pyqt_python_qheaderview_qt_qtreeview.txt
|
Q:
Using Python as a CGI script without the CGI module?
Is it possible to use Python as CGI without using the CGI module and still get access to all of the browser information and everything?
I tried:
#!/usr/bin/python
import sys
print "Content-type: text/html"
print
data = sys.stdin.readlines()
print len(data)
but it always prints 0.
A:
It is indeed possible, but a lot of the information is passed in as environment variables, not on standard input. In fact, the only thing that is passed in on standard input is the body of the incoming request, which would only have contents if a form is being POSTed.
For more information on how to work with CGI, check a website such as http://www.w3.org/CGI/. (It's too much to explain the entire standard in an answer here)
A:
Sure. cgi is a utility module with no magic powers; it does nothing you can't do yourself by reading and processing environment variables (in particular QUERY_STRING) and stdin, which comes into play for POST form bodies. (But remember to read the CONTENT_LENGTH environment variable and only read that many bytes, rather than using readlines(), else you can make your script hang waiting for more input that will never come.)
Indeed, there are complete alternatives to cgi for form submission processing, either as standalone modules or as part of a framework.
cgi module or no, however, I wouldn't write a purely CGI-based webapp today. Much better to write to the WSGI interface, and use wsgiref.handlers.CGIHandler to deploy that WSGI app over CGI. Then you can easily migrate to a more efficient web server interface as and when you need to. You can use the cgi module inside a WSGI app to read form submissions if you like, or, again, do your own thing.
|
Using Python as a CGI script without the CGI module?
|
Is it possible to use Python as CGI without using the CGI module and still get access to all of the browser information and everything?
I tried:
#!/usr/bin/python
import sys
print "Content-type: text/html"
print
data = sys.stdin.readlines()
print len(data)
but it always prints 0.
|
[
"It is indeed possible, but a lot of the information is passed in as environment variables, not on standard input. In fact, the only thing that is passed in on standard input is the body of the incoming request, which would only have contents if a form is being POSTed.\nFor more information on how to work with CGI, check a website such as http://www.w3.org/CGI/. (It's too much to explain the entire standard in an answer here)\n",
"Sure. cgi is a utility module with no magic powers; it does nothing you can't do yourself by reading and processing environment variables (in particular QUERY_STRING) and stdin, which comes into play for POST form bodies. (But remember to read the CONTENT_LENGTH environment variable and only read that many bytes, rather than using readlines(), else you can make your script hang waiting for more input that will never come.)\nIndeed, there are complete alternatives to cgi for form submission processing, either as standalone modules or as part of a framework.\ncgi module or no, however, I wouldn't write a purely CGI-based webapp today. Much better to write to the WSGI interface, and use wsgiref.handlers.CGIHandler to deploy that WSGI app over CGI. Then you can easily migrate to a more efficient web server interface as and when you need to. You can use the cgi module inside a WSGI app to read form submissions if you like, or, again, do your own thing.\n"
] |
[
3,
2
] |
[] |
[] |
[
"cgi",
"python"
] |
stackoverflow_0002680119_cgi_python.txt
|
Q:
how to write or create (when no exist) a file using python and Google AppEngine
this is my code:
f = open('text/a.log', 'wb')
f.write('hahaha')
f.close()
and it is not create a new file when not exist
how to do this ,
thanks
updated
class MyThread(threading.Thread):
def run(self):
f = open('a.log', 'w')
f.write('hahaha')
f.close()
error is :
Traceback (most recent call last):
File "D:\Python25\lib\threading.py", line 486, in __bootstrap_inner
self.run()
File "D:\zjm_code\helloworld\views.py", line 15, in run
f = open('a.log', 'w')
File "d:\Program Files\Google\google_appengine\google\appengine\tools\dev_appserver.py", line 1188, in __init__
raise IOError('invalid mode: %s' % mode)
IOError: invalid mode: w
A:
You are using the Google App Engine.
From the Google App Engine documentation:
The Sandbox
Applications run in a secure environment that provides limited access to the underlying operating system. These limitations allow App Engine to distribute web requests for the application across multiple servers, and start and stop servers to meet traffic demands. The sandbox isolates your application in its own secure, reliable environment that is independent of the hardware, operating system and physical location of the web server.
Examples of the limitations of the secure sandbox environment include:
An application cannot write to the file system. An app can read files, but only files uploaded with the application code. The app must use the App Engine datastore, memcache or other services for all data that persists between requests.
A:
Its because of google appengine not allowed you to write files
its define like this
ALLOWED_MODES = frozenset(['r', 'rb', 'U', 'rU'])
and
if mode not in FakeFile.ALLOWED_MODES:
raise IOError('invalid mode: %s' % mode)
Note: 'U' is universal newline mode, http://docs.python.org/library/io.html#io.open
Edit: You might interest Google AppEngine Logging session in their documents
Example
import logging
....
logging.error('There was an error retrieving ...')
logging.debug('Finish something')
A:
You don't show the error you get; despite the community pleading you to do so here and in previous questions.
I expect you get an IOError because the text directory is not created yet.
Use something like this instead:
from __future__ import with_statement
import os
dir = 'text'
filename = 'a.log'
log_path = os.path.join(dir, filename)
if not os.path.exists(dir):
os.makedirs(dir)
with open(log_path, 'w') as f:
f.write("Nobody expects the Spanish inquisition!")
Notes:
Joining paths with slashes willy-nilly is a good way to write code that doesn't work cross-platform.
Open files using the with statement. The file is closed at the end of the with block. Use from __future__ import with_statement in versions <= 2.5
A:
It seems most probably the relative directory path to 'text' not existing. Do check DIR path and then open file in write mode.
A:
agreed with @bp and @S.Mark: App Engine does not allow you to create files... period. in addition to the page that @bp pointed out, it's documented in a few more places:
http://code.google.com/appengine/docs/java/overview.html
http://code.google.com/appengine/docs/python/overview.html
specifically, those pages state, "...an app cannot spawn threads, write data to the local file system or make arbitrary network connections."
it's interesting that the OP tried 2 of the 3. :-)
however, if you want certain files, you need to upload them with your app, either individual files or a bunch thrown into a ZIP archive. finally, if you have really large files, you may wish to consider using the Blobstore (up to 50MB each):
http://code.google.com/appengine/docs/python/blobstore/
http://code.google.com/appengine/docs/java/blobstore/
|
how to write or create (when no exist) a file using python and Google AppEngine
|
this is my code:
f = open('text/a.log', 'wb')
f.write('hahaha')
f.close()
and it is not create a new file when not exist
how to do this ,
thanks
updated
class MyThread(threading.Thread):
def run(self):
f = open('a.log', 'w')
f.write('hahaha')
f.close()
error is :
Traceback (most recent call last):
File "D:\Python25\lib\threading.py", line 486, in __bootstrap_inner
self.run()
File "D:\zjm_code\helloworld\views.py", line 15, in run
f = open('a.log', 'w')
File "d:\Program Files\Google\google_appengine\google\appengine\tools\dev_appserver.py", line 1188, in __init__
raise IOError('invalid mode: %s' % mode)
IOError: invalid mode: w
|
[
"You are using the Google App Engine.\nFrom the Google App Engine documentation:\n\nThe Sandbox\nApplications run in a secure environment that provides limited access to the underlying operating system. These limitations allow App Engine to distribute web requests for the application across multiple servers, and start and stop servers to meet traffic demands. The sandbox isolates your application in its own secure, reliable environment that is independent of the hardware, operating system and physical location of the web server.\nExamples of the limitations of the secure sandbox environment include:\n\nAn application cannot write to the file system. An app can read files, but only files uploaded with the application code. The app must use the App Engine datastore, memcache or other services for all data that persists between requests.\n\n\n",
"Its because of google appengine not allowed you to write files\nits define like this\nALLOWED_MODES = frozenset(['r', 'rb', 'U', 'rU'])\n\nand\nif mode not in FakeFile.ALLOWED_MODES:\n raise IOError('invalid mode: %s' % mode)\n\nNote: 'U' is universal newline mode, http://docs.python.org/library/io.html#io.open\nEdit: You might interest Google AppEngine Logging session in their documents\nExample\nimport logging\n....\nlogging.error('There was an error retrieving ...')\nlogging.debug('Finish something')\n\n",
"You don't show the error you get; despite the community pleading you to do so here and in previous questions. \nI expect you get an IOError because the text directory is not created yet.\nUse something like this instead:\nfrom __future__ import with_statement\nimport os\n\ndir = 'text'\nfilename = 'a.log'\nlog_path = os.path.join(dir, filename)\n\nif not os.path.exists(dir):\n os.makedirs(dir)\n\nwith open(log_path, 'w') as f:\n f.write(\"Nobody expects the Spanish inquisition!\")\n\nNotes:\nJoining paths with slashes willy-nilly is a good way to write code that doesn't work cross-platform.\nOpen files using the with statement. The file is closed at the end of the with block. Use from __future__ import with_statement in versions <= 2.5\n",
"It seems most probably the relative directory path to 'text' not existing. Do check DIR path and then open file in write mode. \n",
"agreed with @bp and @S.Mark: App Engine does not allow you to create files... period. in addition to the page that @bp pointed out, it's documented in a few more places:\nhttp://code.google.com/appengine/docs/java/overview.html\nhttp://code.google.com/appengine/docs/python/overview.html\nspecifically, those pages state, \"...an app cannot spawn threads, write data to the local file system or make arbitrary network connections.\"\nit's interesting that the OP tried 2 of the 3. :-)\nhowever, if you want certain files, you need to upload them with your app, either individual files or a bunch thrown into a ZIP archive. finally, if you have really large files, you may wish to consider using the Blobstore (up to 50MB each):\nhttp://code.google.com/appengine/docs/python/blobstore/\nhttp://code.google.com/appengine/docs/java/blobstore/\n"
] |
[
9,
7,
3,
0,
0
] |
[] |
[] |
[
"file",
"google_app_engine",
"python"
] |
stackoverflow_0002680215_file_google_app_engine_python.txt
|
Q:
Facebook connect on Google App Engine with Django Patch
We are building a website on Google App Engine, using django patch.
We would like to use Facebook connect for two purposes:
Authenticate users.
Access user's social data.
Searching for a solution in the usual places (google, FB, SO) brigs up a lot of noise, many partial solutions and no clear answer.
So the question is this: does anyone has a clear working solution? maybe even a recipe?
Thanks.
A:
Honza: we where looking for something that also does authentication Django style.
We ended up doing the login on the client side than sending an AJAX request to Django and wrote our own authenticate/login logic.
Once we get the user's credentials, we use PyFacebook for FB connectivity.
|
Facebook connect on Google App Engine with Django Patch
|
We are building a website on Google App Engine, using django patch.
We would like to use Facebook connect for two purposes:
Authenticate users.
Access user's social data.
Searching for a solution in the usual places (google, FB, SO) brigs up a lot of noise, many partial solutions and no clear answer.
So the question is this: does anyone has a clear working solution? maybe even a recipe?
Thanks.
|
[
"Honza: we where looking for something that also does authentication Django style.\nWe ended up doing the login on the client side than sending an AJAX request to Django and wrote our own authenticate/login logic.\nOnce we get the user's credentials, we use PyFacebook for FB connectivity.\n"
] |
[
0
] |
[] |
[] |
[
"django",
"facebook",
"google_app_engine",
"python"
] |
stackoverflow_0002064673_django_facebook_google_app_engine_python.txt
|
Q:
how to send some data to the Thread module on python and google-map-engine
from google.appengine.ext import db
class Log(db.Model):
content = db.StringProperty(multiline=True)
class MyThread(threading.Thread):
def run(self,request):
#logs_query = Log.all().order('-date')
#logs = logs_query.fetch(3)
log=Log()
log.content=request.POST.get('content',None)
log.put()
def Log(request):
thr = MyThread()
thr.start(request)
return HttpResponse('')
error is :
TypeError at /log
start() takes exactly 1 argument (2 given)
and when i don't send the request,
class MyThread(threading.Thread):
def run(self):
log=Log()
log.content=request.POST.get('content',None)
log.put()
def Log(request):
thr = MyThread()
thr.start()
return HttpResponse('')
the error is :
Exception in thread Thread-1:
Traceback (most recent call last):
File "D:\Python25\lib\threading.py", line 486, in __bootstrap_inner
self.run()
File "D:\zjm_code\helloworld\views.py", line 33, in run
log.content=request.POST.get('content',None)
NameError: global name 'request' is not defined
A:
You cannot use threads on App Engine.
A:
I am not sure this will meet your needs or even possible in google appengine but
if you change thr.start(request) to thr.run(request) the error should gone
|
how to send some data to the Thread module on python and google-map-engine
|
from google.appengine.ext import db
class Log(db.Model):
content = db.StringProperty(multiline=True)
class MyThread(threading.Thread):
def run(self,request):
#logs_query = Log.all().order('-date')
#logs = logs_query.fetch(3)
log=Log()
log.content=request.POST.get('content',None)
log.put()
def Log(request):
thr = MyThread()
thr.start(request)
return HttpResponse('')
error is :
TypeError at /log
start() takes exactly 1 argument (2 given)
and when i don't send the request,
class MyThread(threading.Thread):
def run(self):
log=Log()
log.content=request.POST.get('content',None)
log.put()
def Log(request):
thr = MyThread()
thr.start()
return HttpResponse('')
the error is :
Exception in thread Thread-1:
Traceback (most recent call last):
File "D:\Python25\lib\threading.py", line 486, in __bootstrap_inner
self.run()
File "D:\zjm_code\helloworld\views.py", line 33, in run
log.content=request.POST.get('content',None)
NameError: global name 'request' is not defined
|
[
"You cannot use threads on App Engine.\n",
"I am not sure this will meet your needs or even possible in google appengine but\nif you change thr.start(request) to thr.run(request) the error should gone\n"
] |
[
1,
0
] |
[] |
[] |
[
"django",
"google_app_engine",
"multithreading",
"python"
] |
stackoverflow_0002681169_django_google_app_engine_multithreading_python.txt
|
Q:
Is there a way to set the encoding for all files read and written by python
I have a script in python that needs to read iso-8859-1 files and also write in that encoding.
Now I am running the script in an environment with all locales set at utf-8. Is there a way to define in my python scripts that all file acces have to use the iso-8859-1 encoding?
A:
Python doesn't really listen to the environment when it comes to reading and writing files in a particular encoding. It only listens to the environment when it comes to encoding unicode written to stdout, if stdout is connected to a terminal.
When reading and writing files in Python 2.x, you deal with bytestrings (the str type) by default. They're encoded data. You have to decode the data you read by hand, and encode what you want to write. Or you can use codecs.open() to open the files, which will do the encoding for you.
In Python 3.x, you open files either in binary mode, in which case you get bytes, or you open it in text mode, in which case you should specify an encoding just like with codecs.open() in Python 2.x.
None of these are affected by environment variables; you either read bytes, or you specify the encoding.
|
Is there a way to set the encoding for all files read and written by python
|
I have a script in python that needs to read iso-8859-1 files and also write in that encoding.
Now I am running the script in an environment with all locales set at utf-8. Is there a way to define in my python scripts that all file acces have to use the iso-8859-1 encoding?
|
[
"Python doesn't really listen to the environment when it comes to reading and writing files in a particular encoding. It only listens to the environment when it comes to encoding unicode written to stdout, if stdout is connected to a terminal.\nWhen reading and writing files in Python 2.x, you deal with bytestrings (the str type) by default. They're encoded data. You have to decode the data you read by hand, and encode what you want to write. Or you can use codecs.open() to open the files, which will do the encoding for you.\nIn Python 3.x, you open files either in binary mode, in which case you get bytes, or you open it in text mode, in which case you should specify an encoding just like with codecs.open() in Python 2.x.\nNone of these are affected by environment variables; you either read bytes, or you specify the encoding.\n"
] |
[
4
] |
[] |
[] |
[
"encoding",
"file_io",
"python"
] |
stackoverflow_0002681713_encoding_file_io_python.txt
|
Q:
Adaptive Threshold in OpenCV (Version 1 - the swig version)
I'm trying to get adaptive thresholding working in the python binding to opencv
(the swig one - cannot get opencv 2.0 working as I am using a beagleboard as the cross compiling is not working yet). I have a greyscale image (ccg.jpg) and the following code
import opencv
from opencv import highgui
img = highgui.cvLoadImage("ccg.png")
img_bw = opencv.cvCreateImage(opencv.cvGetSize(img), opencv.IPL_DEPTH_8U, 1)
opencv.cvAdaptiveThreshold(img, img_bw, 125, opencv.CV_ADAPTIVE_THRESH_MEAN_C, opencv.CV_THRESH_BINARY, 7, 10)
When I run this I get the error:
RuntimeError: openCV Error:
Status=Formats of input arguments do not match
function name=cvAdaptiveThreshold
error messgae=
file_name=cvadapthresh.cpp
line=122
I've also tried having both the source and dest arguments both the same (greyscale) and I get the error
Unsupported format or combination of formats
Does anyone have any clues as to where I could be going wrong?
A:
I'm not a user of the swig interface, but in C the cvLoadImage function loads an image as 3 channel RGB by default, so if that's true for swig as well, then you're going to need to either change your code to load img as grayscale (CV_LOAD_IMAGE_GRAYSCALE) or do an intermediate step to convert it to grayscale with cvCvtColor.
|
Adaptive Threshold in OpenCV (Version 1 - the swig version)
|
I'm trying to get adaptive thresholding working in the python binding to opencv
(the swig one - cannot get opencv 2.0 working as I am using a beagleboard as the cross compiling is not working yet). I have a greyscale image (ccg.jpg) and the following code
import opencv
from opencv import highgui
img = highgui.cvLoadImage("ccg.png")
img_bw = opencv.cvCreateImage(opencv.cvGetSize(img), opencv.IPL_DEPTH_8U, 1)
opencv.cvAdaptiveThreshold(img, img_bw, 125, opencv.CV_ADAPTIVE_THRESH_MEAN_C, opencv.CV_THRESH_BINARY, 7, 10)
When I run this I get the error:
RuntimeError: openCV Error:
Status=Formats of input arguments do not match
function name=cvAdaptiveThreshold
error messgae=
file_name=cvadapthresh.cpp
line=122
I've also tried having both the source and dest arguments both the same (greyscale) and I get the error
Unsupported format or combination of formats
Does anyone have any clues as to where I could be going wrong?
|
[
"I'm not a user of the swig interface, but in C the cvLoadImage function loads an image as 3 channel RGB by default, so if that's true for swig as well, then you're going to need to either change your code to load img as grayscale (CV_LOAD_IMAGE_GRAYSCALE) or do an intermediate step to convert it to grayscale with cvCvtColor.\n"
] |
[
2
] |
[] |
[] |
[
"beagleboard",
"opencv",
"python"
] |
stackoverflow_0002668663_beagleboard_opencv_python.txt
|
Q:
printing the instance in Python
class Complex:
def init(self, realpart, imagpart):
self.real = realpart
self.imag = imagpart
print self.real, self.imag
I get this output:
>>> Complex(3,2)
3 2
<__main__.Complex instance at 0x01412210>
But why does he print the last line?
A:
You running the code from an interactive python prompt, which prints out the result of any statements, unless it is None.
Try it:
>>> 1
1
>>> 1 + 3
4
>>> "foobar"
'foobar'
>>>
So your call to Complex(3,2) is creating an object, and python is printing it out.
A:
Because it is the result of the statement "Complex(3,2)". In other words, a Complex object is being returned, and the interactive interpreter prints the result of the previous statement to the screen. If you try "c = Complex(3, 2)" you will suppress the message.
A:
Because class constructor always return instance, then you could call its method after that
inst = Complex(3,2)
inst.dosomething()
A:
What you want is to define __str__(self) and make it return a string representation (not print one).
|
printing the instance in Python
|
class Complex:
def init(self, realpart, imagpart):
self.real = realpart
self.imag = imagpart
print self.real, self.imag
I get this output:
>>> Complex(3,2)
3 2
<__main__.Complex instance at 0x01412210>
But why does he print the last line?
|
[
"You running the code from an interactive python prompt, which prints out the result of any statements, unless it is None.\nTry it:\n>>> 1\n1\n>>> 1 + 3\n4\n>>> \"foobar\"\n'foobar'\n>>> \n\nSo your call to Complex(3,2) is creating an object, and python is printing it out.\n",
"Because it is the result of the statement \"Complex(3,2)\". In other words, a Complex object is being returned, and the interactive interpreter prints the result of the previous statement to the screen. If you try \"c = Complex(3, 2)\" you will suppress the message.\n",
"Because class constructor always return instance, then you could call its method after that\ninst = Complex(3,2)\n\ninst.dosomething()\n\n",
"What you want is to define __str__(self) and make it return a string representation (not print one).\n"
] |
[
5,
3,
3,
1
] |
[] |
[] |
[
"class",
"instance",
"python",
"python_idle"
] |
stackoverflow_0002682771_class_instance_python_python_idle.txt
|
Q:
Python: "inline" block / condition to return a char?
I would like to create a string that uses a plural if count > 1.
For that, I would like have an "inline" condition that returns 's' to concatenate to my noun.
print "The plural of plural is plural{0}. {1}".format( {'s' if count > 1}, "Isnt't it!?")
A:
print "The plural of plural is plural{0}. {1}".format('s' if count > 1 else '', "Isnt't it!?")
A:
You need to add the else part to the 's' if count > 1 otherwise this is not a valid expression (because the value to return when count <= 1 has not been specified and Python cannot guess what this should be):
print "The plural of plural is plural{0}. {1}".format(
's' if count > 1 else '', "Isnt't it!?")
|
Python: "inline" block / condition to return a char?
|
I would like to create a string that uses a plural if count > 1.
For that, I would like have an "inline" condition that returns 's' to concatenate to my noun.
print "The plural of plural is plural{0}. {1}".format( {'s' if count > 1}, "Isnt't it!?")
|
[
"print \"The plural of plural is plural{0}. {1}\".format('s' if count > 1 else '', \"Isnt't it!?\")\n\n",
"You need to add the else part to the 's' if count > 1 otherwise this is not a valid expression (because the value to return when count <= 1 has not been specified and Python cannot guess what this should be):\nprint \"The plural of plural is plural{0}. {1}\".format(\n 's' if count > 1 else '', \"Isnt't it!?\")\n\n"
] |
[
1,
1
] |
[] |
[] |
[
"conditional_statements",
"python",
"return"
] |
stackoverflow_0002683086_conditional_statements_python_return.txt
|
Q:
How to read a media file from .py file using Django?
I can read a.txt file like this:
text = open('a.txt', 'rb').read()
But when I put the a.txt to the media folder, this doesn't work:
text = open('/media/a.txt', 'rb').read()
I'm getting the following error:
IOError at /
[Errno 13] file not accessible: '/media/a.txt'
How can I read file from the media directory?
A:
To be more generic (and be sure that you use the media folder), you could change it to:
import os
from django.conf import settings
text = open(os.path.join(settings.MEDIA_ROOT, 'a.txt'), 'rb').read()
A:
The initial / means that it is an absolute path, accessed from the root of the filesystem. If you want to read a file from the project path then you will need to start the filename with the project path instead, or use __file__ along with the functions in os.path to create an appropriate relative or absolute path.
|
How to read a media file from .py file using Django?
|
I can read a.txt file like this:
text = open('a.txt', 'rb').read()
But when I put the a.txt to the media folder, this doesn't work:
text = open('/media/a.txt', 'rb').read()
I'm getting the following error:
IOError at /
[Errno 13] file not accessible: '/media/a.txt'
How can I read file from the media directory?
|
[
"To be more generic (and be sure that you use the media folder), you could change it to:\nimport os\nfrom django.conf import settings\ntext = open(os.path.join(settings.MEDIA_ROOT, 'a.txt'), 'rb').read()\n\n",
"The initial / means that it is an absolute path, accessed from the root of the filesystem. If you want to read a file from the project path then you will need to start the filename with the project path instead, or use __file__ along with the functions in os.path to create an appropriate relative or absolute path.\n"
] |
[
9,
2
] |
[
"You cannot read static files from your application code in Google App Engine. Files marked as static are served from different servers and not included with your application. If your application needs to read them and they don't need to be served directly to users, don't mark them static. If you need to both serve them directly to users and read them in python code, you need to include 2 copies in your project, one of which is marked as static and one which isn't.\n"
] |
[
-1
] |
[
"django",
"file_io",
"python"
] |
stackoverflow_0002679993_django_file_io_python.txt
|
Q:
Visual Studio COM access
Is it possible to control Visual Studio like you can control Excel through the Python COM API?
I'm trying to kick off a build through COM (don't ask!)
An example would be much appreciated.
A:
Yes. See the Visual Studio SDK.
http://msdn.microsoft.com/en-us/library/bb166441%28VS.80%29.aspx
There are C# wrappers for the COM objects, but the underlying technology is COM.
|
Visual Studio COM access
|
Is it possible to control Visual Studio like you can control Excel through the Python COM API?
I'm trying to kick off a build through COM (don't ask!)
An example would be much appreciated.
|
[
"Yes. See the Visual Studio SDK.\nhttp://msdn.microsoft.com/en-us/library/bb166441%28VS.80%29.aspx\nThere are C# wrappers for the COM objects, but the underlying technology is COM.\n"
] |
[
0
] |
[] |
[] |
[
"com",
"python",
"visual_studio"
] |
stackoverflow_0002683712_com_python_visual_studio.txt
|
Q:
Why is this Python class copying another class contents?
I'm trying to understand an estrange behavior in Python.
I have the next python code:
class IntContainer:
listOfInts = []
def __init__(self, initListOfInts):
for i in initListOfInts:
self.listOfInts.append(i)
def printInts(self):
print self.listOfInts
if __name__ == "__main__":
intsGroup1 = [1,2,3,4]
intsGroup2 = [4,5,6,7]
intsGroups = [intsGroup1,intsGroup2]
intsContainers = []
for ig in intsGroups:
newIntContainer = IntContainer(ig)
intsContainers.append(newIntContainer)
for ic in intsContainers:
print ic.listOfInts
I expect to get something like:
[1, 2, 3, 4]
[4, 5, 6, 7]
But i get:
[1, 2, 3, 4, 4, 5, 6, 7]
[1, 2, 3, 4, 4, 5, 6, 7]
I have check the next question:
why is python reusing a class instance inside in function
And a lot of Python reference, but I can not understand what is happening. I think is related with the newIntContainer identifier reutilization, but I do not understand it deeply.
Why Python appears to reused the last reference for the new object, even if I have added it to a permanent list? What can I do to resolve this behavior?
Thanks ;)
A:
Since you made listOfInts a class variable, that's what self.listOfInts is accessing, whatever self instance it may be; so, all the appends are going to the same list.
If that's not what you want, you need to make listOfInts an instance variable, for example by assigning self.listOfInts = [] at the start of the __init__ method.
A:
listOfInts has been defined as a class variable.
Class variables are shared by all the instances of the class.
This behavior is useful if you want to save class-related state (a typical example would be when you want to know the number of instances of the class created.
If you want listOfInts to be unique for each instance, then you should define it in init or other method of the class as self.listOfInts
|
Why is this Python class copying another class contents?
|
I'm trying to understand an estrange behavior in Python.
I have the next python code:
class IntContainer:
listOfInts = []
def __init__(self, initListOfInts):
for i in initListOfInts:
self.listOfInts.append(i)
def printInts(self):
print self.listOfInts
if __name__ == "__main__":
intsGroup1 = [1,2,3,4]
intsGroup2 = [4,5,6,7]
intsGroups = [intsGroup1,intsGroup2]
intsContainers = []
for ig in intsGroups:
newIntContainer = IntContainer(ig)
intsContainers.append(newIntContainer)
for ic in intsContainers:
print ic.listOfInts
I expect to get something like:
[1, 2, 3, 4]
[4, 5, 6, 7]
But i get:
[1, 2, 3, 4, 4, 5, 6, 7]
[1, 2, 3, 4, 4, 5, 6, 7]
I have check the next question:
why is python reusing a class instance inside in function
And a lot of Python reference, but I can not understand what is happening. I think is related with the newIntContainer identifier reutilization, but I do not understand it deeply.
Why Python appears to reused the last reference for the new object, even if I have added it to a permanent list? What can I do to resolve this behavior?
Thanks ;)
|
[
"Since you made listOfInts a class variable, that's what self.listOfInts is accessing, whatever self instance it may be; so, all the appends are going to the same list.\nIf that's not what you want, you need to make listOfInts an instance variable, for example by assigning self.listOfInts = [] at the start of the __init__ method.\n",
"listOfInts has been defined as a class variable.\nClass variables are shared by all the instances of the class.\nThis behavior is useful if you want to save class-related state (a typical example would be when you want to know the number of instances of the class created.\nIf you want listOfInts to be unique for each instance, then you should define it in init or other method of the class as self.listOfInts\n"
] |
[
6,
2
] |
[] |
[] |
[
"class",
"python",
"variables"
] |
stackoverflow_0002684265_class_python_variables.txt
|
Q:
Reload mod_fcgid without killing Python Service
I'm currently running a Django project on my school's webserver with FCGI. I did follow the multiple guides that recommends installing a virtual local Python environment and it worked out great. The only issue i had was that "touching" my fcgi-file to reload source-files wasn't enough, but instead i had to kill the python service via SSH. This because mod_fcgid is used.
However, the admin didn't think it was a great idea that i ran my own local python. He thought it better if i just told him what modules to install on root, which was a pretty nice service really.
But doing this, i can no longer kill python since it's under root(though immoral as I am, I've definitely tried). The admins recommendation was that I should try too make the fcgi script reload itself by checking time stamp. I've tried to find documentation on how to do this, but fund very little and since I'm a absolute beginner i have no idea what would work.
Anyone have experience running python/django under mod_fcgid or tips on where to find related guides/documentation?
A:
here's what I would do:
## top of my .fcgi script
import sys, time
original_modules = sys.modules.copy()
## in a separate thread
old_ctime = os.path.getctime("mymodule.py")
while True:
time.sleep(10)
new_ctime = os.path.getctime("mymodule.py")
if new_ctime > old_ctime:
sys.modules = original_modules # reset all imports
import mymodule
mymodule.dofcgi()
granted this isn't drop-in perfect (you might have to mess w/ the threading) but it should give you a general idea of how to "reload" a module completely.
|
Reload mod_fcgid without killing Python Service
|
I'm currently running a Django project on my school's webserver with FCGI. I did follow the multiple guides that recommends installing a virtual local Python environment and it worked out great. The only issue i had was that "touching" my fcgi-file to reload source-files wasn't enough, but instead i had to kill the python service via SSH. This because mod_fcgid is used.
However, the admin didn't think it was a great idea that i ran my own local python. He thought it better if i just told him what modules to install on root, which was a pretty nice service really.
But doing this, i can no longer kill python since it's under root(though immoral as I am, I've definitely tried). The admins recommendation was that I should try too make the fcgi script reload itself by checking time stamp. I've tried to find documentation on how to do this, but fund very little and since I'm a absolute beginner i have no idea what would work.
Anyone have experience running python/django under mod_fcgid or tips on where to find related guides/documentation?
|
[
"here's what I would do:\n## top of my .fcgi script\nimport sys, time\noriginal_modules = sys.modules.copy()\n\n## in a separate thread\nold_ctime = os.path.getctime(\"mymodule.py\")\nwhile True:\n time.sleep(10)\n new_ctime = os.path.getctime(\"mymodule.py\")\n if new_ctime > old_ctime:\n sys.modules = original_modules # reset all imports\n import mymodule\n mymodule.dofcgi()\n\ngranted this isn't drop-in perfect (you might have to mess w/ the threading) but it should give you a general idea of how to \"reload\" a module completely.\n"
] |
[
0
] |
[] |
[] |
[
"django",
"mod_fcgid",
"python"
] |
stackoverflow_0002684427_django_mod_fcgid_python.txt
|
Q:
Where is the PyGTK event stack?
You can know if the event stack is empty calling the gtk.events_pending() method, but I want to manipulate the pending events and filter it before the next gtk loop cycle, this data must be stored somewhere, but where?
Thanks.
A:
You can control the event loop yourself. Rather than calling gtk.main(), you can use gtk.main_iteration.
Your loop could then be:
while running:
#filter events here
gtk.main_iteration(true)
see here for more info.
|
Where is the PyGTK event stack?
|
You can know if the event stack is empty calling the gtk.events_pending() method, but I want to manipulate the pending events and filter it before the next gtk loop cycle, this data must be stored somewhere, but where?
Thanks.
|
[
"You can control the event loop yourself. Rather than calling gtk.main(), you can use gtk.main_iteration.\nYour loop could then be:\nwhile running:\n #filter events here\n gtk.main_iteration(true)\n\nsee here for more info.\n"
] |
[
1
] |
[] |
[] |
[
"gnome",
"gtk",
"pygtk",
"python"
] |
stackoverflow_0002685014_gnome_gtk_pygtk_python.txt
|
Q:
In MAYA 2009, is it possible to capture the cube rotate event?
I need to call a function ( Maya-Python ) based on cube rotationX. For that I have to capture the event, programmatically.
I tried using while loop but It stucks in the loop, Nothing can be done in that time.
I tried theading (python), still same.
Can it be done this or other way? If yes, How?
Maya 2009 in Windows XP
Some failed code references:
import maya.cmds as cmds
while (count < 90):
lock = cmds.getAttr('pCube1.rotateX',lock=False)
print lock
count = count + 1
Here Python wise:
#!/usr/bin/python
import thread
import time
# Define a function for the thread
def cubeRotateX( threadName, delay):
count = 0
while count < 5:
time.sleep(delay)
count += 1
try:
thread.start_new_thread( cubeRotateX, ("Thread-1", 2, ) )
except:
print "Error: unable to start thread"
while 1:
pass
A:
It sounds like a scriptJob may be what you're after. Here's a simple example below. However, in this example the callback will only be called when you release the mouse from rotating.
import maya.cmds
def myRotateCallback():
print 'do something'
maya.cmds.scriptJob( attributeChange=['pCube1.rotateX', myRotateCallback] )
If you want to receive continuous callbacks while rotating the cube, you can do that at the maya API level with MNodeMessage::addNodeDirtyPlugCallback.
|
In MAYA 2009, is it possible to capture the cube rotate event?
|
I need to call a function ( Maya-Python ) based on cube rotationX. For that I have to capture the event, programmatically.
I tried using while loop but It stucks in the loop, Nothing can be done in that time.
I tried theading (python), still same.
Can it be done this or other way? If yes, How?
Maya 2009 in Windows XP
Some failed code references:
import maya.cmds as cmds
while (count < 90):
lock = cmds.getAttr('pCube1.rotateX',lock=False)
print lock
count = count + 1
Here Python wise:
#!/usr/bin/python
import thread
import time
# Define a function for the thread
def cubeRotateX( threadName, delay):
count = 0
while count < 5:
time.sleep(delay)
count += 1
try:
thread.start_new_thread( cubeRotateX, ("Thread-1", 2, ) )
except:
print "Error: unable to start thread"
while 1:
pass
|
[
"It sounds like a scriptJob may be what you're after. Here's a simple example below. However, in this example the callback will only be called when you release the mouse from rotating.\nimport maya.cmds\n\ndef myRotateCallback():\n print 'do something'\n\nmaya.cmds.scriptJob( attributeChange=['pCube1.rotateX', myRotateCallback] )\n\nIf you want to receive continuous callbacks while rotating the cube, you can do that at the maya API level with MNodeMessage::addNodeDirtyPlugCallback.\n"
] |
[
1
] |
[] |
[] |
[
"3d",
"events",
"maya",
"python"
] |
stackoverflow_0002656891_3d_events_maya_python.txt
|
Q:
How to keep same substrings in vim regex
I'd ideally like a vim answer to this:
I want to change
[*, 1, *, *] to [*, 2, *, *]
Here the stars refer to individual characters in the substring, which I would like to keep unchanged. For example
[0, 1, 0, 1] to [0, 2, 0, 1]
[1, 1, 1, 1] to [1, 2, 1, 1]
If people know how to do this in perl or python or whatever, that would be equally good.
Cheers
A:
This works :)
1,$s/\[\(\d\+\),\s\+\d\+,\s\+\(\d\+\),\s\+\(\d\+\)\]/[\1, 2, \2, \3]/g
or
%s/\[\(\d\+\),\s\+\d\+,\s\+\(\d\+\),\s\+\(\d\+\)\]/[\1, 2, \2, \3]/
A:
The following should do what you want:
:%s/\(\[[^,]*, *\)\(\d\)\([^]]*\]\)/\=submatch(1) . (submatch(2)+1) . submatch(3)/
In Vim, that is.
A:
If those are strings in Python
>>> a = "[0, 1, 0, 1]"
>>> b = a[:4] + '2' + a[5:]
>>> b
'[0, 2, 0, 1]'
Lists are a little more trivial:
>>> c = [0, 1, 0, 1]
>>> c[1] = 2
>>> c
[0, 2, 0, 1]
>>>
A:
This one is shorter and a little more general purpose.
:%s/\(\[[^,],\s*\)1,/\12,/
The pattern doesn't care what is in the first slot of the list, and doesn't look at the rest of the list. This may be better, or worse, depending on what exactly you're trying to do.
A:
Note while using regexes for substitutions/modifications it is important to focus around the portion of the string you want to modify. Here is a short regex to do what you want (in perl), that illustrates this idea with your data.
Assuming $line contains the line you want to modify
my $two=2;
$line =~ s/(,\s+)\d+/\1$two/;
The regex looks for the first comma, matches that and a arbitary number of spaces following the comma. This is remembered in the first back reference. After that it matches a arbitary number of digits. Finally it replaces what was matched by the string in the first backreference followed by 2. Applying this on your sample data gives
[0, 1, 0, 1] becomes [0, 2, 0, 1]
[1, 1, 1, 1] becomes [1, 2, 1, 1]
|
How to keep same substrings in vim regex
|
I'd ideally like a vim answer to this:
I want to change
[*, 1, *, *] to [*, 2, *, *]
Here the stars refer to individual characters in the substring, which I would like to keep unchanged. For example
[0, 1, 0, 1] to [0, 2, 0, 1]
[1, 1, 1, 1] to [1, 2, 1, 1]
If people know how to do this in perl or python or whatever, that would be equally good.
Cheers
|
[
"This works :)\n1,$s/\\[\\(\\d\\+\\),\\s\\+\\d\\+,\\s\\+\\(\\d\\+\\),\\s\\+\\(\\d\\+\\)\\]/[\\1, 2, \\2, \\3]/g\n\nor\n%s/\\[\\(\\d\\+\\),\\s\\+\\d\\+,\\s\\+\\(\\d\\+\\),\\s\\+\\(\\d\\+\\)\\]/[\\1, 2, \\2, \\3]/\n\n",
"The following should do what you want:\n:%s/\\(\\[[^,]*, *\\)\\(\\d\\)\\([^]]*\\]\\)/\\=submatch(1) . (submatch(2)+1) . submatch(3)/\n\nIn Vim, that is.\n",
"If those are strings in Python\n>>> a = \"[0, 1, 0, 1]\"\n>>> b = a[:4] + '2' + a[5:]\n>>> b\n'[0, 2, 0, 1]'\n\nLists are a little more trivial:\n>>> c = [0, 1, 0, 1]\n>>> c[1] = 2\n>>> c\n[0, 2, 0, 1]\n>>>\n\n",
"This one is shorter and a little more general purpose.\n:%s/\\(\\[[^,],\\s*\\)1,/\\12,/\n\nThe pattern doesn't care what is in the first slot of the list, and doesn't look at the rest of the list. This may be better, or worse, depending on what exactly you're trying to do.\n",
"Note while using regexes for substitutions/modifications it is important to focus around the portion of the string you want to modify. Here is a short regex to do what you want (in perl), that illustrates this idea with your data. \nAssuming $line contains the line you want to modify\n my $two=2; \n $line =~ s/(,\\s+)\\d+/\\1$two/;\n\nThe regex looks for the first comma, matches that and a arbitary number of spaces following the comma. This is remembered in the first back reference. After that it matches a arbitary number of digits. Finally it replaces what was matched by the string in the first backreference followed by 2. Applying this on your sample data gives\n[0, 1, 0, 1] becomes [0, 2, 0, 1]\n[1, 1, 1, 1] becomes [1, 2, 1, 1]\n"
] |
[
4,
2,
1,
1,
1
] |
[] |
[] |
[
"perl",
"python",
"regex",
"vim"
] |
stackoverflow_0002683810_perl_python_regex_vim.txt
|
Q:
Why am I getting a TypeError when looping?
I'm working on a Python extension module, and one of my little test scripts is doing something strange, viz.:
x_max, y_max, z_max = m.size
for x in xrange(x_max):
for y in xrange(y_max):
for z in xrange(z_max):
#do my stuff
What makes no sense is that the loop gets to the end of the first 'z' iteration, then throws a TypeError, stating that "an integer is required". If I put a try...except TypeError around it and check the types of x, y, and z, they all come back as < type 'int' >.
Am I missing something here?
EDIT: It appears I've got a problem somewhere in my extension code. Pulling out those lines one by one revealed the culprit. I suspect a reference counting error. Thanks for the replies.
A:
The problem is here: x_max, y_max, z_max = m.size
This syntax x_max, y_max, z_max expects a tuple/list on the other end of the equality sign so unless m.size is one -- and I take it it's an integer -- you need the following:
x_max = y_max = z_max = m.size
|
Why am I getting a TypeError when looping?
|
I'm working on a Python extension module, and one of my little test scripts is doing something strange, viz.:
x_max, y_max, z_max = m.size
for x in xrange(x_max):
for y in xrange(y_max):
for z in xrange(z_max):
#do my stuff
What makes no sense is that the loop gets to the end of the first 'z' iteration, then throws a TypeError, stating that "an integer is required". If I put a try...except TypeError around it and check the types of x, y, and z, they all come back as < type 'int' >.
Am I missing something here?
EDIT: It appears I've got a problem somewhere in my extension code. Pulling out those lines one by one revealed the culprit. I suspect a reference counting error. Thanks for the replies.
|
[
"The problem is here: x_max, y_max, z_max = m.size\nThis syntax x_max, y_max, z_max expects a tuple/list on the other end of the equality sign so unless m.size is one -- and I take it it's an integer -- you need the following:\nx_max = y_max = z_max = m.size\n"
] |
[
0
] |
[] |
[] |
[
"python"
] |
stackoverflow_0002685565_python.txt
|
Q:
Conditional CellRenderCombo in pyGTK TreeView
I have a two column TreeView attached to a ListStore. Both columns are CellRenderCombo combo boxes.
When the user selects an entry in the first box, I need to dynamically load a set of options in the second.
For example, the behavior I want is:
On row 0, the user selects "Alphabet" in the first column box.
The second column box is populated with the letters "A-Z".
On row 1, the user selects "Numbers" in the first column box.
The second column box is populated with the numbers "0-9".
On row 2, the user selects "Alphabet" in the first column box.
The second column box is populated with the letters "A-Z".
etc.
Does anyone know how to do this, or seen any open source pygtk or gtk projects that have similar behavior which I can analyze?
A:
First, you need to bind model property of the second renderer from the model, like:
gtk.TreeViewColumn ('...', gtk.CellRendererCombo (), text = N, model = M)
where M is the column number which stores models (likely gtk.ListStore). Or use any other method of binding properties from model columns.
Then connect to the first renderer's changed signal. In the callback you need to change the model used for the second renderer's combo (i.e. value in column M) accordingly. I'd bet you can use the same models in different rows, i.e. one for numbers, one for letters, without creating more, but I'm not sure. In other words, callback could look similar to this (store is the main gtk.ListStore, X is the column with the value of the first combo):
def combo1_changed (combo, path, iter):
main_iter = store.get_iter (path)
selected = store.get_value (main_iter, X)
if selected == 'Alphabet':
store.set_value (main_iter, M, alphabet_list_store)
elif selected == 'Numbers':
store.set_value (main_iter, M, number_list_store)
...
|
Conditional CellRenderCombo in pyGTK TreeView
|
I have a two column TreeView attached to a ListStore. Both columns are CellRenderCombo combo boxes.
When the user selects an entry in the first box, I need to dynamically load a set of options in the second.
For example, the behavior I want is:
On row 0, the user selects "Alphabet" in the first column box.
The second column box is populated with the letters "A-Z".
On row 1, the user selects "Numbers" in the first column box.
The second column box is populated with the numbers "0-9".
On row 2, the user selects "Alphabet" in the first column box.
The second column box is populated with the letters "A-Z".
etc.
Does anyone know how to do this, or seen any open source pygtk or gtk projects that have similar behavior which I can analyze?
|
[
"First, you need to bind model property of the second renderer from the model, like:\ngtk.TreeViewColumn ('...', gtk.CellRendererCombo (), text = N, model = M)\n\nwhere M is the column number which stores models (likely gtk.ListStore). Or use any other method of binding properties from model columns.\nThen connect to the first renderer's changed signal. In the callback you need to change the model used for the second renderer's combo (i.e. value in column M) accordingly. I'd bet you can use the same models in different rows, i.e. one for numbers, one for letters, without creating more, but I'm not sure. In other words, callback could look similar to this (store is the main gtk.ListStore, X is the column with the value of the first combo):\ndef combo1_changed (combo, path, iter):\n main_iter = store.get_iter (path)\n selected = store.get_value (main_iter, X)\n if selected == 'Alphabet':\n store.set_value (main_iter, M, alphabet_list_store)\n elif selected == 'Numbers':\n store.set_value (main_iter, M, number_list_store)\n ...\n\n"
] |
[
0
] |
[] |
[] |
[
"gtk",
"pygtk",
"python"
] |
stackoverflow_0002682139_gtk_pygtk_python.txt
|
Q:
python multiprocessing member variable not set
In the following script, I get the "stop message received" output but the process never ends. Why is that? Is there another way to end a process besides terminate or os.kill that is along these lines?
from multiprocessing import Process
from time import sleep
class Test(Process):
def __init__(self):
Process.__init__(self)
self.stop = False
def run(self):
while self.stop == False:
print "running"
sleep(1.0)
def end(self):
print "stop message received"
self.stop = True
if __name__ == "__main__":
test = Test()
test.start()
sleep(1.0)
test.end()
test.join()
A:
The start method has cloned the object into a separate process, where it executes run. The end method is nothing special, so it runs in the process that calls it -- the changes it performs to that object are not sent to the clone object.
So, use instead an appropriate means of interprocess communication, such as a multiprocessing.Event instance, e.g.:
from multiprocessing import Process, Event
from time import sleep
class Test(Process):
def __init__(self):
Process.__init__(self)
self.stop = Event()
def run(self):
while not self.stop.is_set():
print "running"
sleep(1.0)
def end(self):
print "stop message received"
self.stop.set()
if __name__ == "__main__":
test = Test()
test.start()
sleep(1.0)
test.end()
test.join()
As you see, the required changes are minimal.
|
python multiprocessing member variable not set
|
In the following script, I get the "stop message received" output but the process never ends. Why is that? Is there another way to end a process besides terminate or os.kill that is along these lines?
from multiprocessing import Process
from time import sleep
class Test(Process):
def __init__(self):
Process.__init__(self)
self.stop = False
def run(self):
while self.stop == False:
print "running"
sleep(1.0)
def end(self):
print "stop message received"
self.stop = True
if __name__ == "__main__":
test = Test()
test.start()
sleep(1.0)
test.end()
test.join()
|
[
"The start method has cloned the object into a separate process, where it executes run. The end method is nothing special, so it runs in the process that calls it -- the changes it performs to that object are not sent to the clone object.\nSo, use instead an appropriate means of interprocess communication, such as a multiprocessing.Event instance, e.g.:\nfrom multiprocessing import Process, Event\nfrom time import sleep\n\nclass Test(Process):\n def __init__(self):\n Process.__init__(self)\n self.stop = Event()\n\n def run(self):\n while not self.stop.is_set():\n print \"running\"\n sleep(1.0)\n\n def end(self):\n print \"stop message received\"\n self.stop.set()\n\nif __name__ == \"__main__\":\n test = Test()\n test.start()\n sleep(1.0)\n test.end()\n test.join()\n\nAs you see, the required changes are minimal.\n"
] |
[
3
] |
[] |
[] |
[
"multiprocessing",
"python"
] |
stackoverflow_0002685845_multiprocessing_python.txt
|
Q:
Google app engine How to count SUM from datestore?
Im wondering, how can i get a SUM of a rating entity i get from the datastore (python)?
should i:
ratingsum = 0
for rating in ratings:
ratingsum + rating
print ratingsum
?
A:
Yep, that's pretty much it. Retrieve all the entities you want to sum, and sum them in your app. There is no SUM in GQL.
If what you're trying to accomplish is to find the average rating for an entity, there's a better way.
class RateableThing(db.Model):
num_ratings = db.IntegerProperty()
avg_rating = db.FloatProperty()
Finding the thing's average rating is a simple lookup, and adding a new rating is just:
thing.avg_ratings = ((thing.avg_ratings * thing.num_ratings) + new_rating) / thing.num_ratings + 1
thing.num_ratings += 1
thing.put()
The prevailing idiom of the App Engine datastore is to do as much work as you can on write, and as little as possible on read, since reads will happen much more often.
A:
I can't answer the Google App Engine part of your question, but your code (if you change the + to a +=) is equivalent to:
ratingsum = sum(ratings)
I'm pretty sure you can use sum() on any sequence or iterable containing number-like objects.
|
Google app engine How to count SUM from datestore?
|
Im wondering, how can i get a SUM of a rating entity i get from the datastore (python)?
should i:
ratingsum = 0
for rating in ratings:
ratingsum + rating
print ratingsum
?
|
[
"Yep, that's pretty much it. Retrieve all the entities you want to sum, and sum them in your app. There is no SUM in GQL.\nIf what you're trying to accomplish is to find the average rating for an entity, there's a better way.\nclass RateableThing(db.Model):\n num_ratings = db.IntegerProperty()\n avg_rating = db.FloatProperty()\n\nFinding the thing's average rating is a simple lookup, and adding a new rating is just:\nthing.avg_ratings = ((thing.avg_ratings * thing.num_ratings) + new_rating) / thing.num_ratings + 1\nthing.num_ratings += 1\nthing.put()\n\nThe prevailing idiom of the App Engine datastore is to do as much work as you can on write, and as little as possible on read, since reads will happen much more often.\n",
"I can't answer the Google App Engine part of your question, but your code (if you change the + to a +=) is equivalent to:\nratingsum = sum(ratings)\n\nI'm pretty sure you can use sum() on any sequence or iterable containing number-like objects.\n"
] |
[
12,
0
] |
[] |
[] |
[
"google_app_engine",
"gql",
"python"
] |
stackoverflow_0002686361_google_app_engine_gql_python.txt
|
Q:
Django Deploy trouble
Well, i've walking around this for a couples of days now... I think is time to ask for some help, i think my installation is ok...
Server OS: Centos 5
Python -v 2.6.5
Django -v (1, 1, 1, 'final', 0)
my apache conf:
<VirtualHost *:80>
DocumentRoot /opt/workshop
ServerName taller.antell.com.py
WSGIScriptAlias / /opt/workshop/workshop.wsgi
WSGIDaemonProcess taller.antell.com.py user=ignacio group=ignacio processes=2 threads=25
ErrorLog /opt/workshop/apache.error.log
CustomLog /opt/workshop/apache.custom.log combined
<Directory "/opt/workshop">
Options +ExecCGI +FollowSymLinks -Indexes -MultiViews
AllowOverride All
Order allow,deny
Allow from all
</Directory>
</VirtualHost>
my mod_wsgi conf:
import os
import sys
sys.path.append('/opt/workshop')
os.environ['DJANGO_SETTINGS_MODULE'] = 'workshop.settings'
os.environ['PYTHON_EGG_CACHE'] = '/tmp/.python-eggs'
import django.core.handlers.wsgi
application = django.core.handlers.wsgi.WSGIHandler( )
the error that i'm getting on my apache error log is:
[Wed Apr 21 15:17:48 2010] [error] [client 190.128.226.122] mod_wsgi (pid=11459): Exception occurred processing WSGI script '/opt/workshop/workshop.wsgi'.
[Wed Apr 21 15:17:48 2010] [error] [client 190.128.226.122] Traceback (most recent call last):
[Wed Apr 21 15:17:48 2010] [error] [client 190.128.226.122] File "/opt/python2.6/lib/python2.6/site-packages/django/core/handlers/wsgi.py", line 241, in __call__
[Wed Apr 21 15:17:48 2010] [error] [client 190.128.226.122] response = self.get_response(request)
[Wed Apr 21 15:17:48 2010] [error] [client 190.128.226.122] File "/opt/python2.6/lib/python2.6/site-packages/django/core/handlers/base.py", line 134, in get_response
[Wed Apr 21 15:17:48 2010] [error] [client 190.128.226.122] return self.handle_uncaught_exception(request, resolver, exc_info)
[Wed Apr 21 15:17:48 2010] [error] [client 190.128.226.122] File "/opt/python2.6/lib/python2.6/site-packages/django/core/handlers/base.py", line 154, in handle_uncaught_exception
[Wed Apr 21 15:17:48 2010] [error] [client 190.128.226.122] return debug.technical_500_response(request, *exc_info)
[Wed Apr 21 15:17:48 2010] [error] [client 190.128.226.122] File "/opt/python2.6/lib/python2.6/site-packages/django/views/debug.py", line 40, in technical_500_response
[Wed Apr 21 15:17:48 2010] [error] [client 190.128.226.122] html = reporter.get_traceback_html()
[Wed Apr 21 15:17:48 2010] [error] [client 190.128.226.122] File "/opt/python2.6/lib/python2.6/site-packages/django/views/debug.py", line 114, in get_traceback_html
[Wed Apr 21 15:17:48 2010] [error] [client 190.128.226.122] return t.render(c)
[Wed Apr 21 15:17:48 2010] [error] [client 190.128.226.122] File "/opt/python2.6/lib/python2.6/site-packages/django/template/__init__.py", line 178, in render
[Wed Apr 21 15:17:48 2010] [error] [client 190.128.226.122] return self.nodelist.render(context)
[Wed Apr 21 15:17:48 2010] [error] [client 190.128.226.122] File "/opt/python2.6/lib/python2.6/site-packages/django/template/__init__.py", line 779, in render
[Wed Apr 21 15:17:48 2010] [error] [client 190.128.226.122] bits.append(self.render_node(node, context))
[Wed Apr 21 15:17:48 2010] [error] [client 190.128.226.122] File "/opt/python2.6/lib/python2.6/site-packages/django/template/debug.py", line 81, in render_node
[Wed Apr 21 15:17:48 2010] [error] [client 190.128.226.122] raise wrapped
[Wed Apr 21 15:17:48 2010] [error] [client 190.128.226.122] TemplateSyntaxError: Caught an exception while rendering: No module named vehicles
[Wed Apr 21 15:17:48 2010] [error] [client 190.128.226.122]
[Wed Apr 21 15:17:48 2010] [error] [client 190.128.226.122] Original Traceback (most recent call last):
[Wed Apr 21 15:17:48 2010] [error] [client 190.128.226.122] File "/opt/python2.6/lib/python2.6/site-packages/django/template/debug.py", line 71, in render_node
[Wed Apr 21 15:17:48 2010] [error] [client 190.128.226.122] result = node.render(context)
[Wed Apr 21 15:17:48 2010] [error] [client 190.128.226.122] File "/opt/python2.6/lib/python2.6/site-packages/django/template/debug.py", line 87, in render
[Wed Apr 21 15:17:48 2010] [error] [client 190.128.226.122] output = force_unicode(self.filter_expression.resolve(context))
[Wed Apr 21 15:17:48 2010] [error] [client 190.128.226.122] File "/opt/python2.6/lib/python2.6/site-packages/django/template/__init__.py", line 572, in resolve
[Wed Apr 21 15:17:48 2010] [error] [client 190.128.226.122] new_obj = func(obj, *arg_vals)
[Wed Apr 21 15:17:48 2010] [error] [client 190.128.226.122] File "/opt/python2.6/lib/python2.6/site-packages/django/template/defaultfilters.py", line 687, in date
[Wed Apr 21 15:17:48 2010] [error] [client 190.128.226.122] return format(value, arg)
[Wed Apr 21 15:17:48 2010] [error] [client 190.128.226.122] File "/opt/python2.6/lib/python2.6/site-packages/django/utils/dateformat.py", line 269, in format
[Wed Apr 21 15:17:48 2010] [error] [client 190.128.226.122] return df.format(format_string)
[Wed Apr 21 15:17:48 2010] [error] [client 190.128.226.122] File "/opt/python2.6/lib/python2.6/site-packages/django/utils/dateformat.py", line 30, in format
[Wed Apr 21 15:17:48 2010] [error] [client 190.128.226.122] pieces.append(force_unicode(getattr(self, piece)()))
[Wed Apr 21 15:17:48 2010] [error] [client 190.128.226.122] File "/opt/python2.6/lib/python2.6/site-packages/django/utils/dateformat.py", line 175, in r
[Wed Apr 21 15:17:48 2010] [error] [client 190.128.226.122] return self.format('D, j M Y H:i:s O')
[Wed Apr 21 15:17:48 2010] [error] [client 190.128.226.122] File "/opt/python2.6/lib/python2.6/site-packages/django/utils/dateformat.py", line 30, in format
[Wed Apr 21 15:17:48 2010] [error] [client 190.128.226.122] pieces.append(force_unicode(getattr(self, piece)()))
[Wed Apr 21 15:17:48 2010] [error] [client 190.128.226.122] File "/opt/python2.6/lib/python2.6/site-packages/django/utils/encoding.py", line 71, in force_unicode
[Wed Apr 21 15:17:48 2010] [error] [client 190.128.226.122] s = unicode(s)
[Wed Apr 21 15:17:48 2010] [error] [client 190.128.226.122] File "/opt/python2.6/lib/python2.6/site-packages/django/utils/functional.py", line 201, in __unicode_cast
[Wed Apr 21 15:17:48 2010] [error] [client 190.128.226.122] return self.__func(*self.__args, **self.__kw)
[Wed Apr 21 15:17:48 2010] [error] [client 190.128.226.122] File "/opt/python2.6/lib/python2.6/site-packages/django/utils/translation/__init__.py", line 62, in ugettext
[Wed Apr 21 15:17:48 2010] [error] [client 190.128.226.122] return real_ugettext(message)
[Wed Apr 21 15:17:48 2010] [error] [client 190.128.226.122] File "/opt/python2.6/lib/python2.6/site-packages/django/utils/translation/trans_real.py", line 286, in ugettext
[Wed Apr 21 15:17:48 2010] [error] [client 190.128.226.122] return do_translate(message, 'ugettext')
[Wed Apr 21 15:17:48 2010] [error] [client 190.128.226.122] File "/opt/python2.6/lib/python2.6/site-packages/django/utils/translation/trans_real.py", line 276, in do_translate
[Wed Apr 21 15:17:48 2010] [error] [client 190.128.226.122] _default = translation(settings.LANGUAGE_CODE)
[Wed Apr 21 15:17:48 2010] [error] [client 190.128.226.122] File "/opt/python2.6/lib/python2.6/site-packages/django/utils/translation/trans_real.py", line 194, in translation
[Wed Apr 21 15:17:48 2010] [error] [client 190.128.226.122] default_translation = _fetch(settings.LANGUAGE_CODE)
[Wed Apr 21 15:17:48 2010] [error] [client 190.128.226.122] File "/opt/python2.6/lib/python2.6/site-packages/django/utils/translation/trans_real.py", line 180, in _fetch
[Wed Apr 21 15:17:48 2010] [error] [client 190.128.226.122] app = import_module(appname)
[Wed Apr 21 15:17:48 2010] [error] [client 190.128.226.122] File "/opt/python2.6/lib/python2.6/site-packages/django/utils/importlib.py", line 35, in import_module
[Wed Apr 21 15:17:48 2010] [error] [client 190.128.226.122] __import__(name)
[Wed Apr 21 15:17:48 2010] [error] [client 190.128.226.122] ImportError: No module named vehicles
[Wed Apr 21 15:17:48 2010] [error] [client 190.128.226.122]
[Wed Apr 21 15:17:48 2010] [error] [client 190.128.226.122] mod_wsgi (pid=11463): Exception occurred processing WSGI script '/opt/workshop/workshop.wsgi'.
[Wed Apr 21 15:17:48 2010] [error] [client 190.128.226.122] Traceback (most recent call last):
[Wed Apr 21 15:17:48 2010] [error] [client 190.128.226.122] File "/opt/python2.6/lib/python2.6/site-packages/django/core/handlers/wsgi.py", line 241, in __call__
[Wed Apr 21 15:17:48 2010] [error] [client 190.128.226.122] response = self.get_response(request)
[Wed Apr 21 15:17:48 2010] [error] [client 190.128.226.122] File "/opt/python2.6/lib/python2.6/site-packages/django/core/handlers/base.py", line 73, in get_response
[Wed Apr 21 15:17:48 2010] [error] [client 190.128.226.122] response = middleware_method(request)
[Wed Apr 21 15:17:48 2010] [error] [client 190.128.226.122] File "/opt/python2.6/lib/python2.6/site-packages/django/middleware/common.py", line 56, in process_request
[Wed Apr 21 15:17:48 2010] [error] [client 190.128.226.122] if (not _is_valid_path(request.path_info) and
[Wed Apr 21 15:17:48 2010] [error] [client 190.128.226.122] File "/opt/python2.6/lib/python2.6/site-packages/django/middleware/common.py", line 142, in _is_valid_path
[Wed Apr 21 15:17:48 2010] [error] [client 190.128.226.122] urlresolvers.resolve(path)
[Wed Apr 21 15:17:48 2010] [error] [client 190.128.226.122] File "/opt/python2.6/lib/python2.6/site-packages/django/core/urlresolvers.py", line 303, in resolve
[Wed Apr 21 15:17:48 2010] [error] [client 190.128.226.122] return get_resolver(urlconf).resolve(path)
[Wed Apr 21 15:17:48 2010] [error] [client 190.128.226.122] File "/opt/python2.6/lib/python2.6/site-packages/django/core/urlresolvers.py", line 218, in resolve
[Wed Apr 21 15:17:48 2010] [error] [client 190.128.226.122] sub_match = pattern.resolve(new_path)
[Wed Apr 21 15:17:48 2010] [error] [client 190.128.226.122] File "/opt/python2.6/lib/python2.6/site-packages/django/core/urlresolvers.py", line 216, in resolve
[Wed Apr 21 15:17:48 2010] [error] [client 190.128.226.122] for pattern in self.url_patterns:
[Wed Apr 21 15:17:48 2010] [error] [client 190.128.226.122] File "/opt/python2.6/lib/python2.6/site-packages/django/core/urlresolvers.py", line 245, in _get_url_patterns
[Wed Apr 21 15:17:48 2010] [error] [client 190.128.226.122] patterns = getattr(self.urlconf_module, "urlpatterns", self.urlconf_module)
[Wed Apr 21 15:17:48 2010] [error] [client 190.128.226.122] File "/opt/python2.6/lib/python2.6/site-packages/django/core/urlresolvers.py", line 240, in _get_urlconf_module
[Wed Apr 21 15:17:48 2010] [error] [client 190.128.226.122] self._urlconf_module = import_module(self.urlconf_name)
[Wed Apr 21 15:17:48 2010] [error] [client 190.128.226.122] File "/opt/python2.6/lib/python2.6/site-packages/django/utils/importlib.py", line 35, in import_module
[Wed Apr 21 15:17:48 2010] [error] [client 190.128.226.122] __import__(name)
[Wed Apr 21 15:17:48 2010] [error] [client 190.128.226.122] ImportError: No module named vehicles.urls
Please give my a hand, i stuck... Obviously is a problem with my vehicle module (the only one in the app), another thing is that when i try:
[root@localhost workshop]# python manage.py runserver 0:8000
The app runs perfectly, i think that the problem is something near the wsgi conf, something is not clicking....
Tks...
Update:
workshop dir looks like...
[root@localhost workshop]# ls -l
total 504
-rw-r--r-- 1 root root 22706 Apr 21 15:17 apache.custom.log
-rw-r--r-- 1 root root 408141 Apr 21 15:17 apache.error.log
-rw-r--r-- 1 root root 0 Apr 17 10:56 __init__.py
-rw-r--r-- 1 root root 124 Apr 21 11:09 __init__.pyc
-rw-r--r-- 1 root root 542 Apr 17 10:56 manage.py
-rw-r--r-- 1 root root 3326 Apr 17 10:56 settings.py
-rw-r--r-- 1 root root 2522 Apr 21 11:09 settings.pyc
drw-r--r-- 4 root root 4096 Apr 17 10:56 templates
-rw-r--r-- 1 root root 381 Apr 21 13:42 urls.py
-rw-r--r-- 1 root root 398 Apr 21 13:00 urls.pyc
drw-r--r-- 2 root root 4096 Apr 21 13:44 vehicles
-rw-r--r-- 1 root root 38912 Apr 17 10:56 workshop.db
-rw-r--r-- 1 root root 263 Apr 21 15:30 workshop.wsgi
vehicles dir
[root@localhost vehicles]# ls -l
total 52
-rw-r--r-- 1 root root 390 Apr 17 10:56 admin.py
-rw-r--r-- 1 root root 967 Apr 21 13:00 admin.pyc
-rw-r--r-- 1 root root 732 Apr 17 10:56 forms.py
-rw-r--r-- 1 root root 2086 Apr 21 13:00 forms.pyc
-rw-r--r-- 1 root root 0 Apr 17 10:56 __init__.py
-rw-r--r-- 1 root root 133 Apr 21 11:36 __init__.pyc
-rw-r--r-- 1 root root 936 Apr 17 10:56 models.py
-rw-r--r-- 1 root root 1827 Apr 21 11:36 models.pyc
-rw-r--r-- 1 root root 514 Apr 17 10:56 tests.py
-rw-r--r-- 1 root root 989 Apr 21 13:44 tests.pyc
-rw-r--r-- 1 root root 1035 Apr 17 10:56 urls.py
-rw-r--r-- 1 root root 1935 Apr 21 13:00 urls.pyc
-rw-r--r-- 1 root root 3164 Apr 17 10:56 views.py
-rw-r--r-- 1 root root 4081 Apr 21 13:00 views.pyc
Update 2: this is my settings.py
# Django settings for workshop project.
DEBUG = True
TEMPLATE_DEBUG = DEBUG
ADMINS = (
('Ignacio Rojas', 'ignacio@antell.com.py'),
('Fabian Biedermann', 'fabian@antell.com.py'),
)
MANAGERS = ADMINS
DATABASE_ENGINE = 'sqlite3'
DATABASE_NAME = '/opt/workshop/workshop.db'
DATABASE_USER = ''
DATABASE_PASSWORD = ''
DATABASE_HOST = ''
DATABASE_PORT = ''
# Local time zone for this installation. Choices can be found here:
# http://en.wikipedia.org/wiki/List_of_tz_zones_by_name
# although not all choices may be available on all operating systems.
# If running in a Windows environment this must be set to the same as your
# system time zone.
TIME_ZONE = 'America/Asuncion'
# Language code for this installation. All choices can be found here:
# http://www.i18nguy.com/unicode/language-identifiers.html
LANGUAGE_CODE = 'es-py'
SITE_ID = 1
# If you set this to False, Django will make some optimizations so as not
# to load the internationalization machinery.
USE_I18N = True
# Absolute path to the directory that holds media.
# Example: "/home/media/media.lawrence.com/"
MEDIA_ROOT = ''
# URL that handles the media served from MEDIA_ROOT. Make sure to use a
# trailing slash if there is a path component (optional in other cases).
# Examples: "http://media.lawrence.com", "http://example.com/media/"
MEDIA_URL = ''
# URL prefix for admin media -- CSS, JavaScript and images. Make sure to use a
# trailing slash.
# Examples: "http://foo.com/media/", "/media/".
ADMIN_MEDIA_PREFIX = '/media/'
# Make this unique, and don't share it with anybody.
SECRET_KEY = '11y0_jb=+b4^nq@2-fo#g$-ihk5*v&d5-8hg_y0i@*9$w8jalp'
MIDDLEWARE_CLASSES = (
'django.middleware.common.CommonMiddleware',
'django.contrib.sessions.middleware.SessionMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
)
ROOT_URLCONF = 'workshop.urls'
TEMPLATE_DIRS = (
# Put strings here, like "/home/html/django_templates" or "C:/www/django/templates".
# Always use forward slashes, even on Windows.
# Don't forget to use absolute paths, not relative paths.
"/opt/workshop/templates"
)
INSTALLED_APPS = (
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.sites',
'workshop.vehicles',
)
TEMPLATE_CONTEXT_PROCESSORS = (
'django.core.context_processors.auth',
'django.core.context_processors.debug',
'django.core.context_processors.i18n',
'django.core.context_processors.media',
)
This is what outputs on the test of:
http://blog.dscpl.com.au/2010/03/improved-wsgi-script-for-use-with.html
__name__ = settings
__file__ = /opt/django/workshop/settings.pyc
os.getpid() = 7207
os.getcwd() = /opt/django/workshop
os.curdir = .
sys.path = ['/opt/django', '/opt/django/workshop', '/opt/django/workshop', '/opt/python2.6/lib/python26.zip', '/opt/python2.6/lib/python2.6', '/opt/python2.6/lib/python2.6/plat-linux2', '/opt/python2.6/lib/python2.6/lib-tk', '/opt/python2.6/lib/python2.6/lib-old', '/opt/python2.6/lib/python2.6/lib-dynload', '/opt/python2.6/lib/python2.6/site-packages']
sys.modules.keys() = ['copy_reg', 'encodings', 'site', '__builtin__', '__main__', 'encodings.encodings', 'abc', 'posixpath', 'errno', 'encodings.codecs', '_abcoll', 'types', '_codecs', '_warnings', 'genericpath', 'stat', 'zipimport', 'encodings.__builtin__', 'warnings', 'UserDict', 'encodings.utf_8', 'sys', 'codecs', 'os.path', 'settings', 'signal', 'linecache', 'posix', 'encodings.aliases', 'exceptions', 'os']
sys.modules.has_key('workshop') = False
__name__ = workshop.settings
__file__ = /opt/django/workshop/settings.pyc
os.getpid() = 7207
os.getcwd() = /opt/django/workshop
os.curdir = .
sys.path = ['/opt/django', '/opt/django/workshop', '/opt/django/workshop', '/opt/python2.6/lib/python26.zip', '/opt/python2.6/lib/python2.6', '/opt/python2.6/lib/python2.6/plat-linux2', '/opt/python2.6/lib/python2.6/lib-tk', '/opt/python2.6/lib/python2.6/lib-old', '/opt/python2.6/lib/python2.6/lib-dynload', '/opt/python2.6/lib/python2.6/site-packages']
sys.modules.keys() = ['django.core.exceptions', 'django.core.management.django', 'copy_reg', 'sre_compile', 'django.conf.os', 'locale', '_sre', 'functools', 'encodings', 'django.conf.global_settings', 'site', '__builtin__', 'django.core.management', 'django.core.management.sys', 'django.utils.functional', '__main__', 'operator', 'encodings.encodings', 'django.utils.re', 'django.core.management.imp', 'django.core.management.color', 'abc', 'posixpath', 'django.utils', 'imp', 'errno', 'encodings.codecs', 'gettext', 'sre_constants', 'django.conf', 're', '_abcoll', 'types', 'django.utils.importlib', '_codecs', 'django.core.management.optparse', 'django.core.management.base', '_struct', '_warnings', 'django.conf.django', 'genericpath', 'stat', 'zipimport', 'encodings.__builtin__', 'string', 'django.utils.termcolors', 'warnings', 'optparse', 'UserDict', 'struct', 'encodings.utf_8', 'django.utils.sys', 'textwrap', 'sys', 'django.django', 'codecs', 'django.utils.version', 'django.utils.os', 'copy', 'workshop.settings', 'os.path', 'strop', '_functools', '_locale', 'django.conf.time', 'django.conf.re', 'workshop.sys', 'settings', 'workshop', 'signal', 'django.core', 'django.utils.django', 'django', 'django.core.management.os', 'linecache', 'posix', 'encodings.aliases', 'time', 'exceptions', 'sre_parse', 'os', 'workshop.os']
sys.modules.has_key('workshop') = True
sys.modules['wokshop'].__name__ = workshop
sys.modules['workshop'].__file__ = /opt/django/workshop/__init__.pyc
os.environ['DJANGO_SETTINGS_MODULE'] = workshop.settings
new wsgi:
import sys
sys.path.insert(0, '/opt/django/workshop')
sys.path.insert(0, '/opt/django')
import settings
import django.core.management
django.core.management.setup_environ( settings)
utility = django.core.management.ManagementUtility( )
command = utility.fetch_command( 'runserver')
command.validate( )
import django.conf
import django.utils
django.utils.translation.activate( django.conf.settings.LANGUAGE_CODE)
import django.core.handlers.wsgi
application = django.core.handlers.wsgi.WSGIHandler( )
Solved with:
chmod -R 755 workshop && chown -R apache:apache workshop
A:
Try adding both the directory containing the settings.py file and its parent directory to sys.path. Better still, read 'http://blog.dscpl.com.au/2010/03/improved-wsgi-script-for-use-with.html' and use the WSGI script file contents described right at the end (after you have read the post as to why it is an issue). :-)
UPDATE 1
In another comment you post your permissions as 'drw-r--r-- 2 root root vehicles'.
The 'x' bit isn't set on the directory for anyone. This will cause anything to fail which needs to be able to generate a directory listing to see what is in the directory.
In other words, look at all your directory permissions and fix things up to be 'drwxr-xr-x'.
Also, because you have made directories owned by root, if your application needs to write to any directories it will not be able to.
In summary, directory/file permissions issues.
A:
My guess is that your path is actually /opt/workshop/workshop/
So in your wsgi file you should have sys.path.append('/opt/workshop/workshop')
And if that's not the case, than workshop.settings should be settings instead.
[edit]
The way I see it you have 3 options.
Add opt to sys.path so workshop.urls and such work (bad idea imho since opt could include anything`
Remove workshop from all paths
Move the Python code to a workshop (or something else) directory (make sure it contains an __init__.py)
Personally I would take option 3 since otherwise you'll be mixing your python apps with the rest (media, templates, etc...)
|
Django Deploy trouble
|
Well, i've walking around this for a couples of days now... I think is time to ask for some help, i think my installation is ok...
Server OS: Centos 5
Python -v 2.6.5
Django -v (1, 1, 1, 'final', 0)
my apache conf:
<VirtualHost *:80>
DocumentRoot /opt/workshop
ServerName taller.antell.com.py
WSGIScriptAlias / /opt/workshop/workshop.wsgi
WSGIDaemonProcess taller.antell.com.py user=ignacio group=ignacio processes=2 threads=25
ErrorLog /opt/workshop/apache.error.log
CustomLog /opt/workshop/apache.custom.log combined
<Directory "/opt/workshop">
Options +ExecCGI +FollowSymLinks -Indexes -MultiViews
AllowOverride All
Order allow,deny
Allow from all
</Directory>
</VirtualHost>
my mod_wsgi conf:
import os
import sys
sys.path.append('/opt/workshop')
os.environ['DJANGO_SETTINGS_MODULE'] = 'workshop.settings'
os.environ['PYTHON_EGG_CACHE'] = '/tmp/.python-eggs'
import django.core.handlers.wsgi
application = django.core.handlers.wsgi.WSGIHandler( )
the error that i'm getting on my apache error log is:
[Wed Apr 21 15:17:48 2010] [error] [client 190.128.226.122] mod_wsgi (pid=11459): Exception occurred processing WSGI script '/opt/workshop/workshop.wsgi'.
[Wed Apr 21 15:17:48 2010] [error] [client 190.128.226.122] Traceback (most recent call last):
[Wed Apr 21 15:17:48 2010] [error] [client 190.128.226.122] File "/opt/python2.6/lib/python2.6/site-packages/django/core/handlers/wsgi.py", line 241, in __call__
[Wed Apr 21 15:17:48 2010] [error] [client 190.128.226.122] response = self.get_response(request)
[Wed Apr 21 15:17:48 2010] [error] [client 190.128.226.122] File "/opt/python2.6/lib/python2.6/site-packages/django/core/handlers/base.py", line 134, in get_response
[Wed Apr 21 15:17:48 2010] [error] [client 190.128.226.122] return self.handle_uncaught_exception(request, resolver, exc_info)
[Wed Apr 21 15:17:48 2010] [error] [client 190.128.226.122] File "/opt/python2.6/lib/python2.6/site-packages/django/core/handlers/base.py", line 154, in handle_uncaught_exception
[Wed Apr 21 15:17:48 2010] [error] [client 190.128.226.122] return debug.technical_500_response(request, *exc_info)
[Wed Apr 21 15:17:48 2010] [error] [client 190.128.226.122] File "/opt/python2.6/lib/python2.6/site-packages/django/views/debug.py", line 40, in technical_500_response
[Wed Apr 21 15:17:48 2010] [error] [client 190.128.226.122] html = reporter.get_traceback_html()
[Wed Apr 21 15:17:48 2010] [error] [client 190.128.226.122] File "/opt/python2.6/lib/python2.6/site-packages/django/views/debug.py", line 114, in get_traceback_html
[Wed Apr 21 15:17:48 2010] [error] [client 190.128.226.122] return t.render(c)
[Wed Apr 21 15:17:48 2010] [error] [client 190.128.226.122] File "/opt/python2.6/lib/python2.6/site-packages/django/template/__init__.py", line 178, in render
[Wed Apr 21 15:17:48 2010] [error] [client 190.128.226.122] return self.nodelist.render(context)
[Wed Apr 21 15:17:48 2010] [error] [client 190.128.226.122] File "/opt/python2.6/lib/python2.6/site-packages/django/template/__init__.py", line 779, in render
[Wed Apr 21 15:17:48 2010] [error] [client 190.128.226.122] bits.append(self.render_node(node, context))
[Wed Apr 21 15:17:48 2010] [error] [client 190.128.226.122] File "/opt/python2.6/lib/python2.6/site-packages/django/template/debug.py", line 81, in render_node
[Wed Apr 21 15:17:48 2010] [error] [client 190.128.226.122] raise wrapped
[Wed Apr 21 15:17:48 2010] [error] [client 190.128.226.122] TemplateSyntaxError: Caught an exception while rendering: No module named vehicles
[Wed Apr 21 15:17:48 2010] [error] [client 190.128.226.122]
[Wed Apr 21 15:17:48 2010] [error] [client 190.128.226.122] Original Traceback (most recent call last):
[Wed Apr 21 15:17:48 2010] [error] [client 190.128.226.122] File "/opt/python2.6/lib/python2.6/site-packages/django/template/debug.py", line 71, in render_node
[Wed Apr 21 15:17:48 2010] [error] [client 190.128.226.122] result = node.render(context)
[Wed Apr 21 15:17:48 2010] [error] [client 190.128.226.122] File "/opt/python2.6/lib/python2.6/site-packages/django/template/debug.py", line 87, in render
[Wed Apr 21 15:17:48 2010] [error] [client 190.128.226.122] output = force_unicode(self.filter_expression.resolve(context))
[Wed Apr 21 15:17:48 2010] [error] [client 190.128.226.122] File "/opt/python2.6/lib/python2.6/site-packages/django/template/__init__.py", line 572, in resolve
[Wed Apr 21 15:17:48 2010] [error] [client 190.128.226.122] new_obj = func(obj, *arg_vals)
[Wed Apr 21 15:17:48 2010] [error] [client 190.128.226.122] File "/opt/python2.6/lib/python2.6/site-packages/django/template/defaultfilters.py", line 687, in date
[Wed Apr 21 15:17:48 2010] [error] [client 190.128.226.122] return format(value, arg)
[Wed Apr 21 15:17:48 2010] [error] [client 190.128.226.122] File "/opt/python2.6/lib/python2.6/site-packages/django/utils/dateformat.py", line 269, in format
[Wed Apr 21 15:17:48 2010] [error] [client 190.128.226.122] return df.format(format_string)
[Wed Apr 21 15:17:48 2010] [error] [client 190.128.226.122] File "/opt/python2.6/lib/python2.6/site-packages/django/utils/dateformat.py", line 30, in format
[Wed Apr 21 15:17:48 2010] [error] [client 190.128.226.122] pieces.append(force_unicode(getattr(self, piece)()))
[Wed Apr 21 15:17:48 2010] [error] [client 190.128.226.122] File "/opt/python2.6/lib/python2.6/site-packages/django/utils/dateformat.py", line 175, in r
[Wed Apr 21 15:17:48 2010] [error] [client 190.128.226.122] return self.format('D, j M Y H:i:s O')
[Wed Apr 21 15:17:48 2010] [error] [client 190.128.226.122] File "/opt/python2.6/lib/python2.6/site-packages/django/utils/dateformat.py", line 30, in format
[Wed Apr 21 15:17:48 2010] [error] [client 190.128.226.122] pieces.append(force_unicode(getattr(self, piece)()))
[Wed Apr 21 15:17:48 2010] [error] [client 190.128.226.122] File "/opt/python2.6/lib/python2.6/site-packages/django/utils/encoding.py", line 71, in force_unicode
[Wed Apr 21 15:17:48 2010] [error] [client 190.128.226.122] s = unicode(s)
[Wed Apr 21 15:17:48 2010] [error] [client 190.128.226.122] File "/opt/python2.6/lib/python2.6/site-packages/django/utils/functional.py", line 201, in __unicode_cast
[Wed Apr 21 15:17:48 2010] [error] [client 190.128.226.122] return self.__func(*self.__args, **self.__kw)
[Wed Apr 21 15:17:48 2010] [error] [client 190.128.226.122] File "/opt/python2.6/lib/python2.6/site-packages/django/utils/translation/__init__.py", line 62, in ugettext
[Wed Apr 21 15:17:48 2010] [error] [client 190.128.226.122] return real_ugettext(message)
[Wed Apr 21 15:17:48 2010] [error] [client 190.128.226.122] File "/opt/python2.6/lib/python2.6/site-packages/django/utils/translation/trans_real.py", line 286, in ugettext
[Wed Apr 21 15:17:48 2010] [error] [client 190.128.226.122] return do_translate(message, 'ugettext')
[Wed Apr 21 15:17:48 2010] [error] [client 190.128.226.122] File "/opt/python2.6/lib/python2.6/site-packages/django/utils/translation/trans_real.py", line 276, in do_translate
[Wed Apr 21 15:17:48 2010] [error] [client 190.128.226.122] _default = translation(settings.LANGUAGE_CODE)
[Wed Apr 21 15:17:48 2010] [error] [client 190.128.226.122] File "/opt/python2.6/lib/python2.6/site-packages/django/utils/translation/trans_real.py", line 194, in translation
[Wed Apr 21 15:17:48 2010] [error] [client 190.128.226.122] default_translation = _fetch(settings.LANGUAGE_CODE)
[Wed Apr 21 15:17:48 2010] [error] [client 190.128.226.122] File "/opt/python2.6/lib/python2.6/site-packages/django/utils/translation/trans_real.py", line 180, in _fetch
[Wed Apr 21 15:17:48 2010] [error] [client 190.128.226.122] app = import_module(appname)
[Wed Apr 21 15:17:48 2010] [error] [client 190.128.226.122] File "/opt/python2.6/lib/python2.6/site-packages/django/utils/importlib.py", line 35, in import_module
[Wed Apr 21 15:17:48 2010] [error] [client 190.128.226.122] __import__(name)
[Wed Apr 21 15:17:48 2010] [error] [client 190.128.226.122] ImportError: No module named vehicles
[Wed Apr 21 15:17:48 2010] [error] [client 190.128.226.122]
[Wed Apr 21 15:17:48 2010] [error] [client 190.128.226.122] mod_wsgi (pid=11463): Exception occurred processing WSGI script '/opt/workshop/workshop.wsgi'.
[Wed Apr 21 15:17:48 2010] [error] [client 190.128.226.122] Traceback (most recent call last):
[Wed Apr 21 15:17:48 2010] [error] [client 190.128.226.122] File "/opt/python2.6/lib/python2.6/site-packages/django/core/handlers/wsgi.py", line 241, in __call__
[Wed Apr 21 15:17:48 2010] [error] [client 190.128.226.122] response = self.get_response(request)
[Wed Apr 21 15:17:48 2010] [error] [client 190.128.226.122] File "/opt/python2.6/lib/python2.6/site-packages/django/core/handlers/base.py", line 73, in get_response
[Wed Apr 21 15:17:48 2010] [error] [client 190.128.226.122] response = middleware_method(request)
[Wed Apr 21 15:17:48 2010] [error] [client 190.128.226.122] File "/opt/python2.6/lib/python2.6/site-packages/django/middleware/common.py", line 56, in process_request
[Wed Apr 21 15:17:48 2010] [error] [client 190.128.226.122] if (not _is_valid_path(request.path_info) and
[Wed Apr 21 15:17:48 2010] [error] [client 190.128.226.122] File "/opt/python2.6/lib/python2.6/site-packages/django/middleware/common.py", line 142, in _is_valid_path
[Wed Apr 21 15:17:48 2010] [error] [client 190.128.226.122] urlresolvers.resolve(path)
[Wed Apr 21 15:17:48 2010] [error] [client 190.128.226.122] File "/opt/python2.6/lib/python2.6/site-packages/django/core/urlresolvers.py", line 303, in resolve
[Wed Apr 21 15:17:48 2010] [error] [client 190.128.226.122] return get_resolver(urlconf).resolve(path)
[Wed Apr 21 15:17:48 2010] [error] [client 190.128.226.122] File "/opt/python2.6/lib/python2.6/site-packages/django/core/urlresolvers.py", line 218, in resolve
[Wed Apr 21 15:17:48 2010] [error] [client 190.128.226.122] sub_match = pattern.resolve(new_path)
[Wed Apr 21 15:17:48 2010] [error] [client 190.128.226.122] File "/opt/python2.6/lib/python2.6/site-packages/django/core/urlresolvers.py", line 216, in resolve
[Wed Apr 21 15:17:48 2010] [error] [client 190.128.226.122] for pattern in self.url_patterns:
[Wed Apr 21 15:17:48 2010] [error] [client 190.128.226.122] File "/opt/python2.6/lib/python2.6/site-packages/django/core/urlresolvers.py", line 245, in _get_url_patterns
[Wed Apr 21 15:17:48 2010] [error] [client 190.128.226.122] patterns = getattr(self.urlconf_module, "urlpatterns", self.urlconf_module)
[Wed Apr 21 15:17:48 2010] [error] [client 190.128.226.122] File "/opt/python2.6/lib/python2.6/site-packages/django/core/urlresolvers.py", line 240, in _get_urlconf_module
[Wed Apr 21 15:17:48 2010] [error] [client 190.128.226.122] self._urlconf_module = import_module(self.urlconf_name)
[Wed Apr 21 15:17:48 2010] [error] [client 190.128.226.122] File "/opt/python2.6/lib/python2.6/site-packages/django/utils/importlib.py", line 35, in import_module
[Wed Apr 21 15:17:48 2010] [error] [client 190.128.226.122] __import__(name)
[Wed Apr 21 15:17:48 2010] [error] [client 190.128.226.122] ImportError: No module named vehicles.urls
Please give my a hand, i stuck... Obviously is a problem with my vehicle module (the only one in the app), another thing is that when i try:
[root@localhost workshop]# python manage.py runserver 0:8000
The app runs perfectly, i think that the problem is something near the wsgi conf, something is not clicking....
Tks...
Update:
workshop dir looks like...
[root@localhost workshop]# ls -l
total 504
-rw-r--r-- 1 root root 22706 Apr 21 15:17 apache.custom.log
-rw-r--r-- 1 root root 408141 Apr 21 15:17 apache.error.log
-rw-r--r-- 1 root root 0 Apr 17 10:56 __init__.py
-rw-r--r-- 1 root root 124 Apr 21 11:09 __init__.pyc
-rw-r--r-- 1 root root 542 Apr 17 10:56 manage.py
-rw-r--r-- 1 root root 3326 Apr 17 10:56 settings.py
-rw-r--r-- 1 root root 2522 Apr 21 11:09 settings.pyc
drw-r--r-- 4 root root 4096 Apr 17 10:56 templates
-rw-r--r-- 1 root root 381 Apr 21 13:42 urls.py
-rw-r--r-- 1 root root 398 Apr 21 13:00 urls.pyc
drw-r--r-- 2 root root 4096 Apr 21 13:44 vehicles
-rw-r--r-- 1 root root 38912 Apr 17 10:56 workshop.db
-rw-r--r-- 1 root root 263 Apr 21 15:30 workshop.wsgi
vehicles dir
[root@localhost vehicles]# ls -l
total 52
-rw-r--r-- 1 root root 390 Apr 17 10:56 admin.py
-rw-r--r-- 1 root root 967 Apr 21 13:00 admin.pyc
-rw-r--r-- 1 root root 732 Apr 17 10:56 forms.py
-rw-r--r-- 1 root root 2086 Apr 21 13:00 forms.pyc
-rw-r--r-- 1 root root 0 Apr 17 10:56 __init__.py
-rw-r--r-- 1 root root 133 Apr 21 11:36 __init__.pyc
-rw-r--r-- 1 root root 936 Apr 17 10:56 models.py
-rw-r--r-- 1 root root 1827 Apr 21 11:36 models.pyc
-rw-r--r-- 1 root root 514 Apr 17 10:56 tests.py
-rw-r--r-- 1 root root 989 Apr 21 13:44 tests.pyc
-rw-r--r-- 1 root root 1035 Apr 17 10:56 urls.py
-rw-r--r-- 1 root root 1935 Apr 21 13:00 urls.pyc
-rw-r--r-- 1 root root 3164 Apr 17 10:56 views.py
-rw-r--r-- 1 root root 4081 Apr 21 13:00 views.pyc
Update 2: this is my settings.py
# Django settings for workshop project.
DEBUG = True
TEMPLATE_DEBUG = DEBUG
ADMINS = (
('Ignacio Rojas', 'ignacio@antell.com.py'),
('Fabian Biedermann', 'fabian@antell.com.py'),
)
MANAGERS = ADMINS
DATABASE_ENGINE = 'sqlite3'
DATABASE_NAME = '/opt/workshop/workshop.db'
DATABASE_USER = ''
DATABASE_PASSWORD = ''
DATABASE_HOST = ''
DATABASE_PORT = ''
# Local time zone for this installation. Choices can be found here:
# http://en.wikipedia.org/wiki/List_of_tz_zones_by_name
# although not all choices may be available on all operating systems.
# If running in a Windows environment this must be set to the same as your
# system time zone.
TIME_ZONE = 'America/Asuncion'
# Language code for this installation. All choices can be found here:
# http://www.i18nguy.com/unicode/language-identifiers.html
LANGUAGE_CODE = 'es-py'
SITE_ID = 1
# If you set this to False, Django will make some optimizations so as not
# to load the internationalization machinery.
USE_I18N = True
# Absolute path to the directory that holds media.
# Example: "/home/media/media.lawrence.com/"
MEDIA_ROOT = ''
# URL that handles the media served from MEDIA_ROOT. Make sure to use a
# trailing slash if there is a path component (optional in other cases).
# Examples: "http://media.lawrence.com", "http://example.com/media/"
MEDIA_URL = ''
# URL prefix for admin media -- CSS, JavaScript and images. Make sure to use a
# trailing slash.
# Examples: "http://foo.com/media/", "/media/".
ADMIN_MEDIA_PREFIX = '/media/'
# Make this unique, and don't share it with anybody.
SECRET_KEY = '11y0_jb=+b4^nq@2-fo#g$-ihk5*v&d5-8hg_y0i@*9$w8jalp'
MIDDLEWARE_CLASSES = (
'django.middleware.common.CommonMiddleware',
'django.contrib.sessions.middleware.SessionMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
)
ROOT_URLCONF = 'workshop.urls'
TEMPLATE_DIRS = (
# Put strings here, like "/home/html/django_templates" or "C:/www/django/templates".
# Always use forward slashes, even on Windows.
# Don't forget to use absolute paths, not relative paths.
"/opt/workshop/templates"
)
INSTALLED_APPS = (
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.sites',
'workshop.vehicles',
)
TEMPLATE_CONTEXT_PROCESSORS = (
'django.core.context_processors.auth',
'django.core.context_processors.debug',
'django.core.context_processors.i18n',
'django.core.context_processors.media',
)
This is what outputs on the test of:
http://blog.dscpl.com.au/2010/03/improved-wsgi-script-for-use-with.html
__name__ = settings
__file__ = /opt/django/workshop/settings.pyc
os.getpid() = 7207
os.getcwd() = /opt/django/workshop
os.curdir = .
sys.path = ['/opt/django', '/opt/django/workshop', '/opt/django/workshop', '/opt/python2.6/lib/python26.zip', '/opt/python2.6/lib/python2.6', '/opt/python2.6/lib/python2.6/plat-linux2', '/opt/python2.6/lib/python2.6/lib-tk', '/opt/python2.6/lib/python2.6/lib-old', '/opt/python2.6/lib/python2.6/lib-dynload', '/opt/python2.6/lib/python2.6/site-packages']
sys.modules.keys() = ['copy_reg', 'encodings', 'site', '__builtin__', '__main__', 'encodings.encodings', 'abc', 'posixpath', 'errno', 'encodings.codecs', '_abcoll', 'types', '_codecs', '_warnings', 'genericpath', 'stat', 'zipimport', 'encodings.__builtin__', 'warnings', 'UserDict', 'encodings.utf_8', 'sys', 'codecs', 'os.path', 'settings', 'signal', 'linecache', 'posix', 'encodings.aliases', 'exceptions', 'os']
sys.modules.has_key('workshop') = False
__name__ = workshop.settings
__file__ = /opt/django/workshop/settings.pyc
os.getpid() = 7207
os.getcwd() = /opt/django/workshop
os.curdir = .
sys.path = ['/opt/django', '/opt/django/workshop', '/opt/django/workshop', '/opt/python2.6/lib/python26.zip', '/opt/python2.6/lib/python2.6', '/opt/python2.6/lib/python2.6/plat-linux2', '/opt/python2.6/lib/python2.6/lib-tk', '/opt/python2.6/lib/python2.6/lib-old', '/opt/python2.6/lib/python2.6/lib-dynload', '/opt/python2.6/lib/python2.6/site-packages']
sys.modules.keys() = ['django.core.exceptions', 'django.core.management.django', 'copy_reg', 'sre_compile', 'django.conf.os', 'locale', '_sre', 'functools', 'encodings', 'django.conf.global_settings', 'site', '__builtin__', 'django.core.management', 'django.core.management.sys', 'django.utils.functional', '__main__', 'operator', 'encodings.encodings', 'django.utils.re', 'django.core.management.imp', 'django.core.management.color', 'abc', 'posixpath', 'django.utils', 'imp', 'errno', 'encodings.codecs', 'gettext', 'sre_constants', 'django.conf', 're', '_abcoll', 'types', 'django.utils.importlib', '_codecs', 'django.core.management.optparse', 'django.core.management.base', '_struct', '_warnings', 'django.conf.django', 'genericpath', 'stat', 'zipimport', 'encodings.__builtin__', 'string', 'django.utils.termcolors', 'warnings', 'optparse', 'UserDict', 'struct', 'encodings.utf_8', 'django.utils.sys', 'textwrap', 'sys', 'django.django', 'codecs', 'django.utils.version', 'django.utils.os', 'copy', 'workshop.settings', 'os.path', 'strop', '_functools', '_locale', 'django.conf.time', 'django.conf.re', 'workshop.sys', 'settings', 'workshop', 'signal', 'django.core', 'django.utils.django', 'django', 'django.core.management.os', 'linecache', 'posix', 'encodings.aliases', 'time', 'exceptions', 'sre_parse', 'os', 'workshop.os']
sys.modules.has_key('workshop') = True
sys.modules['wokshop'].__name__ = workshop
sys.modules['workshop'].__file__ = /opt/django/workshop/__init__.pyc
os.environ['DJANGO_SETTINGS_MODULE'] = workshop.settings
new wsgi:
import sys
sys.path.insert(0, '/opt/django/workshop')
sys.path.insert(0, '/opt/django')
import settings
import django.core.management
django.core.management.setup_environ( settings)
utility = django.core.management.ManagementUtility( )
command = utility.fetch_command( 'runserver')
command.validate( )
import django.conf
import django.utils
django.utils.translation.activate( django.conf.settings.LANGUAGE_CODE)
import django.core.handlers.wsgi
application = django.core.handlers.wsgi.WSGIHandler( )
Solved with:
chmod -R 755 workshop && chown -R apache:apache workshop
|
[
"Try adding both the directory containing the settings.py file and its parent directory to sys.path. Better still, read 'http://blog.dscpl.com.au/2010/03/improved-wsgi-script-for-use-with.html' and use the WSGI script file contents described right at the end (after you have read the post as to why it is an issue). :-)\n\nUPDATE 1\nIn another comment you post your permissions as 'drw-r--r-- 2 root root vehicles'.\nThe 'x' bit isn't set on the directory for anyone. This will cause anything to fail which needs to be able to generate a directory listing to see what is in the directory.\nIn other words, look at all your directory permissions and fix things up to be 'drwxr-xr-x'.\nAlso, because you have made directories owned by root, if your application needs to write to any directories it will not be able to.\nIn summary, directory/file permissions issues.\n",
"My guess is that your path is actually /opt/workshop/workshop/\nSo in your wsgi file you should have sys.path.append('/opt/workshop/workshop')\nAnd if that's not the case, than workshop.settings should be settings instead.\n[edit]\nThe way I see it you have 3 options.\n\nAdd opt to sys.path so workshop.urls and such work (bad idea imho since opt could include anything`\nRemove workshop from all paths\nMove the Python code to a workshop (or something else) directory (make sure it contains an __init__.py)\n\nPersonally I would take option 3 since otherwise you'll be mixing your python apps with the rest (media, templates, etc...)\n"
] |
[
4,
0
] |
[] |
[] |
[
"apache",
"django",
"mod_wsgi",
"python"
] |
stackoverflow_0002685994_apache_django_mod_wsgi_python.txt
|
Q:
Syntax error when using "with open" in Python (python newbie)
[root@234571-app2 git]# ./test.py
File "./test.py", line 4
with open("/home/git/post-receive-email.log",'a') as log_file:
^
SyntaxError: invalid syntax
The code looks like this:
[root@234571-app2 git]# more test.py
#!/usr/bin/python
from __future__ import with_statement
with open("/home/git/post-receive-email.log",'a') as log_file:
log_file.write("hello world")
and I am using Python 2.5.5
[root@234571-app2 git]# python -V
Python 2.5.5
A:
What you have should be correct. Python 2.5 introduced the with statement as something you can import from __future__. Since your code is correct, the only explanation I can think of is that your python version is not what you think it is. There's a good chance you have multiple versions of python installed on the system and for some reason your code is running with an older version. Try running it like this:
[root@234571-app2 git]# /usr/bin/python2.5 test.py
Assuming this works, you can change your first line to indicate which version of python you'd like. That can either be a direct path to python2.5 or you can use the env command to search the user's PATH variable for python2.5. The correct approach depends on what your systems python installs are. Here are the 2 approaches:
To use /usr/bin/python2.5 directly, you can do this:
#!/usr/bin/python2.5
To use whichever version of python2.5 occurs first in your PATH, do this:
#!/usr/bin/env python2.5
A:
Maybe like this?
#!/usr/bin/env python2.5
from __future__ import with_statement
with open("/home/git/post-receive-email.log",'a') as log_file:
log_file.write("hello world")
A:
the answer to this question is buried in the comments of the OP. @Tamas gave the correct solution above once @Tony confirmed that his code was being executed by 2.4:
"So, /usr/local/bin/python is 2.5.5, but you are calling your script with /usr/bin/python which is 2.4.3. Try replacing the shell shebang line with this: #!/usr/bin/env python."
in general, be wary of hardcoding your path, i.e., /usr/bin, /usr/local/bin, etc. this is why the env command was invented. it's especially relevant when you have multiple versions of Python installed on your system.
however, it was a pretty clear giveaway that it was an old Python issue as that OP code will execute on any 2.5 and newer interpreter. that syntax error gives off this message regardless of what version of Python you think you're using.
|
Syntax error when using "with open" in Python (python newbie)
|
[root@234571-app2 git]# ./test.py
File "./test.py", line 4
with open("/home/git/post-receive-email.log",'a') as log_file:
^
SyntaxError: invalid syntax
The code looks like this:
[root@234571-app2 git]# more test.py
#!/usr/bin/python
from __future__ import with_statement
with open("/home/git/post-receive-email.log",'a') as log_file:
log_file.write("hello world")
and I am using Python 2.5.5
[root@234571-app2 git]# python -V
Python 2.5.5
|
[
"What you have should be correct. Python 2.5 introduced the with statement as something you can import from __future__. Since your code is correct, the only explanation I can think of is that your python version is not what you think it is. There's a good chance you have multiple versions of python installed on the system and for some reason your code is running with an older version. Try running it like this:\n[root@234571-app2 git]# /usr/bin/python2.5 test.py\n\nAssuming this works, you can change your first line to indicate which version of python you'd like. That can either be a direct path to python2.5 or you can use the env command to search the user's PATH variable for python2.5. The correct approach depends on what your systems python installs are. Here are the 2 approaches:\nTo use /usr/bin/python2.5 directly, you can do this: \n#!/usr/bin/python2.5\n\nTo use whichever version of python2.5 occurs first in your PATH, do this:\n#!/usr/bin/env python2.5\n\n",
"Maybe like this?\n#!/usr/bin/env python2.5\nfrom __future__ import with_statement\n\nwith open(\"/home/git/post-receive-email.log\",'a') as log_file:\n log_file.write(\"hello world\")\n\n",
"the answer to this question is buried in the comments of the OP. @Tamas gave the correct solution above once @Tony confirmed that his code was being executed by 2.4:\n\"So, /usr/local/bin/python is 2.5.5, but you are calling your script with /usr/bin/python which is 2.4.3. Try replacing the shell shebang line with this: #!/usr/bin/env python.\"\nin general, be wary of hardcoding your path, i.e., /usr/bin, /usr/local/bin, etc. this is why the env command was invented. it's especially relevant when you have multiple versions of Python installed on your system.\nhowever, it was a pretty clear giveaway that it was an old Python issue as that OP code will execute on any 2.5 and newer interpreter. that syntax error gives off this message regardless of what version of Python you think you're using.\n"
] |
[
8,
5,
1
] |
[] |
[] |
[
"python",
"syntax_error"
] |
stackoverflow_0002685097_python_syntax_error.txt
|
Q:
Feedback on availability with Google App Engine
We've had some good experiences building an app on Google App Engine, this first app's target audience are Google Apps users, so no issues there in terms of it being hosted on Google infrastructure.
We like it so much that we would like to investigate using it for another app, however this next project is for a client who is not really that interested in what technology it sits on, they just want it to work, and work all of the time.
In this scenario, given that we have the technology applicability and capability side covered, are there any concerns that this stuff is still relatively new and that we may not be as much "in control" as if we had it done with traditional hosting?
A:
You are correct: you are not in as much control vs. traditional hosting. However, hopefully the gains outweight the negatives. App Engine is extremely scalable -- it runs on the same hardware that runs Google itself. How often have you visited http://google.com and had that page or a search result fail?
Although you are letting Google run your code, the code is still your's to do as you please. With new projects like django-nonrel, you can create and run native Django apps directly on top of App Engine, and if it doesn't meet your needs down the line, it's fairly easy to take that app to an ISP that hosts Django apps (and there are plenty of those). More on this project below.
You don't have to worry about hardware, operating systems, coming up with a machine image, databases, web servers, front-end load balancers, CDNs/edge caching, software/package upgrades, license fees, etc. All these things are tangential to the web or other application that you have or will create to solve a particular problem. All this additional infrastructure is required whether you like it or not; but with App Engine, you only need to think about your app/solution and none of this extra stuff.
Obviously another thing you lose is some of your execution environment. To ensure that you're playing nicely with your cloud neighbors (resource hogging, security issues, etc.), you must execute in a sandbox, meaning your app cannot create local files, open network sockets, etc. However, App Engine provides a rich set of APIs and product features so that you at least can create meaningful apps:
scalable distributed object datastore (see below)
Memcache
URLFetch
images service (resize, crop, etc.)
users service/authentication task queues for background processing
Django web templating
blobstore for large files
denial-of-service blacklisting
transational tasks
datastore cursors
sending (and/or receiving) of email
sending (and/or receiving) of chat/IM/instant messages via XMPP
You also have a full dashboarded administration console which will let you monitor your app's usage, your billing settings and history, a full dump of your quota usage, and even your application logs which you can view or download.
To address the "main sore points" from @Anurag:
1a. the free quotas are fairly generous... enough to power a website that gets 5MM views/month. also, if you trust Google to give them your credit card, they will bump up the free quota levels even higher. look at their quota page and refer to the numbers in both the "Free Default Quota" and "Billing Enabled Default Quota" columns... here are some examples: a) # of Requests: 1.3MM default, 43MM w/billing enabled (wBE), b) Datastore API calls: 10MM default, 140MM wBE, c) URL Fetches: 657K default, 46MM wBE
1b. 30s max for requests: this is more security for you, because your app is now in a playground with others. Google has to ensure that all cloud neighbors play nicely with each other and not hog the CPU. However, the App Engine team is working on a way to allow for longer running background tasks... there's no timetable yet, but it is on the public roadmap.
1c. writing a chat server on App Engine is not only possible, but it is quite simple. here's one created using App Engine's XMPP API -- it's pretty dumb and just echoes back to the sender what they transmitted to us (be aware that you must have already invited the user to chat):
from google.appengine.api import xmpp
from google.appengine.ext import webapp
from google.appengine.ext.webapp.util import run_wsgi_app
class XMPPHandler(webapp.RequestHandler):
def post(self):
msg = xmpp.Message(self.request.POST)
msg.reply("I got your msg: '%s'" % msg.body)
application = webapp.WSGIApplication([
('/_ah/xmpp/message/chat/', XMPPHandler),
], debug=True)
def main():
run_wsgi_app(application)
if __name__ == '__main__':
main()
1d. another item on the the public roadmap is future "[support] for Browser Push (Comet) communication", so that's coming too.
2a. "not SQL" is one of Google App Engine's greatest strengths! relational databases don't scale and must be sharded at some point to keep an RDBMS from falling over. it is true however, that it is slightly more difficult to port because it is not traditional! Based on Google Bigtable, you can think of the App Engine datastore as a scalable distributed object database. App Engine lets you query the datastore using a Query object model, or if you insist, they also provide a SQL-like GqlQuery interface.
2b. with new avantgarde projects like django-nonrel, if you create a Django app and use its ORM, you can take a pure Django app and run it directly on top of App Engine. likewise, you can it off of App Engine and move it directly to more traditional ISP vendor that hosts Django applications. the queries stay exactly the same, and you don't have to care if it does SQL or not.
3a. long-running processes are already addressed in 1b above. Google is aware of this need and are working on it.
3b. the TaskQueue API supports 100k calls, but that's bumped to 1MM wBE... and this is on a daily basis.
3c. Google strongly encourages breaking up tasks into multiple subtasks. low latency apps are seen not to "hog the system" and are given better treatment than those which are slow and consume more resources from their cloud neighbors.
A:
Yes, you would not be in as much control as with traditional hosting. Main sore points of GAE are
Quotas etc, 30 sec max for a request, so comet/reverse ajax etc out of window or very difficult. Try writing a chat server on google app engine.
Not Sql database, so difficult to port to other server if need be and sometime limitation with google database e.g. try sorting a query which has comparison on different column other than the sorted one.
Long running process, there is a Task api but that doesn't suffice if you want to do long running background processing, otherwise you will have to break your task in subtasks, so things get complicated and there are even quotas on how many tasks per sec you can run.
GAE is good if you app can be modeled as request-response registry, with little background processing.
See this too
Feedback on using Google App Engine?
|
Feedback on availability with Google App Engine
|
We've had some good experiences building an app on Google App Engine, this first app's target audience are Google Apps users, so no issues there in terms of it being hosted on Google infrastructure.
We like it so much that we would like to investigate using it for another app, however this next project is for a client who is not really that interested in what technology it sits on, they just want it to work, and work all of the time.
In this scenario, given that we have the technology applicability and capability side covered, are there any concerns that this stuff is still relatively new and that we may not be as much "in control" as if we had it done with traditional hosting?
|
[
"You are correct: you are not in as much control vs. traditional hosting. However, hopefully the gains outweight the negatives. App Engine is extremely scalable -- it runs on the same hardware that runs Google itself. How often have you visited http://google.com and had that page or a search result fail?\nAlthough you are letting Google run your code, the code is still your's to do as you please. With new projects like django-nonrel, you can create and run native Django apps directly on top of App Engine, and if it doesn't meet your needs down the line, it's fairly easy to take that app to an ISP that hosts Django apps (and there are plenty of those). More on this project below.\nYou don't have to worry about hardware, operating systems, coming up with a machine image, databases, web servers, front-end load balancers, CDNs/edge caching, software/package upgrades, license fees, etc. All these things are tangential to the web or other application that you have or will create to solve a particular problem. All this additional infrastructure is required whether you like it or not; but with App Engine, you only need to think about your app/solution and none of this extra stuff.\nObviously another thing you lose is some of your execution environment. To ensure that you're playing nicely with your cloud neighbors (resource hogging, security issues, etc.), you must execute in a sandbox, meaning your app cannot create local files, open network sockets, etc. However, App Engine provides a rich set of APIs and product features so that you at least can create meaningful apps:\n\nscalable distributed object datastore (see below)\nMemcache\nURLFetch\nimages service (resize, crop, etc.)\nusers service/authentication task queues for background processing\nDjango web templating\nblobstore for large files \ndenial-of-service blacklisting \ntransational tasks\ndatastore cursors \nsending (and/or receiving) of email \nsending (and/or receiving) of chat/IM/instant messages via XMPP\n\nYou also have a full dashboarded administration console which will let you monitor your app's usage, your billing settings and history, a full dump of your quota usage, and even your application logs which you can view or download.\nTo address the \"main sore points\" from @Anurag:\n1a. the free quotas are fairly generous... enough to power a website that gets 5MM views/month. also, if you trust Google to give them your credit card, they will bump up the free quota levels even higher. look at their quota page and refer to the numbers in both the \"Free Default Quota\" and \"Billing Enabled Default Quota\" columns... here are some examples: a) # of Requests: 1.3MM default, 43MM w/billing enabled (wBE), b) Datastore API calls: 10MM default, 140MM wBE, c) URL Fetches: 657K default, 46MM wBE\n1b. 30s max for requests: this is more security for you, because your app is now in a playground with others. Google has to ensure that all cloud neighbors play nicely with each other and not hog the CPU. However, the App Engine team is working on a way to allow for longer running background tasks... there's no timetable yet, but it is on the public roadmap.\n1c. writing a chat server on App Engine is not only possible, but it is quite simple. here's one created using App Engine's XMPP API -- it's pretty dumb and just echoes back to the sender what they transmitted to us (be aware that you must have already invited the user to chat):\nfrom google.appengine.api import xmpp\nfrom google.appengine.ext import webapp\nfrom google.appengine.ext.webapp.util import run_wsgi_app\n\nclass XMPPHandler(webapp.RequestHandler):\n def post(self):\n msg = xmpp.Message(self.request.POST)\n msg.reply(\"I got your msg: '%s'\" % msg.body)\n\napplication = webapp.WSGIApplication([\n ('/_ah/xmpp/message/chat/', XMPPHandler),\n], debug=True)\n\ndef main():\n run_wsgi_app(application)\n\nif __name__ == '__main__':\n main()\n\n1d. another item on the the public roadmap is future \"[support] for Browser Push (Comet) communication\", so that's coming too.\n2a. \"not SQL\" is one of Google App Engine's greatest strengths! relational databases don't scale and must be sharded at some point to keep an RDBMS from falling over. it is true however, that it is slightly more difficult to port because it is not traditional! Based on Google Bigtable, you can think of the App Engine datastore as a scalable distributed object database. App Engine lets you query the datastore using a Query object model, or if you insist, they also provide a SQL-like GqlQuery interface.\n2b. with new avantgarde projects like django-nonrel, if you create a Django app and use its ORM, you can take a pure Django app and run it directly on top of App Engine. likewise, you can it off of App Engine and move it directly to more traditional ISP vendor that hosts Django applications. the queries stay exactly the same, and you don't have to care if it does SQL or not.\n3a. long-running processes are already addressed in 1b above. Google is aware of this need and are working on it.\n3b. the TaskQueue API supports 100k calls, but that's bumped to 1MM wBE... and this is on a daily basis.\n3c. Google strongly encourages breaking up tasks into multiple subtasks. low latency apps are seen not to \"hog the system\" and are given better treatment than those which are slow and consume more resources from their cloud neighbors.\n",
"Yes, you would not be in as much control as with traditional hosting. Main sore points of GAE are \n\nQuotas etc, 30 sec max for a request, so comet/reverse ajax etc out of window or very difficult. Try writing a chat server on google app engine.\nNot Sql database, so difficult to port to other server if need be and sometime limitation with google database e.g. try sorting a query which has comparison on different column other than the sorted one.\nLong running process, there is a Task api but that doesn't suffice if you want to do long running background processing, otherwise you will have to break your task in subtasks, so things get complicated and there are even quotas on how many tasks per sec you can run.\n\nGAE is good if you app can be modeled as request-response registry, with little background processing.\nSee this too \nFeedback on using Google App Engine?\n"
] |
[
8,
2
] |
[] |
[] |
[
"google_app_engine",
"google_apps",
"python"
] |
stackoverflow_0002682062_google_app_engine_google_apps_python.txt
|
Q:
Django-admin.py not working (-bash:django-admin.py: command not found)
I'm having trouble getting django-admin.py to work... it's in this first location:
/Users/mycomp/bin/ but I think I need it in another location for the terminal to recognize it, no?
Noob, Please help. Thanks!!
my-computer:~/Django-1.1.1 mycomp$ sudo ln -s /Users/mycomp/bin/django-admin.py /Users/mycomp/django-1.1.1/django-admin.py
Password:
ln: /Users/mycomp/django-1.1.1/django-admin.py: File exists
my-computer:~/Django-1.1.1 mycomp$ django-admin.py --version
-bash: django-admin.py: command not found
A:
you need to export /Users/mycomp/bin to environment variable PATH
for a session
export PATH=/Users/mycomp/bin:$PATH
for permanent, whenever you use bash
echo "export PATH=/Users/mycomp/bin:\$PATH" >> ~/.bashrc
source ~/.bashrc
Note: And I think django automatically create executable django-admin file in the bin folder (notice there is no extensions .py) when you installed, So you should try django-admin only too.
|
Django-admin.py not working (-bash:django-admin.py: command not found)
|
I'm having trouble getting django-admin.py to work... it's in this first location:
/Users/mycomp/bin/ but I think I need it in another location for the terminal to recognize it, no?
Noob, Please help. Thanks!!
my-computer:~/Django-1.1.1 mycomp$ sudo ln -s /Users/mycomp/bin/django-admin.py /Users/mycomp/django-1.1.1/django-admin.py
Password:
ln: /Users/mycomp/django-1.1.1/django-admin.py: File exists
my-computer:~/Django-1.1.1 mycomp$ django-admin.py --version
-bash: django-admin.py: command not found
|
[
"you need to export /Users/mycomp/bin to environment variable PATH\nfor a session\nexport PATH=/Users/mycomp/bin:$PATH\n\nfor permanent, whenever you use bash\necho \"export PATH=/Users/mycomp/bin:\\$PATH\" >> ~/.bashrc\nsource ~/.bashrc\n\nNote: And I think django automatically create executable django-admin file in the bin folder (notice there is no extensions .py) when you installed, So you should try django-admin only too. \n"
] |
[
3
] |
[] |
[] |
[
"django",
"django_admin",
"framework_installation",
"python"
] |
stackoverflow_0002687704_django_django_admin_framework_installation_python.txt
|
Q:
Can't get python.manage.py syncdb to work
I just created my first django app, initialized variables DATABASE_ENGINE and DATABASE_NAME in settings.py, but now when I run python manage.py syncdb, I get the following error Can somebody help? Does this have to do with having two python versions installed?
I'm a django/python noob, please help. thanks!!
my-computer:~/Django-1.1.1 mycomp$ python manage.py syncdb
/Library/Frameworks/Python.framework/Versions/2.6/Resources/Python.app/Contents/MacOS/Python: can't open file 'manage.py': [Errno 2] No such file or directory
my-computer:~/Django-1.1.1 mycomp$ export PATH=/Users/mycomp/bin:$PATH
A:
You need to run manage.py from the root folder of your project. Looks like you are trying from the Django install folder.
|
Can't get python.manage.py syncdb to work
|
I just created my first django app, initialized variables DATABASE_ENGINE and DATABASE_NAME in settings.py, but now when I run python manage.py syncdb, I get the following error Can somebody help? Does this have to do with having two python versions installed?
I'm a django/python noob, please help. thanks!!
my-computer:~/Django-1.1.1 mycomp$ python manage.py syncdb
/Library/Frameworks/Python.framework/Versions/2.6/Resources/Python.app/Contents/MacOS/Python: can't open file 'manage.py': [Errno 2] No such file or directory
my-computer:~/Django-1.1.1 mycomp$ export PATH=/Users/mycomp/bin:$PATH
|
[
"You need to run manage.py from the root folder of your project. Looks like you are trying from the Django install folder. \n"
] |
[
6
] |
[] |
[] |
[
"django",
"django_syncdb",
"manage.py",
"python"
] |
stackoverflow_0002687853_django_django_syncdb_manage.py_python.txt
|
Q:
Problem with recognizing "\t" for vim in python output
I have a python code something like this
file_out.write(str(i).strip()+"\t"+str(dict1[i]).strip()+"\n")
But when i try to recognize this with vim by saying on the file that was written.
:%s/\t/|/g
But it does not recognize the \t
A:
:%s/\\\t/|/g
because the \ is itself a special char that needs escaping with \.
A:
I'd do :%s/^V^I/|/g where ^V means control-V and ^I means control-I -- that's how you get a tab into your vim command!
|
Problem with recognizing "\t" for vim in python output
|
I have a python code something like this
file_out.write(str(i).strip()+"\t"+str(dict1[i]).strip()+"\n")
But when i try to recognize this with vim by saying on the file that was written.
:%s/\t/|/g
But it does not recognize the \t
|
[
":%s/\\\\\\t/|/g\n\nbecause the \\ is itself a special char that needs escaping with \\.\n",
"I'd do :%s/^V^I/|/g where ^V means control-V and ^I means control-I -- that's how you get a tab into your vim command!\n"
] |
[
2,
0
] |
[] |
[] |
[
"python",
"sed",
"vim"
] |
stackoverflow_0002687618_python_sed_vim.txt
|
Q:
Fitting Gaussian KDE in numpy/scipy in Python
I am fitting a Gaussian kernel density estimator to a variable that is the difference of two vectors, called "diff", as follows: gaussian_kde_covfact(diff, smoothing_param) -- where gaussian_kde_covfact is defined as:
class gaussian_kde_covfact(stats.gaussian_kde):
def __init__(self, dataset, covfact = 'scotts'):
self.covfact = covfact
scipy.stats.gaussian_kde.__init__(self, dataset)
def _compute_covariance_(self):
'''not used'''
self.inv_cov = np.linalg.inv(self.covariance)
self._norm_factor = sqrt(np.linalg.det(2*np.pi*self.covariance)) * self.n
def covariance_factor(self):
if self.covfact in ['sc', 'scotts']:
return self.scotts_factor()
if self.covfact in ['si', 'silverman']:
return self.silverman_factor()
elif self.covfact:
return float(self.covfact)
else:
raise ValueError, \
'covariance factor has to be scotts, silverman or a number'
def reset_covfact(self, covfact):
self.covfact = covfact
self.covariance_factor()
self._compute_covariance()
This works, but there is an edge case where the diff is a vector of all 0s. In that case, I get the error:
File "/srv/pkg/python/python-packages/python26/scipy/scipy-0.7.1/lib/python2.6/site-packages/scipy/stats/kde.py", line 334, in _compute_covariance
self.inv_cov = linalg.inv(self.covariance)
File "/srv/pkg/python/python-packages/python26/scipy/scipy-0.7.1/lib/python2.6/site-packages/scipy/linalg/basic.py", line 382, in inv
if info>0: raise LinAlgError, "singular matrix"
numpy.linalg.linalg.LinAlgError: singular matrix
What's a way to get around this? In this case, I'd like it to return a density that's essentially peaked completely at a difference of 0, with no mass everywhere else.
thanks.
A:
A density peaked whose mass is at one point is not Gaussian, so strictly speaking, what you want to do is undefined (and such distribution does not have a finite covariance).
Now, in your case, for a vector which is all zero, you could special-case it, bypassing the whole infrastructure. A simple way to detect the case is to compute the max of the diff and compare this to eps (numpy.finfo(x.dtype).eps for the vector x). You could also simply detect it by catching the LinalgError, but you would have to be careful to differentiate the cases where covariance is ill defined and 0 entries.
|
Fitting Gaussian KDE in numpy/scipy in Python
|
I am fitting a Gaussian kernel density estimator to a variable that is the difference of two vectors, called "diff", as follows: gaussian_kde_covfact(diff, smoothing_param) -- where gaussian_kde_covfact is defined as:
class gaussian_kde_covfact(stats.gaussian_kde):
def __init__(self, dataset, covfact = 'scotts'):
self.covfact = covfact
scipy.stats.gaussian_kde.__init__(self, dataset)
def _compute_covariance_(self):
'''not used'''
self.inv_cov = np.linalg.inv(self.covariance)
self._norm_factor = sqrt(np.linalg.det(2*np.pi*self.covariance)) * self.n
def covariance_factor(self):
if self.covfact in ['sc', 'scotts']:
return self.scotts_factor()
if self.covfact in ['si', 'silverman']:
return self.silverman_factor()
elif self.covfact:
return float(self.covfact)
else:
raise ValueError, \
'covariance factor has to be scotts, silverman or a number'
def reset_covfact(self, covfact):
self.covfact = covfact
self.covariance_factor()
self._compute_covariance()
This works, but there is an edge case where the diff is a vector of all 0s. In that case, I get the error:
File "/srv/pkg/python/python-packages/python26/scipy/scipy-0.7.1/lib/python2.6/site-packages/scipy/stats/kde.py", line 334, in _compute_covariance
self.inv_cov = linalg.inv(self.covariance)
File "/srv/pkg/python/python-packages/python26/scipy/scipy-0.7.1/lib/python2.6/site-packages/scipy/linalg/basic.py", line 382, in inv
if info>0: raise LinAlgError, "singular matrix"
numpy.linalg.linalg.LinAlgError: singular matrix
What's a way to get around this? In this case, I'd like it to return a density that's essentially peaked completely at a difference of 0, with no mass everywhere else.
thanks.
|
[
"A density peaked whose mass is at one point is not Gaussian, so strictly speaking, what you want to do is undefined (and such distribution does not have a finite covariance).\nNow, in your case, for a vector which is all zero, you could special-case it, bypassing the whole infrastructure. A simple way to detect the case is to compute the max of the diff and compare this to eps (numpy.finfo(x.dtype).eps for the vector x). You could also simply detect it by catching the LinalgError, but you would have to be careful to differentiate the cases where covariance is ill defined and 0 entries.\n"
] |
[
2
] |
[] |
[] |
[
"numpy",
"probability",
"python",
"scipy",
"statistics"
] |
stackoverflow_0002678425_numpy_probability_python_scipy_statistics.txt
|
Q:
Compiling scipy on Windows 32-bit: linker error with libf77blas.a
Has anyone tried compiling SciPy 0.7.1 on Windows using numpy-1.3.0 that was built with the pre-built ATLAS libraries (atlas3.6.0_WinNT_P4SSE2.zip) linked in the installation document.
I get the following linker error, and have no ideas as to how to fix this issue.
$ python setup.py config --compiler=mingw32 build --compiler=mingw32 install --root=i
[...]
creating build\temp.win32-2.6\Release
creating build\temp.win32-2.6\Release\scipy
creating build\temp.win32-2.6\Release\scipy\integrate
compile options: '-DNO_ATLAS_INFO=2 -I"C:\Documents and Settings\apy\Application Data\Python\Python26\site-packages\numpy\core\inc
lude" -IC:\Python26\include -IC:\Python26\PC -c'
gcc -mno-cygwin -O2 -Wall -Wstrict-prototypes -DNO_ATLAS_INFO=2 -I"C:\Documents and Settings\apy\Application Data\Python\Python26\
site-packages\numpy\core\include" -IC:\Python26\include -IC:\Python26\PC -c scipy\integrate\_odepackmo
dule.c -o build\temp.win32-2.6\Release\scipy\integrate\_odepackmodule.o
C:\MinGW\bin\g77.exe -g -Wall -mno-cygwin -g -Wall -mno-cygwin -shared build\temp.win32-2.6\Release\scipy\integrate\_odepackmodule
.o -LC:\atlas3.6.0_WinNT_P4SSE2 -LC:\MinGW\lib -LC:\MinGW\lib\gcc\mingw32\3.4.5 -LC:\Python26\libs -LC:\Act
ivePython32Python26\PCbuild -Lbuild\temp.win32-2.6 -lodepack -llinpack_lite -lmach -latlas -lcblas -lf77blas -llapack -lpython26 -
lg2c -o build\lib.win32-2.6\scipy\integrate\_odepack.pyd
C:\atlas3.6.0_WinNT_P4SSE2/libf77blas.a(ATL_F77wrap_daxpy.o):ATL_F77wrap_axpy.c:(.text+0x3c): undefined reference to `ATL
_daxpy'
C:\atlas3.6.0_WinNT_P4SSE2/libf77blas.a(ATL_F77wrap_dscal.o):ATL_F77wrap_scal.c:(.text+0x26): undefined reference to `ATL
_dscal'
C:\atlas3.6.0_WinNT_P4SSE2/libf77blas.a(ATL_F77wrap_dcopy.o):ATL_F77wrap_copy.c:(.text+0x3d): undefined reference to `ATL
_dcopy'
C:\atlas3.6.0_WinNT_P4SSE2/libf77blas.a(ATL_F77wrap_idamax.o):ATL_F77wrap_amax.c:(.text+0x1e): undefined reference to `AT
L_idamax'
C:\atlas3.6.0_WinNT_P4SSE2/libf77blas.a(ATL_F77wrap_ddot.o):ATL_F77wrap_dot.c:(.text+0x36): undefined reference to `ATL_d
dot'
collect2: ld returned 1 exit status
error: Command "C:\MinGW\bin\g77.exe -g -Wall -mno-cygwin -g -Wall -mno-cygwin -shared build\temp.win32-2.6\Release\scipy\integrat
e\_odepackmodule.o -LC:\atlas3.6.0_WinNT_P4SSE2 -LC:\MinGW\lib -LC:\MinGW\lib\gcc\mingw32\3.4.5 -LC:\Python
26\libs -LC:\Python26\PCbuild -Lbuild\temp.win32-2.6 -lodepack -llinpack_lite -lmach -latlas -lcblas -lf77blas -llap
ack -lpython26 -lg2c -o build\lib.win32-2.6\scipy\integrate\_odepack.pyd" failed with exit status 1
Does anyone know what could have gone wrong here? Looking for ATL_daxpy, for example, in libf77blas.a resulted in:
$ strings libf77blas.a | grep -i daxpy
_daxpy_
_atl_f77wrap_daxpy_
ATL_F77wrap_daxpy.o/
daxpy.o/ 1081731936 1003 513 100755 420 `
daxpy.f
_daxpy_
_atl_f77wrap_daxpy_
_atl_f77wrap_daxpy_
_ATL_daxpy
There is _ATL_daxpy, but no ATL_daxpy.
A:
Our installation instructions are awfully out of date. First, you should use the binary installer unless you have a very good reason not to on windows. Here you are linking against an ATLAS which is different than the one numpy itself was built on, which is unlikely to work well (numpy and scipy would use different versions of atlas).
Assuming you have a good reason to build it by yourself, you can get the atlas binaries we use in the binary installers in the vendor directory of our repo.
|
Compiling scipy on Windows 32-bit: linker error with libf77blas.a
|
Has anyone tried compiling SciPy 0.7.1 on Windows using numpy-1.3.0 that was built with the pre-built ATLAS libraries (atlas3.6.0_WinNT_P4SSE2.zip) linked in the installation document.
I get the following linker error, and have no ideas as to how to fix this issue.
$ python setup.py config --compiler=mingw32 build --compiler=mingw32 install --root=i
[...]
creating build\temp.win32-2.6\Release
creating build\temp.win32-2.6\Release\scipy
creating build\temp.win32-2.6\Release\scipy\integrate
compile options: '-DNO_ATLAS_INFO=2 -I"C:\Documents and Settings\apy\Application Data\Python\Python26\site-packages\numpy\core\inc
lude" -IC:\Python26\include -IC:\Python26\PC -c'
gcc -mno-cygwin -O2 -Wall -Wstrict-prototypes -DNO_ATLAS_INFO=2 -I"C:\Documents and Settings\apy\Application Data\Python\Python26\
site-packages\numpy\core\include" -IC:\Python26\include -IC:\Python26\PC -c scipy\integrate\_odepackmo
dule.c -o build\temp.win32-2.6\Release\scipy\integrate\_odepackmodule.o
C:\MinGW\bin\g77.exe -g -Wall -mno-cygwin -g -Wall -mno-cygwin -shared build\temp.win32-2.6\Release\scipy\integrate\_odepackmodule
.o -LC:\atlas3.6.0_WinNT_P4SSE2 -LC:\MinGW\lib -LC:\MinGW\lib\gcc\mingw32\3.4.5 -LC:\Python26\libs -LC:\Act
ivePython32Python26\PCbuild -Lbuild\temp.win32-2.6 -lodepack -llinpack_lite -lmach -latlas -lcblas -lf77blas -llapack -lpython26 -
lg2c -o build\lib.win32-2.6\scipy\integrate\_odepack.pyd
C:\atlas3.6.0_WinNT_P4SSE2/libf77blas.a(ATL_F77wrap_daxpy.o):ATL_F77wrap_axpy.c:(.text+0x3c): undefined reference to `ATL
_daxpy'
C:\atlas3.6.0_WinNT_P4SSE2/libf77blas.a(ATL_F77wrap_dscal.o):ATL_F77wrap_scal.c:(.text+0x26): undefined reference to `ATL
_dscal'
C:\atlas3.6.0_WinNT_P4SSE2/libf77blas.a(ATL_F77wrap_dcopy.o):ATL_F77wrap_copy.c:(.text+0x3d): undefined reference to `ATL
_dcopy'
C:\atlas3.6.0_WinNT_P4SSE2/libf77blas.a(ATL_F77wrap_idamax.o):ATL_F77wrap_amax.c:(.text+0x1e): undefined reference to `AT
L_idamax'
C:\atlas3.6.0_WinNT_P4SSE2/libf77blas.a(ATL_F77wrap_ddot.o):ATL_F77wrap_dot.c:(.text+0x36): undefined reference to `ATL_d
dot'
collect2: ld returned 1 exit status
error: Command "C:\MinGW\bin\g77.exe -g -Wall -mno-cygwin -g -Wall -mno-cygwin -shared build\temp.win32-2.6\Release\scipy\integrat
e\_odepackmodule.o -LC:\atlas3.6.0_WinNT_P4SSE2 -LC:\MinGW\lib -LC:\MinGW\lib\gcc\mingw32\3.4.5 -LC:\Python
26\libs -LC:\Python26\PCbuild -Lbuild\temp.win32-2.6 -lodepack -llinpack_lite -lmach -latlas -lcblas -lf77blas -llap
ack -lpython26 -lg2c -o build\lib.win32-2.6\scipy\integrate\_odepack.pyd" failed with exit status 1
Does anyone know what could have gone wrong here? Looking for ATL_daxpy, for example, in libf77blas.a resulted in:
$ strings libf77blas.a | grep -i daxpy
_daxpy_
_atl_f77wrap_daxpy_
ATL_F77wrap_daxpy.o/
daxpy.o/ 1081731936 1003 513 100755 420 `
daxpy.f
_daxpy_
_atl_f77wrap_daxpy_
_atl_f77wrap_daxpy_
_ATL_daxpy
There is _ATL_daxpy, but no ATL_daxpy.
|
[
"Our installation instructions are awfully out of date. First, you should use the binary installer unless you have a very good reason not to on windows. Here you are linking against an ATLAS which is different than the one numpy itself was built on, which is unlikely to work well (numpy and scipy would use different versions of atlas).\nAssuming you have a good reason to build it by yourself, you can get the atlas binaries we use in the binary installers in the vendor directory of our repo.\n"
] |
[
1
] |
[] |
[] |
[
"atlas",
"linker_errors",
"python",
"scipy",
"windows"
] |
stackoverflow_0002596069_atlas_linker_errors_python_scipy_windows.txt
|
Q:
Mako template depending on object class?
whats a clean way to use different templates depending on an object class? other than buncha if statements
A:
You can make a dict, call it type2templ, with types (i.e., classes) as the keys, and mako.template.Template instances as the values -- then
t = type2templ.get(type(theobj), default_templ)
... t.render() ...
This assumes that theobj is an instance of a new-style class (not the obsolete, best-avoided "legacy" classes that are still the default in Python 2 -- if you use those, you should definitely upgrade your code to new-style classes, but using theobj.__class__ is a workable, if hackish, replacement for type(theobj) here). default_templ is a default template instance to use for "none of the above" (if you'd rather have an exception when theobj is of a non-recognized type, use square-bracket indexing instead of the .get call).
Note that this doesn't (directly) "support inheritance" -- if (for example) class foo maps in type2templ to template bar, then you make a subclass baz of foo but don't explicitly record in type2templ what template its instances should use, you'll get the default template for baz's instances. Supporting inheritance is more complex -- unless you just make the mako template instance one of the class attributes, of course, which makes it trivial (just theobj.thetempl if you name that attribute thetempl!-), but I do understand to separate the view from the model.
|
Mako template depending on object class?
|
whats a clean way to use different templates depending on an object class? other than buncha if statements
|
[
"You can make a dict, call it type2templ, with types (i.e., classes) as the keys, and mako.template.Template instances as the values -- then \nt = type2templ.get(type(theobj), default_templ)\n... t.render() ...\n\nThis assumes that theobj is an instance of a new-style class (not the obsolete, best-avoided \"legacy\" classes that are still the default in Python 2 -- if you use those, you should definitely upgrade your code to new-style classes, but using theobj.__class__ is a workable, if hackish, replacement for type(theobj) here). default_templ is a default template instance to use for \"none of the above\" (if you'd rather have an exception when theobj is of a non-recognized type, use square-bracket indexing instead of the .get call).\nNote that this doesn't (directly) \"support inheritance\" -- if (for example) class foo maps in type2templ to template bar, then you make a subclass baz of foo but don't explicitly record in type2templ what template its instances should use, you'll get the default template for baz's instances. Supporting inheritance is more complex -- unless you just make the mako template instance one of the class attributes, of course, which makes it trivial (just theobj.thetempl if you name that attribute thetempl!-), but I do understand to separate the view from the model.\n"
] |
[
2
] |
[] |
[] |
[
"mako",
"python"
] |
stackoverflow_0002687063_mako_python.txt
|
Q:
python multiprocessing server connections
I wish to get a list of connections to a manager. I can get last_accepted from the servers' listener, but I want all connections. There HAS to be a method I am missing somewhere to return all connections to a server or manager
Please help!!
A:
Looking at multiprocessing/connection.py, the listener just doesn't seem to track all connections -- you could, however, subclass it and override accept to append accepted connections to a list.
|
python multiprocessing server connections
|
I wish to get a list of connections to a manager. I can get last_accepted from the servers' listener, but I want all connections. There HAS to be a method I am missing somewhere to return all connections to a server or manager
Please help!!
|
[
"Looking at multiprocessing/connection.py, the listener just doesn't seem to track all connections -- you could, however, subclass it and override accept to append accepted connections to a list.\n"
] |
[
0
] |
[] |
[] |
[
"multiprocessing",
"python"
] |
stackoverflow_0002686893_multiprocessing_python.txt
|
Q:
Python hash() can't handle long integer?
I defined a class:
class A:
''' hash test class
>>> a = A(9, 1196833379, 1, 1773396906)
>>> hash(a)
-340004569
This is weird, 12544897317L expected.
'''
def __init__(self, a, b, c, d):
self.a = a
self.b = b
self.c = c
self.d = d
def __hash__(self):
return self.a * self.b + self.c * self.d
Why, in the doctest, hash() function gives a negative integer?
A:
It appears to be limited to 32-bits. By reading this question, it looks like your code might have produced the expected result on a 64-bit machine (with those particular values, since the result fits in 64 bits).
The results of the built-in hash function are platform dependent and constrained to the native word size. If you need a deterministic, cross-platform hash, consider using the hashlib module.
A:
See object.__hash__
Notice that
Changed in version 2.5: __hash__() may
now also return a long integer object;
the 32-bit integer is then derived
from the hash of that object.
In your case, expected 12544897317L is a long integer object,
Python derived the 32-bit integer -340004569 by (12544897317 & 0xFFFFFFFF) - (1<<32)
Python derived the 32-bit integer by hash(12544897317L), which results -340004569
The algorithm is something like this:
def s32(x):
x = x & ((1<<32)-1)
if x & (1<<31):
return x - (1<<32)
else:
return x
def hash(x):
h = 0
while x:
h += s32(x)
x >>= 32
return h
A:
Because the purpose of a hash function is to take a set of inputs and distribute them across a range of keys, there is no reason that those keys have to be positive integers.
The fact that pythons hash function returns negative integers is just an implementation detail and is necessarily limited to long ints. For example hash('abc') is negative on my system.
|
Python hash() can't handle long integer?
|
I defined a class:
class A:
''' hash test class
>>> a = A(9, 1196833379, 1, 1773396906)
>>> hash(a)
-340004569
This is weird, 12544897317L expected.
'''
def __init__(self, a, b, c, d):
self.a = a
self.b = b
self.c = c
self.d = d
def __hash__(self):
return self.a * self.b + self.c * self.d
Why, in the doctest, hash() function gives a negative integer?
|
[
"It appears to be limited to 32-bits. By reading this question, it looks like your code might have produced the expected result on a 64-bit machine (with those particular values, since the result fits in 64 bits).\nThe results of the built-in hash function are platform dependent and constrained to the native word size. If you need a deterministic, cross-platform hash, consider using the hashlib module.\n",
"See object.__hash__\nNotice that \n\nChanged in version 2.5: __hash__() may\n now also return a long integer object;\n the 32-bit integer is then derived\n from the hash of that object.\n\nIn your case, expected 12544897317L is a long integer object,\nPython derived the 32-bit integer -340004569 by (12544897317 & 0xFFFFFFFF) - (1<<32)\nPython derived the 32-bit integer by hash(12544897317L), which results -340004569 \nThe algorithm is something like this:\ndef s32(x):\n x = x & ((1<<32)-1)\n if x & (1<<31):\n return x - (1<<32)\n else:\n return x\n\ndef hash(x):\n h = 0\n while x:\n h += s32(x)\n x >>= 32\n return h\n\n",
"Because the purpose of a hash function is to take a set of inputs and distribute them across a range of keys, there is no reason that those keys have to be positive integers.\nThe fact that pythons hash function returns negative integers is just an implementation detail and is necessarily limited to long ints. For example hash('abc') is negative on my system.\n"
] |
[
10,
7,
4
] |
[] |
[] |
[
"hash",
"integer",
"python"
] |
stackoverflow_0002687829_hash_integer_python.txt
|
Q:
How to iterate over the first n elements of a list?
Say I've got a list and I want to iterate over the first n of them. What's the best way to write this in Python?
A:
The normal way would be slicing:
for item in your_list[:n]:
...
A:
I'd probably use itertools.islice (<- follow the link for the docs), which has the benefits of:
working with any iterable object
not copying the list
Usage:
import itertools
n = 2
mylist = [1, 2, 3, 4]
for item in itertools.islice(mylist, n):
print(item)
outputs:
1
2
One downside is that if you wanted a non-zero start, it has to iterate up to that point one by one: https://stackoverflow.com/a/5131550/895245
Tested in Python 3.8.6.
A:
You can just slice the list:
>>> l = [1, 2, 3, 4, 5]
>>> n = 3
>>> l[:n]
[1, 2, 3]
and then iterate on the slice as with any iterable.
A:
Python lists are O(1) random access, so just:
for i in xrange(n):
print list[i]
|
How to iterate over the first n elements of a list?
|
Say I've got a list and I want to iterate over the first n of them. What's the best way to write this in Python?
|
[
"The normal way would be slicing:\nfor item in your_list[:n]: \n ...\n\n",
"I'd probably use itertools.islice (<- follow the link for the docs), which has the benefits of:\n\nworking with any iterable object\nnot copying the list\n\nUsage:\nimport itertools\n\nn = 2\nmylist = [1, 2, 3, 4]\nfor item in itertools.islice(mylist, n):\n print(item)\n\noutputs:\n1\n2\n\nOne downside is that if you wanted a non-zero start, it has to iterate up to that point one by one: https://stackoverflow.com/a/5131550/895245\nTested in Python 3.8.6.\n",
"You can just slice the list:\n>>> l = [1, 2, 3, 4, 5]\n>>> n = 3\n>>> l[:n]\n[1, 2, 3]\n\nand then iterate on the slice as with any iterable.\n",
"Python lists are O(1) random access, so just:\nfor i in xrange(n):\n print list[i]\n\n"
] |
[
120,
38,
13,
2
] |
[] |
[] |
[
"list",
"python",
"slice"
] |
stackoverflow_0002688079_list_python_slice.txt
|
Q:
Writing a blocking wrapper around twisted's IRC client
I'm trying to write a dead-simple interface for an IRC library, like so:
import simpleirc
connection = simpleirc.Connect('irc.freenode.net', 6667)
channel = connection.join('foo')
find_command = re.compile(r'google ([a-z]+)').findall
for msg in channel:
for t in find_command(msg):
channel.say("http://google.com/search?q=%s" % t)
Working from their example, I'm running into trouble (code is a bit lengthy, so I pasted it here). Since the call to channel.__next__ needs to be returned when the callback <IRCClient instance>.privmsg is called, there doesn't seem to be a clean option. Using exceptions or threads seems like the wrong thing here, is there a simpler (blocking?) way of using twisted that would make this possible?
A:
In general, if you're trying to use Twisted in a "blocking" way, you're going to run into a lot of difficulties, because that's neither the way it's intended to be used, nor the way in which most people use it.
Going with the flow is generally a lot easier, and in this case, that means embracing callbacks. The callback-style solution to your question would look something like this:
import re
from twisted.internet import reactor, protocol
from twisted.words.protocols import irc
find_command = re.compile(r'google ([a-z]+)').findall
class Googler(irc.IRCClient):
def privmsg(self, user, channel, message):
for text in find_command(message):
self.say(channel, "http://google.com/search?q=%s" % (text,))
def connect():
cc = protocol.ClientCreator(reactor, Googler)
return cc.connectTCP(host, port)
def run(proto):
proto.join(channel)
def main():
d = connect()
d.addCallback(run)
reactor.run()
This isn't absolutely required (but I strongly suggest you consider trying it). One alternative is inlineCallbacks:
import re
from twisted.internet import reactor, protocol, defer
from twisted.words.protocols import irc
find_command = re.compile(r'google ([a-z]+)').findall
class Googler(irc.IRCClient):
def privmsg(self, user, channel, message):
for text in find_command(message):
self.say(channel, "http://google.com/search?q=%s" % (text,))
@defer.inlineCallbacks
def run():
cc = protocol.ClientCreator(reactor, Googler)
proto = yield cc.connectTCP(host, port)
proto.join(channel)
def main():
run()
reactor.run()
Notice no more addCallbacks. It's been replaced by yield in a decorated generator function. This could get even closer to what you asked for if you had a version of Googler with a different API (the one above should work with IRCClient from Twisted as it is written - though I didn't test it). It would be entirely possible for Googler.join to return a Channel object of some sort, and for that Channel object to be iterable like this:
@defer.inlineCallbacks
def run():
cc = protocol.ClientCreator(reactor, Googler)
proto = yield cc.connectTCP(host, port)
channel = proto.join(channel)
for msg in channel:
msg = yield msg
for text in find_command(msg):
channel.say("http://google.com/search?q=%s" % (text,))
It's only a matter of implementing this API on top of the ones already present. Of course, the yield expressions are still there, and I don't know how much this will upset you. ;)
It's possible to go still further away from callbacks and make the context switches necessary for asynchronous operation to work completely invisible. This is bad for the same reason it would be bad for sidewalks outside your house to be littered with invisible bear traps. However, it's possible. Using something like corotwine, itself based on a third-party coroutine library for CPython, you can have the implementation of Channel do the context switching itself, rather than requiring the calling application code to do it. The result might look something like:
from corotwine import protocol
def run():
proto = Googler()
transport = protocol.gConnectTCP(host, port)
proto.makeConnection(transport)
channel = proto.join(channel)
for msg in channel:
for text in find_command(msg):
channel.say("http://google.com/search?q=%s" % (text,))
with an implementation of Channel that might look something like:
from corotwine import defer
class Channel(object):
def __init__(self, ircClient, name):
self.ircClient = ircClient
self.name = name
def __iter__(self):
while True:
d = self.ircClient.getNextMessage(self.name)
message = defer.blockOn(d)
yield message
This in turn depends on a new Googler method, getNextMessage, which is a straightforward feature addition based on existing IRCClient callbacks:
from twisted.internet import defer
class Googler(irc.IRCClient):
def connectionMade(self):
irc.IRCClient.connectionMade(self)
self._nextMessages = {}
def getNextMessage(self, channel):
if channel not in self._nextMessages:
self._nextMessages[channel] = defer.DeferredQueue()
return self._nextMessages[channel].get()
def privmsg(self, user, channel, message):
if channel not in self._nextMessages:
self._nextMessages[channel] = defer.DeferredQueue()
self._nextMessages[channel].put(message)
To run this, you create a new greenlet for the run function and switch to it, and then start the reactor.
from greenlet import greenlet
def main():
greenlet(run).switch()
reactor.run()
When run gets to its first asynchronous operation, it switches back to the reactor greenlet (which is the "main" greenlet in this case, but it doesn't really matter) to let the asynchronous operation complete. When it completes, corotwine turns the callback into a greenlet switch back into run. So run is granted the illusion of running straight through, like a "normal" synchronous program. Keep in mind that it is just an illusion, though.
So, it's possible to get as far away from the callback-oriented style that is most commonly used with Twisted as you want. It's not necessarily a good idea, though.
|
Writing a blocking wrapper around twisted's IRC client
|
I'm trying to write a dead-simple interface for an IRC library, like so:
import simpleirc
connection = simpleirc.Connect('irc.freenode.net', 6667)
channel = connection.join('foo')
find_command = re.compile(r'google ([a-z]+)').findall
for msg in channel:
for t in find_command(msg):
channel.say("http://google.com/search?q=%s" % t)
Working from their example, I'm running into trouble (code is a bit lengthy, so I pasted it here). Since the call to channel.__next__ needs to be returned when the callback <IRCClient instance>.privmsg is called, there doesn't seem to be a clean option. Using exceptions or threads seems like the wrong thing here, is there a simpler (blocking?) way of using twisted that would make this possible?
|
[
"In general, if you're trying to use Twisted in a \"blocking\" way, you're going to run into a lot of difficulties, because that's neither the way it's intended to be used, nor the way in which most people use it.\nGoing with the flow is generally a lot easier, and in this case, that means embracing callbacks. The callback-style solution to your question would look something like this:\nimport re\nfrom twisted.internet import reactor, protocol\nfrom twisted.words.protocols import irc\n\nfind_command = re.compile(r'google ([a-z]+)').findall\n\nclass Googler(irc.IRCClient):\n def privmsg(self, user, channel, message):\n for text in find_command(message):\n self.say(channel, \"http://google.com/search?q=%s\" % (text,))\n\ndef connect():\n cc = protocol.ClientCreator(reactor, Googler)\n return cc.connectTCP(host, port)\n\ndef run(proto):\n proto.join(channel)\n\ndef main():\n d = connect()\n d.addCallback(run)\n reactor.run()\n\nThis isn't absolutely required (but I strongly suggest you consider trying it). One alternative is inlineCallbacks:\nimport re\nfrom twisted.internet import reactor, protocol, defer\nfrom twisted.words.protocols import irc\n\nfind_command = re.compile(r'google ([a-z]+)').findall\n\nclass Googler(irc.IRCClient):\n def privmsg(self, user, channel, message):\n for text in find_command(message):\n self.say(channel, \"http://google.com/search?q=%s\" % (text,))\n\n@defer.inlineCallbacks\ndef run():\n cc = protocol.ClientCreator(reactor, Googler)\n proto = yield cc.connectTCP(host, port)\n proto.join(channel)\n\ndef main():\n run()\n reactor.run()\n\nNotice no more addCallbacks. It's been replaced by yield in a decorated generator function. This could get even closer to what you asked for if you had a version of Googler with a different API (the one above should work with IRCClient from Twisted as it is written - though I didn't test it). It would be entirely possible for Googler.join to return a Channel object of some sort, and for that Channel object to be iterable like this:\n@defer.inlineCallbacks\ndef run():\n cc = protocol.ClientCreator(reactor, Googler)\n proto = yield cc.connectTCP(host, port)\n channel = proto.join(channel)\n for msg in channel:\n msg = yield msg\n for text in find_command(msg):\n channel.say(\"http://google.com/search?q=%s\" % (text,))\n\nIt's only a matter of implementing this API on top of the ones already present. Of course, the yield expressions are still there, and I don't know how much this will upset you. ;)\nIt's possible to go still further away from callbacks and make the context switches necessary for asynchronous operation to work completely invisible. This is bad for the same reason it would be bad for sidewalks outside your house to be littered with invisible bear traps. However, it's possible. Using something like corotwine, itself based on a third-party coroutine library for CPython, you can have the implementation of Channel do the context switching itself, rather than requiring the calling application code to do it. The result might look something like:\nfrom corotwine import protocol\n\ndef run():\n proto = Googler()\n transport = protocol.gConnectTCP(host, port)\n proto.makeConnection(transport)\n channel = proto.join(channel)\n for msg in channel:\n for text in find_command(msg):\n channel.say(\"http://google.com/search?q=%s\" % (text,))\n\nwith an implementation of Channel that might look something like:\nfrom corotwine import defer\n\nclass Channel(object):\n def __init__(self, ircClient, name):\n self.ircClient = ircClient\n self.name = name\n\n def __iter__(self):\n while True:\n d = self.ircClient.getNextMessage(self.name)\n message = defer.blockOn(d)\n yield message\n\nThis in turn depends on a new Googler method, getNextMessage, which is a straightforward feature addition based on existing IRCClient callbacks:\nfrom twisted.internet import defer\n\nclass Googler(irc.IRCClient):\n def connectionMade(self):\n irc.IRCClient.connectionMade(self)\n self._nextMessages = {}\n\n def getNextMessage(self, channel):\n if channel not in self._nextMessages:\n self._nextMessages[channel] = defer.DeferredQueue()\n return self._nextMessages[channel].get()\n\n def privmsg(self, user, channel, message):\n if channel not in self._nextMessages:\n self._nextMessages[channel] = defer.DeferredQueue()\n self._nextMessages[channel].put(message)\n\nTo run this, you create a new greenlet for the run function and switch to it, and then start the reactor.\nfrom greenlet import greenlet\n\ndef main():\n greenlet(run).switch()\n reactor.run()\n\nWhen run gets to its first asynchronous operation, it switches back to the reactor greenlet (which is the \"main\" greenlet in this case, but it doesn't really matter) to let the asynchronous operation complete. When it completes, corotwine turns the callback into a greenlet switch back into run. So run is granted the illusion of running straight through, like a \"normal\" synchronous program. Keep in mind that it is just an illusion, though.\nSo, it's possible to get as far away from the callback-oriented style that is most commonly used with Twisted as you want. It's not necessarily a good idea, though.\n"
] |
[
10
] |
[] |
[] |
[
"asynchronous",
"python",
"twisted"
] |
stackoverflow_0002687656_asynchronous_python_twisted.txt
|
Q:
Can PyAMF support service deployment by way of the filesystem?
I'm evaluating PyAMF to replace our current PHP (ugh) AMF services framework, and I'm unable to find the one crucial piece of information that would allow me to provide a compelling use case for changing over:
Right now, new PHP AMF services are deployed simply by putting the .php files in the filesystem; the next time they're accessed, the new service is in play. Removal of a service is as simple as deleting the .php file that provided it, and updating it is correspondingly simple. I need that same ease-of-deployment from PyAMF. If we have to rewrite our installers to deploy these services, it'll be a nonstarter.
So, what I need to know is, can PyAMF support new service discovery by way of the filesystem, can it support service upgrading and removal by way of same, and if so, what is the best way to set it up to do this?
I'm open to any of the various server options; I can easily have cherrypy, django, whatever installed and running on its own, and even -- with a bit more sturm nd drang -- have mod_python or mod_wsgi made available.
A:
web2py includes pyamf support. The way it works is that you create functions like
def add(a,b): return a+b
and then you decorate them with @service.amfrpc3('domain')
@service.amfrpc3('domain')
def add(a,b): return a+b
You do not need to restart the web server or do anything else. You just add and delete functions in your controller file (the file where you define the services) and the service is made available or removed. You can also serve the same function using other protocols (xmlrpc, jsonrpc, rss, csv, xml, json) using multiple decorators.
@service.xmlrpc
@service.jsonrpc
@service.amfrpc3('domain')
def add(a,b): return a+b
You do not need to instantiate a Gateway (as with other frameworks. All decorated functions are exposed via a single action that you do not need to write because it is already in the scaffolding application (created by web2py for you):
def call(): return service()
The functions can access the web2py database abstraction layer (DAL) and (with some limitations) the web2py authentication mechanism.
You can edit the controller that contains the function using a shell (emacs/vi/etc) but you can also use the web2py web based IDE (called "admin") and add services using the browser.
Web2py includes a ticketing system therefore it is easy to debug web services. Any server side error results in a ticket. There is a web page in admin that lists all tickets. You click on one and it shows the code that caused the problem and the complete traceback.
You can import and use any third party python module. You must have pyamf pre-installed.
This is well documented in chapter 9 of the book:
http://web2py.com/book/default/section/9/2
web2py apps are very easy to deploy. One way is with point and click using admin. Another way is simply by copying files from one machine to another. There is no metadata, no installation procedure (not even for web2py itself), not settings, no configuration files.
The latter process is somewhat described here:
http://gluonframework.wordpress.com/2010/03/02/shell-only-web2py/
web2py is based on WSGI. It run with any web server you can think of (apache+mod_wsgi/mod_python/mod_proxy;lighttpd/cheorkeey/ngnix+fcgi/wsgi.py;cherrypy;etc).
Some options are documented in detail here:
http://www.web2py.com/book/default/section/11/0
Other options can be found on http://web2pyslices.com
web2py also comes with its own web server, Rocket, which supports https and is very fast. web2py code can also be deployed on Google App Engine.
Check for activity on the web2py google group.
A:
I use PyAMF together with Django. A possible solution could roughly look like this:
Create a python module containing all your different AMF services py files
Create a view that wrapps the DjangoGateway and initialize all your services. Inside this view you could do the following:
reload() your service module
populate a dictionary based on i.e. the file names ({SERVICE_NAME: SERVICE_INSTANCE})
Instantiate DjangoGateway with this dictionary and let it handle the incoming request.
This is a hackish solution based on the fact that you can only deploy files without any additional actions like restarting a server.
|
Can PyAMF support service deployment by way of the filesystem?
|
I'm evaluating PyAMF to replace our current PHP (ugh) AMF services framework, and I'm unable to find the one crucial piece of information that would allow me to provide a compelling use case for changing over:
Right now, new PHP AMF services are deployed simply by putting the .php files in the filesystem; the next time they're accessed, the new service is in play. Removal of a service is as simple as deleting the .php file that provided it, and updating it is correspondingly simple. I need that same ease-of-deployment from PyAMF. If we have to rewrite our installers to deploy these services, it'll be a nonstarter.
So, what I need to know is, can PyAMF support new service discovery by way of the filesystem, can it support service upgrading and removal by way of same, and if so, what is the best way to set it up to do this?
I'm open to any of the various server options; I can easily have cherrypy, django, whatever installed and running on its own, and even -- with a bit more sturm nd drang -- have mod_python or mod_wsgi made available.
|
[
"web2py includes pyamf support. The way it works is that you create functions like\ndef add(a,b): return a+b\n\nand then you decorate them with @service.amfrpc3('domain')\n@service.amfrpc3('domain')\ndef add(a,b): return a+b\n\nYou do not need to restart the web server or do anything else. You just add and delete functions in your controller file (the file where you define the services) and the service is made available or removed. You can also serve the same function using other protocols (xmlrpc, jsonrpc, rss, csv, xml, json) using multiple decorators.\n@service.xmlrpc\n@service.jsonrpc\n@service.amfrpc3('domain')\ndef add(a,b): return a+b\n\nYou do not need to instantiate a Gateway (as with other frameworks. All decorated functions are exposed via a single action that you do not need to write because it is already in the scaffolding application (created by web2py for you):\ndef call(): return service()\n\nThe functions can access the web2py database abstraction layer (DAL) and (with some limitations) the web2py authentication mechanism.\nYou can edit the controller that contains the function using a shell (emacs/vi/etc) but you can also use the web2py web based IDE (called \"admin\") and add services using the browser.\nWeb2py includes a ticketing system therefore it is easy to debug web services. Any server side error results in a ticket. There is a web page in admin that lists all tickets. You click on one and it shows the code that caused the problem and the complete traceback.\nYou can import and use any third party python module. You must have pyamf pre-installed.\nThis is well documented in chapter 9 of the book:\nhttp://web2py.com/book/default/section/9/2\nweb2py apps are very easy to deploy. One way is with point and click using admin. Another way is simply by copying files from one machine to another. There is no metadata, no installation procedure (not even for web2py itself), not settings, no configuration files.\nThe latter process is somewhat described here:\nhttp://gluonframework.wordpress.com/2010/03/02/shell-only-web2py/\nweb2py is based on WSGI. It run with any web server you can think of (apache+mod_wsgi/mod_python/mod_proxy;lighttpd/cheorkeey/ngnix+fcgi/wsgi.py;cherrypy;etc). \nSome options are documented in detail here:\nhttp://www.web2py.com/book/default/section/11/0\nOther options can be found on http://web2pyslices.com\nweb2py also comes with its own web server, Rocket, which supports https and is very fast. web2py code can also be deployed on Google App Engine.\nCheck for activity on the web2py google group.\n",
"I use PyAMF together with Django. A possible solution could roughly look like this:\n\nCreate a python module containing all your different AMF services py files\nCreate a view that wrapps the DjangoGateway and initialize all your services. Inside this view you could do the following: \n\n\nreload() your service module\npopulate a dictionary based on i.e. the file names ({SERVICE_NAME: SERVICE_INSTANCE})\nInstantiate DjangoGateway with this dictionary and let it handle the incoming request.\n\n\nThis is a hackish solution based on the fact that you can only deploy files without any additional actions like restarting a server.\n"
] |
[
2,
0
] |
[] |
[] |
[
"cherrypy",
"django",
"mod_wsgi",
"pyamf",
"python"
] |
stackoverflow_0002683946_cherrypy_django_mod_wsgi_pyamf_python.txt
|
Q:
Python Job Service Daemon?
What packages should I look at for writing a python daemon and processing jobs? Also, what do I need to do for a python daemon?
A:
I'm pretty happy with beanstalkd, which has client libraries available in various languages:
Daemon:
http://kr.github.com/beanstalkd/
Python client library:
http://code.google.com/p/pybeanstalk/
A:
Your question is a bit ambiguous, but I'm assuming you mean you would like to write a python daemon that will process jobs that get thrown in a queue. If not, please say as much. :-)
I've heard a lot of great things about redis. The folks at github built resque as a job processing daemon for Ruby. If you're language flexible, you could just use that, but if you're not, you could emulate it in as much or as little depth as you like making use of redis as your queue system. Depending on how pluggable and extensible you need it to be, this could be a really simple thing to implement.
Another option I ran across after some more googling is redqueue. It looks like it might already implement most of a job queue.
If you're using django, you may wish to consider the Celery project. It's a job queue system based on RabbitMQ which is yet another queuing server with excellent reviews.
As far as creating a daemon in python, there are a number of options. You can look at this page on activestate, which is a good start. Better yet, you can use python-daemon to do it all for you. But if you use one of the above options or beanstalkd as recommended by mczepiel, you probably won't have to make your process run as a daemon.
A:
I have recently (this week) implemented a queue in RabbitMQ with a python daemon extracting the information and storing it on a database (using Django ORM). The daemon has a intermediate buffer so it will wait a little and write in the database in batches, instead of writing each time a little message arrives.
I've made the integration with the queue using this little flopsy module, which is easy to set up. The only problem I've got it to be able to set up a timeout for waiting a message, as the module has not a clear way of doing that. After a while playing with the interactive shell and making a few dir(), I manage to get to the socket object and set up the timeout.
I considered also Celery, but seems to be more focused on using internally a RabbitMQ to allow you to launch tasks (periodically or asynchronously), more that using a queue to communicating with other systems. In our case, the queue can be feed both by Python systems and Ruby ones.
Once I've completed the process, I've made some adjustments to allow running it as a daemon (mostly storing the standard output to a file to allow easy logging) and then create a bash script that launch a start-stop-daemon command. I've followed more or less this schema
I discovered python-daemon just about one day late, so after the work is done it makes no sense revisiting it, but maybe it makes more sense for a Python project.
|
Python Job Service Daemon?
|
What packages should I look at for writing a python daemon and processing jobs? Also, what do I need to do for a python daemon?
|
[
"I'm pretty happy with beanstalkd, which has client libraries available in various languages:\nDaemon:\nhttp://kr.github.com/beanstalkd/\nPython client library:\nhttp://code.google.com/p/pybeanstalk/\n",
"Your question is a bit ambiguous, but I'm assuming you mean you would like to write a python daemon that will process jobs that get thrown in a queue. If not, please say as much. :-)\nI've heard a lot of great things about redis. The folks at github built resque as a job processing daemon for Ruby. If you're language flexible, you could just use that, but if you're not, you could emulate it in as much or as little depth as you like making use of redis as your queue system. Depending on how pluggable and extensible you need it to be, this could be a really simple thing to implement. \nAnother option I ran across after some more googling is redqueue. It looks like it might already implement most of a job queue. \nIf you're using django, you may wish to consider the Celery project. It's a job queue system based on RabbitMQ which is yet another queuing server with excellent reviews. \nAs far as creating a daemon in python, there are a number of options. You can look at this page on activestate, which is a good start. Better yet, you can use python-daemon to do it all for you. But if you use one of the above options or beanstalkd as recommended by mczepiel, you probably won't have to make your process run as a daemon. \n",
"I have recently (this week) implemented a queue in RabbitMQ with a python daemon extracting the information and storing it on a database (using Django ORM). The daemon has a intermediate buffer so it will wait a little and write in the database in batches, instead of writing each time a little message arrives.\nI've made the integration with the queue using this little flopsy module, which is easy to set up. The only problem I've got it to be able to set up a timeout for waiting a message, as the module has not a clear way of doing that. After a while playing with the interactive shell and making a few dir(), I manage to get to the socket object and set up the timeout.\nI considered also Celery, but seems to be more focused on using internally a RabbitMQ to allow you to launch tasks (periodically or asynchronously), more that using a queue to communicating with other systems. In our case, the queue can be feed both by Python systems and Ruby ones.\nOnce I've completed the process, I've made some adjustments to allow running it as a daemon (mostly storing the standard output to a file to allow easy logging) and then create a bash script that launch a start-stop-daemon command. I've followed more or less this schema\nI discovered python-daemon just about one day late, so after the work is done it makes no sense revisiting it, but maybe it makes more sense for a Python project.\n"
] |
[
3,
2,
1
] |
[] |
[] |
[
"python"
] |
stackoverflow_0002688306_python.txt
|
Q:
Python reference external module in Netbeans
I'm working with a Netbeans for Python development, I have a number of projects (which have a number of modules). What I basically want to know is, how do I import one of these modules into a new project? I have tried editing the python path in netbeans, but to no avail. Here's my setup:
Netbeans projects
=================
ProjectA
ModuleA
ClassA.py (Assume a class called TestClass exists in this file)
ModuleB
...
ProjectB
...
ProjectC
...
Now what I want to do is in a "new project" is the following:
from ProjectA.ModuleA.ClassA import TestClass
Do I have to add the src folders for each of the projects to the pythonpath? I
have tried this but still I get "No Module named ..."
A:
Hadji, you may want to discard Netbeans' default structures for Python development.
First of all, Python code file (.py) is a module. A package contains a number of modules.
What you should do is structure your files like the following:
Netbeans projects
=================
PackageA
__init__.py (This file is crucial for Python to recognise the folder as a package.)
ClassA.py (Assume a class called TestClass exists in this file)
...
PackageB
...
PackageC
...
Then, in your ProjectC (which is now basically a folder), you can do
from PackageA.ClassA import TestClass
Again, please remember a Python module is a .py file. You also don't need the src folder, and all of your modules should be inside appropriate packages. =]
More references:
Filesystem structure of a Python project
|
Python reference external module in Netbeans
|
I'm working with a Netbeans for Python development, I have a number of projects (which have a number of modules). What I basically want to know is, how do I import one of these modules into a new project? I have tried editing the python path in netbeans, but to no avail. Here's my setup:
Netbeans projects
=================
ProjectA
ModuleA
ClassA.py (Assume a class called TestClass exists in this file)
ModuleB
...
ProjectB
...
ProjectC
...
Now what I want to do is in a "new project" is the following:
from ProjectA.ModuleA.ClassA import TestClass
Do I have to add the src folders for each of the projects to the pythonpath? I
have tried this but still I get "No Module named ..."
|
[
"Hadji, you may want to discard Netbeans' default structures for Python development.\nFirst of all, Python code file (.py) is a module. A package contains a number of modules.\nWhat you should do is structure your files like the following:\nNetbeans projects\n=================\nPackageA\n __init__.py (This file is crucial for Python to recognise the folder as a package.)\n ClassA.py (Assume a class called TestClass exists in this file)\n ...\nPackageB\n ...\nPackageC\n ...\n\nThen, in your ProjectC (which is now basically a folder), you can do\nfrom PackageA.ClassA import TestClass\n\nAgain, please remember a Python module is a .py file. You also don't need the src folder, and all of your modules should be inside appropriate packages. =]\nMore references:\nFilesystem structure of a Python project\n"
] |
[
2
] |
[] |
[] |
[
"module",
"netbeans",
"projects",
"python"
] |
stackoverflow_0002279628_module_netbeans_projects_python.txt
|
Q:
Code completion in NetBeans' python plugin does not work properly
I am asking on StackOverflow because surely I am doing something completely silly and I hope S.O. might provide me with a quick answer. I've installed the latest stable Python-plugin for NetBeans. It works great, and I tested code completion with various packages such as sys, os and so on. It works beautifully.
However, it does not seem to pick up the code completion for the code in my own project.
I created a package called mypackage (it has __init__.py as well), and in it I have a module called mymodule.py. Inside mymodule I've put a class called MyClass, complete with doc-strings and all.
Please refer to this screenshot to describe what happens in code-completion:
alt text http://rasterburn.org/~sgt/stuff2/pythonproblem.png
As you see, it's suggesting irrelevant things, as opposed to just MyClass.
(Note that if I execute mymodule.MyClass() it works 100%, it's just that I would really like code completion on my own code)
Hope I'm just doing something silly here... Any ideas?
A:
I'm afraid to tell you that this is a Known Bug for over a year. Some people have suggested that it seems the Python development in NetBeans is stalled.
Personally, I'm using Eclipse. PyDev is still under active support, and the auto-completion is smart. In addition, it supports more variety in syntax-highlighting. (This is my personal configuration.)
I would recommend you switch to another IDE while you can. If you're using Jython, let me know how that works out for you. Share with us your solution when you have one. =]
Related topic:
Has anyone tried NetBeans 6.5 Python IDE?
|
Code completion in NetBeans' python plugin does not work properly
|
I am asking on StackOverflow because surely I am doing something completely silly and I hope S.O. might provide me with a quick answer. I've installed the latest stable Python-plugin for NetBeans. It works great, and I tested code completion with various packages such as sys, os and so on. It works beautifully.
However, it does not seem to pick up the code completion for the code in my own project.
I created a package called mypackage (it has __init__.py as well), and in it I have a module called mymodule.py. Inside mymodule I've put a class called MyClass, complete with doc-strings and all.
Please refer to this screenshot to describe what happens in code-completion:
alt text http://rasterburn.org/~sgt/stuff2/pythonproblem.png
As you see, it's suggesting irrelevant things, as opposed to just MyClass.
(Note that if I execute mymodule.MyClass() it works 100%, it's just that I would really like code completion on my own code)
Hope I'm just doing something silly here... Any ideas?
|
[
"I'm afraid to tell you that this is a Known Bug for over a year. Some people have suggested that it seems the Python development in NetBeans is stalled.\nPersonally, I'm using Eclipse. PyDev is still under active support, and the auto-completion is smart. In addition, it supports more variety in syntax-highlighting. (This is my personal configuration.)\nI would recommend you switch to another IDE while you can. If you're using Jython, let me know how that works out for you. Share with us your solution when you have one. =]\nRelated topic:\nHas anyone tried NetBeans 6.5 Python IDE?\n"
] |
[
4
] |
[] |
[] |
[
"netbeans",
"netbeans6.8",
"python"
] |
stackoverflow_0002624137_netbeans_netbeans6.8_python.txt
|
Q:
help with UnicodeEncodeError('ascii', u'Phase \u2013 II', 6, 7, 'ordinal not in range(128)')
having problem with
UnicodeEncodeError('ascii', u'Phase \u2013 II', 6, 7, 'ordinal not in range(128)')
Basically what I am doing here is reading the value from excel sheet
and sheet contain address in this format
Phase- II
So wanted to know how to change`
somestring = u'Phase \u2013 II'
to str
thanks
`
A:
Excel mostly uses cp1252, so try this:
>>> somestring.encode('cp1252', 'replace')
'Phase \x96 II'
>>> print somestring.encode('cp1252', 'replace')
Phase – II
That doesn't give you an ascii string (since your unicode string contains non-ascii characters it cannot), but it does give you a byte string that Excel will interpret correctly if for example you write it into a csv file.
If you just want to print it for display then you'll need to know the output encoding of whatever you use to display the text: I copied the example from idle which will, at least on my system displays cp1252, but if you print it in a command prompt you may have another encoding in effect. Use the DOS chcp command to select an appropriate encoding if required as the default encoding may not support that character:
C:\>chcp
Active code page: 850
C:\>\python26\python
Python 2.6.2 (r262:71605, Apr 14 2009, 22:40:02) [MSC v.1500 32 bit (Intel)] on win32
Type "help", "copyright", "credits" or "license" for more information.
>>> somestring = u'Phase \u2013 II'
>>> print somestring.encode('cp850', 'replace')
Phase ? II
>>>
Using the 'replace' argument to encode means that if you do manage to get any characters that cannot be interpreted as cp1252 will be replaced by question marks.
|
help with UnicodeEncodeError('ascii', u'Phase \u2013 II', 6, 7, 'ordinal not in range(128)')
|
having problem with
UnicodeEncodeError('ascii', u'Phase \u2013 II', 6, 7, 'ordinal not in range(128)')
Basically what I am doing here is reading the value from excel sheet
and sheet contain address in this format
Phase- II
So wanted to know how to change`
somestring = u'Phase \u2013 II'
to str
thanks
`
|
[
"Excel mostly uses cp1252, so try this:\n>>> somestring.encode('cp1252', 'replace')\n'Phase \\x96 II'\n>>> print somestring.encode('cp1252', 'replace')\nPhase – II\n\nThat doesn't give you an ascii string (since your unicode string contains non-ascii characters it cannot), but it does give you a byte string that Excel will interpret correctly if for example you write it into a csv file.\nIf you just want to print it for display then you'll need to know the output encoding of whatever you use to display the text: I copied the example from idle which will, at least on my system displays cp1252, but if you print it in a command prompt you may have another encoding in effect. Use the DOS chcp command to select an appropriate encoding if required as the default encoding may not support that character:\nC:\\>chcp\nActive code page: 850\n\nC:\\>\\python26\\python\nPython 2.6.2 (r262:71605, Apr 14 2009, 22:40:02) [MSC v.1500 32 bit (Intel)] on win32\nType \"help\", \"copyright\", \"credits\" or \"license\" for more information.\n>>> somestring = u'Phase \\u2013 II'\n>>> print somestring.encode('cp850', 'replace')\nPhase ? II\n>>>\n\nUsing the 'replace' argument to encode means that if you do manage to get any characters that cannot be interpreted as cp1252 will be replaced by question marks.\n"
] |
[
3
] |
[] |
[] |
[
"python"
] |
stackoverflow_0002688847_python.txt
|
Q:
foo and _foo - about variables inside a class
class ClassName(object):
"""
"""
def __init__(self, foo, bar):
"""
"""
self.foo = foo # read-write property
self.bar = bar # simple attribute
def _set_foo(self, value):
self._foo = value
def _get_foo(self):
return self._foo
foo = property(_get_foo, _set_foo)
a = ClassName(1,2)
#a._set_foo(3)
print a._get_foo()
When I print a._get_foo() the function _get_foo prints the variable self._foo .
But where does it come from?
self._foo and self.foo are different, aren't they?
EDIT: The problem is that I still not understand what property does. Give me some time.
A:
Docs for property explain how it's supposed to be used. There is no difference between these lines:
self.foo = foo # read-write property
and
a.foo = 3
You're also not supposed to call setters and getters manually.
eta: if you don't understand what property does after looking at the examples provided in the docs and reading our answers, you perhaps should just abstain from using it. It really is not the most essential of Python's features. You might want to start with a simpler example, which is easy to understand:
>>> class ClassName(object):
def __init__(self, foo):
self.foo = foo
>>> a = ClassName(1, 2)
>>> a.foo
1
>>> a.foo = 42
>>> a.foo
42
A:
I really recommend this site:
http://adam.gomaa.us/blog/2008/aug/11/the-python-property-builtin/
A good explanation of the property-function.
A:
You define foo to be a property with getters and setters.
Those getters and setters use the variable self._foo, since you coded it that way:
def _set_foo(self, value):
self._foo = value
In your case you would get a problem if you had a slightly different implementation:
class ClassName(object):
"""
"""
def __init__(self,):
"""
"""
pass
def _set_foo(self, value):
self._foo = value
def _get_foo(self):
return self._foo
foo = property(_get_foo, _set_foo)
a = ClassName()
print a.foo
-> AttributeError
b = ClassName()
b.foo = 1 # implicitely sets self._foo !
print b.foo
>> OK, this is 1
As it happens you indeed should set self.foo in the __init__ since the setter creates self._foo. (Or initialize self._foo in the __init__ directly of course).
So, where do self.foo and self._foo come from? It's explicit in the code. self.foo is a property, and self._foo is the variable in which you decided to keep the value of that property.
A:
self._foo and self.foo would be different except that you have assigned the property you created to the name foo: foo = property(_get_foo, _set_foo).
So now you have two names defined foo which is property that is defined in terms of the methods _set_foo and _get_foo. You also have a name _foo defined but this is the same attribute used in _set_foo and _get_foo and therefore in property foo.
So you two names but only one object.
foo
/\
/ \
_set_foo _get_foo
\ /
\ /
_foo --> object
Note: For the example you have Python this is overkill, there is no need to use getter and setter methods unless they are going to have business logic in them. Just use an attribute named foo, you can always wrap that in a property in future without affecting client code if it turns out that you need some smarts around the access of the attribute.
Change your code to:
class ClassName(object):
def __init__(self, foo, bar):
self.foo = foo # read-write property
self.bar = bar # simple attribute
Both foo and bar are read write, if you need finer control you can then consider using a property.
A:
According to your code, it "comes from" _set_foo. In your init, when you do self.foo = foo, that calls _set_foo(1), which performs self._foo = 1.
You can see this more clearly if you add a print statement inside _set_foo().
|
foo and _foo - about variables inside a class
|
class ClassName(object):
"""
"""
def __init__(self, foo, bar):
"""
"""
self.foo = foo # read-write property
self.bar = bar # simple attribute
def _set_foo(self, value):
self._foo = value
def _get_foo(self):
return self._foo
foo = property(_get_foo, _set_foo)
a = ClassName(1,2)
#a._set_foo(3)
print a._get_foo()
When I print a._get_foo() the function _get_foo prints the variable self._foo .
But where does it come from?
self._foo and self.foo are different, aren't they?
EDIT: The problem is that I still not understand what property does. Give me some time.
|
[
"Docs for property explain how it's supposed to be used. There is no difference between these lines:\nself.foo = foo # read-write property\n\nand \na.foo = 3\n\nYou're also not supposed to call setters and getters manually.\neta: if you don't understand what property does after looking at the examples provided in the docs and reading our answers, you perhaps should just abstain from using it. It really is not the most essential of Python's features. You might want to start with a simpler example, which is easy to understand:\n>>> class ClassName(object):\n def __init__(self, foo):\n self.foo = foo\n\n\n>>> a = ClassName(1, 2)\n>>> a.foo\n1\n>>> a.foo = 42\n>>> a.foo\n42\n\n",
"I really recommend this site:\nhttp://adam.gomaa.us/blog/2008/aug/11/the-python-property-builtin/\nA good explanation of the property-function.\n",
"You define foo to be a property with getters and setters. \nThose getters and setters use the variable self._foo, since you coded it that way:\ndef _set_foo(self, value):\n self._foo = value\n\nIn your case you would get a problem if you had a slightly different implementation:\nclass ClassName(object):\n \"\"\"\n \"\"\" \n def __init__(self,):\n \"\"\"\n \"\"\"\n pass\n\n def _set_foo(self, value):\n self._foo = value\n\n def _get_foo(self):\n return self._foo\n\n foo = property(_get_foo, _set_foo)\n\n\n a = ClassName()\n print a.foo\n -> AttributeError\n\n b = ClassName()\n b.foo = 1 # implicitely sets self._foo !\n print b.foo\n >> OK, this is 1\n\nAs it happens you indeed should set self.foo in the __init__ since the setter creates self._foo. (Or initialize self._foo in the __init__ directly of course).\nSo, where do self.foo and self._foo come from? It's explicit in the code. self.foo is a property, and self._foo is the variable in which you decided to keep the value of that property.\n",
"self._foo and self.foo would be different except that you have assigned the property you created to the name foo: foo = property(_get_foo, _set_foo). \nSo now you have two names defined foo which is property that is defined in terms of the methods _set_foo and _get_foo. You also have a name _foo defined but this is the same attribute used in _set_foo and _get_foo and therefore in property foo.\nSo you two names but only one object.\n foo\n /\\\n / \\\n_set_foo _get_foo\n \\ /\n \\ /\n _foo --> object\n\nNote: For the example you have Python this is overkill, there is no need to use getter and setter methods unless they are going to have business logic in them. Just use an attribute named foo, you can always wrap that in a property in future without affecting client code if it turns out that you need some smarts around the access of the attribute. \nChange your code to:\nclass ClassName(object): \n def __init__(self, foo, bar):\n self.foo = foo # read-write property\n self.bar = bar # simple attribute\n\nBoth foo and bar are read write, if you need finer control you can then consider using a property.\n",
"According to your code, it \"comes from\" _set_foo. In your init, when you do self.foo = foo, that calls _set_foo(1), which performs self._foo = 1.\nYou can see this more clearly if you add a print statement inside _set_foo().\n"
] |
[
2,
2,
1,
1,
0
] |
[] |
[] |
[
"class",
"python",
"variables"
] |
stackoverflow_0002683447_class_python_variables.txt
|
Q:
get average from set of objects in django
Hay, i have a simple rating system for a property. You give it a mark out of 5 (stars). The models are defined like this
def Property(models.Model)
# stuff here
def Rating(models.Model)
property = models.ForeignKey(Property)
stars = models.IntegerField()
What i want to do is get a property, find all the Rating objects, collect them, then get the average 'stars' from them.
any ideas how to do this?
A:
You should use Aggregation(doc):
from django.db.models import Avg
p = Property.objects.get(...)
stars_average = p.rating_set.aggregate(Avg('stars')).values()[0]
A little bit unsure about my example though.
|
get average from set of objects in django
|
Hay, i have a simple rating system for a property. You give it a mark out of 5 (stars). The models are defined like this
def Property(models.Model)
# stuff here
def Rating(models.Model)
property = models.ForeignKey(Property)
stars = models.IntegerField()
What i want to do is get a property, find all the Rating objects, collect them, then get the average 'stars' from them.
any ideas how to do this?
|
[
"You should use Aggregation(doc):\nfrom django.db.models import Avg\n\np = Property.objects.get(...)\nstars_average = p.rating_set.aggregate(Avg('stars')).values()[0]\n\nA little bit unsure about my example though.\n"
] |
[
41
] |
[] |
[] |
[
"average",
"django",
"python"
] |
stackoverflow_0002689664_average_django_python.txt
|
Q:
How do I install pyCurl?
I tried everything! I cannot find a way to install pyCurl on my Windows 7 machine!
I found these binaries link... BUT there are no binaries for 2.6. : (
Help would be great. : )
A:
Here is a python2.6 binary for pycurl someone compiled for that, and for amd64 also
A:
http://wiki.woodpecker.org.cn/moin/PyCurl?action=AttachFile&do=get&target=pycurl-7.20.1.win32-py2.6.zip
and this is mine, with newer libcurl 7.20.1, openSSL 1.0.0, etc.
|
How do I install pyCurl?
|
I tried everything! I cannot find a way to install pyCurl on my Windows 7 machine!
I found these binaries link... BUT there are no binaries for 2.6. : (
Help would be great. : )
|
[
"Here is a python2.6 binary for pycurl someone compiled for that, and for amd64 also\n",
"http://wiki.woodpecker.org.cn/moin/PyCurl?action=AttachFile&do=get&target=pycurl-7.20.1.win32-py2.6.zip\nand this is mine, with newer libcurl 7.20.1, openSSL 1.0.0, etc.\n"
] |
[
3,
1
] |
[] |
[] |
[
"installation",
"pycurl",
"python",
"windows"
] |
stackoverflow_0002666365_installation_pycurl_python_windows.txt
|
Q:
What is it in Java standard library that Python's lacks?
I hear that the Java standard library is larger than that of Python. That makes me curious about what is missing in Python's?
A:
The one flaw in Python imho is that Python lacks one real canonical method of deployment. (Yes there are good ones out there, but nothing that's really rock solid).
Which can hamper its adoption in some Enterprise environments.
A:
Java provides a lot of varied implementations of interfaces for the basic types. Java has an ArrayList and single-linked-list and double-linked list, whereas Python just has a list. Java includes multiple Map implementations such as TreeMap or LinkedHashMap, whereas Python generally sticks to the single dict implementation. An ordered dictionary was proposed is now part of Python 3.1, but in general, Java has a richer set of collections and base classes.
In defense of Python, however, the need for more rigorously defined base classes and interfaces is much less necessary with the dynamically-typed approach (where interfaces are often accepted implicitly).
A:
Python also comes With Batteries Included... The only place where I've felt Python lacking is a good GUI toolkit (no, TK doesn't compare to Swing xD).
A:
Python lacks a robust XML implementation (with full XSLT and XPATH support). The Python stdlib has a few decent implementations for working with XML (DOM parser, SAX parser, and a tree builder called ElementTree), but more advanced XML requires a third party library. I've used 4XSLT and now defer to LXML when I need to do some real XML work in Python.
|
What is it in Java standard library that Python's lacks?
|
I hear that the Java standard library is larger than that of Python. That makes me curious about what is missing in Python's?
|
[
"The one flaw in Python imho is that Python lacks one real canonical method of deployment. (Yes there are good ones out there, but nothing that's really rock solid).\nWhich can hamper its adoption in some Enterprise environments.\n",
"Java provides a lot of varied implementations of interfaces for the basic types. Java has an ArrayList and single-linked-list and double-linked list, whereas Python just has a list. Java includes multiple Map implementations such as TreeMap or LinkedHashMap, whereas Python generally sticks to the single dict implementation. An ordered dictionary was proposed is now part of Python 3.1, but in general, Java has a richer set of collections and base classes.\nIn defense of Python, however, the need for more rigorously defined base classes and interfaces is much less necessary with the dynamically-typed approach (where interfaces are often accepted implicitly).\n",
"Python also comes With Batteries Included... The only place where I've felt Python lacking is a good GUI toolkit (no, TK doesn't compare to Swing xD).\n",
"Python lacks a robust XML implementation (with full XSLT and XPATH support). The Python stdlib has a few decent implementations for working with XML (DOM parser, SAX parser, and a tree builder called ElementTree), but more advanced XML requires a third party library. I've used 4XSLT and now defer to LXML when I need to do some real XML work in Python.\n"
] |
[
8,
6,
4,
3
] |
[] |
[] |
[
"java",
"python"
] |
stackoverflow_0002690147_java_python.txt
|
Q:
Django: Serving Media Behind Custom URL
So I of course know that serving static files through Django will send you straight to hell but I am confused on how to use a custom url to mask the true location of the file using Django. Django: Serving a Download in a Generic View but the answer I accepted seems to be the "wrong" way of doing things.
urls.py:
url(r'^song/(?P<song_id>\d+)/download/$', song_download, name='song_download'),
views.py:
def song_download(request, song_id):
song = Song.objects.get(id=song_id)
fsock = open(os.path.join(song.path, song.filename))
response = HttpResponse(fsock, mimetype='audio/mpeg')
response['Content-Disposition'] = "attachment; filename=%s - %s.mp3" % (song.artist, song.title)
return response
This solution works perfectly but not perfectly enough it turns out. How can I avoid having a direct link to the mp3 while still serving through nginx/apache?
EDIT 1 - ADDITIONAL INFO
Currently I can get my files by using an address such as:
http://www.example.com/music/song/1692/download/
But the above mentioned method is the devil's work.
How can I accomplished what I get above while still making nginx/apache serve the media? Is this something that should be done at the webserver level? Some crazy mod_rewrite?
http://static.example.com/music/Aphex%20Twin%20-%20Richard%20D.%20James%20(V0)/10%20Logon-Rock%20Witch.mp3
EDIT 2 - ADDITIONAL ADDITIONAL INFO
I use nginx for my frontend and reverse proxy back apache/development server so I think if it does require some sort of mod_rewrite work I will have to find something that would work with nginx.
A:
To expand on the previous answers you should be able to modify the following code and have nginx directly serve your download files whilst still having the files protected.
First of all add a location such as :
location /files/ {
alias /true/path/to/mp3/files/;
internal;
}
to your nginx.conf file (the internal makes this not directly accessible). Then you need a Django View something like this:
def song_download(request, song_id):
try:
song = Song.objects.get(id=song_id)
response = HttpResponse()
response['Content-Type'] = 'application/mp3'
response['X-Accel-Redirect'] = '/files/' + song.filename
response['Content-Disposition'] = 'attachment;filename=' + song.filename
except Exception:
raise Http404
return response
which will hand off the file download to nginx.
A:
The basic idea is to get your Django view to redirect to a secure URL that is served by your media server.
See this list of suggestions by Graham Dumpleton, author of mod_wsgi.
A:
Both httpd and Nginx have a way to specify a static file to serve via a header. The exact header varies though, so it's best to put something in the settings to pick the method.
|
Django: Serving Media Behind Custom URL
|
So I of course know that serving static files through Django will send you straight to hell but I am confused on how to use a custom url to mask the true location of the file using Django. Django: Serving a Download in a Generic View but the answer I accepted seems to be the "wrong" way of doing things.
urls.py:
url(r'^song/(?P<song_id>\d+)/download/$', song_download, name='song_download'),
views.py:
def song_download(request, song_id):
song = Song.objects.get(id=song_id)
fsock = open(os.path.join(song.path, song.filename))
response = HttpResponse(fsock, mimetype='audio/mpeg')
response['Content-Disposition'] = "attachment; filename=%s - %s.mp3" % (song.artist, song.title)
return response
This solution works perfectly but not perfectly enough it turns out. How can I avoid having a direct link to the mp3 while still serving through nginx/apache?
EDIT 1 - ADDITIONAL INFO
Currently I can get my files by using an address such as:
http://www.example.com/music/song/1692/download/
But the above mentioned method is the devil's work.
How can I accomplished what I get above while still making nginx/apache serve the media? Is this something that should be done at the webserver level? Some crazy mod_rewrite?
http://static.example.com/music/Aphex%20Twin%20-%20Richard%20D.%20James%20(V0)/10%20Logon-Rock%20Witch.mp3
EDIT 2 - ADDITIONAL ADDITIONAL INFO
I use nginx for my frontend and reverse proxy back apache/development server so I think if it does require some sort of mod_rewrite work I will have to find something that would work with nginx.
|
[
"To expand on the previous answers you should be able to modify the following code and have nginx directly serve your download files whilst still having the files protected.\nFirst of all add a location such as :\nlocation /files/ {\n alias /true/path/to/mp3/files/;\n internal;\n}\n\nto your nginx.conf file (the internal makes this not directly accessible). Then you need a Django View something like this:\ndef song_download(request, song_id):\n try:\n song = Song.objects.get(id=song_id)\n response = HttpResponse()\n response['Content-Type'] = 'application/mp3'\n response['X-Accel-Redirect'] = '/files/' + song.filename\n response['Content-Disposition'] = 'attachment;filename=' + song.filename\n except Exception:\n raise Http404\n return response\n\nwhich will hand off the file download to nginx.\n",
"The basic idea is to get your Django view to redirect to a secure URL that is served by your media server.\nSee this list of suggestions by Graham Dumpleton, author of mod_wsgi.\n",
"Both httpd and Nginx have a way to specify a static file to serve via a header. The exact header varies though, so it's best to put something in the settings to pick the method.\n"
] |
[
25,
3,
1
] |
[] |
[] |
[
"django",
"nginx",
"python",
"url_rewriting"
] |
stackoverflow_0002687957_django_nginx_python_url_rewriting.txt
|
Q:
Permutations in python 2.5.2
I have a list of numbers for input, e.g.
671.00
1,636.00
436.00
9,224.00
and I want to generate all possible sums with a way to id it for output, e.g.:
671.00 + 1,636.00 = 2,307.00
671.00 + 436.00 = 1,107.00
671.00 + 9,224.00 = 9,224.00
671.00 + 1,636.00 + 436.00 = 2,743.00
...
and I would like to do it in Python
My current constrains are:
a) I'm just learning python now (that's part of the idea)
b) I will have to use Python 2.5.2 (no intertools)
I think I have found a piece of code that may help:
def all_perms(str):
if len(str) <=1:
yield str
else:
for perm in all_perms(str[1:]):
for i in range(len(perm)+1):
#nb str[0:1] works in both string and list contexts
yield perm[:i] + str[0:1] + perm[i:]
( from these guys )
But I'm not sure how to use it in my propose.
Could someone trow some tips and pieces of code of help?
cheers,
f.
A:
Permutations are about taking an ordered set of things and moving these things around (i.e. changing order). Your question is about combinations of things from your list.
Now, an easy way of enumerating combinations is by mapping entries from your list to bits in a number. For example, lets assume that if bit #0 is set (i.e. 1), then number lst[0] participates in the combination, if bit #1 is set, then lst[1] participates in the combination, etc. This way, numbers in range 0 <= n < 2**(len(lst)) identify all possible combinations of lst members, including an empty one (n = 0) and the whole lst (n = 2**(len(lst)) - 1).
You need only combinations of 2 items or more, i.e. only those combination IDs that have at least two nonzero bits in their binary representation. Here is how to identify these:
def HasAtLeastTwoBitsSet(x) :
return (x & (x-1)) != 0
# Testing:
>>> [x for x in range(33) if HasAtLeastTwoBitsSet(x)]
[3, 5, 6, 7, 9, 10, 11, 12, 13, 14, 15, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31]
Next step is to extract a combination of list members identified by a combination id. This is easy, thanks to the power of list comprehensions:
def GetSublistByCombination(lst, combination_id) :
res = [x for (i,x) in enumerate(lst) if combination_id & (1 << i)]
return res
# Testing:
>>> GetSublistByCombination([0,1,2,3], 1)
[0]
>>> GetSublistByCombination([0,1,2,3], 3)
[0, 1]
>>> GetSublistByCombination([0,1,2,3], 12)
[2, 3]
>>> GetSublistByCombination([0,1,2,3], 15)
[0, 1, 2, 3]
Now let's make a generator that produces all sums, together with their string representations:
def IterAllSums(lst) :
combinations = [i for i in range(1 << len(lst)) if HasAtLeastTwoBitsSet(i)]
for comb in combinations :
sublist = GetSublistByCombination(lst, comb)
sum_str = '+'.join(map(str, sublist))
sum_val = sum(sublist)
yield (sum_str, sum_val)
And, finally, let's use it:
>>> for sum_str, sum_val in IterAllSums([1,2,3,4]) : print sum_str, sum_val
1+2 3
1+3 4
2+3 5
1+2+3 6
1+4 5
2+4 6
1+2+4 7
3+4 7
1+3+4 8
2+3+4 9
1+2+3+4 10
A:
The code below generates all "subsets" of a given list (except the empty set), i.e. it returns a list of lists.
def all_sums(l): #assumes that l is non-empty
if len(l)==1:
return ([[l[0]]])
if len(l)==0:
return []
result = []
for i in range(0,len(l)):
result.append([l[i]])
for p in all_sums(l[i+1:]):
result.append([l[i]]+p)
return result
Now you could just write a short function doit for output also:
def doit(l):
mylist = all_sums(l)
print mylist
for i in mylist:
print str(i) + " = " + str(sum(i))
doit([1,2,3,4])
A:
With itertools (Python >=2.6) would be:
from itertools import *
a=[1,2,3,4]
sumVal=[tuple(imap(sum,combinations(a,i))) for i in range(2,len(a)+1)]
|
Permutations in python 2.5.2
|
I have a list of numbers for input, e.g.
671.00
1,636.00
436.00
9,224.00
and I want to generate all possible sums with a way to id it for output, e.g.:
671.00 + 1,636.00 = 2,307.00
671.00 + 436.00 = 1,107.00
671.00 + 9,224.00 = 9,224.00
671.00 + 1,636.00 + 436.00 = 2,743.00
...
and I would like to do it in Python
My current constrains are:
a) I'm just learning python now (that's part of the idea)
b) I will have to use Python 2.5.2 (no intertools)
I think I have found a piece of code that may help:
def all_perms(str):
if len(str) <=1:
yield str
else:
for perm in all_perms(str[1:]):
for i in range(len(perm)+1):
#nb str[0:1] works in both string and list contexts
yield perm[:i] + str[0:1] + perm[i:]
( from these guys )
But I'm not sure how to use it in my propose.
Could someone trow some tips and pieces of code of help?
cheers,
f.
|
[
"Permutations are about taking an ordered set of things and moving these things around (i.e. changing order). Your question is about combinations of things from your list.\nNow, an easy way of enumerating combinations is by mapping entries from your list to bits in a number. For example, lets assume that if bit #0 is set (i.e. 1), then number lst[0] participates in the combination, if bit #1 is set, then lst[1] participates in the combination, etc. This way, numbers in range 0 <= n < 2**(len(lst)) identify all possible combinations of lst members, including an empty one (n = 0) and the whole lst (n = 2**(len(lst)) - 1).\nYou need only combinations of 2 items or more, i.e. only those combination IDs that have at least two nonzero bits in their binary representation. Here is how to identify these:\ndef HasAtLeastTwoBitsSet(x) :\n return (x & (x-1)) != 0\n\n# Testing:\n>>> [x for x in range(33) if HasAtLeastTwoBitsSet(x)]\n[3, 5, 6, 7, 9, 10, 11, 12, 13, 14, 15, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31]\n\nNext step is to extract a combination of list members identified by a combination id. This is easy, thanks to the power of list comprehensions:\ndef GetSublistByCombination(lst, combination_id) :\n res = [x for (i,x) in enumerate(lst) if combination_id & (1 << i)]\n return res\n\n# Testing:\n>>> GetSublistByCombination([0,1,2,3], 1)\n[0]\n>>> GetSublistByCombination([0,1,2,3], 3)\n[0, 1]\n>>> GetSublistByCombination([0,1,2,3], 12)\n[2, 3]\n>>> GetSublistByCombination([0,1,2,3], 15)\n[0, 1, 2, 3]\n\nNow let's make a generator that produces all sums, together with their string representations:\ndef IterAllSums(lst) :\n combinations = [i for i in range(1 << len(lst)) if HasAtLeastTwoBitsSet(i)]\n for comb in combinations :\n sublist = GetSublistByCombination(lst, comb)\n sum_str = '+'.join(map(str, sublist))\n sum_val = sum(sublist)\n yield (sum_str, sum_val)\n\nAnd, finally, let's use it:\n>>> for sum_str, sum_val in IterAllSums([1,2,3,4]) : print sum_str, sum_val\n\n1+2 3\n1+3 4\n2+3 5\n1+2+3 6\n1+4 5\n2+4 6\n1+2+4 7\n3+4 7\n1+3+4 8\n2+3+4 9\n1+2+3+4 10\n\n",
"The code below generates all \"subsets\" of a given list (except the empty set), i.e. it returns a list of lists.\ndef all_sums(l): #assumes that l is non-empty\n if len(l)==1:\n return ([[l[0]]])\n if len(l)==0:\n return []\n result = []\n for i in range(0,len(l)):\n result.append([l[i]])\n for p in all_sums(l[i+1:]):\n result.append([l[i]]+p)\n return result\n\nNow you could just write a short function doit for output also:\ndef doit(l):\n mylist = all_sums(l)\n print mylist\n for i in mylist:\n print str(i) + \" = \" + str(sum(i))\n\ndoit([1,2,3,4])\n\n",
"With itertools (Python >=2.6) would be:\nfrom itertools import *\na=[1,2,3,4]\nsumVal=[tuple(imap(sum,combinations(a,i))) for i in range(2,len(a)+1)]\n\n"
] |
[
3,
0,
0
] |
[] |
[] |
[
"list",
"permutation",
"python"
] |
stackoverflow_0002689903_list_permutation_python.txt
|
Q:
How to create A matrix of images in opencv with python bindings to feed Kmeans2
i am trying to cluster a set of images, my peblems resides in using Kmeans2 parameters in opencv. i dont know exactly how to form the points input for Kmeans2 for clustering.
here what i do :
samples = CreateMat ( samples_len,1,CV_32FC2)
labels = CreateMat ( samples_len,1,CV_43SC1)
index = 0
for name in imglist :
img = LoadImage ('someting')
sample[index] = img
index += 1
The error i get is : key length does not match array dimension
so how to fix it ?
any help would be appreciated
Regards.
A:
Kmeans2 only takes 2-dimensional input data, so unless your images are only 2 pixels this approach will not work. You'll either need to write your own clustering algorithm that handle higher dimensional dagta or write a function that maps your images down to only 2 points (e.g. mean and variance of the grayscale version of the image). In any case, "clustering" images is a very difficult problem in general.
|
How to create A matrix of images in opencv with python bindings to feed Kmeans2
|
i am trying to cluster a set of images, my peblems resides in using Kmeans2 parameters in opencv. i dont know exactly how to form the points input for Kmeans2 for clustering.
here what i do :
samples = CreateMat ( samples_len,1,CV_32FC2)
labels = CreateMat ( samples_len,1,CV_43SC1)
index = 0
for name in imglist :
img = LoadImage ('someting')
sample[index] = img
index += 1
The error i get is : key length does not match array dimension
so how to fix it ?
any help would be appreciated
Regards.
|
[
"Kmeans2 only takes 2-dimensional input data, so unless your images are only 2 pixels this approach will not work. You'll either need to write your own clustering algorithm that handle higher dimensional dagta or write a function that maps your images down to only 2 points (e.g. mean and variance of the grayscale version of the image). In any case, \"clustering\" images is a very difficult problem in general.\n"
] |
[
0
] |
[] |
[] |
[
"opencv",
"python"
] |
stackoverflow_0002690052_opencv_python.txt
|
Q:
Error in writing a class
I am running through a tutorial online at http://www.sthurlow.com/python/lesson08/ and I believe I understand how classes work in python, at least to some degree but when I run this code:
class Shape:
def __init__(self,x,y):
self.x = x
self.y = y
description = "This shape has not been described yet"
author = "Nobody has claimed to make this shape yet"
def area(self):
return self.x * self.y
def perimeter(self):
return 2 * self.x + 2 * self.y
def describe(self,text):
self.description = text
def authorName(self,text):
self.author = text
def scaleSize(self,scale):
self.x = self.x * scale
self.y = self.y * scale
I get this error:
Traceback (most recent call last):
File "Y:/python/Shape.py", line 1, in -toplevel-
class Shape:
File "Y:/python/Shape.py", line 17, in Shape
self.y = self.y * scale
NameError: name 'self' is not defined
Any Help would be great
Thanks
Richard
A:
You need to indent the last line.
def scaleSize(self,scale):
self.x = self.x * scale
self.y = self.y * scale
Should be
def scaleSize(self,scale):
self.x = self.x * scale
self.y = self.y * scale
A:
The last part of your code is wrong,
def scaleSize(self,scale):
self.x = self.x * scale
self.y = self.y * scale
Notice the indentation, which is important in Python. By what you have now, means self.y = self.y * scale is not inside the scaleSize method and the keyword self is undefined for your Shape class.
What you need to do is properly indent,
def scaleSize(self,scale):
self.x = self.x * scale
self.y = self.y * scale
A:
The indicated line has the wrong indent level, so it's not in the scaleSize() method.
A:
You need to align line 17 with line 16
You have:
def scaleSize(self,scale):
self.x = self.x * scale
self.y = self.y * scale
Must be:
def scaleSize(self,scale):
self.x = self.x * scale
self.y = self.y * scale
That's how python knows they belong to the same method.
|
Error in writing a class
|
I am running through a tutorial online at http://www.sthurlow.com/python/lesson08/ and I believe I understand how classes work in python, at least to some degree but when I run this code:
class Shape:
def __init__(self,x,y):
self.x = x
self.y = y
description = "This shape has not been described yet"
author = "Nobody has claimed to make this shape yet"
def area(self):
return self.x * self.y
def perimeter(self):
return 2 * self.x + 2 * self.y
def describe(self,text):
self.description = text
def authorName(self,text):
self.author = text
def scaleSize(self,scale):
self.x = self.x * scale
self.y = self.y * scale
I get this error:
Traceback (most recent call last):
File "Y:/python/Shape.py", line 1, in -toplevel-
class Shape:
File "Y:/python/Shape.py", line 17, in Shape
self.y = self.y * scale
NameError: name 'self' is not defined
Any Help would be great
Thanks
Richard
|
[
"You need to indent the last line.\ndef scaleSize(self,scale): \n self.x = self.x * scale \nself.y = self.y * scale \n\nShould be \ndef scaleSize(self,scale): \n self.x = self.x * scale \n self.y = self.y * scale \n\n",
"The last part of your code is wrong,\ndef scaleSize(self,scale):\n self.x = self.x * scale\nself.y = self.y * scale\n\nNotice the indentation, which is important in Python. By what you have now, means self.y = self.y * scale is not inside the scaleSize method and the keyword self is undefined for your Shape class.\nWhat you need to do is properly indent,\ndef scaleSize(self,scale):\n self.x = self.x * scale\n self.y = self.y * scale\n\n",
"The indicated line has the wrong indent level, so it's not in the scaleSize() method.\n",
"You need to align line 17 with line 16\nYou have:\ndef scaleSize(self,scale):\n self.x = self.x * scale\nself.y = self.y * scale\n\nMust be:\ndef scaleSize(self,scale):\n self.x = self.x * scale\n self.y = self.y * scale\n\nThat's how python knows they belong to the same method. \n"
] |
[
10,
3,
1,
1
] |
[] |
[] |
[
"class",
"python"
] |
stackoverflow_0002691627_class_python.txt
|
Q:
Can I find the path of the executable running a python script from within the python script?
Is there a way to retreive the path of the executable that is running the current python script (from within the python script)?
A:
That should do what you want
>>> import sys
>>> sys.executable
'C:\\Python26\\python.exe'
>>> import os
>>> os.path.dirname(sys.executable)
'C:\\Python26'
|
Can I find the path of the executable running a python script from within the python script?
|
Is there a way to retreive the path of the executable that is running the current python script (from within the python script)?
|
[
"That should do what you want \n>>> import sys\n>>> sys.executable\n'C:\\\\Python26\\\\python.exe'\n\n>>> import os\n>>> os.path.dirname(sys.executable)\n'C:\\\\Python26'\n\n"
] |
[
7
] |
[] |
[] |
[
"introspection",
"python"
] |
stackoverflow_0002691655_introspection_python.txt
|
Q:
Where to store deployment scripts
Assuming that I have the following directory structure for a Python project:
config/ scripts/ src/
where should a fabric deployment script should go? I assume that it should be in scripts, obviously, but for me it seems more appropriate to store in scripts, the actual code that fires up the project.
A:
This is really a preference thing -- however there are a couple places I like, depending on situation.
Most frequently, and particularly in cases like yours where the fabfile is tied to a piece of software, I like to put it the project directory. I view fabfiles as akin to Makefiles in this case, so this feels like a natural place. (e.g. for your example, put the fabfile in the same directory holding config/ scripts/ and src/)
In other cases, I use fab for information gathering. Specifically I run a few commands and pull files from a series of servers. Similarly I initiate various tests on remote hosts. In these cases I like to set up a special directory for the fabfile (called tests, or whatever) and pull data to the relevant subdirectory.
Finally I have a few fabfiles I keep in $HOME/lib. These do some remote tasks that I frequently deal with. One of these is for setting up new pylons projects on my dev server. I have rpaste set up as an alias to fab -f $HOME/lib/rpaste.py. This allows me to select the target action at will.
|
Where to store deployment scripts
|
Assuming that I have the following directory structure for a Python project:
config/ scripts/ src/
where should a fabric deployment script should go? I assume that it should be in scripts, obviously, but for me it seems more appropriate to store in scripts, the actual code that fires up the project.
|
[
"This is really a preference thing -- however there are a couple places I like, depending on situation.\nMost frequently, and particularly in cases like yours where the fabfile is tied to a piece of software, I like to put it the project directory. I view fabfiles as akin to Makefiles in this case, so this feels like a natural place. (e.g. for your example, put the fabfile in the same directory holding config/ scripts/ and src/)\nIn other cases, I use fab for information gathering. Specifically I run a few commands and pull files from a series of servers. Similarly I initiate various tests on remote hosts. In these cases I like to set up a special directory for the fabfile (called tests, or whatever) and pull data to the relevant subdirectory.\nFinally I have a few fabfiles I keep in $HOME/lib. These do some remote tasks that I frequently deal with. One of these is for setting up new pylons projects on my dev server. I have rpaste set up as an alias to fab -f $HOME/lib/rpaste.py. This allows me to select the target action at will.\n"
] |
[
2
] |
[] |
[] |
[
"deployment",
"fabric",
"python"
] |
stackoverflow_0002691528_deployment_fabric_python.txt
|
Q:
use python glob to find a folder that is a 14 digit number
I have a folder with subfolders that are all in the pattern YYYYMMDDHHMMSS (timestamp).
I want to use glob to only select the folders that match that pattern.
A:
Since glob doesn't support regular expressions, you'll have to brute-force creating the match string. One way is to take advantage of the fact that character ranges in [] are expanded:
C:\temp\py>mkdir 12345678901234
C:\temp\py>C:\Python26\python.exe
Python 2.6.2 Stackless 3.1b3 060516 (release26-maint, Apr 14 2009, 21:19:36) [M
C v.1500 32 bit (Intel)] on win32
Type "help", "copyright", "credits" or "license" for more information.
>>> import glob
>>> glob.glob('./' + ('[0-9]' * 14))
['.\\12345678901234']
>>>
I took advantage of the fact that in Python, multiplying a string with an integer n results in that string being repeated n times.
Of course, you might want to go ahead and put in a check to verify that the given path is actually a directory:
>>> [path for path in glob.iglob('./' + ('[0-9]' * 14))]
['.\\11223344556677', '.\\12345678901234']
>>> [path for path in glob.iglob('./' + ('[0-9]' * 14)) if os.path.isdir(path)]
['.\\12345678901234']
|
use python glob to find a folder that is a 14 digit number
|
I have a folder with subfolders that are all in the pattern YYYYMMDDHHMMSS (timestamp).
I want to use glob to only select the folders that match that pattern.
|
[
"Since glob doesn't support regular expressions, you'll have to brute-force creating the match string. One way is to take advantage of the fact that character ranges in [] are expanded:\nC:\\temp\\py>mkdir 12345678901234\n\nC:\\temp\\py>C:\\Python26\\python.exe\nPython 2.6.2 Stackless 3.1b3 060516 (release26-maint, Apr 14 2009, 21:19:36) [M\nC v.1500 32 bit (Intel)] on win32\nType \"help\", \"copyright\", \"credits\" or \"license\" for more information.\n>>> import glob\n>>> glob.glob('./' + ('[0-9]' * 14))\n['.\\\\12345678901234']\n>>>\n\nI took advantage of the fact that in Python, multiplying a string with an integer n results in that string being repeated n times.\nOf course, you might want to go ahead and put in a check to verify that the given path is actually a directory:\n>>> [path for path in glob.iglob('./' + ('[0-9]' * 14))]\n['.\\\\11223344556677', '.\\\\12345678901234']\n>>> [path for path in glob.iglob('./' + ('[0-9]' * 14)) if os.path.isdir(path)]\n['.\\\\12345678901234']\n\n"
] |
[
31
] |
[] |
[] |
[
"glob",
"python"
] |
stackoverflow_0002692706_glob_python.txt
|
Q:
Quote POSIX shell special characters in Python output
There are times that I automagically create small shell scripts from Python, and I want to make sure that the filename arguments do not contain non-escaped special characters. I've rolled my own solution, that I will provide as an answer, but I am almost certain I've seen such a function lost somewhere in the standard library. By “lost” I mean I didn't find it in an obvious module like shlex, cmd or subprocess.
Do you know of such a function in the stdlib? If yes, where is it?
Even a negative (but definite and correct :) answer will be accepted.
A:
pipes.quote():
>>> from pipes import quote
>>> quote("""some'horrible"string\with lots of junk!$$!""")
'"some\'horrible\\"string\\\\with lots of junk!\\$\\$!"'
Although note that it's arguably got a bug where a zero-length arg will return nothing:
>>> quote("")
''
Probably it would be better if it returned '""'.
A:
The function I use is:
def quote_filename(filename):
return '"%s"' % (
filename
.replace('\\', '\\\\')
.replace('"', '\"')
.replace('$', '\$')
.replace('`', '\`')
)
that is: I always enclose the filename in double quotes, and then quote the only characters special inside double quotes.
|
Quote POSIX shell special characters in Python output
|
There are times that I automagically create small shell scripts from Python, and I want to make sure that the filename arguments do not contain non-escaped special characters. I've rolled my own solution, that I will provide as an answer, but I am almost certain I've seen such a function lost somewhere in the standard library. By “lost” I mean I didn't find it in an obvious module like shlex, cmd or subprocess.
Do you know of such a function in the stdlib? If yes, where is it?
Even a negative (but definite and correct :) answer will be accepted.
|
[
"pipes.quote():\n>>> from pipes import quote\n>>> quote(\"\"\"some'horrible\"string\\with lots of junk!$$!\"\"\")\n'\"some\\'horrible\\\\\"string\\\\\\\\with lots of junk!\\\\$\\\\$!\"'\n\nAlthough note that it's arguably got a bug where a zero-length arg will return nothing:\n>>> quote(\"\")\n''\n\nProbably it would be better if it returned '\"\"'.\n",
"The function I use is:\ndef quote_filename(filename):\n return '\"%s\"' % (\n filename\n .replace('\\\\', '\\\\\\\\')\n .replace('\"', '\\\"')\n .replace('$', '\\$')\n .replace('`', '\\`')\n )\n\nthat is: I always enclose the filename in double quotes, and then quote the only characters special inside double quotes.\n"
] |
[
6,
1
] |
[] |
[] |
[
"escaping",
"posix",
"python",
"shell",
"special_characters"
] |
stackoverflow_0002692873_escaping_posix_python_shell_special_characters.txt
|
Q:
python: find and replace numbers < 1 in text file
I'm pretty new to Python programming and would appreciate some help to a problem I have...
Basically I have multiple text files which contain velocity values as such:
0.259515E+03 0.235095E+03 0.208262E+03 0.230223E+03 0.267333E+03 0.217889E+03 0.156233E+03 0.144876E+03 0.136187E+03 0.137865E+00
etc for many lines...
What I need to do is convert all the values in the text file that are less than 1 (e.g. 0.137865E+00 above) to an arbitrary value of 0.100000E+01. While it seems pretty simple to replace specific values with the 'replace()' method and a while loop, how do you do this if you want to replace a range?
thanks
A:
I think when you are beginning programming, it's useful to see some examples; and I assume you've tried this problem on your own first!
Here is a break-down of how you could approach this:
contents='0.259515E+03 0.235095E+03 0.208262E+03 0.230223E+03 0.267333E+03 0.217889E+03 0.156233E+03 0.144876E+03 0.136187E+03 0.137865E+00'
The split method works on strings. It returns a list of strings. By default, it splits on whitespace:
string_numbers=contents.split()
print(string_numbers)
# ['0.259515E+03', '0.235095E+03', '0.208262E+03', '0.230223E+03', '0.267333E+03', '0.217889E+03', '0.156233E+03', '0.144876E+03', '0.136187E+03', '0.137865E+00']
The map command applies its first argument (the function float) to each of the elements of its second argument (the list string_numbers). The float function converts each string into a floating-point object.
float_numbers=map(float,string_numbers)
print(float_numbers)
# [259.51499999999999, 235.095, 208.262, 230.22300000000001, 267.33300000000003, 217.88900000000001, 156.233, 144.876, 136.18700000000001, 0.13786499999999999]
You can use a list comprehension to process the list, converting numbers less than 1 into the number 1. The conditional expression (1 if num<1 else num) equals 1 when num is less than 1, otherwise, it equals num.
processed_numbers=[(1 if num<1 else num) for num in float_numbers]
print(processed_numbers)
# [259.51499999999999, 235.095, 208.262, 230.22300000000001, 267.33300000000003, 217.88900000000001, 156.233, 144.876, 136.18700000000001, 1]
This is the same thing, all in one line:
processed_numbers=[(1 if num<1 else num) for num in map(float,contents.split())]
To generate a string out of the elements of processed_numbers, you could use the str.join method:
comma_separated_string=', '.join(map(str,processed_numbers))
# '259.515, 235.095, 208.262, 230.223, 267.333, 217.889, 156.233, 144.876, 136.187, 1'
A:
typical technique would be:
read file line by line
split each line into a list of strings
convert each string to the float
compare converted value with 1
replace when needed
write back to the new file
As I don't see you having any code yet, I hope that this would be a good start
A:
def float_filter(input):
for number in input.split():
if float(number) < 1.0:
yield "0.100000E+01"
else:
yield number
input = "0.259515E+03 0.235095E+03 0.208262E+03 0.230223E+03 0.267333E+03 0.217889E+03 0.156233E+03 0.144876E+03 0.136187E+03 0.137865E+00"
print " ".join(float_filter(input))
A:
import numpy as np
a = np.genfromtxt('file.txt') # read file
a[a<1] = 0.1 # replace
np.savetxt('converted.txt', a) # save to file
A:
You could use regular expressions for parsing the string. I'm assuming here that the mantissa is never larger than 1 (ie, begins with 0). This means that for the number to be less than 1, the exponent must be either 0 or negative. The following regular expression matches '0', '.', unlimited number of decimal digits (at least 1), 'E' and either '+00' or '-' and two decimal digits.
0\.\d+E(-\d\d|\+00)
Assuming that you have the file read into variable 'text', you can use the regexp with the following python code:
result = re.sub(r"0\.\d*E(-\d\d|\+00)", "0.100000E+01", text)
Edit: Just realized that the description doesn't limit the valid range of input numbers to positive numbers. Negative numbers can be matched with the following regexp:
-0\.\d+E[-+]\d\d
This can be alternated with the first one using the (pattern1|pattern2) syntax which results in the following Python code:
result = re.sub(r"(0\.\d+E(-\d\d|\+00)|-0\.\d+E[-+]\d\d)", "0.100000E+00", subject)
Also if there's a chance that the exponent goes past 99, the regexp can be further modified by adding a '+' sign after the '\d\d' patterns. This allows matching digits ending in two OR MORE digits.
A:
I've got the script working as I want now...thanks people.
When writing the list to a new file I used the replace method to get rid of the brackets and commas - is there a simpler way?
ftext = open("C:\\Users\\hhp06\\Desktop\\out.grd", "r")
otext = open("C:\\Users\\hhp06\\Desktop\\out2.grd", "w+")
for line in ftext:
stringnum = line.split()
floatnum = map(float, stringnum)
procnum = [(1.0 if num<1 else num) for num in floatnum]
stringproc = str(procnum)
s = (stringproc).replace(",", " ").replace("[", " ").replace("]", "")
otext.writelines(s + "\n")
otext.close()
|
python: find and replace numbers < 1 in text file
|
I'm pretty new to Python programming and would appreciate some help to a problem I have...
Basically I have multiple text files which contain velocity values as such:
0.259515E+03 0.235095E+03 0.208262E+03 0.230223E+03 0.267333E+03 0.217889E+03 0.156233E+03 0.144876E+03 0.136187E+03 0.137865E+00
etc for many lines...
What I need to do is convert all the values in the text file that are less than 1 (e.g. 0.137865E+00 above) to an arbitrary value of 0.100000E+01. While it seems pretty simple to replace specific values with the 'replace()' method and a while loop, how do you do this if you want to replace a range?
thanks
|
[
"I think when you are beginning programming, it's useful to see some examples; and I assume you've tried this problem on your own first!\nHere is a break-down of how you could approach this:\ncontents='0.259515E+03 0.235095E+03 0.208262E+03 0.230223E+03 0.267333E+03 0.217889E+03 0.156233E+03 0.144876E+03 0.136187E+03 0.137865E+00'\n\nThe split method works on strings. It returns a list of strings. By default, it splits on whitespace:\nstring_numbers=contents.split()\nprint(string_numbers)\n# ['0.259515E+03', '0.235095E+03', '0.208262E+03', '0.230223E+03', '0.267333E+03', '0.217889E+03', '0.156233E+03', '0.144876E+03', '0.136187E+03', '0.137865E+00']\n\nThe map command applies its first argument (the function float) to each of the elements of its second argument (the list string_numbers). The float function converts each string into a floating-point object.\nfloat_numbers=map(float,string_numbers)\nprint(float_numbers)\n# [259.51499999999999, 235.095, 208.262, 230.22300000000001, 267.33300000000003, 217.88900000000001, 156.233, 144.876, 136.18700000000001, 0.13786499999999999]\n\nYou can use a list comprehension to process the list, converting numbers less than 1 into the number 1. The conditional expression (1 if num<1 else num) equals 1 when num is less than 1, otherwise, it equals num.\nprocessed_numbers=[(1 if num<1 else num) for num in float_numbers]\nprint(processed_numbers)\n# [259.51499999999999, 235.095, 208.262, 230.22300000000001, 267.33300000000003, 217.88900000000001, 156.233, 144.876, 136.18700000000001, 1]\n\nThis is the same thing, all in one line:\nprocessed_numbers=[(1 if num<1 else num) for num in map(float,contents.split())]\n\nTo generate a string out of the elements of processed_numbers, you could use the str.join method:\ncomma_separated_string=', '.join(map(str,processed_numbers))\n# '259.515, 235.095, 208.262, 230.223, 267.333, 217.889, 156.233, 144.876, 136.187, 1'\n\n",
"typical technique would be:\n\nread file line by line\nsplit each line into a list of strings\nconvert each string to the float\ncompare converted value with 1\nreplace when needed\nwrite back to the new file\n\nAs I don't see you having any code yet, I hope that this would be a good start\n",
"def float_filter(input):\n for number in input.split():\n if float(number) < 1.0:\n yield \"0.100000E+01\"\n else:\n yield number\n\ninput = \"0.259515E+03 0.235095E+03 0.208262E+03 0.230223E+03 0.267333E+03 0.217889E+03 0.156233E+03 0.144876E+03 0.136187E+03 0.137865E+00\"\nprint \" \".join(float_filter(input))\n\n",
"import numpy as np\n\na = np.genfromtxt('file.txt') # read file\na[a<1] = 0.1 # replace\nnp.savetxt('converted.txt', a) # save to file\n\n",
"You could use regular expressions for parsing the string. I'm assuming here that the mantissa is never larger than 1 (ie, begins with 0). This means that for the number to be less than 1, the exponent must be either 0 or negative. The following regular expression matches '0', '.', unlimited number of decimal digits (at least 1), 'E' and either '+00' or '-' and two decimal digits.\n0\\.\\d+E(-\\d\\d|\\+00)\n\nAssuming that you have the file read into variable 'text', you can use the regexp with the following python code:\nresult = re.sub(r\"0\\.\\d*E(-\\d\\d|\\+00)\", \"0.100000E+01\", text)\n\nEdit: Just realized that the description doesn't limit the valid range of input numbers to positive numbers. Negative numbers can be matched with the following regexp:\n-0\\.\\d+E[-+]\\d\\d\n\nThis can be alternated with the first one using the (pattern1|pattern2) syntax which results in the following Python code:\nresult = re.sub(r\"(0\\.\\d+E(-\\d\\d|\\+00)|-0\\.\\d+E[-+]\\d\\d)\", \"0.100000E+00\", subject)\n\nAlso if there's a chance that the exponent goes past 99, the regexp can be further modified by adding a '+' sign after the '\\d\\d' patterns. This allows matching digits ending in two OR MORE digits.\n",
"I've got the script working as I want now...thanks people.\nWhen writing the list to a new file I used the replace method to get rid of the brackets and commas - is there a simpler way?\nftext = open(\"C:\\\\Users\\\\hhp06\\\\Desktop\\\\out.grd\", \"r\")\notext = open(\"C:\\\\Users\\\\hhp06\\\\Desktop\\\\out2.grd\", \"w+\")\n\nfor line in ftext:\n stringnum = line.split()\n floatnum = map(float, stringnum)\n procnum = [(1.0 if num<1 else num) for num in floatnum]\n stringproc = str(procnum)\n s = (stringproc).replace(\",\", \" \").replace(\"[\", \" \").replace(\"]\", \"\")\n otext.writelines(s + \"\\n\")\notext.close()\n\n"
] |
[
7,
4,
3,
3,
0,
0
] |
[] |
[] |
[
"python",
"replace"
] |
stackoverflow_0002685015_python_replace.txt
|
Q:
Programming language for opengl screenshot software
I need to develop a multiplatform software that takes screenshots from opengl games without affecting the game in performance, it will run in the background and will add a watermark to my screenshots.
What language should i use? I thought of Perl / Python.
Anyone can point me out something to start?
Thanks!
A:
I would suggest C++. That way you can use OpenGL and DirectX libraries and API calls natively. Libraries that provide such functionality to other languages typically abstract the good stuff away from reach.
A:
The language you know best that has some sort of OpenGL Bindings.
My personal preference for such kind of applications is C, C++ or (if available) C# but it's a simple matter of preference.
A:
Do you need to add a watermark right when you take the screenshot? It would be a lot easier to simply add the watermark later to the static image, as many applications can do this (e.g. Photoshop).
A:
Have you thought about modifying Shutter for your purpose? It is written in Perl.
|
Programming language for opengl screenshot software
|
I need to develop a multiplatform software that takes screenshots from opengl games without affecting the game in performance, it will run in the background and will add a watermark to my screenshots.
What language should i use? I thought of Perl / Python.
Anyone can point me out something to start?
Thanks!
|
[
"I would suggest C++. That way you can use OpenGL and DirectX libraries and API calls natively. Libraries that provide such functionality to other languages typically abstract the good stuff away from reach.\n",
"The language you know best that has some sort of OpenGL Bindings.\nMy personal preference for such kind of applications is C, C++ or (if available) C# but it's a simple matter of preference.\n",
"Do you need to add a watermark right when you take the screenshot? It would be a lot easier to simply add the watermark later to the static image, as many applications can do this (e.g. Photoshop).\n",
"Have you thought about modifying Shutter for your purpose? It is written in Perl.\n"
] |
[
1,
0,
0,
0
] |
[] |
[] |
[
"opengl",
"perl",
"python"
] |
stackoverflow_0002691289_opengl_perl_python.txt
|
Q:
Rare PyCairo antialias getting directly the surface data
After create a Pycairo context and surface (ImageSurface) I get a diferent export results if I get directly from surface buffer
surface.get_data()
or from PNG export method
surface.write_to_png()
The context antialias flag is obviously the same and, yes, the get_data method result has antialiasing, but with much poorer quality. Why?
Thanks.
A:
I answer myself, Cairo uses premultiplied color (ARGB) and GTK only it's able to manage true color (RGBA). Use it directly result in a display with gray fridges
I could make the conversion manually, losing a lot of performace, obviously.
|
Rare PyCairo antialias getting directly the surface data
|
After create a Pycairo context and surface (ImageSurface) I get a diferent export results if I get directly from surface buffer
surface.get_data()
or from PNG export method
surface.write_to_png()
The context antialias flag is obviously the same and, yes, the get_data method result has antialiasing, but with much poorer quality. Why?
Thanks.
|
[
"I answer myself, Cairo uses premultiplied color (ARGB) and GTK only it's able to manage true color (RGBA). Use it directly result in a display with gray fridges\nI could make the conversion manually, losing a lot of performace, obviously.\n"
] |
[
0
] |
[] |
[] |
[
"cairo",
"pycairo",
"python",
"vector"
] |
stackoverflow_0002690047_cairo_pycairo_python_vector.txt
|
Q:
Best (or appropriate) WSGI server for this Python script? - Python
I'm having quite a problem deciding how to serve a few Python scripts.
The problem is that the basic functionality could be generalized by this:
do_something()
time.sleep(3)
do_something()
I tried various WSGI servers, but they have all been giving me concurrency limitations, as in I have to specify how many threads to use and so on.
I only wish that the resources on the server be used efficiently and liberally.
Any ideas?
A:
Have you checked tornado with its non-blocking asynchronous requests?
http://www.tornadoweb.org/
I have never used it though but here is an example from doc:
class MainHandler(tornado.web.RequestHandler):
@tornado.web.asynchronous
def get(self):
http = tornado.httpclient.AsyncHTTPClient()
http.fetch("http://friendfeed-api.com/v2/feed/bret",
callback=self.async_callback(self.on_response))
def on_response(self, response):
if response.error: raise tornado.web.HTTPError(500)
json = tornado.escape.json_decode(response.body)
self.write("Fetched " + str(len(json["entries"])) + " entries "
"from the FriendFeed API")
self.finish()
A:
You might find Spawning a good fit. It has several options for deployment, one of which is somewhat transparent async (as implemented by Eventlet). So if you literally do time.sleep(3) it'll be okay. Not everything you might do is transparently handled, so you have to pay some attention to Eventlet and how it works. Sockets are, for instance, so if you read from a socket (and that socket blocks) it won't halt the server or consume a thread. But if you do CPU-heavy work that will block all requests. So... it's a bit tricky. Spawning has some other deployment options that might work for you too.
You might be able to use WaitForIt, though it has some gotchas. It will spawn threads for long-running requests, and provides some browser feedback, so if you are creating a very simplistic frontend to long-running backend processes it might be useful. It acts as WSGI middleware.
A:
What about CherryPy WSGI server?
What does that sleep mean? Are you really writing a web application?
A:
So it's OK for the client to be tied up waiting for an answer for 3 seconds, but not OK for the server? That seems...odd.
If you'd rather not have the client tied up for 3 seconds, a common mechanism is to have the initial request return "202 Accepted" ASAP with a URL to a status monitor. Then the server can spawn a new thread or subprocess for the task, and the client can do other things, and then poll the status URL to find out when the task is done.
|
Best (or appropriate) WSGI server for this Python script? - Python
|
I'm having quite a problem deciding how to serve a few Python scripts.
The problem is that the basic functionality could be generalized by this:
do_something()
time.sleep(3)
do_something()
I tried various WSGI servers, but they have all been giving me concurrency limitations, as in I have to specify how many threads to use and so on.
I only wish that the resources on the server be used efficiently and liberally.
Any ideas?
|
[
"Have you checked tornado with its non-blocking asynchronous requests?\nhttp://www.tornadoweb.org/\nI have never used it though but here is an example from doc:\nclass MainHandler(tornado.web.RequestHandler):\n @tornado.web.asynchronous\n def get(self):\n http = tornado.httpclient.AsyncHTTPClient()\n http.fetch(\"http://friendfeed-api.com/v2/feed/bret\",\n callback=self.async_callback(self.on_response))\n\n def on_response(self, response):\n if response.error: raise tornado.web.HTTPError(500)\n json = tornado.escape.json_decode(response.body)\n self.write(\"Fetched \" + str(len(json[\"entries\"])) + \" entries \"\n \"from the FriendFeed API\")\n self.finish()\n\n",
"You might find Spawning a good fit. It has several options for deployment, one of which is somewhat transparent async (as implemented by Eventlet). So if you literally do time.sleep(3) it'll be okay. Not everything you might do is transparently handled, so you have to pay some attention to Eventlet and how it works. Sockets are, for instance, so if you read from a socket (and that socket blocks) it won't halt the server or consume a thread. But if you do CPU-heavy work that will block all requests. So... it's a bit tricky. Spawning has some other deployment options that might work for you too.\nYou might be able to use WaitForIt, though it has some gotchas. It will spawn threads for long-running requests, and provides some browser feedback, so if you are creating a very simplistic frontend to long-running backend processes it might be useful. It acts as WSGI middleware.\n",
"What about CherryPy WSGI server?\nWhat does that sleep mean? Are you really writing a web application?\n",
"So it's OK for the client to be tied up waiting for an answer for 3 seconds, but not OK for the server? That seems...odd.\nIf you'd rather not have the client tied up for 3 seconds, a common mechanism is to have the initial request return \"202 Accepted\" ASAP with a URL to a status monitor. Then the server can spawn a new thread or subprocess for the task, and the client can do other things, and then poll the status URL to find out when the task is done.\n"
] |
[
1,
1,
0,
0
] |
[] |
[] |
[
"cherrypy",
"concurrency",
"mod_wsgi",
"python",
"wsgi"
] |
stackoverflow_0002692189_cherrypy_concurrency_mod_wsgi_python_wsgi.txt
|
Q:
Python - set source port number with sockets
I'd like to send a specific UDP broadcast packet. Unfortunately, I need to send the UDP packets from a very specific port.
Let's say I broadcast via UDP "BLABLAH". The server will only answer if my incoming packet source port was 1444; if not, then the packet is discarded.
My broadcast socket setup looks like this:
s = socket(AF_INET,SOCK_DGRAM)
s.setsockopt(SOL_SOCKET, SO_BROADCAST, 1)
How can I then set the source port in Python?
A:
You need to bind the socket to the specific port you want to send from. The bind method takes an address tuple, much like connect, though you can use the wildcard address. For example:
s.bind(('0.0.0.0', 1444))
A:
Use s.bind(('', port)).
|
Python - set source port number with sockets
|
I'd like to send a specific UDP broadcast packet. Unfortunately, I need to send the UDP packets from a very specific port.
Let's say I broadcast via UDP "BLABLAH". The server will only answer if my incoming packet source port was 1444; if not, then the packet is discarded.
My broadcast socket setup looks like this:
s = socket(AF_INET,SOCK_DGRAM)
s.setsockopt(SOL_SOCKET, SO_BROADCAST, 1)
How can I then set the source port in Python?
|
[
"You need to bind the socket to the specific port you want to send from. The bind method takes an address tuple, much like connect, though you can use the wildcard address. For example:\ns.bind(('0.0.0.0', 1444))\n\n",
"Use s.bind(('', port)).\n"
] |
[
20,
10
] |
[] |
[] |
[
"port",
"python",
"sockets"
] |
stackoverflow_0002694212_port_python_sockets.txt
|
Q:
Best canvas for drawing in wxPython?
I have to draw a graph of elements composing a topological model of a physical network. There would be nodes and arches, and the latter could be unidirectional or bidirectional.
I would like to capture the clicking events for the nodes and the arches (to select the element and show its properties somewhere), and the dragging events for the nodes (to move them around) and arches (to connect or disconnect elements).
I've done some research and I've narrowed the alternatives down to OGL (Object Graphics Library) and FloatCanvas. I would not like to go down to the DrawingContext, but it is not discarded if necessary.
Which canvas option would you choose?
A:
I've tried FloatCanvas, although there has been a lot of work to get everything to work. I've managed to get through mouse interaction things like connectivity, movement, automatic reconnection in case of movement, etc.
FloatCanvas is also quite nice in terms of performance and visual results. Anti-aliasing (1) (2) is also possible to improve them if necessary.
A:
It seems that OGL is not being updated, and in general FloatCanvas looks more modern. I don't really know deeply enough the two options.
It seems that event capturing is easier with FloatCanvas. I would try to use it before OGL.
|
Best canvas for drawing in wxPython?
|
I have to draw a graph of elements composing a topological model of a physical network. There would be nodes and arches, and the latter could be unidirectional or bidirectional.
I would like to capture the clicking events for the nodes and the arches (to select the element and show its properties somewhere), and the dragging events for the nodes (to move them around) and arches (to connect or disconnect elements).
I've done some research and I've narrowed the alternatives down to OGL (Object Graphics Library) and FloatCanvas. I would not like to go down to the DrawingContext, but it is not discarded if necessary.
Which canvas option would you choose?
|
[
"I've tried FloatCanvas, although there has been a lot of work to get everything to work. I've managed to get through mouse interaction things like connectivity, movement, automatic reconnection in case of movement, etc.\nFloatCanvas is also quite nice in terms of performance and visual results. Anti-aliasing (1) (2) is also possible to improve them if necessary.\n",
"It seems that OGL is not being updated, and in general FloatCanvas looks more modern. I don't really know deeply enough the two options.\nIt seems that event capturing is easier with FloatCanvas. I would try to use it before OGL.\n"
] |
[
3,
2
] |
[] |
[] |
[
"canvas",
"python",
"wxpython"
] |
stackoverflow_0002327918_canvas_python_wxpython.txt
|
Q:
Maintenance Scripts with Pylons' objects?
How do I import classes from a pylons project for maintenance scripts?
A:
Maybe this could be interesting to you:
You'll need to know where your config ini file is, and load your app
from the script. Your websetup.py script in your project should have
code to do this (in 0.9.6 it does). If it doesn't, you'll need to run
this first before importing your models (again, this works in 0.9.6):
from paste.deploy import appconfig
from pylons import config
from YOURPROJECT.config.environment import load_environment
conf = appconfig('config:' +'/wherever/your/config.ini')
load_environment(conf.global_conf, conf.local_conf)
import YOURPROJECT.model as model
Source: Ben Bangert http://groups.google.com/group/pylons-discuss/browse_thread/thread/90c47dc6120fa43d/52f25a08f7234fa7
|
Maintenance Scripts with Pylons' objects?
|
How do I import classes from a pylons project for maintenance scripts?
|
[
"Maybe this could be interesting to you:\n\nYou'll need to know where your config ini file is, and load your app\n from the script. Your websetup.py script in your project should have\n code to do this (in 0.9.6 it does). If it doesn't, you'll need to run\n this first before importing your models (again, this works in 0.9.6): \n from paste.deploy import appconfig \n from pylons import config \n from YOURPROJECT.config.environment import load_environment \n conf = appconfig('config:' +'/wherever/your/config.ini') \n load_environment(conf.global_conf, conf.local_conf) \n import YOURPROJECT.model as model \n\nSource: Ben Bangert http://groups.google.com/group/pylons-discuss/browse_thread/thread/90c47dc6120fa43d/52f25a08f7234fa7\n"
] |
[
1
] |
[] |
[] |
[
"pylons",
"python"
] |
stackoverflow_0002694057_pylons_python.txt
|
Q:
Anyone tried Solace? Solace - a multilingual support platform
Has anyone tried Solace yet?
"Solace is a fully open-sourced multilingual support and knowledge exchange platform written in Python."
Just wanted to know your experience. Are there any other such platforms available in open source?
A:
This one seems better.
A:
I already set up my own server. Solace seems great.
A:
We just started using it at our company. You get what you pay for. Feels like a weekender project. Gets the job done, but lacks the polish of Stack Overflow. The documentation is weak. I find it ironic that Plurk doesn't run an instance of Solace to field support questions for Solace. If they do they don't advertise it.
|
Anyone tried Solace? Solace - a multilingual support platform
|
Has anyone tried Solace yet?
"Solace is a fully open-sourced multilingual support and knowledge exchange platform written in Python."
Just wanted to know your experience. Are there any other such platforms available in open source?
|
[
"This one seems better.\n",
"I already set up my own server. Solace seems great. \n",
"We just started using it at our company. You get what you pay for. Feels like a weekender project. Gets the job done, but lacks the polish of Stack Overflow. The documentation is weak. I find it ironic that Plurk doesn't run an instance of Solace to field support questions for Solace. If they do they don't advertise it.\n"
] |
[
3,
2,
2
] |
[] |
[] |
[
"open_source",
"platform",
"python"
] |
stackoverflow_0001369167_open_source_platform_python.txt
|
Q:
Dynamic Operator Overloading on dict classes in Python
I have a class that dynamically overloads basic arithmetic operators like so...
import operator
class IshyNum:
def __init__(self, n):
self.num=n
self.buildArith()
def arithmetic(self, other, o):
return o(self.num, other)
def buildArith(self):
map(lambda o: setattr(self, "__%s__"%o,lambda f: self.arithmetic(f, getattr(operator, o))), ["add", "sub", "mul", "div"])
if __name__=="__main__":
number=IshyNum(5)
print number+5
print number/2
print number*3
print number-3
But if I change the class to inherit from the dictionary (class IshyNum(dict):) it doesn't work. I need to explicitly def __add__(self, other) or whatever in order for this to work. Why?
A:
The answer is found in the two types of class that Python has.
The first code-snippet you provided uses a legacy "old-style" class (you can tell because it doesn't subclass anything - there's nothing before the colon). Its semantics are peculiar. In particular, you can add a special method to an instance:
class Foo:
def __init__(self, num):
self.num = num
def _fn(other):
return self.num + other.num
self.__add__ = _fn
and get a valid response:
>>> f = Foo(2)
>>> g = Foo(1)
>>> f + g
3
But, subclassing dict means you are generating a new-style class. And the semantics of operator overloading are different:
class Foo (object):
def __init__(self, num):
self.num = num
def _fn(other):
return self.num + other.num
self.__add__ = _fn
>>> f = Foo(2)
>>> g = Foo(1)
>>> f + g
Traceback ...
TypeError: unsupported operand type(s) for +: 'Foo' and 'Foo'
To make this work with new-style classes (which includes subclasses of dict or just about any other type you will find), you have to make sure the special method is defined on the class. You can do this through a metaclass:
class _MetaFoo(type):
def __init__(cls, name, bases, args):
def _fn(self, other):
return self.num + other.num
cls.__add__ = _fn
class Foo(object):
__metaclass__ = _MetaFoo
def __init__(self, num):
self.num = num
>>> f = Foo(2)
>>> g = Foo(1)
>>> f+g
3
Also, the semantic difference means that in the very first case I could define my local add method with one argument (the self it uses is captured from the surrounding scope in which it is defined), but with new-style classes, Python expects to pass in both values explicitly, so the inner function has two arguments.
As a previous commenter mentioned, best to avoid old-style classes if possible and stick with new-style classes (old-style classes are removed in Python 3+). Its unfortunate that the old-style classes happened to work for you in this case, where new-style classes will require more code.
Edit:
You can also do this more in the way you originally tried by setting the method on the class rather than the instance:
class Foo(object):
def __init__(self, num):
self.num = num
setattr(Foo, '__add__', (lambda self, other: self.num + other.num))
>>> f = Foo(2)
>>> g = Foo(1)
>>> f+g
3
I'm afraid I sometimes think in Metaclasses, where simpler solutions would be better :)
A:
In general, never set __ methods on the instance -- they're only supported on the class. (In this instance, the problem is that they happen to work on old-style classes. Don't use old-style classes).
You probably want to use a metaclass, not the weird thing you're doing here.
Here's a metaclass tutorial: http://www.voidspace.org.uk/python/articles/metaclasses.shtml
A:
I do not understand what you are trying to accomplish, but I am almost certain you are going about it in the wrong way. Some of my observations:
I don't see why you're trying to dynamically generate those arithmetic methods. You don't do anything instance-specific with them, so I don't see why you would not just define them on the class.
The only reason they work at all is because IshyNum is an old-style class; this isn't a good thing, since old-style classes are long-deprecated and not as nice as new-style classes. (I'll explain later why you should be especially interested in this.)
If you wanted to automate the process of doing the same thing for multiple methods (probably not worth it in this case), you could just do this right after the class definition block.
Don't use map to do that. map is for making a list; using it for side effects is silly. Just use a normal for loop.
If you want to use composition to refer lots of methods to the same attribute automatedly when using composition, use __getattr__ and redirect to that attribute's methods.
Don't inherit dict. There is nothing much to gain from inheriting built-in types. It turns out it is more confusing than it's worth, and you don't get to re-use much.
If your code above is anything close to the stuff in your post, you really don't want to inherit dict. If it's not, try posting your real use case.
Here is what you really wanted to know:
When you inherit dict, you are making a new-style class. IshyNum is an old-style class because it doesn't inherit object (or one of its subclasses).
New-style classes have been Python's flagship kind of class for a decade and are what you want to use. In this case, they actually cause your technique no longer to work. This is fine, though, since there is no reason in the code you posted to set magic methods on a per-instance level and little reason ever to want to.
A:
For new-style classes, Python does not check the instance for an __add__ method when performing an addition, it checks the class instead. The problem is that you are binding the __add__ method (and all the others) to the instance as a bound method and not to the class as an unbound method. (This is true to other special methods as well, you can attach them only to the class, not to an instance). So, you'll probably want to use a metaclass to achieve this functionality (although I think this is a very awkward thing to do as it is much more readable to spell out these methods explicitly). Anyway, here is an example with metaclasses:
import operator
class OperatorMeta(type):
def __new__(mcs, name, bases, attrs):
for opname in ["add", "sub", "mul", "div"]:
op = getattr(operator, opname)
attrs["__%s__" % opname] = mcs._arithmetic_func_factory(op)
return type.__new__(mcs, name, bases, attrs)
@staticmethod
def _arithmetic_func_factory(op):
def func(self, other):
return op(self.num, other)
return func
class IshyNum(dict):
__metaclass__ = OperatorMeta
def __init__(self, n):
dict.__init__(self)
self.num=n
if __name__=="__main__":
number=IshyNum(5)
print number+5
print number/2
print number*3
print number-3
|
Dynamic Operator Overloading on dict classes in Python
|
I have a class that dynamically overloads basic arithmetic operators like so...
import operator
class IshyNum:
def __init__(self, n):
self.num=n
self.buildArith()
def arithmetic(self, other, o):
return o(self.num, other)
def buildArith(self):
map(lambda o: setattr(self, "__%s__"%o,lambda f: self.arithmetic(f, getattr(operator, o))), ["add", "sub", "mul", "div"])
if __name__=="__main__":
number=IshyNum(5)
print number+5
print number/2
print number*3
print number-3
But if I change the class to inherit from the dictionary (class IshyNum(dict):) it doesn't work. I need to explicitly def __add__(self, other) or whatever in order for this to work. Why?
|
[
"The answer is found in the two types of class that Python has.\nThe first code-snippet you provided uses a legacy \"old-style\" class (you can tell because it doesn't subclass anything - there's nothing before the colon). Its semantics are peculiar. In particular, you can add a special method to an instance:\nclass Foo:\n def __init__(self, num):\n self.num = num\n def _fn(other):\n return self.num + other.num\n self.__add__ = _fn\n\nand get a valid response:\n>>> f = Foo(2)\n>>> g = Foo(1)\n>>> f + g\n3\n\nBut, subclassing dict means you are generating a new-style class. And the semantics of operator overloading are different:\nclass Foo (object):\n def __init__(self, num):\n self.num = num\n def _fn(other):\n return self.num + other.num\n self.__add__ = _fn\n>>> f = Foo(2)\n>>> g = Foo(1)\n>>> f + g\nTraceback ...\nTypeError: unsupported operand type(s) for +: 'Foo' and 'Foo'\n\nTo make this work with new-style classes (which includes subclasses of dict or just about any other type you will find), you have to make sure the special method is defined on the class. You can do this through a metaclass:\nclass _MetaFoo(type):\n def __init__(cls, name, bases, args):\n def _fn(self, other):\n return self.num + other.num\n cls.__add__ = _fn\n\nclass Foo(object):\n __metaclass__ = _MetaFoo\n def __init__(self, num):\n self.num = num\n\n>>> f = Foo(2)\n>>> g = Foo(1)\n>>> f+g\n3\n\nAlso, the semantic difference means that in the very first case I could define my local add method with one argument (the self it uses is captured from the surrounding scope in which it is defined), but with new-style classes, Python expects to pass in both values explicitly, so the inner function has two arguments.\nAs a previous commenter mentioned, best to avoid old-style classes if possible and stick with new-style classes (old-style classes are removed in Python 3+). Its unfortunate that the old-style classes happened to work for you in this case, where new-style classes will require more code.\n\nEdit: \nYou can also do this more in the way you originally tried by setting the method on the class rather than the instance:\nclass Foo(object):\n def __init__(self, num):\n self.num = num\nsetattr(Foo, '__add__', (lambda self, other: self.num + other.num))\n>>> f = Foo(2)\n>>> g = Foo(1)\n>>> f+g\n3\n\nI'm afraid I sometimes think in Metaclasses, where simpler solutions would be better :)\n",
"In general, never set __ methods on the instance -- they're only supported on the class. (In this instance, the problem is that they happen to work on old-style classes. Don't use old-style classes).\nYou probably want to use a metaclass, not the weird thing you're doing here.\nHere's a metaclass tutorial: http://www.voidspace.org.uk/python/articles/metaclasses.shtml\n",
"I do not understand what you are trying to accomplish, but I am almost certain you are going about it in the wrong way. Some of my observations:\n\nI don't see why you're trying to dynamically generate those arithmetic methods. You don't do anything instance-specific with them, so I don't see why you would not just define them on the class.\n\nThe only reason they work at all is because IshyNum is an old-style class; this isn't a good thing, since old-style classes are long-deprecated and not as nice as new-style classes. (I'll explain later why you should be especially interested in this.)\nIf you wanted to automate the process of doing the same thing for multiple methods (probably not worth it in this case), you could just do this right after the class definition block.\n\nDon't use map to do that. map is for making a list; using it for side effects is silly. Just use a normal for loop.\n\n\nIf you want to use composition to refer lots of methods to the same attribute automatedly when using composition, use __getattr__ and redirect to that attribute's methods.\nDon't inherit dict. There is nothing much to gain from inheriting built-in types. It turns out it is more confusing than it's worth, and you don't get to re-use much.\n\nIf your code above is anything close to the stuff in your post, you really don't want to inherit dict. If it's not, try posting your real use case.\n\n\nHere is what you really wanted to know:\n\nWhen you inherit dict, you are making a new-style class. IshyNum is an old-style class because it doesn't inherit object (or one of its subclasses). \nNew-style classes have been Python's flagship kind of class for a decade and are what you want to use. In this case, they actually cause your technique no longer to work. This is fine, though, since there is no reason in the code you posted to set magic methods on a per-instance level and little reason ever to want to.\n\n",
"For new-style classes, Python does not check the instance for an __add__ method when performing an addition, it checks the class instead. The problem is that you are binding the __add__ method (and all the others) to the instance as a bound method and not to the class as an unbound method. (This is true to other special methods as well, you can attach them only to the class, not to an instance). So, you'll probably want to use a metaclass to achieve this functionality (although I think this is a very awkward thing to do as it is much more readable to spell out these methods explicitly). Anyway, here is an example with metaclasses:\nimport operator\n\nclass OperatorMeta(type):\n def __new__(mcs, name, bases, attrs):\n for opname in [\"add\", \"sub\", \"mul\", \"div\"]:\n op = getattr(operator, opname)\n attrs[\"__%s__\" % opname] = mcs._arithmetic_func_factory(op)\n return type.__new__(mcs, name, bases, attrs)\n\n @staticmethod\n def _arithmetic_func_factory(op):\n def func(self, other):\n return op(self.num, other)\n return func\n\nclass IshyNum(dict):\n __metaclass__ = OperatorMeta\n\n def __init__(self, n):\n dict.__init__(self)\n self.num=n\n\nif __name__==\"__main__\":\n number=IshyNum(5)\n print number+5\n print number/2\n print number*3\n print number-3\n\n"
] |
[
4,
3,
2,
2
] |
[] |
[] |
[
"dictionary",
"operator_overloading",
"python"
] |
stackoverflow_0002694619_dictionary_operator_overloading_python.txt
|
Q:
Open Source Library for Linguistic Inquiry and Word Count (LIWC)
I am looking for an open source library for Linguistic Inquiry and Word Count (LIWC). Something in java or python will be good, though I am open to use other language.
Does anyone know where I can get one ?
Cheers,
A:
As ealdent points out, LIWC is both software and a data set. The data set is proprietary so there is no open-source version of that. For the software side, TAWC is a useful open source Perl version. From the comments:
This is a semi-complicated script adapted from the one used in my CHI
papers. The task of this script is to read in regular expressions from a
dictionary (or if they're not REs, to make them into REs), which must be
backwards-compatible with the LIWC software set (c.f.
http://www.liwc.net). It then counts the number of matches for the RE in
a single input row / user, and outputs it for that row / user.
You could then buy LIWClite which is less than half the cost of LIWC. You can also use TAWC with your own dictionaries for free.
|
Open Source Library for Linguistic Inquiry and Word Count (LIWC)
|
I am looking for an open source library for Linguistic Inquiry and Word Count (LIWC). Something in java or python will be good, though I am open to use other language.
Does anyone know where I can get one ?
Cheers,
|
[
"As ealdent points out, LIWC is both software and a data set. The data set is proprietary so there is no open-source version of that. For the software side, TAWC is a useful open source Perl version. From the comments:\n\nThis is a semi-complicated script adapted from the one used in my CHI\n papers. The task of this script is to read in regular expressions from a\n dictionary (or if they're not REs, to make them into REs), which must be\n backwards-compatible with the LIWC software set (c.f. \n http://www.liwc.net). It then counts the number of matches for the RE in\n a single input row / user, and outputs it for that row / user.\n\nYou could then buy LIWClite which is less than half the cost of LIWC. You can also use TAWC with your own dictionaries for free.\n"
] |
[
2
] |
[
"You may find the Natural Language Toolkit (NLTK) for Python useful: http://www.nltk.org/\n"
] |
[
-6
] |
[
"java",
"nlp",
"open_source",
"python"
] |
stackoverflow_0002511876_java_nlp_open_source_python.txt
|
Q:
python list Index out of range error
I am working on a python tetris game that my proffessor assigned for the final project of a concepts of programming class. I have got just about everything he wanted to work on it at this point but I am having a slight problem with one part of it. Whenever I start moving pieces left and right I keep getting "index out of range error". This only happens when it is up against a piece. Here are the culprits that are giving me grief.
def clearRight(block=None):
global board, activeBlock, stackedBlocks
isClear = True
if(block == None):
block = activeBlock
if(block != None):
for square in block['squares']:
row = square[1]
col = square[0]+1
if(col >= 0 and stackedBlocks[row][col] !=None):
isClear=False
return isClear
def clearLeft(block=None):
global board, activeBlock, stackedBlocks
isClear = True
if(block == None):
block = activeBlock
if(block != None):
for square in block['squares']:
row = square[1]
col = square[0]-1
if(col >= 0 and stackedBlocks[row][col] !=None):
isClear=False
return isClear
I am not looking to get anyone to fix it for me, I'm only looking for tips on how to fix it myself. Thanks in advance for any help that is given.
A:
There a typo that would cause that problem in the first method.
When you're checking each cell in the block shifted one right, you don't check if they are off the grid.
if (col >= 0 and ...)
probably should be
if (col < num_cols and ...)
I also agree with CrazyDrummer, make a generic clear function
Spoilers ...
def clear(x_offset, block=None):
if not block:
block = activeBlock
if not block: return True
for x,y in block:
x += x_offset
if not (0 <= x < num_cols) or stackedBlocks[x, y]:
return False
return True
A:
Look at what's different when you're getting the exception. Try printing out program state information to help you zero in. There's only one place where you access an array with variable indexes, so you can narrow your search radius a bit.
Separate suggestion: Make a generic clear that takes determines what direction you want to clear from by the parameters.
I highly recommend the book debugging rules!, it will aid you in searching out and properly fixing problems. :D
|
python list Index out of range error
|
I am working on a python tetris game that my proffessor assigned for the final project of a concepts of programming class. I have got just about everything he wanted to work on it at this point but I am having a slight problem with one part of it. Whenever I start moving pieces left and right I keep getting "index out of range error". This only happens when it is up against a piece. Here are the culprits that are giving me grief.
def clearRight(block=None):
global board, activeBlock, stackedBlocks
isClear = True
if(block == None):
block = activeBlock
if(block != None):
for square in block['squares']:
row = square[1]
col = square[0]+1
if(col >= 0 and stackedBlocks[row][col] !=None):
isClear=False
return isClear
def clearLeft(block=None):
global board, activeBlock, stackedBlocks
isClear = True
if(block == None):
block = activeBlock
if(block != None):
for square in block['squares']:
row = square[1]
col = square[0]-1
if(col >= 0 and stackedBlocks[row][col] !=None):
isClear=False
return isClear
I am not looking to get anyone to fix it for me, I'm only looking for tips on how to fix it myself. Thanks in advance for any help that is given.
|
[
"There a typo that would cause that problem in the first method.\nWhen you're checking each cell in the block shifted one right, you don't check if they are off the grid.\nif (col >= 0 and ...)\n\nprobably should be\nif (col < num_cols and ...)\n\nI also agree with CrazyDrummer, make a generic clear function\n\nSpoilers ...\ndef clear(x_offset, block=None):\n if not block: \n block = activeBlock\n if not block: return True\n for x,y in block:\n x += x_offset\n if not (0 <= x < num_cols) or stackedBlocks[x, y]:\n return False\n return True\n\n",
"Look at what's different when you're getting the exception. Try printing out program state information to help you zero in. There's only one place where you access an array with variable indexes, so you can narrow your search radius a bit.\nSeparate suggestion: Make a generic clear that takes determines what direction you want to clear from by the parameters. \nI highly recommend the book debugging rules!, it will aid you in searching out and properly fixing problems. :D\n"
] |
[
2,
0
] |
[] |
[] |
[
"python",
"tetris"
] |
stackoverflow_0002695118_python_tetris.txt
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.