title stringlengths 10 172 | question_id int64 469 40.1M | question_body stringlengths 22 48.2k | question_score int64 -44 5.52k | question_date stringlengths 20 20 | answer_id int64 497 40.1M | answer_body stringlengths 18 33.9k | answer_score int64 -38 8.38k | answer_date stringlengths 20 20 | tags list |
|---|---|---|---|---|---|---|---|---|---|
How do I remove a substring from the end of a string in Python? | 1,038,824 | <p>I have the following code:</p>
<pre><code>url = 'abcdc.com'
print(url.strip('.com'))
</code></pre>
<p>I expected: <code>abcdc</code></p>
<p>I got: <code>abcd</code></p>
<p>Now I do </p>
<pre><code>url.rsplit('.com', 1)
</code></pre>
<p>Is there a better way?</p>
| 151 | 2009-06-24T14:44:01Z | 25,126,098 | <p>Since it seems like nobody has pointed this on out yet.</p>
<pre><code>url = "www.test.example.com"
new_url = url[:url.rfind("."):]
</code></pre>
<p>This should be more efficient than the methods using split(), as no new list object is created, and this solution works for strings with several dots.</p>
| 11 | 2014-08-04T19:27:22Z | [
"python",
"string"
] |
How do I remove a substring from the end of a string in Python? | 1,038,824 | <p>I have the following code:</p>
<pre><code>url = 'abcdc.com'
print(url.strip('.com'))
</code></pre>
<p>I expected: <code>abcdc</code></p>
<p>I got: <code>abcd</code></p>
<p>Now I do </p>
<pre><code>url.rsplit('.com', 1)
</code></pre>
<p>Is there a better way?</p>
| 151 | 2009-06-24T14:44:01Z | 39,752,431 | <p>In my case I needed to raise an exception so I did:</p>
<pre><code>class UnableToStripEnd(Exception):
"""A Exception type to indicate that the suffix cannot be removed from the text."""
@staticmethod
def get_exception(text, suffix):
return UnableToStripEnd("Could not find suffix ({0}) on text: {1}."
.format(suffix, text))
def strip_end(text, suffix):
"""Removes the end of a string. Otherwise fails."""
if not text.endswith(suffix):
raise UnableToStripEnd.get_exception(text, suffix)
return text[:len(text)-len(suffix)]
</code></pre>
| 0 | 2016-09-28T15:59:55Z | [
"python",
"string"
] |
Configure pyflakes to work with Zope's "script (python)" objects on the filesystem | 1,038,863 | <p>When I run pyflakes on a Zope Filesystem Directory View file (as are found a lot in plone) it always returns lots of warnings that my parameters and special values like 'context' are not defined, which would be true if it were a real python script, but for a Filesystem Directory View script, they are defined by magic comments at the top, for example:</p>
<pre><code>## Python Script "Name"
##bind container=container
##bind context=context
##bind namespace=
##bind script=script
##bind subpath=traverse_subpath
##parameters=foo, bar, baz
##
from AccessControl import getSecurityManager
user = getSecurityManager().getUser()
from Products.PythonScripts.standard import html_quote
request = container.REQUEST
RESPONSE = request.RESPONSE
return foo + bar + baz
</code></pre>
<p>Is this kind of python used anywhere except Zope?</p>
<p>Is it, or can it be supported by pyflakes, pylint or similar tools?</p>
| 3 | 2009-06-24T14:51:02Z | 1,039,003 | <p>No, that kind of python is not used anywhere except Zope, and in fact almost exclusively in Plone nowadays. And the Plone community is moving away from it because it has many drawbacks, this being one of them.</p>
<p>Pyflakes isn't very configurable, at least not in a documented way. Pylint can be configured to skip some error messages, but the ones you need to skip would be the ones that are most useful, so that is probably not helpful either.</p>
<p>So the short answer is: No you can't syntax check them. On the other hand you don't need to restart the server to run them, so the syntax check won't save you that much time, which it will with other Python code in the Zope world.</p>
| 1 | 2009-06-24T15:13:49Z | [
"python",
"zope"
] |
Configure pyflakes to work with Zope's "script (python)" objects on the filesystem | 1,038,863 | <p>When I run pyflakes on a Zope Filesystem Directory View file (as are found a lot in plone) it always returns lots of warnings that my parameters and special values like 'context' are not defined, which would be true if it were a real python script, but for a Filesystem Directory View script, they are defined by magic comments at the top, for example:</p>
<pre><code>## Python Script "Name"
##bind container=container
##bind context=context
##bind namespace=
##bind script=script
##bind subpath=traverse_subpath
##parameters=foo, bar, baz
##
from AccessControl import getSecurityManager
user = getSecurityManager().getUser()
from Products.PythonScripts.standard import html_quote
request = container.REQUEST
RESPONSE = request.RESPONSE
return foo + bar + baz
</code></pre>
<p>Is this kind of python used anywhere except Zope?</p>
<p>Is it, or can it be supported by pyflakes, pylint or similar tools?</p>
| 3 | 2009-06-24T14:51:02Z | 1,041,571 | <p>A possible approach I just tried is to pre-process the zope fspython script so that it is vaild. I've used a few calls to sed (below):</p>
<pre><code>#!/bin/bash
sed "s/\(^[^#]\)/ \1/" $1 | \
sed "s/^##bind [a-z]*=\([a-z][a-z]*\)$/import \1/" | \
sed "s/^##parameters=\(.*\)/def foo(\1):/" | pyflakes
</code></pre>
<p>It would be good to replace this with a python script that wraps around pyflakes and doesn't alter normal python scripts.</p>
| 2 | 2009-06-25T00:02:24Z | [
"python",
"zope"
] |
When reading a socket in python, is there any difference between os.read and socket.recv? | 1,039,462 | <p>Suppose I have a socket. What is the difference between these two lines of code?</p>
<p><strong>line 1:</strong></p>
<pre><code>os.read(some_socket.fileno(), 1024)
</code></pre>
<p><strong>line 2:</strong></p>
<pre><code>some_socket.recv(1024)
</code></pre>
<p>...other than the fact that the first one doesn't work on Windows. In other words, can I substitute the second line for the first one? I've got a codebase that hasn't really been tested with Windows, and this is causing trouble.</p>
| 2 | 2009-06-24T16:30:35Z | 1,039,486 | <p>line 1 uses the underlining file descriptor to read the socket, so it is platform-dependant. Use line 2, since it is a portable, multi-platform way of accomplishing the same thing.</p>
<p>Obligatory: If you're doing anything serious, it's better to avoid having to deal with low-level sockets. They are hard to get right, it may seem things are working but there are many details. Those details are already solved in many networking frameworks and there's no reason to reinvent the wheel. I suggest <a href="http://twistedmatrix.com/" rel="nofollow">twisted</a>, it is pretty good.</p>
| 6 | 2009-06-24T16:34:35Z | [
"python",
"windows",
"sockets",
"tcp"
] |
Remove all files in a directory | 1,039,711 | <p>Trying to remove all of the files in a certain directory gives me the follwing error:</p>
<pre><code>OSError: [Errno 2] No such file or directory: '/home/me/test/*'
</code></pre>
<p>The code I'm running is:</p>
<pre><code>import os
test = "/home/me/test/*"
os.remove(test)
</code></pre>
| 18 | 2009-06-24T17:12:19Z | 1,039,724 | <p>os.remove will only remove a single file.</p>
<p>In order to remove with wildcards, you'll need to write your own routine that handles this.</p>
<p>There are <a href="http://forums.devshed.com/python-programming-11/deleting-files-with-python-108565.html" rel="nofollow">quite a few suggested approaches</a> listed on this forum page.</p>
| 0 | 2009-06-24T17:17:04Z | [
"python",
"unix"
] |
Remove all files in a directory | 1,039,711 | <p>Trying to remove all of the files in a certain directory gives me the follwing error:</p>
<pre><code>OSError: [Errno 2] No such file or directory: '/home/me/test/*'
</code></pre>
<p>The code I'm running is:</p>
<pre><code>import os
test = "/home/me/test/*"
os.remove(test)
</code></pre>
| 18 | 2009-06-24T17:12:19Z | 1,039,737 | <p>os.remove() does not work on a directory, and os.rmdir() will only work on an empty directory.</p>
<p>You can use shutil.rmtree() to do this, however.</p>
| 23 | 2009-06-24T17:19:30Z | [
"python",
"unix"
] |
Remove all files in a directory | 1,039,711 | <p>Trying to remove all of the files in a certain directory gives me the follwing error:</p>
<pre><code>OSError: [Errno 2] No such file or directory: '/home/me/test/*'
</code></pre>
<p>The code I'm running is:</p>
<pre><code>import os
test = "/home/me/test/*"
os.remove(test)
</code></pre>
| 18 | 2009-06-24T17:12:19Z | 1,039,744 | <p>Because the * is a shell construct. Python is literally looking for a file named "*" in the directory /home/me/test. Use listdir to get a list of the files first and then call remove on each one.</p>
| 7 | 2009-06-24T17:20:59Z | [
"python",
"unix"
] |
Remove all files in a directory | 1,039,711 | <p>Trying to remove all of the files in a certain directory gives me the follwing error:</p>
<pre><code>OSError: [Errno 2] No such file or directory: '/home/me/test/*'
</code></pre>
<p>The code I'm running is:</p>
<pre><code>import os
test = "/home/me/test/*"
os.remove(test)
</code></pre>
| 18 | 2009-06-24T17:12:19Z | 1,039,747 | <p>os.remove doesn't resolve unix-style patterns. If you are on a unix-like system you can:</p>
<pre><code>os.system('rm '+test)
</code></pre>
<p>Else you can:</p>
<pre><code>import glob, os
test = '/path/*'
r = glob.glob(test)
for i in r:
os.remove(i)
</code></pre>
| 6 | 2009-06-24T17:22:31Z | [
"python",
"unix"
] |
Remove all files in a directory | 1,039,711 | <p>Trying to remove all of the files in a certain directory gives me the follwing error:</p>
<pre><code>OSError: [Errno 2] No such file or directory: '/home/me/test/*'
</code></pre>
<p>The code I'm running is:</p>
<pre><code>import os
test = "/home/me/test/*"
os.remove(test)
</code></pre>
| 18 | 2009-06-24T17:12:19Z | 1,039,748 | <p>star is expanded by Unix shell. Your call is not accessing shell, it's merely trying to remove a file with the name ending with the star</p>
| 1 | 2009-06-24T17:22:37Z | [
"python",
"unix"
] |
Remove all files in a directory | 1,039,711 | <p>Trying to remove all of the files in a certain directory gives me the follwing error:</p>
<pre><code>OSError: [Errno 2] No such file or directory: '/home/me/test/*'
</code></pre>
<p>The code I'm running is:</p>
<pre><code>import os
test = "/home/me/test/*"
os.remove(test)
</code></pre>
| 18 | 2009-06-24T17:12:19Z | 1,041,871 | <p>official document of os.walk does have a demo :)</p>
<p><a href="http://docs.python.org/library/os.html#os.walk" rel="nofollow">http://docs.python.org/library/os.html#os.walk</a></p>
| 2 | 2009-06-25T02:10:38Z | [
"python",
"unix"
] |
Remove all files in a directory | 1,039,711 | <p>Trying to remove all of the files in a certain directory gives me the follwing error:</p>
<pre><code>OSError: [Errno 2] No such file or directory: '/home/me/test/*'
</code></pre>
<p>The code I'm running is:</p>
<pre><code>import os
test = "/home/me/test/*"
os.remove(test)
</code></pre>
| 18 | 2009-06-24T17:12:19Z | 1,042,167 | <p>shutil.rmtree() for most cases. But it doesn't work for in Windows for readonly files. For windows import win32api and win32con modules from PyWin32.</p>
<pre><code>def rmtree(dirname):
retry = True
while retry:
retry = False
try:
shutil.rmtree(dirname)
except exceptions.WindowsError, e:
if e.winerror == 5: # No write permission
win32api.SetFileAttributes(dirname, win32con.FILE_ATTRIBUTE_NORMAL)
retry = True
</code></pre>
| 0 | 2009-06-25T04:19:54Z | [
"python",
"unix"
] |
Remove all files in a directory | 1,039,711 | <p>Trying to remove all of the files in a certain directory gives me the follwing error:</p>
<pre><code>OSError: [Errno 2] No such file or directory: '/home/me/test/*'
</code></pre>
<p>The code I'm running is:</p>
<pre><code>import os
test = "/home/me/test/*"
os.remove(test)
</code></pre>
| 18 | 2009-06-24T17:12:19Z | 14,613,399 | <p>Another way I've done this:</p>
<pre><code>os.popen('rm -f ./yourdir')
</code></pre>
| 6 | 2013-01-30T20:44:43Z | [
"python",
"unix"
] |
Remove all files in a directory | 1,039,711 | <p>Trying to remove all of the files in a certain directory gives me the follwing error:</p>
<pre><code>OSError: [Errno 2] No such file or directory: '/home/me/test/*'
</code></pre>
<p>The code I'm running is:</p>
<pre><code>import os
test = "/home/me/test/*"
os.remove(test)
</code></pre>
| 18 | 2009-06-24T17:12:19Z | 24,844,846 | <p>Please see my answer here:</p>
<p><a href="http://stackoverflow.com/a/24844618/2293304">http://stackoverflow.com/a/24844618/2293304</a></p>
<p>It's a long and ugly, but reliable and efficient solution.</p>
<p>It resolves a few problems which are not addressed by the other answerers:</p>
<ul>
<li>It correctly handles symbolic links, including not calling <code>shutil.rmtree()</code> on a symbolic link (which will pass the <code>os.path.isdir()</code> test if it links to a directory).</li>
<li>It handles read-only files nicely.</li>
</ul>
| 0 | 2014-07-19T20:48:54Z | [
"python",
"unix"
] |
Remove all files in a directory | 1,039,711 | <p>Trying to remove all of the files in a certain directory gives me the follwing error:</p>
<pre><code>OSError: [Errno 2] No such file or directory: '/home/me/test/*'
</code></pre>
<p>The code I'm running is:</p>
<pre><code>import os
test = "/home/me/test/*"
os.remove(test)
</code></pre>
| 18 | 2009-06-24T17:12:19Z | 28,965,973 | <pre><code>#python 2.7
import tempfile
import shutil
import exceptions
import os
def TempCleaner():
temp_dir_name = tempfile.gettempdir()
for currentdir in os.listdir(temp_dir_name):
try:
shutil.rmtree(os.path.join(temp_dir_name, currentdir))
except exceptions.WindowsError, e:
print u'Ðе ÑдалоÑÑ ÑдалиÑÑ:'+ e.filename
</code></pre>
| 0 | 2015-03-10T14:10:38Z | [
"python",
"unix"
] |
Remove all files in a directory | 1,039,711 | <p>Trying to remove all of the files in a certain directory gives me the follwing error:</p>
<pre><code>OSError: [Errno 2] No such file or directory: '/home/me/test/*'
</code></pre>
<p>The code I'm running is:</p>
<pre><code>import os
test = "/home/me/test/*"
os.remove(test)
</code></pre>
| 18 | 2009-06-24T17:12:19Z | 37,215,944 | <p>Although this is an old question, I think none has already answered using this approach:</p>
<pre><code>#python 2.7
import os
filesToRemove = [f for f in os.listdir('/home/me/test')]
os.remove(f) for f in files
</code></pre>
| 0 | 2016-05-13T17:24:56Z | [
"python",
"unix"
] |
Crunching json with python | 1,039,877 | <p>Echoing my <a href="http://stackoverflow.com/questions/667359/crunching-xml-with-python">other question</a> now need to find a way to crunch json down to one line: e.g.</p>
<pre><code>{"node0":{
"node1":{
"attr0":"foo",
"attr1":"foo bar",
"attr2":"value with long spaces"
}
}}
</code></pre>
<p>would like to crunch down to a single line:</p>
<pre><code>{"node0":{"node1":{"attr0":"foo","attr1":"foo bar","attr2":"value with long spaces"}}}
</code></pre>
<p>by removing insignificant white spaces and preserving the ones that are within the value. Is there a library to do this in python?</p>
<p><b>EDIT</b>
Thank you both drdaeman and Eli Courtwright for super quick response!</p>
| 9 | 2009-06-24T17:47:58Z | 1,039,897 | <p><a href="http://docs.python.org/library/json.html">http://docs.python.org/library/json.html</a></p>
<pre><code>>>> import json
>>> json.dumps(json.loads("""
... {"node0":{
... "node1":{
... "attr0":"foo",
... "attr1":"foo bar",
... "attr2":"value with long spaces"
... }
... }}
... """))
'{"node0": {"node1": {"attr2": "value with long spaces", "attr0": "foo", "attr1": "foo bar"}}}'
</code></pre>
| 14 | 2009-06-24T17:51:22Z | [
"python",
"json",
"parsing"
] |
Crunching json with python | 1,039,877 | <p>Echoing my <a href="http://stackoverflow.com/questions/667359/crunching-xml-with-python">other question</a> now need to find a way to crunch json down to one line: e.g.</p>
<pre><code>{"node0":{
"node1":{
"attr0":"foo",
"attr1":"foo bar",
"attr2":"value with long spaces"
}
}}
</code></pre>
<p>would like to crunch down to a single line:</p>
<pre><code>{"node0":{"node1":{"attr0":"foo","attr1":"foo bar","attr2":"value with long spaces"}}}
</code></pre>
<p>by removing insignificant white spaces and preserving the ones that are within the value. Is there a library to do this in python?</p>
<p><b>EDIT</b>
Thank you both drdaeman and Eli Courtwright for super quick response!</p>
| 9 | 2009-06-24T17:47:58Z | 1,039,900 | <p>In Python 2.6:</p>
<pre><code>import json
print json.loads( json_string )
</code></pre>
<p>Basically, when you use the json module to parse json, then you get a Python dict. If you simply print a dict and/or convert it to a string, it'll all be on one line. Of course, in some cases the Python dict will be slightly different than the json-encoded string (such as with booleans and nulls), so if this matters then you can say</p>
<pre><code>import json
print json.dumps( json.loads(json_string) )
</code></pre>
<p>If you don't have Python 2.6 then you can use <a href="http://pypi.python.org/pypi/simplejson/" rel="nofollow">the simplejson module</a>. In this case you'd simply say </p>
<pre><code>import simplejson
print simplejson.loads( json_string )
</code></pre>
| 1 | 2009-06-24T17:51:46Z | [
"python",
"json",
"parsing"
] |
reading a configuration information only once in Python | 1,040,135 | <p>I'm using the ConfigParser to read the configuration information stored in a file. I'm able to read the content and use it across other modules in the project. I'm not sure if the configuration file is read every time I call config.get(parameters). How can I make sure that the configuration information is read only once and rest of the time its read from the cache. </p>
| 1 | 2009-06-24T18:36:42Z | 1,040,169 | <p>I would try assigning the configuration to a variable.</p>
<p>configVariable = config.get(parameters)</p>
<p>Then you can pass the configuration variable to other modules as necessary.</p>
| 2 | 2009-06-24T18:42:08Z | [
"python",
"oop"
] |
reading a configuration information only once in Python | 1,040,135 | <p>I'm using the ConfigParser to read the configuration information stored in a file. I'm able to read the content and use it across other modules in the project. I'm not sure if the configuration file is read every time I call config.get(parameters). How can I make sure that the configuration information is read only once and rest of the time its read from the cache. </p>
| 1 | 2009-06-24T18:36:42Z | 1,040,180 | <p>This isn't my answer, but user <strong>gimel</strong> came with this nifty solution: <a href="http://stackoverflow.com/questions/990867/closing-file-opened-by-configparser/990927#990927">click</a> </p>
<p>(You can check whole question pointed by this link, it is very similar to Yours.)</p>
| 0 | 2009-06-24T18:44:38Z | [
"python",
"oop"
] |
reading a configuration information only once in Python | 1,040,135 | <p>I'm using the ConfigParser to read the configuration information stored in a file. I'm able to read the content and use it across other modules in the project. I'm not sure if the configuration file is read every time I call config.get(parameters). How can I make sure that the configuration information is read only once and rest of the time its read from the cache. </p>
| 1 | 2009-06-24T18:36:42Z | 1,040,220 | <p>The default implementation of the ConfigParser class reads its data only once. </p>
| 1 | 2009-06-24T18:51:41Z | [
"python",
"oop"
] |
Disable Python return statement from printing object it returns | 1,040,285 | <p>I want to disable "return" from printing any object it is returning to python shell.</p>
<p>e.g A sample python script test.py looks like:</p>
<pre><code>def func1():
list = [1,2,3,4,5]
print list
return list
</code></pre>
<p>Now, If i do following: </p>
<pre><code>python -i test.py
>>>func1()
</code></pre>
<p>This always give me two prints on python shell.
I just want to print and get returned object.</p>
| 2 | 2009-06-24T19:03:18Z | 1,040,315 | <p>There's no way to configure the Python shell suppress printing the return values of function calls. However, if you assign the returned value to a variable, then it won't get printed. For example, if you say</p>
<pre><code>rv = func1()
</code></pre>
<p>instead of</p>
<pre><code>func1()
</code></pre>
<p>then nothing will get printed.</p>
| 3 | 2009-06-24T19:07:58Z | [
"python"
] |
Disable Python return statement from printing object it returns | 1,040,285 | <p>I want to disable "return" from printing any object it is returning to python shell.</p>
<p>e.g A sample python script test.py looks like:</p>
<pre><code>def func1():
list = [1,2,3,4,5]
print list
return list
</code></pre>
<p>Now, If i do following: </p>
<pre><code>python -i test.py
>>>func1()
</code></pre>
<p>This always give me two prints on python shell.
I just want to print and get returned object.</p>
| 2 | 2009-06-24T19:03:18Z | 1,040,369 | <p>The reason for the print is not the return statement, but the shell itself. The shell does print any object that is a result of an operation on the command line.</p>
<p>Thats the reason this happens:</p>
<pre><code>>>> a = 'hallo'
>>> a
'hallo'
</code></pre>
<p>The last statement has the value of a as result (since it is not assigned to anything else). So it is printed by the shell.</p>
<p>The problem is not "return" but the shell itself. But that is not a problem, since working code normaly is not executed in the interactive shell (thus, nothing is printed). Thus, no problem.</p>
| 9 | 2009-06-24T19:16:56Z | [
"python"
] |
Disable Python return statement from printing object it returns | 1,040,285 | <p>I want to disable "return" from printing any object it is returning to python shell.</p>
<p>e.g A sample python script test.py looks like:</p>
<pre><code>def func1():
list = [1,2,3,4,5]
print list
return list
</code></pre>
<p>Now, If i do following: </p>
<pre><code>python -i test.py
>>>func1()
</code></pre>
<p>This always give me two prints on python shell.
I just want to print and get returned object.</p>
| 2 | 2009-06-24T19:03:18Z | 1,040,379 | <p>In general, printing from within a function, and then returning the value, isn't a great idea.</p>
<p>In fact, printing within a function is most often the wrong thing. Most often functions get called several times in a program. Sometimes you want to print the value, most often you just want to use that data for something.</p>
<p>Let the function just return it's value. Let the code that called the function print it out, if that is the right thing to do.</p>
| 5 | 2009-06-24T19:18:23Z | [
"python"
] |
Disable Python return statement from printing object it returns | 1,040,285 | <p>I want to disable "return" from printing any object it is returning to python shell.</p>
<p>e.g A sample python script test.py looks like:</p>
<pre><code>def func1():
list = [1,2,3,4,5]
print list
return list
</code></pre>
<p>Now, If i do following: </p>
<pre><code>python -i test.py
>>>func1()
</code></pre>
<p>This always give me two prints on python shell.
I just want to print and get returned object.</p>
| 2 | 2009-06-24T19:03:18Z | 1,040,432 | <p>If you don't want it to show the value, then assign the result of the function to a variable:</p>
<pre><code>H:\test>copy con test.py
def func1():
list = [1,2,3,4,5]
print list
return list
^Z
1 file(s) copied.
H:\test>python -i test.py
>>> func1()
[1, 2, 3, 4, 5]
[1, 2, 3, 4, 5]
>>> x = func1() # assign result to a variable to suppress auto printout
[1, 2, 3, 4, 5]
>>>
</code></pre>
| 0 | 2009-06-24T19:26:53Z | [
"python"
] |
Python "Event" equivalent in Java? | 1,040,818 | <p>What's the closest thing in Java (perhaps an idiom) to <a href="http://docs.python.org/library/threading.html#event-objects">threading.Event</a> in Python?</p>
| 5 | 2009-06-24T20:32:52Z | 1,040,821 | <p>The <a href="http://java.sun.com/javase/6/docs/api/java/lang/Object.html#wait%28%29" rel="nofollow"><code>Object.wait()</code></a> <a href="http://java.sun.com/javase/6/docs/api/java/lang/Object.html#notify%28%29" rel="nofollow"><code>Object.notify()</code></a>/<a href="http://java.sun.com/javase/6/docs/api/java/lang/Object.html#notifyAll%28%29" rel="nofollow"><code>Object.notifyAll()</code></a>.</p>
<p>Or <a href="http://java.sun.com/javase/6/docs/api/java/util/concurrent/locks/Condition.html#await%28%29" rel="nofollow"><code>Condition.await()</code></a> and <a href="http://java.sun.com/javase/6/docs/api/java/util/concurrent/locks/Condition.html#signal%28%29" rel="nofollow"><code>Condition.signal()</code></a>/<a href="http://java.sun.com/javase/6/docs/api/java/util/concurrent/locks/Condition.html#signalAll%28%29" rel="nofollow"><code>Condition.signalAll()</code></a> for Java 5+.</p>
<p><strong>Edit:</strong> Because the python specification is similar how we usually wait a Java implementation would look like this:</p>
<pre><code>class Event {
Lock lock = new ReentrantLock();
Condition cond = lock.newCondition();
boolean flag;
public void doWait() throws InterruptedException {
lock.lock();
try {
while (!flag) {
cond.await();
}
} finally {
lock.unlock();
}
}
public void doWait(float seconds) throws InterruptedException {
lock.lock();
try {
while (!flag) {
cond.await((int)(seconds * 1000), TimeUnit.MILLISECONDS);
}
} finally {
lock.unlock();
}
}
public boolean isSet() {
lock.lock();
try {
return flag;
} finally {
lock.unlock();
}
}
public void set() {
lock.lock();
try {
flag = true;
cond.signalAll();
} finally {
lock.unlock();
}
}
public void clear() {
lock.lock();
try {
flag = false;
cond.signalAll();
} finally {
lock.unlock();
}
}
}
</code></pre>
| 7 | 2009-06-24T20:34:07Z | [
"java",
"python",
"multithreading"
] |
Python "Event" equivalent in Java? | 1,040,818 | <p>What's the closest thing in Java (perhaps an idiom) to <a href="http://docs.python.org/library/threading.html#event-objects">threading.Event</a> in Python?</p>
| 5 | 2009-06-24T20:32:52Z | 1,041,112 | <p>A <a href="http://stackoverflow.com/questions/226455/can-anyone-explain-thread-monitors-and-wait">related thread</a>. There is a comment on the accepted answer which suggests a <a href="http://java.sun.com/javase/6/docs/api/java/util/concurrent/Semaphore.html" rel="nofollow">Semaphore</a> or a <a href="http://java.sun.com/javase/6/docs/api/java/util/concurrent/CountDownLatch.html" rel="nofollow">Latch</a>. Not the same semantics as the above implementation, but handy.</p>
| 0 | 2009-06-24T21:30:38Z | [
"java",
"python",
"multithreading"
] |
DJANGO - How do you access the current model instance from inside a form | 1,040,887 | <pre><code>class EditAdminForm(forms.ModelForm):
password = username.CharField(widget=forms.TextInput())
password = forms.CharField(widget=forms.PasswordInput())
password_confirm = forms.CharField(widget=forms.PasswordInput(), initial=???)
</code></pre>
<p>You can see what I'm trying to do here. How would I go about pre-populating the pasword_confirm field (which is not part of the model). I'm so confused.</p>
| 0 | 2009-06-24T20:46:37Z | 1,041,169 | <p>You can define <code>__init__</code> method in EditAdminForm.</p>
<p>something like:</p>
<pre><code>class EditAdminForm(forms.ModelForm):
username = forms.CharField(widget=forms.TextInput())
password = forms.CharField(widget=forms.PasswordInput())
def __init__(self, initial_from, data=None, initial=None)
sefl.fields['password_confirm'] = forms.CharField(widget=forms.PasswordInput(), initial=initial_from)
</code></pre>
| 0 | 2009-06-24T21:46:28Z | [
"python",
"django",
"model",
"instance"
] |
DJANGO - How do you access the current model instance from inside a form | 1,040,887 | <pre><code>class EditAdminForm(forms.ModelForm):
password = username.CharField(widget=forms.TextInput())
password = forms.CharField(widget=forms.PasswordInput())
password_confirm = forms.CharField(widget=forms.PasswordInput(), initial=???)
</code></pre>
<p>You can see what I'm trying to do here. How would I go about pre-populating the pasword_confirm field (which is not part of the model). I'm so confused.</p>
| 0 | 2009-06-24T20:46:37Z | 1,042,422 | <p>You can't access the instance in the form declaration, because there isn't one until you instantiate it.</p>
<p>However, if all you want to do is set dynamic initial data, do this with the <code>initial</code> parameter on instantation:</p>
<pre><code>form = EditAdminForm(initial={'password':'abcdef'})
</code></pre>
| 2 | 2009-06-25T06:29:53Z | [
"python",
"django",
"model",
"instance"
] |
Unable to make a factorial function in Python | 1,041,348 | <p><strong>My code</strong></p>
<pre><code>import sys
number=int(sys.argv[1])
if number == 0
fact=1
else
fact=number
for (x=1; x<number; x++)
fact*=x; // mistake probably here
print fact
</code></pre>
<p>I get the error</p>
<pre><code>File "factorial.py", line 5
if number == 0
^
SyntaxError: invalid syntax
</code></pre>
<p><strong>How can you make a factorial function in Python?</strong></p>
| 0 | 2009-06-24T22:29:36Z | 1,041,370 | <p>The line that your error is on should read</p>
<pre><code>if number == 0:
</code></pre>
<p>Note the colon on the end.</p>
<p>Additionally, you would need to add the same colon after the else and the for. The colons work similarly to {} in other languages.</p>
<p>Finally, thats not how for loops work in Python. The code you want to use that list would be</p>
<pre><code>for x in range(1,number):
</code></pre>
<p>Which would have the same effect of what you wrote, if you put that in a C style language.</p>
<p>EDIT: Oops, the for loop I gave was wrong, it would have included 0. I updated the code to correct this.</p>
| 12 | 2009-06-24T22:38:44Z | [
"python",
"factorial"
] |
Unable to make a factorial function in Python | 1,041,348 | <p><strong>My code</strong></p>
<pre><code>import sys
number=int(sys.argv[1])
if number == 0
fact=1
else
fact=number
for (x=1; x<number; x++)
fact*=x; // mistake probably here
print fact
</code></pre>
<p>I get the error</p>
<pre><code>File "factorial.py", line 5
if number == 0
^
SyntaxError: invalid syntax
</code></pre>
<p><strong>How can you make a factorial function in Python?</strong></p>
| 0 | 2009-06-24T22:29:36Z | 1,041,375 | <p>Here's your code, fixed up and working:</p>
<pre><code>import sys
number = int(sys.argv[1])
fact = 1
for x in range(1, number+1):
fact *= x
print fact
</code></pre>
<p>(Factorial zero is one, for anyone who didn't know - I had to look it up. 8-)</p>
<p>You need colons after <code>if</code>, <code>else</code>, <code>for</code>, etc., and the way <code>for</code> works in Python is different from C.</p>
| 8 | 2009-06-24T22:40:43Z | [
"python",
"factorial"
] |
Unable to make a factorial function in Python | 1,041,348 | <p><strong>My code</strong></p>
<pre><code>import sys
number=int(sys.argv[1])
if number == 0
fact=1
else
fact=number
for (x=1; x<number; x++)
fact*=x; // mistake probably here
print fact
</code></pre>
<p>I get the error</p>
<pre><code>File "factorial.py", line 5
if number == 0
^
SyntaxError: invalid syntax
</code></pre>
<p><strong>How can you make a factorial function in Python?</strong></p>
| 0 | 2009-06-24T22:29:36Z | 1,041,398 | <p>Here's a functional factorial, which you almost asked for:</p>
<pre><code>>>> def fact(n): return reduce (lambda x,y: x*y, range(1,n+1))
...
>>> fact(5)
120
</code></pre>
<p>It doesn't work for fact(0), but you can worry about that outside the scope of <code>fact</code> :)</p>
<p><hr></p>
<p>Masi has asked whether the functional style is more efficient than Richie's implementation. According to my quick benchmark (and to my surprise!) yes, mine is faster. But there's a couple things we can do to change.</p>
<p>First, we can substitute <code>lambda x,y: x*y</code> with <code>operator.mul</code> as suggested in another comment. Python's <code>lambda</code> operator comes with a not-insignificant overhead. Second, we can substitute <code>xrange</code> for <code>range</code>. <code>xrange</code> should work in linear space, returning numbers as necessary, while <code>range</code> creates the whole list all at once. (Note then, that you almost certainly must use <code>xrange</code> for an excessively large range of numbers)</p>
<p>So the new definition becomes:</p>
<pre><code>>>> import operator
>>> def fact2(n): return reduce(operator.mul, xrange(1,n+1))
...
>>> fact2(5)
120
</code></pre>
<p>To my surprise, this actually resulted in slower performance. Here's the Q&D benchmarks:</p>
<pre><code>>>> def fact(n): return (lambda x,y: x*y, range(1,n+1))
...
>>> t1 = Timer("fact(500)", "from __main__ import fact")
>>> print t1.timeit(number = 500)
0.00656795501709
>>> def fact2(n): return reduce(operator.mul, xrange(1,n+1))
...
>>> t2 = Timer("fact2(500)", "from __main__ import fact2")
>>> print t2.timeit(number = 500)
0.35856294632
>>> def fact3(n): return reduce(operator.mul, range(1,n+1))
...
>>> t3 = Timer("fact3(500)", "from __main__ import fact3")
>>> print t3.timeit(number = 500)
0.354646205902
>>> def fact4(n): return reduce(lambda x,y: x*y, xrange(1,n+1))
...
>>> t4 = Timer("fact4(500)", "from __main__ import fact4")
>>> print t4.timeit(number = 500)
0.479015111923
>>> def fact5(n):
... x = 1
... for i in range(1, n+1):
... x *= i
... return x
...
>>> t5 = Timer("fact5(500)", "from __main__ import fact5")
>>> print t5.timeit(number = 500)
0.388549804688
</code></pre>
<p>Here's my Python version in case anyone wants to cross-check my results:</p>
<pre><code>Python 2.6.2 (release26-maint, Apr 19 2009, 01:56:41)
[GCC 4.3.3] on linux2
</code></pre>
| 2 | 2009-06-24T22:51:24Z | [
"python",
"factorial"
] |
Unable to make a factorial function in Python | 1,041,348 | <p><strong>My code</strong></p>
<pre><code>import sys
number=int(sys.argv[1])
if number == 0
fact=1
else
fact=number
for (x=1; x<number; x++)
fact*=x; // mistake probably here
print fact
</code></pre>
<p>I get the error</p>
<pre><code>File "factorial.py", line 5
if number == 0
^
SyntaxError: invalid syntax
</code></pre>
<p><strong>How can you make a factorial function in Python?</strong></p>
| 0 | 2009-06-24T22:29:36Z | 1,041,719 | <p>A correct implementation of fact (returning 1 for fact(0)) is as follow:</p>
<pre><code>def fact(n): return reduce(operator.mul, xrange(2,n+1), 1)
</code></pre>
<p>This is slightly faster (1.18 time faster) than the more readable </p>
<pre><code>def fact1(n):
x = 1
for i in xrange(2,n+1):
x*=i
return x
</code></pre>
<p>P.S: the one can be skipped in both iterations because multiplying by one does not change the value</p>
<p>P.P.S: After timing, math.factorial seems slower than reduce:</p>
<pre><code>>>> t1 = Timer("factorial(1000)", "from math import factorial")
>>> t1.timeit(number=1000)
0.8635700906120749
>>> def fact(n): return reduce(operator.mul, xrange(2,n+1), 1)
>>> t2 = Timer("fact(1000)", 'from __main__ import fact')
>>> t2.timeit(number=1000)
0.78937295103149552
</code></pre>
<p>The tests were done with python 2.6.2 on win32. </p>
<p>But I agree that the speed-up is probably not sufficient to justify writing your own factorial and math.factorial do some error checking (input must be a non negative integer)</p>
| 0 | 2009-06-25T01:08:53Z | [
"python",
"factorial"
] |
Unable to make a factorial function in Python | 1,041,348 | <p><strong>My code</strong></p>
<pre><code>import sys
number=int(sys.argv[1])
if number == 0
fact=1
else
fact=number
for (x=1; x<number; x++)
fact*=x; // mistake probably here
print fact
</code></pre>
<p>I get the error</p>
<pre><code>File "factorial.py", line 5
if number == 0
^
SyntaxError: invalid syntax
</code></pre>
<p><strong>How can you make a factorial function in Python?</strong></p>
| 0 | 2009-06-24T22:29:36Z | 1,041,755 | <p>I understand that you are probably trying to implement this yourself for educational reasons.</p>
<p>However, if not, I recommend using the <code>math</code> modules built-in factorial function (note: requires python 2.6 or higher):</p>
<pre><code>>>> import math
>>> math.factorial(5)
120
</code></pre>
<p>This module is written in C, and as such, it'll be much much faster than writing it in python. (although, if you aren't computing large factorials, it won't really be too slow either way).</p>
| 9 | 2009-06-25T01:25:10Z | [
"python",
"factorial"
] |
Unable to make a factorial function in Python | 1,041,348 | <p><strong>My code</strong></p>
<pre><code>import sys
number=int(sys.argv[1])
if number == 0
fact=1
else
fact=number
for (x=1; x<number; x++)
fact*=x; // mistake probably here
print fact
</code></pre>
<p>I get the error</p>
<pre><code>File "factorial.py", line 5
if number == 0
^
SyntaxError: invalid syntax
</code></pre>
<p><strong>How can you make a factorial function in Python?</strong></p>
| 0 | 2009-06-24T22:29:36Z | 3,881,733 | <p>The reason Mark Rushakoff's fact(n) function was so much more efficient was that he missed-off the reduce() function. Thus it never actually did the calculation.</p>
<p>Corrected it reads (and I get):</p>
<pre><code>import operator, timeit, math
#
def fact1(n): return reduce(lambda x,y: x*y, range(1,n+1),1)
def fact1x(n): return reduce(lambda x,y: x*y, xrange(1,n+1),1)
def fact2(n): return reduce(operator.mul , range(1,n+1),1)
def fact2x(n): return reduce(operator.mul , xrange(1,n+1),1)
#
def factorialtimer():
for myfunc in [ "fact1", "fact1x", "fact2", "fact2x" ]:
mytimer = timeit.Timer(myfunc+"(1500)", "from __main__ import "+myfunc)
print("{0:15} : {1:2.6f}".format(myfunc, mytimer.timeit(number=1000)))
mytimer = timeit.Timer("factorial(1500)", "from math import factorial")
print("{0:15} : {1:2.6f}".format("math.factorial", mytimer.timeit(number=1000)))
</code></pre>
<p>Resulting output for 1500!, 1000x:</p>
<pre><code>fact1 : 3.537624
fact1x : 4.448408
fact2 : 4.390820
fact2x : 4.333070
math.factorial : 4.091470
</code></pre>
<p>And yes, I have checked they all yield the same value!
I Can't understand why the lambda xrange is so much worse than the lambda range. Hmmm.
Version:
PythonWin 2.6.2 (r262:71605, Apr 14 2009, 22:40:02) [MSC v.1500 32 bit (Intel)] on win32.</p>
<p>Hmm... on re-running it I get something more believable</p>
<pre><code>fact1 : 7.771696
fact1x : 7.799568
fact2 : 7.056820
fact2x : 7.247851
math.factorial : 6.875827
</code></pre>
<p>And on Python 2.6.5 (r265:79063, Jun 12 2010, 17:07:01) [GCC 4.3.4 20090804 (release) 1] on cygwin:</p>
<pre><code>fact1 : 6.547000
fact1x : 6.411000
fact2 : 6.068000
fact2x : 6.246000
math.factorial : 6.276000
</code></pre>
<p>All in the noise really, isn't it?</p>
| 3 | 2010-10-07T12:44:34Z | [
"python",
"factorial"
] |
Unable to make a factorial function in Python | 1,041,348 | <p><strong>My code</strong></p>
<pre><code>import sys
number=int(sys.argv[1])
if number == 0
fact=1
else
fact=number
for (x=1; x<number; x++)
fact*=x; // mistake probably here
print fact
</code></pre>
<p>I get the error</p>
<pre><code>File "factorial.py", line 5
if number == 0
^
SyntaxError: invalid syntax
</code></pre>
<p><strong>How can you make a factorial function in Python?</strong></p>
| 0 | 2009-06-24T22:29:36Z | 8,528,520 | <p>really, the simplest option would be:</p>
<pre><code>def factorial(n):
x = n
for j in range(1, n):
x = j*x
return x
</code></pre>
<p>yes, somehow, it works.</p>
<p>How could you not think of this? I don't know.</p>
<p>A <code>for</code> loop and a multiplier, really simplicity is the best way to go, right?</p>
<p>EDIT: Oh, wait, we're working for the most cpu-efficeint way? ohhhh.....</p>
| 1 | 2011-12-16T00:37:55Z | [
"python",
"factorial"
] |
Pylons is confusing: help! | 1,041,471 | <p>I'm a long-time PHP developer looking to try out Python for web development. I've used Python in the past a bit, but I'm still quite new at it.</p>
<p>I've taken a look at Pylons, and I have to say that it's extremely <em>confusing</em> to me. All the documentation I can find are just "copy and paste this" tutorials which don't seem to explain much.</p>
<p>For example, why can't controllers automatically render a specific view on a default template or something? Do I need to add a million import statements on top of every controller?</p>
<p>It's just that it feels so glued together - like there is no standardization between the components.</p>
<p>So what's the best way to learn Pylons?</p>
<p>Of course there's other options, but do you have something else to recommend? I'm not really looking for much - MVC, an ORM and some form generation would be more than enough to satisfy me.</p>
<p>I've also looked at Django, but from what I can gather, it's more of a thing suited for CMS with all the admin panels etc. than generic "web services" (or whatever the term is).</p>
| 6 | 2009-06-24T23:21:22Z | 1,041,494 | <p>If you're just exploring the wilderness, have a stronger look at Django. </p>
<p>It really has nothing to do with CMSs in the traditional sense. You create data models and yes, with a line, you can have an admin panel so you can manage your data. You <em>can</em> spin that into a traditional CMS, but that's not what it is by default.</p>
<p>I think you'll find Django's tutorials (and books) a lot more useful that the Pylons ones... Plus there's a lot more code floating around to help you out for Django.</p>
| 7 | 2009-06-24T23:32:25Z | [
"python",
"pylons"
] |
Pylons is confusing: help! | 1,041,471 | <p>I'm a long-time PHP developer looking to try out Python for web development. I've used Python in the past a bit, but I'm still quite new at it.</p>
<p>I've taken a look at Pylons, and I have to say that it's extremely <em>confusing</em> to me. All the documentation I can find are just "copy and paste this" tutorials which don't seem to explain much.</p>
<p>For example, why can't controllers automatically render a specific view on a default template or something? Do I need to add a million import statements on top of every controller?</p>
<p>It's just that it feels so glued together - like there is no standardization between the components.</p>
<p>So what's the best way to learn Pylons?</p>
<p>Of course there's other options, but do you have something else to recommend? I'm not really looking for much - MVC, an ORM and some form generation would be more than enough to satisfy me.</p>
<p>I've also looked at Django, but from what I can gather, it's more of a thing suited for CMS with all the admin panels etc. than generic "web services" (or whatever the term is).</p>
| 6 | 2009-06-24T23:21:22Z | 1,041,885 | <p>You should probably learn Python via something other than a big MVC framework first -- those frameworks will make obvious sense once you do, and won't until you have. The idioms, the modules, the functions and data types, are all simple and intuitive but there are so many of them in a framework that you will be a bit overwhelmed (as you seem to be, this happens to everyone at some point.) </p>
<p>Start a little lower down -- install a database and a module for it, like psycopg2 or MySQLdb, or the included sqlite3. Learn the basics of urllib2 and something like lxml or BeautifulSoup and get comfortable pulling data from somewhere and feeding it to your database. Make some html forms and format them with Python's own string formatting methods a few times, write them to files and poke around them in your browser. </p>
<p>Then read and reread the <a href="http://www.python.org/dev/peps/pep-0333/" rel="nofollow">Python wsgi spec</a> and actually do the examples in the Pylons documentation, simple as they may seem. Instead of "hello world", figure out a way to get your little app to do something with the url it has been given, like return a welcome page or something from your database -- a text search, whatever. Keep doing this for a few hours or days until you start wishing someone had written something that would automate the url parsing, and eliminate or minimize the SQL queries, etc., and then you will be happy about all those import statements.</p>
| 5 | 2009-06-25T02:15:09Z | [
"python",
"pylons"
] |
Pylons is confusing: help! | 1,041,471 | <p>I'm a long-time PHP developer looking to try out Python for web development. I've used Python in the past a bit, but I'm still quite new at it.</p>
<p>I've taken a look at Pylons, and I have to say that it's extremely <em>confusing</em> to me. All the documentation I can find are just "copy and paste this" tutorials which don't seem to explain much.</p>
<p>For example, why can't controllers automatically render a specific view on a default template or something? Do I need to add a million import statements on top of every controller?</p>
<p>It's just that it feels so glued together - like there is no standardization between the components.</p>
<p>So what's the best way to learn Pylons?</p>
<p>Of course there's other options, but do you have something else to recommend? I'm not really looking for much - MVC, an ORM and some form generation would be more than enough to satisfy me.</p>
<p>I've also looked at Django, but from what I can gather, it's more of a thing suited for CMS with all the admin panels etc. than generic "web services" (or whatever the term is).</p>
| 6 | 2009-06-24T23:21:22Z | 1,042,273 | <p>I am a python newbie too. I have spent the last week playing with Django, and I think you are selling it short. It seems to have sufficient power to do most of the things I want to do in web apps. The only problems I have found so far are MS Sql Server support (not there) and the lack of database evolution. Both of these are apparently solvable with addins and may not be problems for you.</p>
<p>I haven't found any problems learning python along with Django.</p>
<p>You might also want to take a look at TurboGears 2 which is built on top of pylons with extra glue. </p>
| 3 | 2009-06-25T05:07:35Z | [
"python",
"pylons"
] |
Pylons is confusing: help! | 1,041,471 | <p>I'm a long-time PHP developer looking to try out Python for web development. I've used Python in the past a bit, but I'm still quite new at it.</p>
<p>I've taken a look at Pylons, and I have to say that it's extremely <em>confusing</em> to me. All the documentation I can find are just "copy and paste this" tutorials which don't seem to explain much.</p>
<p>For example, why can't controllers automatically render a specific view on a default template or something? Do I need to add a million import statements on top of every controller?</p>
<p>It's just that it feels so glued together - like there is no standardization between the components.</p>
<p>So what's the best way to learn Pylons?</p>
<p>Of course there's other options, but do you have something else to recommend? I'm not really looking for much - MVC, an ORM and some form generation would be more than enough to satisfy me.</p>
<p>I've also looked at Django, but from what I can gather, it's more of a thing suited for CMS with all the admin panels etc. than generic "web services" (or whatever the term is).</p>
| 6 | 2009-06-24T23:21:22Z | 1,043,362 | <p>Am afraid it is because Pylons is comparatively for people who have already got a clue of Python web frameworks and how to get things done with them. This doesn't mean that Pylons is hard, but because Pylons is very flexible and allows you to choose every piece of the puzzle as you want it is not easy for someone new to the web framework arena to adapt to it. </p>
<p>You should be starting with a comparatively rigid (in terms of flexibility of module level choices) framework like Django for a start. Django also enjoys a bigger and more active community compared to Pylons, and also a wonderful documentation (Pylons' documentation is also really good) and a book on using Django.</p>
<p>And if you want to start getting accustomed to Python and developing web apps with it try a smaller barebones framework like web.py so that you could get used to the MVC model that's prevalent in most web frameworks.</p>
<p>For the CMS part, there is already some projects out there for CMS based on Django. May be you can pick one up, play with it and customize it as per your requirements.</p>
| 1 | 2009-06-25T11:13:16Z | [
"python",
"pylons"
] |
Pylons is confusing: help! | 1,041,471 | <p>I'm a long-time PHP developer looking to try out Python for web development. I've used Python in the past a bit, but I'm still quite new at it.</p>
<p>I've taken a look at Pylons, and I have to say that it's extremely <em>confusing</em> to me. All the documentation I can find are just "copy and paste this" tutorials which don't seem to explain much.</p>
<p>For example, why can't controllers automatically render a specific view on a default template or something? Do I need to add a million import statements on top of every controller?</p>
<p>It's just that it feels so glued together - like there is no standardization between the components.</p>
<p>So what's the best way to learn Pylons?</p>
<p>Of course there's other options, but do you have something else to recommend? I'm not really looking for much - MVC, an ORM and some form generation would be more than enough to satisfy me.</p>
<p>I've also looked at Django, but from what I can gather, it's more of a thing suited for CMS with all the admin panels etc. than generic "web services" (or whatever the term is).</p>
| 6 | 2009-06-24T23:21:22Z | 1,043,954 | <p>Have you looked at the <a href="http://pylonsbook.com/" rel="nofollow">Pylons book</a>? I think it does a much better job documenting and explaining how Pylons works. If you are really interested in Pylons, I'd start there.</p>
| 9 | 2009-06-25T13:32:03Z | [
"python",
"pylons"
] |
Pylons is confusing: help! | 1,041,471 | <p>I'm a long-time PHP developer looking to try out Python for web development. I've used Python in the past a bit, but I'm still quite new at it.</p>
<p>I've taken a look at Pylons, and I have to say that it's extremely <em>confusing</em> to me. All the documentation I can find are just "copy and paste this" tutorials which don't seem to explain much.</p>
<p>For example, why can't controllers automatically render a specific view on a default template or something? Do I need to add a million import statements on top of every controller?</p>
<p>It's just that it feels so glued together - like there is no standardization between the components.</p>
<p>So what's the best way to learn Pylons?</p>
<p>Of course there's other options, but do you have something else to recommend? I'm not really looking for much - MVC, an ORM and some form generation would be more than enough to satisfy me.</p>
<p>I've also looked at Django, but from what I can gather, it's more of a thing suited for CMS with all the admin panels etc. than generic "web services" (or whatever the term is).</p>
| 6 | 2009-06-24T23:21:22Z | 1,044,321 | <p>+1 for the <a href="http://pylonsbook.com/" rel="nofollow">pylons book</a>, it's invaluable for understanding the how and the why's of the framework and in general WSGI. After you read through and understand it, you'll be in a better position to not use pylons, which was kind of the original intent of the framework.</p>
| 3 | 2009-06-25T14:39:00Z | [
"python",
"pylons"
] |
Pylons is confusing: help! | 1,041,471 | <p>I'm a long-time PHP developer looking to try out Python for web development. I've used Python in the past a bit, but I'm still quite new at it.</p>
<p>I've taken a look at Pylons, and I have to say that it's extremely <em>confusing</em> to me. All the documentation I can find are just "copy and paste this" tutorials which don't seem to explain much.</p>
<p>For example, why can't controllers automatically render a specific view on a default template or something? Do I need to add a million import statements on top of every controller?</p>
<p>It's just that it feels so glued together - like there is no standardization between the components.</p>
<p>So what's the best way to learn Pylons?</p>
<p>Of course there's other options, but do you have something else to recommend? I'm not really looking for much - MVC, an ORM and some form generation would be more than enough to satisfy me.</p>
<p>I've also looked at Django, but from what I can gather, it's more of a thing suited for CMS with all the admin panels etc. than generic "web services" (or whatever the term is).</p>
| 6 | 2009-06-24T23:21:22Z | 1,061,295 | <p>I like WHIFF myself (because I wrote it). Please let me know if you find my tutorials more helpful or not. <a href="http://whiff.sourceforge.net" rel="nofollow">http://whiff.sourceforge.net</a></p>
| 1 | 2009-06-30T00:58:53Z | [
"python",
"pylons"
] |
Pylons is confusing: help! | 1,041,471 | <p>I'm a long-time PHP developer looking to try out Python for web development. I've used Python in the past a bit, but I'm still quite new at it.</p>
<p>I've taken a look at Pylons, and I have to say that it's extremely <em>confusing</em> to me. All the documentation I can find are just "copy and paste this" tutorials which don't seem to explain much.</p>
<p>For example, why can't controllers automatically render a specific view on a default template or something? Do I need to add a million import statements on top of every controller?</p>
<p>It's just that it feels so glued together - like there is no standardization between the components.</p>
<p>So what's the best way to learn Pylons?</p>
<p>Of course there's other options, but do you have something else to recommend? I'm not really looking for much - MVC, an ORM and some form generation would be more than enough to satisfy me.</p>
<p>I've also looked at Django, but from what I can gather, it's more of a thing suited for CMS with all the admin panels etc. than generic "web services" (or whatever the term is).</p>
| 6 | 2009-06-24T23:21:22Z | 1,416,766 | <p>Django is the easiest way to go if you want to get started in Python web development. I have been learning and working in Django for the last few months, then I gave Pylons a shot. It isn't that hard to get into it if you know Python well and the MVC framework. You will see a lot of similarities with other frameworks.</p>
<p>Some might argue how explicit all these imports are but if you have a look at Rails, you will wonder where do things come from. Not that magic is a bad thing but it illustrates to you two extreme cases of a very explicit and implicit framework.</p>
<p>Embrace the current frameworks as they are and learn from them.</p>
| 1 | 2009-09-13T03:23:34Z | [
"python",
"pylons"
] |
Pylons is confusing: help! | 1,041,471 | <p>I'm a long-time PHP developer looking to try out Python for web development. I've used Python in the past a bit, but I'm still quite new at it.</p>
<p>I've taken a look at Pylons, and I have to say that it's extremely <em>confusing</em> to me. All the documentation I can find are just "copy and paste this" tutorials which don't seem to explain much.</p>
<p>For example, why can't controllers automatically render a specific view on a default template or something? Do I need to add a million import statements on top of every controller?</p>
<p>It's just that it feels so glued together - like there is no standardization between the components.</p>
<p>So what's the best way to learn Pylons?</p>
<p>Of course there's other options, but do you have something else to recommend? I'm not really looking for much - MVC, an ORM and some form generation would be more than enough to satisfy me.</p>
<p>I've also looked at Django, but from what I can gather, it's more of a thing suited for CMS with all the admin panels etc. than generic "web services" (or whatever the term is).</p>
| 6 | 2009-06-24T23:21:22Z | 1,894,589 | <p>Having just went through the Pylons learning curve I can say that the easiest way to learn it is to dive right in with an open mind.</p>
<p>Pylons provides a lot of structure. In return you pay the price of additional complexity.</p>
<p>Controllers don't automatically render a specific view on a default template because that is somewhat limiting. Sometimes I don't want to even render views. How about if I just want to return some JSON? Pylons is powerful in that it lets you choose what you want to do.</p>
<p>Pylons provides just a small amount of glue and some basic components that everyone uses. Then you build the rest depending on what libraries you want to use.</p>
<p>The 3 things you need to really understand in Pylons</p>
<ul>
<li>routing.py (learn to love nice looking URLs)</li>
<li>controllers directory (all your logic)</li>
<li>templates directory</li>
</ul>
| 2 | 2009-12-12T20:22:39Z | [
"python",
"pylons"
] |
Unable to see Python's approximations in mathematical calculations | 1,041,543 | <p><strong>Problem:</strong> to see when computer makes approximation in mathematical calculations when I use Python</p>
<p><strong>Example of the problem:</strong></p>
<p>My old teacher once said the following statement</p>
<pre><code>You cannot never calculate 200! with your computer.
</code></pre>
<p>I am not completely sure whether it is true or not nowadays.
It seems that it is, since I get a lot zeros for it from a <a href="http://stackoverflow.com/questions/1041348/unable-to-make-a-factorial-function-in-python">Python script</a>.</p>
<p><strong>How can you see when your Python code makes approximations?</strong></p>
| 1 | 2009-06-24T23:52:49Z | 1,041,567 | <p>See <a href="http://stackoverflow.com/questions/538551/handling-very-large-numbers-in-python">Handling very large numbers in Python</a>. </p>
<p>Python has a BigNum class for holding 200! and will use it automatically. </p>
<p>Your teacher's statement, though not exactly true here is true in general. Computers have limitations, and it is good to know what they are. Remember that every time you add another integer of data storage, you can store a number that is 2^32 (4 billion +) times larger. It is hard to comprehend how many more numbers that is - but maths gets slower as you add more integers to store the exact value of a very large number.</p>
<p>As an example (what you can store with 1000 bits)</p>
<pre><code>>>> 2 << 1000
2143017214372534641896850098120003621122809623411067214887500776740702102249872244986396
7576313917162551893458351062936503742905713846280871969155149397149607869135549648461970
8421492101247422837559083643060929499671638825347975351183310878921541258291423929553730
84335320859663305248773674411336138752L
</code></pre>
<p>I tried to illustrate how big a number you can store with 10000 bits, or even 8,000,000 bits (a megabyte) but that number is many pages long.</p>
| 1 | 2009-06-25T00:01:46Z | [
"python"
] |
Unable to see Python's approximations in mathematical calculations | 1,041,543 | <p><strong>Problem:</strong> to see when computer makes approximation in mathematical calculations when I use Python</p>
<p><strong>Example of the problem:</strong></p>
<p>My old teacher once said the following statement</p>
<pre><code>You cannot never calculate 200! with your computer.
</code></pre>
<p>I am not completely sure whether it is true or not nowadays.
It seems that it is, since I get a lot zeros for it from a <a href="http://stackoverflow.com/questions/1041348/unable-to-make-a-factorial-function-in-python">Python script</a>.</p>
<p><strong>How can you see when your Python code makes approximations?</strong></p>
| 1 | 2009-06-24T23:52:49Z | 1,041,570 | <p>Python has unbounded <strong>integer</strong> sizes in the form of a <strong>long</strong> type. That is to say, if it is a whole number, the limit on the size of the number is restricted by the memory available to Python.</p>
<p>When you compute a large number such as 200! and you see an L on the end of it, that means Python has automatically cast the int to a <em>long</em>, because an int was not large enough to hold that number.</p>
<p>See section 6.4 of <a href="http://docs.python.org/library/stdtypes.html" rel="nofollow">this page</a> for more information.</p>
| 2 | 2009-06-25T00:02:13Z | [
"python"
] |
Unable to see Python's approximations in mathematical calculations | 1,041,543 | <p><strong>Problem:</strong> to see when computer makes approximation in mathematical calculations when I use Python</p>
<p><strong>Example of the problem:</strong></p>
<p>My old teacher once said the following statement</p>
<pre><code>You cannot never calculate 200! with your computer.
</code></pre>
<p>I am not completely sure whether it is true or not nowadays.
It seems that it is, since I get a lot zeros for it from a <a href="http://stackoverflow.com/questions/1041348/unable-to-make-a-factorial-function-in-python">Python script</a>.</p>
<p><strong>How can you see when your Python code makes approximations?</strong></p>
| 1 | 2009-06-24T23:52:49Z | 1,041,576 | <p>Python use <a href="http://en.wikipedia.org/wiki/Arbitrary-precision%5Farithmetic" rel="nofollow">arbitrary-precision arithmetic</a> to calculate with integers, so it can exactly calculate 200!. For real numbers (so-called <a href="http://en.wikipedia.org/wiki/Floating-point" rel="nofollow"><em>floating-point</em></a>), Python does not use an exact representation. It uses a binary representation called <a href="http://en.wikipedia.org/wiki/IEEE%5F754" rel="nofollow">IEEE 754</a>, which is essentially scientific notation, except in base 2 instead of base 10.</p>
<p>Thus, any real number that cannot be exactly represented in base 2 with 53 bits of precision, Python cannot produce an exact result. For example, 0.1 (in base 10) is an infinite decimal in base 2, 0.0001100110011..., so it cannot be exactly represented. Hence, if you enter on a Python prompt:</p>
<pre><code>>>> 0.1
0.10000000000000001
</code></pre>
<p>The result you get back is different, since has been converted from decimal to binary (with 53 bits of precision), back to decimal. As a consequence, you get things like this:</p>
<pre><code>>>> 0.1 + 0.2 == 0.3
False
</code></pre>
<p>For a good (but long) read, see <a href="http://docs.sun.com/source/806-3568/ncg%5Fgoldberg.html" rel="nofollow">What Every Programmer Should Know About Floating-Point Arithmetic</a>.</p>
| 7 | 2009-06-25T00:07:29Z | [
"python"
] |
Unable to see Python's approximations in mathematical calculations | 1,041,543 | <p><strong>Problem:</strong> to see when computer makes approximation in mathematical calculations when I use Python</p>
<p><strong>Example of the problem:</strong></p>
<p>My old teacher once said the following statement</p>
<pre><code>You cannot never calculate 200! with your computer.
</code></pre>
<p>I am not completely sure whether it is true or not nowadays.
It seems that it is, since I get a lot zeros for it from a <a href="http://stackoverflow.com/questions/1041348/unable-to-make-a-factorial-function-in-python">Python script</a>.</p>
<p><strong>How can you see when your Python code makes approximations?</strong></p>
| 1 | 2009-06-24T23:52:49Z | 1,041,592 | <p>200! is a very large number indeed. </p>
<p>If the range of an IEEE 64-bit double is 1.7E +/- 308 (15 digits), you can see that the largest factorial you can get is around 170!. </p>
<p>Python can handle arbitrary sized numbers, as can Java with its BigInteger.</p>
| 1 | 2009-06-25T00:16:53Z | [
"python"
] |
Unable to see Python's approximations in mathematical calculations | 1,041,543 | <p><strong>Problem:</strong> to see when computer makes approximation in mathematical calculations when I use Python</p>
<p><strong>Example of the problem:</strong></p>
<p>My old teacher once said the following statement</p>
<pre><code>You cannot never calculate 200! with your computer.
</code></pre>
<p>I am not completely sure whether it is true or not nowadays.
It seems that it is, since I get a lot zeros for it from a <a href="http://stackoverflow.com/questions/1041348/unable-to-make-a-factorial-function-in-python">Python script</a>.</p>
<p><strong>How can you see when your Python code makes approximations?</strong></p>
| 1 | 2009-06-24T23:52:49Z | 1,041,594 | <p>Without some sort of clarification to that statement, it's obviously false. Just from personal experience, early lessons in programming (in the late 1980s) included solving very similar, if not exactly the same, problems. In general, to know some device which does calculations isn't making approximations, you have to prove (in the math sense of a proof) that it isn't.</p>
<p>Python's integer types (named <code>int</code> and <code>long</code> in 2.x, both folded into just the <code>int</code> type in 3.x) are very good, and do not overflow like, for example, the <code>int</code> type in C. If you do the obvious of <code>print 200 * 199 * 198 * ...</code> it may be slow, but it will be exact. Similiarly, addition, subtraction, and modulus are exact. Division is a mixed bag, as there's two operators, <code>/</code> and <code>//</code>, and they underwent a change in 2.x—in general you can only treat it as inexact.</p>
<p>If you want more control yet don't want to limit yourself to integers, look at the <a href="http://docs.python.org/library/decimal.html" rel="nofollow"><code>decimal</code></a> module.</p>
| 1 | 2009-06-25T00:17:26Z | [
"python"
] |
Unable to see Python's approximations in mathematical calculations | 1,041,543 | <p><strong>Problem:</strong> to see when computer makes approximation in mathematical calculations when I use Python</p>
<p><strong>Example of the problem:</strong></p>
<p>My old teacher once said the following statement</p>
<pre><code>You cannot never calculate 200! with your computer.
</code></pre>
<p>I am not completely sure whether it is true or not nowadays.
It seems that it is, since I get a lot zeros for it from a <a href="http://stackoverflow.com/questions/1041348/unable-to-make-a-factorial-function-in-python">Python script</a>.</p>
<p><strong>How can you see when your Python code makes approximations?</strong></p>
| 1 | 2009-06-24T23:52:49Z | 1,041,638 | <p>Python handles large numbers automatically (unlike a language like C where you can overflow its datatypes and the values reset to zero, for example) - over a certain point (<code>sys.maxint</code> or 2147483647) it converts the integer to a "long" (denoted by the <code>L</code> after the number), which can be any length:</p>
<pre><code>>>> def fact(x):
... return reduce(lambda x, y: x * y, range(1, x+1))
...
>>> fact(10)
3628800
>>> fact(200)
788657867364790503552363213932185062295135977687173263294742533244359449963403342920304284011984623904177212138919638830257642790242637105061926624952829931113462857270763317237396988943922445621451664240254033291864131227428294853277524242407573903240321257405579568660226031904170324062351700858796178922222789623703897374720000000000000000000000000000000000000000000000000L
</code></pre>
<p>Long numbers are "easy", floating point is more complicated, and almost any computer representation of a floating point number is an approximation, for example:</p>
<pre><code>>>> float(1)/3
0.33333333333333331
</code></pre>
<p>Obviously you can't store an infinite number of 3's in memory, so it cheats and rounds it a bit..</p>
<p>You may want to look at the <a href="http://docs.python.org/library/decimal.html" rel="nofollow">decimal</a> module:</p>
<blockquote>
<ul>
<li>Decimal numbers can be represented exactly. In contrast, numbers like 1.1 do not have an exact representation in binary floating point. End users typically would not expect 1.1 to display as 1.1000000000000001 as it does with binary floating point.</li>
<li>Unlike hardware based binary floating point, the decimal module has a user alterable precision (defaulting to 28 places) which can be as large as needed for a given problem</li>
</ul>
</blockquote>
| 1 | 2009-06-25T00:37:18Z | [
"python"
] |
Context-sensitive string splitting, preserving delimiters | 1,041,600 | <p>I have a string of the form "foo-bar-1.23-4", and I need to split at the first hypen followed by a numeral, such that the result is ['foo-bar', '1.23-4']. I've tried the following:</p>
<pre><code>>>> re.split('-\d', 'foo-bar-1.23-4', 1)
['foo-bar', '.23-4']
</code></pre>
<p>and</p>
<pre><code>>>> re.split('-(\d)', 'foo-bar-1.23-4', 1)
['foo-bar', '1', '.23-4']
</code></pre>
<p>with suboptimal results. Is there a one-liner that will get me what I want, without having to munge the delimiter with the last element?</p>
| 0 | 2009-06-25T00:19:27Z | 1,041,608 | <p>You were very close, try this:</p>
<pre><code>re.split('-(?=\d)', 'foo-bar-1.23-4', 1)
</code></pre>
<p>I am using <a href="http://www.regular-expressions.info/lookaround.html" rel="nofollow">positive lookahead</a> to accomplish this - basically I am matching a dash that is immediately followed by a numeric character.</p>
| 2 | 2009-06-25T00:22:50Z | [
"python",
"string",
"split"
] |
Context-sensitive string splitting, preserving delimiters | 1,041,600 | <p>I have a string of the form "foo-bar-1.23-4", and I need to split at the first hypen followed by a numeral, such that the result is ['foo-bar', '1.23-4']. I've tried the following:</p>
<pre><code>>>> re.split('-\d', 'foo-bar-1.23-4', 1)
['foo-bar', '.23-4']
</code></pre>
<p>and</p>
<pre><code>>>> re.split('-(\d)', 'foo-bar-1.23-4', 1)
['foo-bar', '1', '.23-4']
</code></pre>
<p>with suboptimal results. Is there a one-liner that will get me what I want, without having to munge the delimiter with the last element?</p>
| 0 | 2009-06-25T00:19:27Z | 1,041,611 | <pre><code>re.split('-(?=\d)', 'foo-bar-1.23-4', 1)
</code></pre>
<p>Using <a href="http://docs.python.org/library/re.html" rel="nofollow">lookahead</a>, which is exactly what Andrew did but beat me by a minute... :-)</p>
| 0 | 2009-06-25T00:24:28Z | [
"python",
"string",
"split"
] |
Context-sensitive string splitting, preserving delimiters | 1,041,600 | <p>I have a string of the form "foo-bar-1.23-4", and I need to split at the first hypen followed by a numeral, such that the result is ['foo-bar', '1.23-4']. I've tried the following:</p>
<pre><code>>>> re.split('-\d', 'foo-bar-1.23-4', 1)
['foo-bar', '.23-4']
</code></pre>
<p>and</p>
<pre><code>>>> re.split('-(\d)', 'foo-bar-1.23-4', 1)
['foo-bar', '1', '.23-4']
</code></pre>
<p>with suboptimal results. Is there a one-liner that will get me what I want, without having to munge the delimiter with the last element?</p>
| 0 | 2009-06-25T00:19:27Z | 1,041,614 | <p>Would a positive lookahead work?</p>
<pre><code>re.split('-?=\d', 'foo-bar-1.23-4', 1)
</code></pre>
<p>Not sure if you need the ( and the ) surrounding the lookahead, but give it a shot.</p>
| 0 | 2009-06-25T00:27:08Z | [
"python",
"string",
"split"
] |
Get a dict of all variables currently in scope and their values | 1,041,639 | <p>Consider this snippet:</p>
<pre><code>globalVar = 25
def myfunc(paramVar):
localVar = 30
print "Vars: {globalVar}, {paramVar}, {localVar}!".format(**VARS_IN_SCOPE)
myfunc(123)
</code></pre>
<p>Where <code>VARS_IN_SCOPE</code> is the dict I'm after that would contain <code>globalVar</code>, <code>paramVar</code> and <code>localVar</code>, among other things.</p>
<p>I'd like to basically be able to reference all the variables that are currently in scope inside the string. Hence the expected output would be:</p>
<p><code>Vars: 25, 123, 30</code></p>
<p>I can achieve this by passing <code>**dict(globals().items() + locals().items())</code> to <code>format()</code>. Is this always correct or are there some corner cases that this expression would handle incorrectly?</p>
<p><em>Rewritten to clarify the question.</em></p>
| 24 | 2009-06-25T00:37:23Z | 1,041,660 | <p>Does this do what you intended?</p>
<pre><code>d = dict(globals())
d.update(locals())
</code></pre>
<p>If I read the documentation correctly, you create a copy of the <code>globals()</code> dict, then you overwrite any duplicates <em>and</em> insert new entries from the <code>locals()</code> dict (since the <code>locals()</code> should have preference within your scope, anyway).</p>
<p><hr></p>
<p>I haven't had <em>any</em> luck in getting a proper function to return the full dictionary of variables in scope of the <strong>calling</strong> function. Here's the code (I only used pprint to format the output nicely for SO):</p>
<pre><code>from pprint import *
def allvars_bad():
fake_temp_var = 1
d = dict(globals())
d.update(locals())
return d
def foo_bad():
x = 5
return allvars_bad()
def foo_good():
x = 5
fake_temp_var = "good"
d = dict(globals())
d.update(locals())
return d
pprint (foo_bad(), width=50)
pprint (foo_good(), width=50)
</code></pre>
<p>and the output:</p>
<pre><code> {'PrettyPrinter': <class pprint.PrettyPrinter at 0xb7d316ec>,
'__builtins__': <module '__builtin__' (built-in)>,
'__doc__': None,
'__file__': 'temp.py',
'__name__': '__main__',
'__package__': None,
'allvars_bad': <function allvars_bad at 0xb7d32b1c>,
'd': <Recursion on dict with id=3084093748>,
'fake_temp_var': 1,
'foo_bad': <function foo_bad at 0xb7d329cc>,
'foo_good': <function foo_good at 0xb7d32f0c>,
'isreadable': <function isreadable at 0xb7d32c34>,
'isrecursive': <function isrecursive at 0xb7d32c6c>,
'pformat': <function pformat at 0xb7d32bc4>,
'pprint': <function pprint at 0xb7d32b8c>,
'saferepr': <function saferepr at 0xb7d32bfc>}
{'PrettyPrinter': <class pprint.PrettyPrinter at 0xb7d316ec>,
'__builtins__': <module '__builtin__' (built-in)>,
'__doc__': None,
'__file__': 'temp.py',
'__name__': '__main__',
'__package__': None,
'allvars_bad': <function allvars_bad at 0xb7d32b1c>,
'd': <Recursion on dict with id=3084093884>,
'fake_temp_var': 'good',
'foo_bad': <function foo_bad at 0xb7d329cc>,
'foo_good': <function foo_good at 0xb7d32f0c>,
'isreadable': <function isreadable at 0xb7d32c34>,
'isrecursive': <function isrecursive at 0xb7d32c6c>,
'pformat': <function pformat at 0xb7d32bc4>,
'pprint': <function pprint at 0xb7d32b8c>,
'saferepr': <function saferepr at 0xb7d32bfc>,
'x': 5}
</code></pre>
<p>Note that in the second output, we have overwritten <code>fake_temp_var</code>, and x is present; the first output only included the local vars within the scope of <code>allvars_bad</code>.</p>
<p>So if you want to access the full variable scope, you cannot put locals() inside another function.</p>
<p><hr/></p>
<p>I had suspected there was some sort of frame object, I just didn't (know where to) look for it.</p>
<p>This works to your spec, I believe:</p>
<pre><code>def allvars_good(offset=0):
frame = sys._getframe(1+offset)
d = frame.f_globals
d.update(frame.f_locals)
return d
def foo_good2():
a = 1
b = 2
return allvars_good()
</code></pre>
<p>--></p>
<pre><code>{'PrettyPrinter': <class pprint.PrettyPrinter at 0xb7d6474c>,
'__builtins__': <module '__builtin__' (built-in)>,
'__doc__': None,
'__file__': 'temp.py',
'__name__': '__main__',
'__package__': None,
'a': 1,
'allvars_bad': <function allvars_bad at 0xb7d65b54>,
'allvars_good': <function allvars_good at 0xb7d65a04>,
'b': 2,
'foo_bad': <function foo_bad at 0xb7d65f44>,
'foo_good': <function foo_good at 0xb7d65f7c>,
'foo_good2': <function foo_good2 at 0xb7d65fb4>,
'isreadable': <function isreadable at 0xb7d65c6c>,
'isrecursive': <function isrecursive at 0xb7d65ca4>,
'pformat': <function pformat at 0xb7d65bfc>,
'pprint': <function pprint at 0xb7d65bc4>,
'saferepr': <function saferepr at 0xb7d65c34>,
'sys': <module 'sys' (built-in)>}
</code></pre>
| 5 | 2009-06-25T00:45:23Z | [
"python"
] |
Get a dict of all variables currently in scope and their values | 1,041,639 | <p>Consider this snippet:</p>
<pre><code>globalVar = 25
def myfunc(paramVar):
localVar = 30
print "Vars: {globalVar}, {paramVar}, {localVar}!".format(**VARS_IN_SCOPE)
myfunc(123)
</code></pre>
<p>Where <code>VARS_IN_SCOPE</code> is the dict I'm after that would contain <code>globalVar</code>, <code>paramVar</code> and <code>localVar</code>, among other things.</p>
<p>I'd like to basically be able to reference all the variables that are currently in scope inside the string. Hence the expected output would be:</p>
<p><code>Vars: 25, 123, 30</code></p>
<p>I can achieve this by passing <code>**dict(globals().items() + locals().items())</code> to <code>format()</code>. Is this always correct or are there some corner cases that this expression would handle incorrectly?</p>
<p><em>Rewritten to clarify the question.</em></p>
| 24 | 2009-06-25T00:37:23Z | 1,041,663 | <p>You could make your own:</p>
<pre><code>allvars = dict()
allvars.update(globals())
allvars.update(locals())
</code></pre>
<p>or combine the first two lines:</p>
<pre><code>allvars = dict(globals())
allvars.update(locals())
</code></pre>
| 0 | 2009-06-25T00:46:20Z | [
"python"
] |
Get a dict of all variables currently in scope and their values | 1,041,639 | <p>Consider this snippet:</p>
<pre><code>globalVar = 25
def myfunc(paramVar):
localVar = 30
print "Vars: {globalVar}, {paramVar}, {localVar}!".format(**VARS_IN_SCOPE)
myfunc(123)
</code></pre>
<p>Where <code>VARS_IN_SCOPE</code> is the dict I'm after that would contain <code>globalVar</code>, <code>paramVar</code> and <code>localVar</code>, among other things.</p>
<p>I'd like to basically be able to reference all the variables that are currently in scope inside the string. Hence the expected output would be:</p>
<p><code>Vars: 25, 123, 30</code></p>
<p>I can achieve this by passing <code>**dict(globals().items() + locals().items())</code> to <code>format()</code>. Is this always correct or are there some corner cases that this expression would handle incorrectly?</p>
<p><em>Rewritten to clarify the question.</em></p>
| 24 | 2009-06-25T00:37:23Z | 1,041,891 | <p>Interpolation into strings works in the simplest possible way. Just list your variables. Python checks locals and globals for you.</p>
<pre><code>globalVar = 25
def myfunc(paramVar):
localVar = 30
print "Vars: %d, %d, %d!" % ( globalVar, paramVar, localVar )
myfunc(123)
</code></pre>
| 0 | 2009-06-25T02:17:25Z | [
"python"
] |
Get a dict of all variables currently in scope and their values | 1,041,639 | <p>Consider this snippet:</p>
<pre><code>globalVar = 25
def myfunc(paramVar):
localVar = 30
print "Vars: {globalVar}, {paramVar}, {localVar}!".format(**VARS_IN_SCOPE)
myfunc(123)
</code></pre>
<p>Where <code>VARS_IN_SCOPE</code> is the dict I'm after that would contain <code>globalVar</code>, <code>paramVar</code> and <code>localVar</code>, among other things.</p>
<p>I'd like to basically be able to reference all the variables that are currently in scope inside the string. Hence the expected output would be:</p>
<p><code>Vars: 25, 123, 30</code></p>
<p>I can achieve this by passing <code>**dict(globals().items() + locals().items())</code> to <code>format()</code>. Is this always correct or are there some corner cases that this expression would handle incorrectly?</p>
<p><em>Rewritten to clarify the question.</em></p>
| 24 | 2009-06-25T00:37:23Z | 1,041,906 | <p>Best way to merge two dicts as you're doing (with locals overriding globals) is <code>dict(globals(), **locals())</code>.</p>
<p>What the approach of merging globals and locals is missing is (a) builtins (I imagine that's deliberate, i.e. you don't think of builtins as "variables"... but, they COULD be, if you so choose!-), and (b) if you're in a <em>nested</em> function, any variables that are local to enclosing functions (no really good way to get a dict with all of <em>those</em>, plus -- only those explicitly accessed in the nested function, i.e. "free variables" thereof, survive as cells in a closure, anyway).</p>
<p>I imagine these issues are no big deal for your intended use, but you did mention "corner cases";-). If you need to cover them, there are ways to get the built-ins (that's easy) and (not so easy) all the cells (variables from enclosing functions that you explicitly mention in the nested function -- <code>thefunction.func_code.co_freevars</code> to get the names, <code>thefunction.func_closure</code> to get the cells, <code>cell_contents</code> on each cell to get its value). (But, remember, those will only be variables from enclosing functions that are <em>explicitly accessed</em> in your nested function's code!).</p>
| 25 | 2009-06-25T02:28:20Z | [
"python"
] |
Get a dict of all variables currently in scope and their values | 1,041,639 | <p>Consider this snippet:</p>
<pre><code>globalVar = 25
def myfunc(paramVar):
localVar = 30
print "Vars: {globalVar}, {paramVar}, {localVar}!".format(**VARS_IN_SCOPE)
myfunc(123)
</code></pre>
<p>Where <code>VARS_IN_SCOPE</code> is the dict I'm after that would contain <code>globalVar</code>, <code>paramVar</code> and <code>localVar</code>, among other things.</p>
<p>I'd like to basically be able to reference all the variables that are currently in scope inside the string. Hence the expected output would be:</p>
<p><code>Vars: 25, 123, 30</code></p>
<p>I can achieve this by passing <code>**dict(globals().items() + locals().items())</code> to <code>format()</code>. Is this always correct or are there some corner cases that this expression would handle incorrectly?</p>
<p><em>Rewritten to clarify the question.</em></p>
| 24 | 2009-06-25T00:37:23Z | 1,041,957 | <pre><code>globalVar = 25
def myfunc(paramVar):
localVar = 30
all_vars = locals.copy()
all_vars.update(globals())
print "Vars: {globalVar}, {paramVar}, {localVar}!".format(all_vars)
myfunc(123)
</code></pre>
| 1 | 2009-06-25T02:55:14Z | [
"python"
] |
Convert param into python? | 1,042,391 | <p>I am trying to learn web programming in python. I am converting my old php-flash project into python. Now, I am confused about how to set param value and create object using python.</p>
<p>FYI I used a single php file, index.php to communicate with flash.swf. So, my other php files like login.php, logout.php, mail.php, xml.php etc used to be called from this.</p>
<p>Below is the flash object call from index.php-</p>
<pre><code><object classid="clsid:XXXXXXXXX-YYYY-ZZZZ-AAAA-BBBBBBBBBB" codebase="http://fpdownload.macromedia.com/pub/shockwave/cabs/flash/swflash.cab#version=7,0,0,0" width="100%" height="100%" id="main" align="middle">
<param name="allowScriptAccess" value="all" />
<param name="flashvars" value= />
<param name="movie" value="flash.swf?<?=substr($_SERVER["REQUEST_URI"],strrpos($_SERVER["SCRIPT_NAME"],"/")+1);?>" />
<param name="loop" value="false" />
<param name="quality" value="high" />
<param name="bgcolor" value="#eeeeee" />
<embed src="flash.swf?<?=substr($_SERVER["REQUEST_URI"],strrpos($_SERVER["SCRIPT_NAME"],"/")+1);?>" loop="false" quality="high" bgcolor="#eeeeee" width="100%" height="100%" name="main" align="middle" allowScriptAccess="all" type="application/x-shockwave-flash" pluginspage="http://www.macromedia.com/go/getflashplayer" />
</object>
</code></pre>
<p>Can any geek help me out with examples how I can convert this into python? Or, any reference on how it can be done?</p>
<p>Cheers :)</p>
| 0 | 2009-06-25T06:08:10Z | 1,042,425 | <p>php itself can be used as templating language for generatin html, but in python you will need to use one of the <a href="http://wiki.python.org/moin/Templating" rel="nofollow">several templating engines</a> available. If you want you can do simple templating using string.Template class but that is not what you would want to do.</p>
<p>Your first step should be to decide on web framework you are going to use, and use templating it provides, e.g django</p>
<p>But if you want just a plane cgi python script, you will need to write your html to stdout.
so create a simple html and replace template values with your parameters e.g.</p>
<pre><code>from string import Template
htmlTemplate = Template("""
<html>
<title>$title</title>
</html>
""")
myvalues = {'title':'wow it works!'}
print "Content-type: text/html"
print
print htmlTemplate.substitute(myvalues)
</code></pre>
<p>to work with cgi you can use cgi module e.g.</p>
<pre><code>import cgi
form = cgi.FieldStorage()
</code></pre>
| 0 | 2009-06-25T06:33:49Z | [
"php",
"python",
"parameters"
] |
Convert param into python? | 1,042,391 | <p>I am trying to learn web programming in python. I am converting my old php-flash project into python. Now, I am confused about how to set param value and create object using python.</p>
<p>FYI I used a single php file, index.php to communicate with flash.swf. So, my other php files like login.php, logout.php, mail.php, xml.php etc used to be called from this.</p>
<p>Below is the flash object call from index.php-</p>
<pre><code><object classid="clsid:XXXXXXXXX-YYYY-ZZZZ-AAAA-BBBBBBBBBB" codebase="http://fpdownload.macromedia.com/pub/shockwave/cabs/flash/swflash.cab#version=7,0,0,0" width="100%" height="100%" id="main" align="middle">
<param name="allowScriptAccess" value="all" />
<param name="flashvars" value= />
<param name="movie" value="flash.swf?<?=substr($_SERVER["REQUEST_URI"],strrpos($_SERVER["SCRIPT_NAME"],"/")+1);?>" />
<param name="loop" value="false" />
<param name="quality" value="high" />
<param name="bgcolor" value="#eeeeee" />
<embed src="flash.swf?<?=substr($_SERVER["REQUEST_URI"],strrpos($_SERVER["SCRIPT_NAME"],"/")+1);?>" loop="false" quality="high" bgcolor="#eeeeee" width="100%" height="100%" name="main" align="middle" allowScriptAccess="all" type="application/x-shockwave-flash" pluginspage="http://www.macromedia.com/go/getflashplayer" />
</object>
</code></pre>
<p>Can any geek help me out with examples how I can convert this into python? Or, any reference on how it can be done?</p>
<p>Cheers :)</p>
| 0 | 2009-06-25T06:08:10Z | 1,042,471 | <p>Python is a general purpose language, not exactly made for web. There exists some embeddable PHP-like solutions, but in most Python web frameworks, you write Python and HTML (template) code separately.</p>
<p>For example in <a href="http://djangoproject.com/" rel="nofollow">Django web framework</a> you first write a <a href="http://docs.djangoproject.com/en/dev/topics/http/views/#topics-http-views" rel="nofollow">view</a> (view â you know â from that famous <a href="http://en.wikipedia.org/wiki/Model-View-Controller" rel="nofollow">Model-View-Controller</a> pattern) function:</p>
<pre><code>def my_view(request, movie):
return render_to_template('my_view.html',
{'movie': settings.MEDIA_URL + 'flash.swf?' + movie})
</code></pre>
<p>And register it with <a href="http://docs.djangoproject.com/en/dev/topics/http/urls/#topics-http-urls" rel="nofollow">URL dispatcher</a> (in Django, there is a special file, called <code>urls.py</code>):</p>
<pre><code>...
url(r'/flash/(?P<movie>.+)$', 'myapp.views.my_view'),
...
</code></pre>
<p>Then a <code>my_view.html</code> <a href="http://docs.djangoproject.com/en/dev/topics/templates/#topics-templates" rel="nofollow">template</a>:</p>
<pre><code>...
<object classid="clsid:XXXXXXXXX-YYYY-ZZZZ-AAAA-BBBBBBBBBB" codebase="http://fpdownload.macromedia.com/pub/shockwave/cabs/flash/swflash.cab#version=7,0,0,0" width="100%" height="100%" id="main" align="middle">
<param name="allowScriptAccess" value="all" />
<param name="flashvars" value= />
<param name="movie" value="{{ movie }}" />
<param name="loop" value="false" />
<param name="quality" value="high" />
<param name="bgcolor" value="#eeeeee" />
<embed src="{{ movie }}" loop="false" quality="high" bgcolor="#eeeeee" width="100%" height="100%" name="main" align="middle" allowScriptAccess="all" type="application/x-shockwave-flash" pluginspage="http://www.macromedia.com/go/getflashplayer" />
</object>
...
</code></pre>
<p>While this may seem like a lot of work for such a tiny task, when you have to write something bigger than simple value-substituting script, the framework pays back. For example, you may actually write a simple blog application in less than 100 lines of code. The framework will automatically take care of URL parsing (somehow like Apache's mod_rewrite for PHP), complex templating, database access, form generation, processing and validation, user authentication, debugging and so on.</p>
<p>There are a lot of different frameworks, each having its own good and bad sides. I recommend spending some time reading introductions and choosing one you like. Personally, I like Django, and had success with <a href="http://webpy.org/" rel="nofollow">web.py</a>. I've also heard good things about <a href="http://pylonshq.com/" rel="nofollow">Pylons</a> and <a href="http://turbogears.org/" rel="nofollow">TurboGears</a>.</p>
<p>If you need something really simple (like in your example), where you don't need almost anything, you may just write small <a href="http://wsgi.org/wsgi/" rel="nofollow">WSGI</a> application, which then can be used, for example, with Apache's mod_python or mod_wsgi. It will be something like this:</p>
<pre><code>def return_movie_html(environ, start_response):
request_uri = environ.get('REQUEST_URI')
movie_uri = request_uri[request_uri.rfind('/')+1:]
start_response('200 OK', [('Content-Type', 'text/html')])
return ['''
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN"
"http://www.w3.org/TR/html4/strict.dtd">
<html>
...
<object ...>
<param name="allowScriptAccess" value="all" />
<param name="flashvars" value= />
<param name="movie" value="%(movie)s" />
<param name="loop" value="false" />
<param name="quality" value="high" />
<param name="bgcolor" value="#eeeeee" />
<embed src="%(movie)s" loop="false" ... />
</object>
...
</html>
''' % {'movie': movie_uri}]
</code></pre>
<p>To sum it up: without additional support libraries, Python web programming is somehow painful, and requires doing <em>everything</em> from the URI parsing to output formatting from scratch. However, there are a lot of good libraries and frameworks, to make job not only painless, but sometimes even pleasant :) Learn about them more, and I believe you won't regret it.</p>
| 3 | 2009-06-25T06:51:10Z | [
"php",
"python",
"parameters"
] |
Convert param into python? | 1,042,391 | <p>I am trying to learn web programming in python. I am converting my old php-flash project into python. Now, I am confused about how to set param value and create object using python.</p>
<p>FYI I used a single php file, index.php to communicate with flash.swf. So, my other php files like login.php, logout.php, mail.php, xml.php etc used to be called from this.</p>
<p>Below is the flash object call from index.php-</p>
<pre><code><object classid="clsid:XXXXXXXXX-YYYY-ZZZZ-AAAA-BBBBBBBBBB" codebase="http://fpdownload.macromedia.com/pub/shockwave/cabs/flash/swflash.cab#version=7,0,0,0" width="100%" height="100%" id="main" align="middle">
<param name="allowScriptAccess" value="all" />
<param name="flashvars" value= />
<param name="movie" value="flash.swf?<?=substr($_SERVER["REQUEST_URI"],strrpos($_SERVER["SCRIPT_NAME"],"/")+1);?>" />
<param name="loop" value="false" />
<param name="quality" value="high" />
<param name="bgcolor" value="#eeeeee" />
<embed src="flash.swf?<?=substr($_SERVER["REQUEST_URI"],strrpos($_SERVER["SCRIPT_NAME"],"/")+1);?>" loop="false" quality="high" bgcolor="#eeeeee" width="100%" height="100%" name="main" align="middle" allowScriptAccess="all" type="application/x-shockwave-flash" pluginspage="http://www.macromedia.com/go/getflashplayer" />
</object>
</code></pre>
<p>Can any geek help me out with examples how I can convert this into python? Or, any reference on how it can be done?</p>
<p>Cheers :)</p>
| 0 | 2009-06-25T06:08:10Z | 1,043,324 | <p>You can also try using simple web framework like web.py which has a simple templating system along with a simple ORM for database related functionalities. A basic tutorial is available <a href="http://webpy.org/tutorial3.en" rel="nofollow">here</a> which is enough to help you get a simple web page, such as yours, up and running.</p>
| 0 | 2009-06-25T11:04:54Z | [
"php",
"python",
"parameters"
] |
Convert param into python? | 1,042,391 | <p>I am trying to learn web programming in python. I am converting my old php-flash project into python. Now, I am confused about how to set param value and create object using python.</p>
<p>FYI I used a single php file, index.php to communicate with flash.swf. So, my other php files like login.php, logout.php, mail.php, xml.php etc used to be called from this.</p>
<p>Below is the flash object call from index.php-</p>
<pre><code><object classid="clsid:XXXXXXXXX-YYYY-ZZZZ-AAAA-BBBBBBBBBB" codebase="http://fpdownload.macromedia.com/pub/shockwave/cabs/flash/swflash.cab#version=7,0,0,0" width="100%" height="100%" id="main" align="middle">
<param name="allowScriptAccess" value="all" />
<param name="flashvars" value= />
<param name="movie" value="flash.swf?<?=substr($_SERVER["REQUEST_URI"],strrpos($_SERVER["SCRIPT_NAME"],"/")+1);?>" />
<param name="loop" value="false" />
<param name="quality" value="high" />
<param name="bgcolor" value="#eeeeee" />
<embed src="flash.swf?<?=substr($_SERVER["REQUEST_URI"],strrpos($_SERVER["SCRIPT_NAME"],"/")+1);?>" loop="false" quality="high" bgcolor="#eeeeee" width="100%" height="100%" name="main" align="middle" allowScriptAccess="all" type="application/x-shockwave-flash" pluginspage="http://www.macromedia.com/go/getflashplayer" />
</object>
</code></pre>
<p>Can any geek help me out with examples how I can convert this into python? Or, any reference on how it can be done?</p>
<p>Cheers :)</p>
| 0 | 2009-06-25T06:08:10Z | 1,044,079 | <p>First of all just make a web2py view that contains {{=BEAUTIFY(response.env)}} you will be able to see all environment systems variables defined in web2py. </p>
<p>Look into slide 24 (www.web2py.com) to see the default mapping of urls into web2py variables.</p>
<p>To solve your problem, the easier way would be to change the paths in the flash code, but I will assume you do not want to do that. I will assume instead your urls all look like</p>
<pre><code>http://127.0.0.1:8000/[..script..].php[..anything..]
</code></pre>
<p>and your web2py app is called "app".</p>
<p>Here is what you do:</p>
<p>Create routes.py in the main web2py folder that contains</p>
<pre><code>routes_in=(('/(?P<script>\w+)\.php(?P<anything>.*)',
'/app/default/\g<script>\g<anything>'),
(('/flash.swf','/app/static/slash.swf'))
routes_out(('/app/default/(?P<script>\w+)\.php(?P<anything>.*)',
'/\g<script>\.php\g<anything>'),)
</code></pre>
<p>this maps</p>
<pre><code>http://127.0.0.1:8000/index.php into http://127.0.0.1:8000/app/default/index
http://127.0.0.1:8000/index.php/junk into http://127.0.0.1:8000/app/default/index/junk
http://127.0.0.1:8000/flash.swf into http://127.0.0.1:8000/app/static/flash.swf
</code></pre>
<p>create a controller default.py that contains</p>
<pre><code>def index(): return dict()
</code></pre>
<p>Put the file "flash.swf" in the "app/static" folder.</p>
<p>Create a view default/index.html that contains</p>
<pre><code><object classid="clsid:XXXXXXXXX-YYYY-ZZZZ-AAAA-BBBBBBBBBB" codebase="http://fpdownload.macromedia.com/pub/shockwave/cabs/flash/swflash.cab#version=7,0,0,0" width="100%" height="100%" id="main" align="middle">
<param name="allowScriptAccess" value="all" />
<param name="flashvars" value= />
<param name="movie" value="flash.swf?{{=request.env.web2py_original_uri[len(request.function)+5:]}}" />
<param name="loop" value="false" />
<param name="quality" value="high" />
<param name="bgcolor" value="#eeeeee" />
<embed src="flash.swf?{{=request.env.web2py_original_uri[len(request.function)+5:]}}" />
" loop="false" quality="high" bgcolor="#eeeeee" width="100%" height="100%" name="main" align="middle" allowScriptAccess="all" type="application/x-shockwave-flash" pluginspage="http://www.macromedia.com/go/getflashplayer" />
</object>
</code></pre>
<p>I am not sure on whether it is "+5" or "+4"above. Give it a try.</p>
<p>I suggest moving this discussion on the web2py mailing list since there is a much simpler way by changing the paths.</p>
| 0 | 2009-06-25T13:55:37Z | [
"php",
"python",
"parameters"
] |
Python 2.6 - Upload zip file - Poster 0.4 | 1,042,451 | <p>I came here via this question:
<a href="http://stackoverflow.com/questions/68477/send-file-using-post-from-a-python-script">http://stackoverflow.com/questions/68477/send-file-using-post-from-a-python-script</a></p>
<p>And by and large it's what I need, plus some additional. </p>
<p>Besides the zipfile som additional information is needed and the POST_DATA looks something like this:</p>
<pre><code>POSTDATA =-----------------------------293432744627532
Content-Disposition: form-data; name="categoryID"
1
-----------------------------293432744627532
Content-Disposition: form-data; name="cID"
-3
-----------------------------293432744627532
Content-Disposition: form-data; name="FileType"
zip
-----------------------------293432744627532
Content-Disposition: form-data; name="name"
Kylie Minogue
-----------------------------293432744627532
Content-Disposition: form-data; name="file1"; filename="At the Beach x8-8283.zip"
Content-Type: application/x-zip-compressed
PK........................
</code></pre>
<p>Is this somehow possible with the poster 0.4 module (and before you ask, yes, I'm fairly new to Python...)</p>
<p>Kind regards,
Brian K. Andersen</p>
| 0 | 2009-06-25T06:43:29Z | 1,042,712 | <p>Poster has basic and advanced multipart support.<br />
You may try something like this (modified from poster documentation):</p>
<pre><code># test_client.py
from poster.encode import multipart_encode
from poster.streaminghttp import register_openers
import urllib2
# Register the streaming http handlers with urllib2
register_openers()
# headers contains the necessary Content-Type and Content-Length
# datagen is a generator object that yields the encoded parameters
datagen, headers = multipart_encode({
'categoryID' : 1,
'cID' : -3,
'FileType' : 'zip',
'name' : 'Kylie Minogue',
'file1' : open('At the Beach x8-8283.zip')
})
# Create the Request object
request = urllib2.Request("http://localhost:5000/upload_data", datagen, headers)
# Actually do the request, and get the response
print urllib2.urlopen(request).read()
</code></pre>
| 4 | 2009-06-25T08:04:24Z | [
"python",
"upload",
"file-upload",
"urllib2",
"zipfile"
] |
Get the index of an element in a queryset | 1,042,596 | <p>I have a QuerySet, let's call it <code>qs</code>, which is ordered by some attribute which is irrelevant to this problem. Then I have an object, let's call it <code>obj</code>. Now I'd like to know at what index <code>obj</code> has in <code>qs</code>, as <em>efficiently</em> as possible. I know that I could use <code>.index()</code> from Python or possibly loop through <code>qs</code> comparing each object to <code>obj</code>, but what is the best way to go about doing this? I'm looking for high performance and that's my only criteria.</p>
<p>Using Python 2.6.2 with Django 1.0.2 on Windows.</p>
| 17 | 2009-06-25T07:31:24Z | 1,042,651 | <p>QuerySets in Django are actually generators, not lists (for further details, see <a href="http://docs.djangoproject.com/en/dev/ref/models/querysets/#ref-models-querysets">Django documentation on QuerySets</a>).<br />
As such, there is no shortcut to get the index of an element, and I think a plain iteration is the best way to do it.</p>
<p>For starter, I would implement your requirement in the simplest way possible (like iterating); if you really have performance issues, then I would use some different approach, like building a queryset with a smaller amount of fields, or whatever.<br />
In any case, the idea is to leave such tricks as late as possible, when you definitely knows you need them.<br />
<strong>Update:</strong> You may want to use directly some SQL statement to get the rownumber (something lie . However, Django's ORM does not support this natively and you have to use a raw SQL query (see <a href="http://docs.djangoproject.com/en/dev/topics/db/sql/#topics-db-sql">documentation</a>). I think this could be the best option, but again - only if you really see a real performance issue.</p>
| 11 | 2009-06-25T07:43:46Z | [
"python",
"django",
"indexing",
"django-queryset"
] |
Get the index of an element in a queryset | 1,042,596 | <p>I have a QuerySet, let's call it <code>qs</code>, which is ordered by some attribute which is irrelevant to this problem. Then I have an object, let's call it <code>obj</code>. Now I'd like to know at what index <code>obj</code> has in <code>qs</code>, as <em>efficiently</em> as possible. I know that I could use <code>.index()</code> from Python or possibly loop through <code>qs</code> comparing each object to <code>obj</code>, but what is the best way to go about doing this? I'm looking for high performance and that's my only criteria.</p>
<p>Using Python 2.6.2 with Django 1.0.2 on Windows.</p>
| 17 | 2009-06-25T07:31:24Z | 1,042,664 | <p>Compact and probably the most efficient:</p>
<pre><code>for index, item in enumerate(your_queryset):
...
</code></pre>
| 38 | 2009-06-25T07:50:35Z | [
"python",
"django",
"indexing",
"django-queryset"
] |
Get the index of an element in a queryset | 1,042,596 | <p>I have a QuerySet, let's call it <code>qs</code>, which is ordered by some attribute which is irrelevant to this problem. Then I have an object, let's call it <code>obj</code>. Now I'd like to know at what index <code>obj</code> has in <code>qs</code>, as <em>efficiently</em> as possible. I know that I could use <code>.index()</code> from Python or possibly loop through <code>qs</code> comparing each object to <code>obj</code>, but what is the best way to go about doing this? I'm looking for high performance and that's my only criteria.</p>
<p>Using Python 2.6.2 with Django 1.0.2 on Windows.</p>
| 17 | 2009-06-25T07:31:24Z | 1,044,552 | <p>Assuming for the purpose of illustration that your models are standard with a primary key <code>id</code>, then evaluating</p>
<pre><code>list(qs.values_list('id', flat=True)).index(obj.id)
</code></pre>
<p>will find the index of <code>obj</code> in <code>qs</code>. While the use of <code>list</code> evaluates the queryset, it evaluates not the original queryset but a derived queryset. This evaluation runs a SQL query to get the id fields only, not wasting time fetching other fields.</p>
| 7 | 2009-06-25T15:22:17Z | [
"python",
"django",
"indexing",
"django-queryset"
] |
Get the index of an element in a queryset | 1,042,596 | <p>I have a QuerySet, let's call it <code>qs</code>, which is ordered by some attribute which is irrelevant to this problem. Then I have an object, let's call it <code>obj</code>. Now I'd like to know at what index <code>obj</code> has in <code>qs</code>, as <em>efficiently</em> as possible. I know that I could use <code>.index()</code> from Python or possibly loop through <code>qs</code> comparing each object to <code>obj</code>, but what is the best way to go about doing this? I'm looking for high performance and that's my only criteria.</p>
<p>Using Python 2.6.2 with Django 1.0.2 on Windows.</p>
| 17 | 2009-06-25T07:31:24Z | 12,418,866 | <p>Just for an update, first of all, query set is unordered. So, the index may vary for different iteration. You need to do <code>order_by</code> over any field and then following Vinay's answer will help in case if you just need the index.</p>
| 1 | 2012-09-14T05:55:50Z | [
"python",
"django",
"indexing",
"django-queryset"
] |
Get the index of an element in a queryset | 1,042,596 | <p>I have a QuerySet, let's call it <code>qs</code>, which is ordered by some attribute which is irrelevant to this problem. Then I have an object, let's call it <code>obj</code>. Now I'd like to know at what index <code>obj</code> has in <code>qs</code>, as <em>efficiently</em> as possible. I know that I could use <code>.index()</code> from Python or possibly loop through <code>qs</code> comparing each object to <code>obj</code>, but what is the best way to go about doing this? I'm looking for high performance and that's my only criteria.</p>
<p>Using Python 2.6.2 with Django 1.0.2 on Windows.</p>
| 17 | 2009-06-25T07:31:24Z | 14,772,317 | <p>If you just want to know where you object sits amongst all others (e.g. when determining rank), you can do it quickly by counting the objects before you:</p>
<pre><code> index = MyModel.objects.filter(sortField__lt = myObject.sortField).count()
</code></pre>
| 14 | 2013-02-08T12:13:05Z | [
"python",
"django",
"indexing",
"django-queryset"
] |
Get the index of an element in a queryset | 1,042,596 | <p>I have a QuerySet, let's call it <code>qs</code>, which is ordered by some attribute which is irrelevant to this problem. Then I have an object, let's call it <code>obj</code>. Now I'd like to know at what index <code>obj</code> has in <code>qs</code>, as <em>efficiently</em> as possible. I know that I could use <code>.index()</code> from Python or possibly loop through <code>qs</code> comparing each object to <code>obj</code>, but what is the best way to go about doing this? I'm looking for high performance and that's my only criteria.</p>
<p>Using Python 2.6.2 with Django 1.0.2 on Windows.</p>
| 17 | 2009-06-25T07:31:24Z | 21,466,637 | <p>You can do this using <a href="https://docs.djangoproject.com/en/dev/ref/models/querysets/#django.db.models.query.QuerySet.extra" rel="nofollow"><code>queryset.extra(â¦)</code></a> and some raw SQL like so:</p>
<pre><code>queryset = queryset.order_by("id")
record500 = queryset[500]
numbered_qs = queryset.extra(select={
'queryset_row_number': 'ROW_NUMBER() OVER (ORDER BY "id")'
})
from django.db import connection
cursor = connection.cursor()
cursor.execute(
"WITH OrderedQueryset AS (" + str(numbered_qs.query) + ") "
"SELECT queryset_row_number FROM OrderedQueryset WHERE id = %s",
[record500.id]
)
index = cursor.fetchall()[0][0]
index == 501 # because row_number() is 1 indexed not 0 indexed
</code></pre>
| 1 | 2014-01-30T20:17:59Z | [
"python",
"django",
"indexing",
"django-queryset"
] |
Splitting a string @ once using different seps | 1,042,751 | <pre><code>datetime = '0000-00-00 00:00:00'.split('-')
</code></pre>
<p>Right now it just splits it at the hyphen, but is it possible to split this string at both -'s and :'s ?</p>
| 0 | 2009-06-25T08:14:42Z | 1,042,756 | <p>One idea would be something like this (untested):</p>
<pre><code>years, months, days = the_string.split('-')
days, time = days.split(' ')
time = time.split(':')
</code></pre>
<p>Or this, which fits your data better.</p>
<pre><code>date, time = the_string.split(' ')
years, months, days = date.split('-')
hours, minute, seconds = time.split(":")
</code></pre>
| 5 | 2009-06-25T08:15:47Z | [
"python",
"string",
"split"
] |
Splitting a string @ once using different seps | 1,042,751 | <pre><code>datetime = '0000-00-00 00:00:00'.split('-')
</code></pre>
<p>Right now it just splits it at the hyphen, but is it possible to split this string at both -'s and :'s ?</p>
| 0 | 2009-06-25T08:14:42Z | 1,042,770 | <p>I'm guessing you also want to split on the space in the middle:</p>
<pre><code>import re
values = re.split(r'[- :]', "1122-33-44 55:66:77")
print values
# Prints ['1122', '33', '44', '55', '66', '77']
</code></pre>
| 13 | 2009-06-25T08:18:34Z | [
"python",
"string",
"split"
] |
Splitting a string @ once using different seps | 1,042,751 | <pre><code>datetime = '0000-00-00 00:00:00'.split('-')
</code></pre>
<p>Right now it just splits it at the hyphen, but is it possible to split this string at both -'s and :'s ?</p>
| 0 | 2009-06-25T08:14:42Z | 1,042,782 | <p>Using regexps, and using a pattern to match the desired format,</p>
<pre><code>>>> pat = r"(\d{4})-(\d\d)-(\d\d) (\d\d):(\d\d):(\d\d)"
>>> m = re.match(pat,'0000-00-00 00:00:00')
>>> m.groups()
('0000', '00', '00', '00', '00', '00')
>>>
</code></pre>
<p>A more verbose option, named groups, will pair field names with values (for <a href="http://stackoverflow.com/users/86472/skurpur">@skurpur</a>).</p>
<pre><code>>>> pat = "(?P<year>\d{4})-(?P<month>\d\d)-(?P<day>\d\d) (?P<hour>\d\d):(?P<min>\d\d):(?P<sec>\d\d)"
>>> m = re.match(pat,'0000-00-00 00:00:00')
>>> m.groupdict()
{'hour': '00', 'min': '00', 'month': '00', 'sec': '00', 'year': '0000', 'day': '00'}
>>>
</code></pre>
| 0 | 2009-06-25T09:07:39Z | [
"python",
"string",
"split"
] |
Splitting a string @ once using different seps | 1,042,751 | <pre><code>datetime = '0000-00-00 00:00:00'.split('-')
</code></pre>
<p>Right now it just splits it at the hyphen, but is it possible to split this string at both -'s and :'s ?</p>
| 0 | 2009-06-25T08:14:42Z | 1,044,663 | <p>Maybe what you really want is to parse the date </p>
<pre><code>>>> from time import strptime
>>> strptime( '2000-01-01 00:00:00', '%Y-%m-%d %H:%M:%S')
time.struct_time(tm_year=2000, tm_mon=1, tm_mday=1, tm_hour=0, tm_min=0, tm_sec=0, tm_wday=5, tm_yday=1, tm_isdst=-1)
>>>
</code></pre>
| 2 | 2009-06-25T15:42:30Z | [
"python",
"string",
"split"
] |
can I use expect on windows without installing cygwin? | 1,042,778 | <p>expect is a module used for spawning child applications and controlling them. I'm interested in python/ruby.</p>
| 11 | 2009-06-25T09:06:01Z | 1,042,973 | <p>use pexpect <a href="http://sourceforge.net/projects/pexpect/" rel="nofollow">http://sourceforge.net/projects/pexpect/</a></p>
<p>"Pexpect is pure Python" so it will run anywhere, without cygwin too,</p>
<p>edit: pexpect depends on pty module which is currently availble only for linux, so as <strong>Nik</strong> suggested you should be using wexpect which is port of pexpect </p>
| 0 | 2009-06-25T09:52:41Z | [
"python",
"ruby",
"expect"
] |
can I use expect on windows without installing cygwin? | 1,042,778 | <p>expect is a module used for spawning child applications and controlling them. I'm interested in python/ruby.</p>
| 11 | 2009-06-25T09:06:01Z | 1,042,975 | <p>There is <a href="http://sage.math.washington.edu/home/goreckc/sage/wexpect/">WExpect for Python</a>. </p>
<p>Notes in the <code>wexpect.py</code> file (typos unchanged and highlighting added)</p>
<blockquote>
<p><b>Wexpect</b> is a port of pexpext to Windows. Since python for Windows lacks
the requisite modules (pty, tty, select, termios, fctnl, and resource) to run
pexpect, it was necessary to create a back-end that implemented any functions
that were used that relied on these modules. <b>Wtty.py</b> is this back-end. In
the Windows world consoles are not homogeneous. They can use low level or high
level input and output functions, and to correctly deal with both cases two
child processes are created for instacne of Spawn, with an intermidate child
that can continuously read from the console, and send that data over a pipe
to an instance of wtty. <b>Spawner.py</b> is resposible from reading and piping
data.</p>
<p>I've left as much code intact as I could and also tried to leave as many comments
intact is possible (espicially for functions that have not been changed) so many
of the comments will be misleading in their relationship to os specific
functionality. Also, <b>the functions sendcontrol and sendeof are unimplemnted at
this time, as I could not find meaningful Windows versions of these functions.</b><br>
additionally, consoles do not have associated fild descriptors on Windows, so the
global variable child_fd will always be None.</p>
</blockquote>
| 15 | 2009-06-25T09:52:59Z | [
"python",
"ruby",
"expect"
] |
can I use expect on windows without installing cygwin? | 1,042,778 | <p>expect is a module used for spawning child applications and controlling them. I'm interested in python/ruby.</p>
| 11 | 2009-06-25T09:06:01Z | 2,581,825 | <p>The latest working version of wexpect lives at <a href="http://sage.math.washington.edu/home/goreckc/sage/wexpect/" rel="nofollow">http://sage.math.washington.edu/home/goreckc/sage/wexpect/</a></p>
<p>Hopefully it will be merged upstream soon.</p>
| 2 | 2010-04-05T23:47:49Z | [
"python",
"ruby",
"expect"
] |
can I use expect on windows without installing cygwin? | 1,042,778 | <p>expect is a module used for spawning child applications and controlling them. I'm interested in python/ruby.</p>
| 11 | 2009-06-25T09:06:01Z | 3,285,197 | <p>winpexpect is a native port of pexpect to windows. It can be found here:</p>
<p><a href="http://bitbucket.org/geertj/winpexpect" rel="nofollow">http://bitbucket.org/geertj/winpexpect</a></p>
| 3 | 2010-07-19T21:21:36Z | [
"python",
"ruby",
"expect"
] |
can I use expect on windows without installing cygwin? | 1,042,778 | <p>expect is a module used for spawning child applications and controlling them. I'm interested in python/ruby.</p>
| 11 | 2009-06-25T09:06:01Z | 31,612,918 | <p>I know it's an old post, but I've successfully used Pexpect under Cygwin.
For now there is no other way due to POSIX compatibility problems under Windows.</p>
<p>Another thing: WExpect works like Pexpect, infact it requires Cygwin!
At this point, PExpect is a better choice.</p>
<p>Hope this will help</p>
<p>Fabio</p>
| 0 | 2015-07-24T14:18:18Z | [
"python",
"ruby",
"expect"
] |
can I use expect on windows without installing cygwin? | 1,042,778 | <p>expect is a module used for spawning child applications and controlling them. I'm interested in python/ruby.</p>
| 11 | 2009-06-25T09:06:01Z | 37,293,437 | <p>You can use windows CMD prompt.</p>
<p>You need to have python installed in your windows.</p>
<p>open cmd prompt and execute the below command.</p>
<p><strong>C:\Users\xxx>pip install pexpect</strong> (if you have set Python Path in system variable)</p>
<p>or </p>
<p><strong>C:\Users\xxx>c:\python27\scripts\pip.exe install pexpect</strong> </p>
<p>You are using pip version 7.1.0, however version 8.1.2 is available.
You should consider upgrading via the 'python -m pip install --upgrade pip' command.</p>
<p>Collecting pexpect</p>
<p>Downloading pexpect-4.0.1.tar.gz (143kB)</p>
<pre><code>100% |################################| 147kB 1.2MB/s
</code></pre>
<p>Collecting ptyprocess>=0.5 (from pexpect)</p>
<p>Downloading ptyprocess-0.5.1-py2.py3-none-any.whl</p>
<p>Building wheels for collected packages: pexpect</p>
<p>Running setup.py bdist_wheel for pexpect</p>
<p>Stored in directory: C:\Users\xxx\AppData\Local\pip\Cache\wheels\f2\65\89\09578bcd0efeabc7e2b0079cd62d3955c1477f2e55aa5031a4</p>
<p>Successfully built pexpect</p>
<p>Installing collected packages: ptyprocess, pexpect</p>
<p>Successfully installed pexpect-4.0.1 ptyprocess-0.5.1</p>
| 2 | 2016-05-18T07:52:55Z | [
"python",
"ruby",
"expect"
] |
Does Key.from_path hit the datastore? | 1,042,783 | <p>I have a list of key names that I want to bulk fetch
(the key names are stored in a StringListProperty attached to an entity).
My general plan was to do: </p>
<pre><code>usernames = userrefInstance.users # A collection of strings on another
model.
keys = [Key.from_path('User', key_name) for username in usernames]
users = db.get(keys)
</code></pre>
<p>My questions does Key.from_path hit the datastore? I am trying to be as
quick as possible and if Key.from_path hits the data store I need to work
another way to store a collection of keys - I don't particularly want to
store the Key object in a list property as I also provide user
friendly queries across the StringListPropererties. </p>
| 2 | 2009-06-25T09:07:42Z | 1,042,794 | <p>After digging and questions on another group, it turns out that:</p>
<blockquote>
<p>keys are entirely determined by the app
ID and the path, so there's no need to
access the datastore for this. - Nick Johnson </p>
</blockquote>
<p>Or you can also use a List of db.Key</p>
| 3 | 2009-06-25T09:10:27Z | [
"python",
"google-app-engine",
"gae-datastore"
] |
Does Key.from_path hit the datastore? | 1,042,783 | <p>I have a list of key names that I want to bulk fetch
(the key names are stored in a StringListProperty attached to an entity).
My general plan was to do: </p>
<pre><code>usernames = userrefInstance.users # A collection of strings on another
model.
keys = [Key.from_path('User', key_name) for username in usernames]
users = db.get(keys)
</code></pre>
<p>My questions does Key.from_path hit the datastore? I am trying to be as
quick as possible and if Key.from_path hits the data store I need to work
another way to store a collection of keys - I don't particularly want to
store the Key object in a list property as I also provide user
friendly queries across the StringListPropererties. </p>
| 2 | 2009-06-25T09:07:42Z | 11,876,962 | <p>The parameters you pass to <code>Key.from_path()</code> contain all the information necessary to build the unique key so there is no need for it to hit the datastore.</p>
<blockquote>
<p>Each entity in the Datastore has a key that uniquely identifies it.
The key consists of the following components:</p>
<ol>
<li>The kind of the entity, which categorizes it for the purpose of Datastore queries</li>
<li>An identifier for the individual entity, which can be either
<ul>
<li>a key name string</li>
<li>an integer numeric ID</li>
</ul></li>
<li>An optional ancestor path locating the entity within the Datastore hierarchy</li>
</ol>
</blockquote>
<p>source: <a href="https://developers.google.com/appengine/docs/python/datastore/entities" rel="nofollow">https://developers.google.com/appengine/docs/python/datastore/entities</a></p>
| 0 | 2012-08-09T04:46:37Z | [
"python",
"google-app-engine",
"gae-datastore"
] |
Django unit testing with date/time-based objects | 1,042,900 | <p>Suppose I have the following <code>Event</code> model:</p>
<pre><code>from django.db import models
import datetime
class Event(models.Model):
date_start = models.DateField()
date_end = models.DateField()
def is_over(self):
return datetime.date.today() > self.date_end
</code></pre>
<p>I want to test <code>Event.is_over()</code> by creating an Event that ends in the future (today + 1 or something), and stubbing the date and time so the system thinks we've reached that future date.</p>
<p>I'd like to be able to stub ALL system time objects as far as python is concerned. This includes <code>datetime.date.today()</code>, <code>datetime.datetime.now()</code>, and any other standard date/time objects.</p>
<p>What's the standard way to do this?</p>
| 19 | 2009-06-25T09:35:09Z | 1,043,090 | <p>Two choices.</p>
<ol>
<li><p>Mock out datetime by providing your own. Since the local directory is searched before the standard library directories, you can put your tests in a directory with your own mock version of datetime. This is harder than it appears, because you don't know all the places datetime is secretly used.</p></li>
<li><p>Use <strong>Strategy</strong>. Replace explicit references to <code>datetime.date.today()</code> and <code>datetime.date.now()</code> in your code with a <strong>Factory</strong> that generates these. The <strong>Factory</strong> must be configured with the module by the application (or the unittest). This configuration (called "Dependency Injection" by some) allows you to replace the normal run-time <strong>Factory</strong> with a special test factory. You gain a lot of flexibility with no special case handling of production. No "if testing do this differently" business.</p></li>
</ol>
<p>Here's the <strong>Strategy</strong> version.</p>
<pre><code>class DateTimeFactory( object ):
"""Today and now, based on server's defined locale.
A subclass may apply different rules for determining "today".
For example, the broswer's time-zone could be used instead of the
server's timezone.
"""
def getToday( self ):
return datetime.date.today()
def getNow( self ):
return datetime.datetime.now()
class Event( models.Model ):
dateFactory= DateTimeFactory() # Definitions of "now" and "today".
... etc. ...
def is_over( self ):
return dateFactory.getToday() > self.date_end
class DateTimeMock( object ):
def __init__( self, year, month, day, hour=0, minute=0, second=0, date=None ):
if date:
self.today= date
self.now= datetime.datetime.combine(date,datetime.time(hour,minute,second))
else:
self.today= datetime.date(year, month, day )
self.now= datetime.datetime( year, month, day, hour, minute, second )
def getToday( self ):
return self.today
def getNow( self ):
return self.now
</code></pre>
<p>Now you can do this</p>
<pre><code>class SomeTest( unittest.TestCase ):
def setUp( self ):
tomorrow = datetime.date.today() + datetime.timedelta(1)
self.dateFactoryTomorrow= DateTimeMock( date=tomorrow )
yesterday = datetime.date.today() + datetime.timedelta(1)
self.dateFactoryYesterday= DateTimeMock( date=yesterday )
def testThis( self ):
x= Event( ... )
x.dateFactory= self.dateFactoryTomorrow
self.assertFalse( x.is_over() )
x.dateFactory= self.dateFactoryYesterday
self.asserTrue( x.is_over() )
</code></pre>
<p>In the long run, you more-or-less <strong>must</strong> do this to account for browser locale separate from server locale. Using default <code>datetime.datetime.now()</code> uses the server's locale, which may piss off users who are in a different time zone.</p>
| -5 | 2009-06-25T10:16:29Z | [
"python",
"django",
"unit-testing",
"datetime",
"stub"
] |
Django unit testing with date/time-based objects | 1,042,900 | <p>Suppose I have the following <code>Event</code> model:</p>
<pre><code>from django.db import models
import datetime
class Event(models.Model):
date_start = models.DateField()
date_end = models.DateField()
def is_over(self):
return datetime.date.today() > self.date_end
</code></pre>
<p>I want to test <code>Event.is_over()</code> by creating an Event that ends in the future (today + 1 or something), and stubbing the date and time so the system thinks we've reached that future date.</p>
<p>I'd like to be able to stub ALL system time objects as far as python is concerned. This includes <code>datetime.date.today()</code>, <code>datetime.datetime.now()</code>, and any other standard date/time objects.</p>
<p>What's the standard way to do this?</p>
| 19 | 2009-06-25T09:35:09Z | 1,043,119 | <p>You could write your own datetime module replacement class, implementing the methods and classes from datetime that you want to replace. For example:</p>
<pre><code>import datetime as datetime_orig
class DatetimeStub(object):
"""A datetimestub object to replace methods and classes from
the datetime module.
Usage:
import sys
sys.modules['datetime'] = DatetimeStub()
"""
class datetime(datetime_orig.datetime):
@classmethod
def now(cls):
"""Override the datetime.now() method to return a
datetime one year in the future
"""
result = datetime_orig.datetime.now()
return result.replace(year=result.year + 1)
def __getattr__(self, attr):
"""Get the default implementation for the classes and methods
from datetime that are not replaced
"""
return getattr(datetime_orig, attr)
</code></pre>
<p>Let's put this in its own module we'll call <code>datetimestub.py</code></p>
<p>Then, at the start of your test, you can do this:</p>
<pre><code>import sys
import datetimestub
sys.modules['datetime'] = datetimestub.DatetimeStub()
</code></pre>
<p>Any subsequent import of the <code>datetime</code> module will then use the <code>datetimestub.DatetimeStub</code> instance, because when a module's name is used as a key in the <code>sys.modules</code> dictionary, the module will not be imported: the object at <code>sys.modules[module_name]</code> will be used instead.</p>
| 7 | 2009-06-25T10:23:35Z | [
"python",
"django",
"unit-testing",
"datetime",
"stub"
] |
Django unit testing with date/time-based objects | 1,042,900 | <p>Suppose I have the following <code>Event</code> model:</p>
<pre><code>from django.db import models
import datetime
class Event(models.Model):
date_start = models.DateField()
date_end = models.DateField()
def is_over(self):
return datetime.date.today() > self.date_end
</code></pre>
<p>I want to test <code>Event.is_over()</code> by creating an Event that ends in the future (today + 1 or something), and stubbing the date and time so the system thinks we've reached that future date.</p>
<p>I'd like to be able to stub ALL system time objects as far as python is concerned. This includes <code>datetime.date.today()</code>, <code>datetime.datetime.now()</code>, and any other standard date/time objects.</p>
<p>What's the standard way to do this?</p>
| 19 | 2009-06-25T09:35:09Z | 1,044,010 | <p>Slight variation to Steef's solution. Rather than replacing datetime globally instead you could just replace the datetime module in just the module you are testing, e.g.:</p>
<pre>
<code>
import models # your module with the Event model
import datetimestub
models.datetime = datetimestub.DatetimeStub()
</code>
</pre>
<p>That way the change is much more localised during your test.</p>
| 6 | 2009-06-25T13:41:46Z | [
"python",
"django",
"unit-testing",
"datetime",
"stub"
] |
Django unit testing with date/time-based objects | 1,042,900 | <p>Suppose I have the following <code>Event</code> model:</p>
<pre><code>from django.db import models
import datetime
class Event(models.Model):
date_start = models.DateField()
date_end = models.DateField()
def is_over(self):
return datetime.date.today() > self.date_end
</code></pre>
<p>I want to test <code>Event.is_over()</code> by creating an Event that ends in the future (today + 1 or something), and stubbing the date and time so the system thinks we've reached that future date.</p>
<p>I'd like to be able to stub ALL system time objects as far as python is concerned. This includes <code>datetime.date.today()</code>, <code>datetime.datetime.now()</code>, and any other standard date/time objects.</p>
<p>What's the standard way to do this?</p>
| 19 | 2009-06-25T09:35:09Z | 1,047,458 | <p>This doesn't perform system-wide datetime replacement, but if you get fed up with trying to get something to work you could always add an optional parameter to make it easier for testing.</p>
<pre><code>def is_over(self, today=datetime.datetime.now()):
return today > self.date_end
</code></pre>
| 1 | 2009-06-26T05:11:33Z | [
"python",
"django",
"unit-testing",
"datetime",
"stub"
] |
Django unit testing with date/time-based objects | 1,042,900 | <p>Suppose I have the following <code>Event</code> model:</p>
<pre><code>from django.db import models
import datetime
class Event(models.Model):
date_start = models.DateField()
date_end = models.DateField()
def is_over(self):
return datetime.date.today() > self.date_end
</code></pre>
<p>I want to test <code>Event.is_over()</code> by creating an Event that ends in the future (today + 1 or something), and stubbing the date and time so the system thinks we've reached that future date.</p>
<p>I'd like to be able to stub ALL system time objects as far as python is concerned. This includes <code>datetime.date.today()</code>, <code>datetime.datetime.now()</code>, and any other standard date/time objects.</p>
<p>What's the standard way to do this?</p>
| 19 | 2009-06-25T09:35:09Z | 3,155,865 | <p><strong>EDIT</strong>: Since my answer is the accepted answer here I'm updating it to let everyone know a better way has been created in the meantime, the freezegun library: <a href="https://pypi.python.org/pypi/freezegun" rel="nofollow">https://pypi.python.org/pypi/freezegun</a>. I use this in all my projects when I want to influence time in tests. Have a look at it.</p>
<p><strong>Original answer:</strong></p>
<p>Replacing internal stuff like this is always dangerous because it can have nasty side effects. So what you indeed want, is to have the monkey patching be as local as possible.</p>
<p>We use Michael Foord's excellent mock library: <a href="http://www.voidspace.org.uk/python/mock/" rel="nofollow">http://www.voidspace.org.uk/python/mock/</a> that has a <code>@patch</code> decorator which patches certain functionality, but the monkey patch only lives in the scope of the testing function, and everything is automatically restored after the function runs out of its scope.</p>
<p>The only problem is that the internal <code>datetime</code> module is implemented in C, so by default you won't be able to monkey patch it. We fixed this by making our own simple implementation which <em>can</em> be mocked.</p>
<p>The total solution is something like this (the example is a validator function used within a Django project to validate that a date is in the future). Mind you I took this from a project but took out the non-important stuff, so things may not actually work when copy-pasting this, but you get the idea, I hope :)</p>
<p>First we define our own very simple implementation of <code>datetime.date.today</code> in a file called <code>utils/date.py</code>:</p>
<pre><code>import datetime
def today():
return datetime.date.today()
</code></pre>
<p>Then we create the unittest for this validator in <code>tests.py</code>:</p>
<pre><code>import datetime
import mock
from unittest2 import TestCase
from django.core.exceptions import ValidationError
from .. import validators
class ValidationTests(TestCase):
@mock.patch('utils.date.today')
def test_validate_future_date(self, today_mock):
# Pin python's today to returning the same date
# always so we can actually keep on unit testing in the future :)
today_mock.return_value = datetime.date(2010, 1, 1)
# A future date should work
validators.validate_future_date(datetime.date(2010, 1, 2))
# The mocked today's date should fail
with self.assertRaises(ValidationError) as e:
validators.validate_future_date(datetime.date(2010, 1, 1))
self.assertEquals([u'Date should be in the future.'], e.exception.messages)
# Date in the past should also fail
with self.assertRaises(ValidationError) as e:
validators.validate_future_date(datetime.date(2009, 12, 31))
self.assertEquals([u'Date should be in the future.'], e.exception.messages)
</code></pre>
<p>The final implementation looks like this:</p>
<pre><code>from django.utils.translation import ugettext_lazy as _
from django.core.exceptions import ValidationError
from utils import date
def validate_future_date(value):
if value <= date.today():
raise ValidationError(_('Date should be in the future.'))
</code></pre>
<p>Hope this helps</p>
| 23 | 2010-07-01T07:38:18Z | [
"python",
"django",
"unit-testing",
"datetime",
"stub"
] |
Django unit testing with date/time-based objects | 1,042,900 | <p>Suppose I have the following <code>Event</code> model:</p>
<pre><code>from django.db import models
import datetime
class Event(models.Model):
date_start = models.DateField()
date_end = models.DateField()
def is_over(self):
return datetime.date.today() > self.date_end
</code></pre>
<p>I want to test <code>Event.is_over()</code> by creating an Event that ends in the future (today + 1 or something), and stubbing the date and time so the system thinks we've reached that future date.</p>
<p>I'd like to be able to stub ALL system time objects as far as python is concerned. This includes <code>datetime.date.today()</code>, <code>datetime.datetime.now()</code>, and any other standard date/time objects.</p>
<p>What's the standard way to do this?</p>
| 19 | 2009-06-25T09:35:09Z | 3,790,876 | <p>What if you mocked the self.end_date instead of the datetime? Then you could still test that the function is doing what you want without all the other crazy workarounds suggested.</p>
<p>This wouldn't let you stub all date/times like your question initially asks, but that might not be completely necessary.</p>
<pre>
today = datetime.date.today()
event1 = Event()
event1.end_date = today - datetime.timedelta(days=1) # 1 day ago
event2 = Event()
event2.end_date = today + datetime.timedelta(days=1) # 1 day in future
self.assertTrue(event1.is_over())
self.assertFalse(event2.is_over())
</pre>
| 3 | 2010-09-24T20:49:54Z | [
"python",
"django",
"unit-testing",
"datetime",
"stub"
] |
Django unit testing with date/time-based objects | 1,042,900 | <p>Suppose I have the following <code>Event</code> model:</p>
<pre><code>from django.db import models
import datetime
class Event(models.Model):
date_start = models.DateField()
date_end = models.DateField()
def is_over(self):
return datetime.date.today() > self.date_end
</code></pre>
<p>I want to test <code>Event.is_over()</code> by creating an Event that ends in the future (today + 1 or something), and stubbing the date and time so the system thinks we've reached that future date.</p>
<p>I'd like to be able to stub ALL system time objects as far as python is concerned. This includes <code>datetime.date.today()</code>, <code>datetime.datetime.now()</code>, and any other standard date/time objects.</p>
<p>What's the standard way to do this?</p>
| 19 | 2009-06-25T09:35:09Z | 6,941,305 | <p>I'd suggest taking a look at testfixtures test_datetime:</p>
<p><a href="http://packages.python.org/testfixtures/datetime.html" rel="nofollow">http://packages.python.org/testfixtures/datetime.html</a></p>
| 4 | 2011-08-04T12:21:37Z | [
"python",
"django",
"unit-testing",
"datetime",
"stub"
] |
Encrypt a string using a public key | 1,043,382 | <p>I need to take a string in Python and encrypt it using a public key.</p>
<p>Can anyone give me an example or recommendation about how to go about doing this?</p>
| 2 | 2009-06-25T11:19:47Z | 1,043,593 | <p>You'll need a Python cryptography library to do this.</p>
<p>Have a look at <a href="http://www.freenet.org.nz/ezPyCrypto/" rel="nofollow">ezPyCrypto</a>: <em>"As a reaction to some other crypto libraries, which can be painfully complex to understand and use, ezPyCrypto has been designed from the ground up for absolute ease of use, without compromising security."</em></p>
<p>It has an API:</p>
<pre><code>encString(self, raw)
</code></pre>
<p>which looks like what you're after: <em>"High-level func. encrypts an entire string of data, returning the encrypted string as binary."</em></p>
| 3 | 2009-06-25T12:15:47Z | [
"python",
"encryption"
] |
Encrypt a string using a public key | 1,043,382 | <p>I need to take a string in Python and encrypt it using a public key.</p>
<p>Can anyone give me an example or recommendation about how to go about doing this?</p>
| 2 | 2009-06-25T11:19:47Z | 1,044,385 | <p><a href="http://pyme.sourceforge.net/" rel="nofollow">PyMe</a> provides a Python interface to the <a href="http://www.gnupg.org/related%5Fsoftware/gpgme/" rel="nofollow">GPGME</a> library.</p>
<p>You should, in theory, be able to use that to interact with GPG from Python to do whatever encrypting you need to do.</p>
<p>Here's a <strong>very simple</strong> code sample from the <a href="http://pyme.sourceforge.net/doc/pyme/index.html" rel="nofollow">documentation</a>:</p>
<p><strong><em>This program is not for serious encryption, but for example purposes only!</em></strong></p>
<pre><code>import sys
from pyme import core, constants
# Set up our input and output buffers.
plain = core.Data('This is my message.')
cipher = core.Data()
# Initialize our context.
c = core.Context()
c.set_armor(1)
# Set up the recipients.
sys.stdout.write("Enter name of your recipient: ")
name = sys.stdin.readline().strip()
c.op_keylist_start(name, 0)
r = c.op_keylist_next()
# Do the encryption.
c.op_encrypt([r], 1, plain, cipher)
cipher.seek(0,0)
print cipher.read()
</code></pre>
| 2 | 2009-06-25T14:50:24Z | [
"python",
"encryption"
] |
Encrypt a string using a public key | 1,043,382 | <p>I need to take a string in Python and encrypt it using a public key.</p>
<p>Can anyone give me an example or recommendation about how to go about doing this?</p>
| 2 | 2009-06-25T11:19:47Z | 1,051,793 | <p>I looked at the ezPyCrypto library that was recommended in another answer.
Please don't use this library. It is very incomplete and in some cases incorrect and highly insecure. Public key algorithms have many pitfalls and need to be implemented carefully.
For example, RSA message should use a padding scheme such as PKCS #1, OAEP etc to be secure. This library doesn't pad. DSA signatures should use the SHA1 hash function. This library uses the broken MD5 hash and there is even a bigger bug in the random number generation. Hence the DSA implementation is neither standards conform nor secure. ElGamal is also implemented incorrectly.</p>
<p>Following standards does make implementations somewhat more complex. But not following any is not an option. At least not if you care about security. </p>
| 2 | 2009-06-27T00:22:06Z | [
"python",
"encryption"
] |
Encrypt a string using a public key | 1,043,382 | <p>I need to take a string in Python and encrypt it using a public key.</p>
<p>Can anyone give me an example or recommendation about how to go about doing this?</p>
| 2 | 2009-06-25T11:19:47Z | 15,749,621 | <p>An even "simpler" example without the use of any additional libraries would be:</p>
<pre><code>def rsa():
# Choose two prime numbers p and q
p = raw_input('Choose a p: ')
p = int(p)
while isPrime(p) == False:
print "Please ensure p is prime"
p = raw_input('Choose a p: ')
p = int(p)
q = raw_input('Choose a q: ')
q = int(q)
while isPrime(q) == False or p==q:
print "Please ensure q is prime and NOT the same value as p"
q = raw_input('Choose a q: ')
q = int(q)
# Compute n = pq
n = p * q
# Compute the phi of n
phi = (p-1) * (q-1)
# Choose an integer e such that e and phi(n) are coprime
e = random.randrange(1,phi)
# Use Euclid's Algorithm to verify that e and phi(n) are comprime
g = euclid(e,phi)
while(g!=1):
e = random.randrange(1,phi)
g = euclid(e,phi)
# Use Extended Euclid's Algorithm
d = extended_euclid(e,phi)
# Public and Private Key have been generated
public_key=(e,n)
private_key=(d,n)
print "Public Key [E,N]: ", public_key
print "Private Key [D,N]: ", private_key
# Enter plain text to be encrypted using the Public Key
sentence = raw_input('Enter plain text: ')
letters = list(sentence)
cipher = []
num = ""
# Encrypt the plain text
for i in range(0,len(letters)):
print "Value of ", letters[i], " is ", character[letters[i]]
c = (character[letters[i]]**e)%n
cipher += [c]
num += str(c)
print "Cipher Text is: ", num
plain = []
sentence = ""
# Decrypt the cipher text
for j in range(0,len(cipher)):
p = (cipher[j]**d)%n
for key in character.keys():
if character[key]==p:
plain += [key]
sentence += key
break
print "Plain Text is: ", sentence
# Euclid's Algorithm
def euclid(a, b):
if b==0:
return a
else:
return euclid(b, a % b)
# Euclid's Extended Algorithm
def extended_euclid(e,phi):
d=0
x1=0
x2=1
y1=1
orig_phi = phi
tempPhi = phi
while (e>0):
temp1 = int(tempPhi/e)
temp2 = tempPhi - temp1 * e
tempPhi = e
e = temp2
x = x2- temp1* x1
y = d - temp1 * y1
x2 = x1
x1 = x
d = y1
y1 = y
if tempPhi == 1:
d += phi
break
return d
# Checks if n is a prime number
def isPrime(n):
for i in range(2,n):
if n%i == 0:
return False
return True
character = {"A":1,"B":2,"C":3,"D":4,"E":5,"F":6,"G":7,"H":8,"I":9,"J":10,
"K":11,"L":12,"M":13,"N":14,"O":15,"P":16,"Q":17,"R":18,"S":19,
"T":20,"U":21,"V":22,"W":23,"X":24,"Y":25,"Z":26,"a":27,"b":28,
"c":29,"d":30,"e":31,"f":32,"g":33,"h":34,"i":35,"j":36,"k":37,
"l":38,"m":39,"n":40,"o":41,"p":42,"q":43,"r":44,"s":45,"t":46,
"u":47,"v":48,"w":49,"x":50,"y":51,"z":52, " ":53, ".":54, ",":55,
"?":56,"/":57,"!":58,"(":59,")":60,"$":61,":":62,";":63,"'":64,"@":65,
"#":66,"%":67,"^":68,"&":69,"*":70,"+":71,"-":72,"_":73,"=":74}
</code></pre>
| 0 | 2013-04-01T18:49:51Z | [
"python",
"encryption"
] |
Best Practise for transferring a MySQL table to another server? | 1,043,528 | <p>I have a system sitting on a "Master Server", that is periodically transferring quite a few chunks of information from a MySQL DB to another server in the web.</p>
<p>Both servers have a MySQL Server and an Apache running. I would like an easy-to-use solution for this.</p>
<p>Currently I'm looking into:</p>
<ul>
<li>XMLRPC</li>
<li>RestFul Services</li>
<li>a simple POST to a processing script</li>
<li>socket transfers</li>
</ul>
<p>The app on my master is a TurboGears app, so I would prefer "pythonic" aka less ugly solutions. Copying a dumped table to another server via FTP / SCP or something like that might be quick, but in my eyes it is also very (quick and) dirty, and I'd love to have a nicer solution.</p>
<p>Can anyone describe shortly how you would do this the "best-practise" way?</p>
<p>This doesn't necessarily have to involve Databases. Dumping the table on Server1 and transferring the raw data in a structured way so server2 can process it without parsing too much is just as good. One requirement though: As soon as the data arrives on server2, I want it to be processed, so there has to be a notification of some sort when the transfer is done. Of course I could just write my whole own server sitting on a socket on the second machine and accepting the file with own code and processing it and so forth, but this is just a very very small piece of a very big system, so I dont want to spend half a day implementing this.</p>
<p>Thanks,</p>
<p>Tom</p>
| 2 | 2009-06-25T11:59:01Z | 1,043,595 | <p>Assuming your situation allows this security-wise, you forgot one transport mechanism: simply opening a mysql connection from one server to another.</p>
<p>Me, I would start by thinking about one script that ran regularly on the write server and opens a read only db connection to the read server (A bit of added security) and a full connection to it's own data base server. </p>
<p>How you then proceed depends on the data (is it just inserts to deal with? do you have to mirror deletes? how many inserts vs updates? etc) but basically you could write a script that pulled data from the read server and processed it immediately into the write server.</p>
<p>Also, would mysql server replication work or would it be to over-blown as a solution?</p>
| 0 | 2009-06-25T12:16:06Z | [
"python",
"web-services",
"database-design"
] |
Best Practise for transferring a MySQL table to another server? | 1,043,528 | <p>I have a system sitting on a "Master Server", that is periodically transferring quite a few chunks of information from a MySQL DB to another server in the web.</p>
<p>Both servers have a MySQL Server and an Apache running. I would like an easy-to-use solution for this.</p>
<p>Currently I'm looking into:</p>
<ul>
<li>XMLRPC</li>
<li>RestFul Services</li>
<li>a simple POST to a processing script</li>
<li>socket transfers</li>
</ul>
<p>The app on my master is a TurboGears app, so I would prefer "pythonic" aka less ugly solutions. Copying a dumped table to another server via FTP / SCP or something like that might be quick, but in my eyes it is also very (quick and) dirty, and I'd love to have a nicer solution.</p>
<p>Can anyone describe shortly how you would do this the "best-practise" way?</p>
<p>This doesn't necessarily have to involve Databases. Dumping the table on Server1 and transferring the raw data in a structured way so server2 can process it without parsing too much is just as good. One requirement though: As soon as the data arrives on server2, I want it to be processed, so there has to be a notification of some sort when the transfer is done. Of course I could just write my whole own server sitting on a socket on the second machine and accepting the file with own code and processing it and so forth, but this is just a very very small piece of a very big system, so I dont want to spend half a day implementing this.</p>
<p>Thanks,</p>
<p>Tom</p>
| 2 | 2009-06-25T11:59:01Z | 1,043,596 | <p>If you have access to MySQL's data port, and don't mind the constant network traffic, you can use <a href="http://dev.mysql.com/doc/refman/5.1/en/replication-howto.html" rel="nofollow">replication</a>.</p>
| 0 | 2009-06-25T12:16:16Z | [
"python",
"web-services",
"database-design"
] |
Best Practise for transferring a MySQL table to another server? | 1,043,528 | <p>I have a system sitting on a "Master Server", that is periodically transferring quite a few chunks of information from a MySQL DB to another server in the web.</p>
<p>Both servers have a MySQL Server and an Apache running. I would like an easy-to-use solution for this.</p>
<p>Currently I'm looking into:</p>
<ul>
<li>XMLRPC</li>
<li>RestFul Services</li>
<li>a simple POST to a processing script</li>
<li>socket transfers</li>
</ul>
<p>The app on my master is a TurboGears app, so I would prefer "pythonic" aka less ugly solutions. Copying a dumped table to another server via FTP / SCP or something like that might be quick, but in my eyes it is also very (quick and) dirty, and I'd love to have a nicer solution.</p>
<p>Can anyone describe shortly how you would do this the "best-practise" way?</p>
<p>This doesn't necessarily have to involve Databases. Dumping the table on Server1 and transferring the raw data in a structured way so server2 can process it without parsing too much is just as good. One requirement though: As soon as the data arrives on server2, I want it to be processed, so there has to be a notification of some sort when the transfer is done. Of course I could just write my whole own server sitting on a socket on the second machine and accepting the file with own code and processing it and so forth, but this is just a very very small piece of a very big system, so I dont want to spend half a day implementing this.</p>
<p>Thanks,</p>
<p>Tom</p>
| 2 | 2009-06-25T11:59:01Z | 1,043,615 | <p>If the table is small and you can send the whole table and just delete the old data and then insert the new data on remote server - then there can be an easy generic solution: you can create a long string with table data and send it via webservice. Here is how it can be implemented. Note, that this is far not perfect solution, just an example how I transfer small simple tables between websites:</p>
<pre><code>function DumpTableIntoString($tableName, $includeFieldsHeader = true)
{
global $adoConn;
$recordSet = $adoConn->Execute("SELECT * FROM $tableName");
if(!$recordSet) return false;
$data = "";
if($includeFieldsHeader)
{
// fetching fields
$numFields = $recordSet->FieldCount();
for($i = 0; $i < $numFields; $i++)
$data .= $recordSet->FetchField($i)->name . ",";
$data = substr($data, 0, -1) . "\n";
}
while(!$recordSet->EOF)
{
$row = $recordSet->GetRowAssoc();
foreach ($row as &$value)
{
$value = str_replace("\r\n", "", $value);
$value = str_replace('"', '\\"', $value);
if($value == null) $value = "\\N";
$value = "\"" . $value . "\"";
}
$data .= join(',', $row);
$recordSet->MoveNext();
if(!$recordSet->EOF)
$data .= "\n";
}
return $data;
}
// NOTE: CURRENTLY FUNCTION DOESN'T SUPPORT HANDLING FIELDS HEADER, SO NOW IT JUST SKIPS IT
// IF NECESSARRY
function FillTableFromDumpString($tableName, $dumpString, $truncateTable = true, $fieldsHeaderIncluded = true)
{
global $adoConn;
if($truncateTable)
if($adoConn->Execute("TRUNCATE TABLE $tableName") === false)
return false;
$rows = explode("\n", $dumpString);
$startRowIndex = $fieldsHeaderIncluded ? 1 : 0;
$query = "INSERT INTO $tableName VALUES ";
$numRows = count($rows);
for($i = $startRowIndex; $i < $numRows; $i++)
{
$row = explode(",", $rows[$i]);
foreach($row as &$value)
{
if($value == "\"\\N\"")
$value = "NULL";
}
$query .= "(". implode(",", $row) .")";
if($i != $numRows - 1)
$query .= ",";
}
if($adoConn->Execute($query) === false)
{
return false;
}
return true;
}
</code></pre>
<p>If you have large tables, then I think that you need to send only new data. Ask your remote server for the latest timestamp, and then read all newer data from your main server and send the data either in generic way (as I've shown above) or in non-generic way (in this case you have to write separate functions for each table).</p>
| 1 | 2009-06-25T12:24:14Z | [
"python",
"web-services",
"database-design"
] |
Best Practise for transferring a MySQL table to another server? | 1,043,528 | <p>I have a system sitting on a "Master Server", that is periodically transferring quite a few chunks of information from a MySQL DB to another server in the web.</p>
<p>Both servers have a MySQL Server and an Apache running. I would like an easy-to-use solution for this.</p>
<p>Currently I'm looking into:</p>
<ul>
<li>XMLRPC</li>
<li>RestFul Services</li>
<li>a simple POST to a processing script</li>
<li>socket transfers</li>
</ul>
<p>The app on my master is a TurboGears app, so I would prefer "pythonic" aka less ugly solutions. Copying a dumped table to another server via FTP / SCP or something like that might be quick, but in my eyes it is also very (quick and) dirty, and I'd love to have a nicer solution.</p>
<p>Can anyone describe shortly how you would do this the "best-practise" way?</p>
<p>This doesn't necessarily have to involve Databases. Dumping the table on Server1 and transferring the raw data in a structured way so server2 can process it without parsing too much is just as good. One requirement though: As soon as the data arrives on server2, I want it to be processed, so there has to be a notification of some sort when the transfer is done. Of course I could just write my whole own server sitting on a socket on the second machine and accepting the file with own code and processing it and so forth, but this is just a very very small piece of a very big system, so I dont want to spend half a day implementing this.</p>
<p>Thanks,</p>
<p>Tom</p>
| 2 | 2009-06-25T11:59:01Z | 1,043,653 | <p>Server 1: Convert rows to JSON, call the RESTful api of second with JSON data</p>
<p>Server 2: listens on a URI e.g. POST /data , get json data convert back to dictionary or ORM objects, insert into db</p>
<p>sqlalchemy/sqlobject and simplejson is what you need.</p>
| 2 | 2009-06-25T12:34:33Z | [
"python",
"web-services",
"database-design"
] |
Best Practise for transferring a MySQL table to another server? | 1,043,528 | <p>I have a system sitting on a "Master Server", that is periodically transferring quite a few chunks of information from a MySQL DB to another server in the web.</p>
<p>Both servers have a MySQL Server and an Apache running. I would like an easy-to-use solution for this.</p>
<p>Currently I'm looking into:</p>
<ul>
<li>XMLRPC</li>
<li>RestFul Services</li>
<li>a simple POST to a processing script</li>
<li>socket transfers</li>
</ul>
<p>The app on my master is a TurboGears app, so I would prefer "pythonic" aka less ugly solutions. Copying a dumped table to another server via FTP / SCP or something like that might be quick, but in my eyes it is also very (quick and) dirty, and I'd love to have a nicer solution.</p>
<p>Can anyone describe shortly how you would do this the "best-practise" way?</p>
<p>This doesn't necessarily have to involve Databases. Dumping the table on Server1 and transferring the raw data in a structured way so server2 can process it without parsing too much is just as good. One requirement though: As soon as the data arrives on server2, I want it to be processed, so there has to be a notification of some sort when the transfer is done. Of course I could just write my whole own server sitting on a socket on the second machine and accepting the file with own code and processing it and so forth, but this is just a very very small piece of a very big system, so I dont want to spend half a day implementing this.</p>
<p>Thanks,</p>
<p>Tom</p>
| 2 | 2009-06-25T11:59:01Z | 1,043,697 | <p>If you're using MyISAM or Archive tables, then I would highly recommend <a href="http://dev.mysql.com/doc/refman/5.0/en/mysqlhotcopy.html" rel="nofollow">mysqlhotcopy</a></p>
| 0 | 2009-06-25T12:46:08Z | [
"python",
"web-services",
"database-design"
] |
Making a wxPython application multilingual | 1,043,708 | <p>I have a application written in wxPython which I want to make multilingual.
Our options are</p>
<ol>
<li>using gettext <a href="http://docs.python.org/library/gettext.html" rel="nofollow">http://docs.python.org/library/gettext.html</a></li>
<li>seprating out all UI text to
a messages.py file, and using it to
translate text </li>
</ol>
<p>I am very much inclined towards 2nd and I see no benefit in going gettext way,
using 2nd way i can have all my messages at one place not in code, so If i need to change a message, code need not be changed, in case of gettext i may have confusing msg-constants as I will be just wrapping the orginal msg instead of converting it to a constant in messages.py</p>
<p>basically instead of </p>
<pre><code>wx.MessageBox(_("Hi stackoverflow!"))
</code></pre>
<p>I think</p>
<pre><code>wx.MessageBox(messages.GREET_SO)
</code></pre>
<p>is better, so is there any advantage in gettext way and disadvantage 2nd way? and is there a 3rd way?</p>
<p>edit:
also gettext languages files seems to be too tied to code, and what happens if i want two messages same in english but different in french e.g. suppose french has more subtle translation for different scnerarios for english one is ok</p>
<p>experience:
I have already gone 2nd way, and i must say every application should try to extract UI text from code, it gives a chance to refactor, see where UI is creeping into model and where UI text can be improved, gettext in comparison is mechanic, doesn't gives any input for coder, and i think would be more difficult to maintain.</p>
<p>and while creating a name for text e.g. PRINT_PROGRESS_MSG, gives a chance to see that at many places, same msg is being used slightly differently and can be merged into a single name, which later on will help when i need to change msg only once.</p>
<p>Conclusion: I am still not sure of any advantage to use gettext and am using my own messages file. but I have selected the answer which at least explained few points why gettext can be beneficial.
The final solution IMO is which takes the best from both ways i.e my own message identifier wrapped by gettext e.g</p>
<pre><code>wx.MessageBox(_("GREET_SO"))
</code></pre>
| 2 | 2009-06-25T12:49:08Z | 1,043,747 | <p>For the web (this is PHP but the idea's the same), I always create multiple language files in a specific directory. en.php, fr.php, et cetera. Those files contain definitions of all output text, in the given language. The user preference for language determines which of those files get included, thus, which language the output appears in. For example...</p>
<p>in en.php:
TEXT_I_AM = "I am"</p>
<p>in fr.php:
TEXT_I_AM = "Je suis"</p>
| -1 | 2009-06-25T12:55:10Z | [
"python",
"internationalization",
"multilingual",
"gettext"
] |
Making a wxPython application multilingual | 1,043,708 | <p>I have a application written in wxPython which I want to make multilingual.
Our options are</p>
<ol>
<li>using gettext <a href="http://docs.python.org/library/gettext.html" rel="nofollow">http://docs.python.org/library/gettext.html</a></li>
<li>seprating out all UI text to
a messages.py file, and using it to
translate text </li>
</ol>
<p>I am very much inclined towards 2nd and I see no benefit in going gettext way,
using 2nd way i can have all my messages at one place not in code, so If i need to change a message, code need not be changed, in case of gettext i may have confusing msg-constants as I will be just wrapping the orginal msg instead of converting it to a constant in messages.py</p>
<p>basically instead of </p>
<pre><code>wx.MessageBox(_("Hi stackoverflow!"))
</code></pre>
<p>I think</p>
<pre><code>wx.MessageBox(messages.GREET_SO)
</code></pre>
<p>is better, so is there any advantage in gettext way and disadvantage 2nd way? and is there a 3rd way?</p>
<p>edit:
also gettext languages files seems to be too tied to code, and what happens if i want two messages same in english but different in french e.g. suppose french has more subtle translation for different scnerarios for english one is ok</p>
<p>experience:
I have already gone 2nd way, and i must say every application should try to extract UI text from code, it gives a chance to refactor, see where UI is creeping into model and where UI text can be improved, gettext in comparison is mechanic, doesn't gives any input for coder, and i think would be more difficult to maintain.</p>
<p>and while creating a name for text e.g. PRINT_PROGRESS_MSG, gives a chance to see that at many places, same msg is being used slightly differently and can be merged into a single name, which later on will help when i need to change msg only once.</p>
<p>Conclusion: I am still not sure of any advantage to use gettext and am using my own messages file. but I have selected the answer which at least explained few points why gettext can be beneficial.
The final solution IMO is which takes the best from both ways i.e my own message identifier wrapped by gettext e.g</p>
<pre><code>wx.MessageBox(_("GREET_SO"))
</code></pre>
| 2 | 2009-06-25T12:49:08Z | 1,044,466 | <p>There are some advantages of gettext:</p>
<ol>
<li>One of the biggest advantages is: when using poedit to do the translations you can benefit from the translation database. Basically poedit ca scan your harddisk and find already translated files and will make suggestions when you translate your file.</li>
<li>When you give the code to other people to translate they might already know the gettext way of translating, while you have to explain them your way of translating.</li>
<li>You have the text in the context of the code, so it should be easier to translate, when you see the code around the translation</li>
<li>Consider text like: <code>print _('%d files of %d files selected') % (num, numTotal)</code> and even more complicated situations. Here it really helps having the code around ...</li>
</ol>
| 1 | 2009-06-25T15:05:52Z | [
"python",
"internationalization",
"multilingual",
"gettext"
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.