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
listlengths
1
5
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: ...
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 magi...
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 ski...
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 magi...
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> ...
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 ...
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 r...
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 o...
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....
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 han...
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: ...
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" ...
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>&gt;&gt;&gt; import json &gt;&gt;&gt; json.dumps(json.loads(""" ... {"node0":{ ... "node1":{ ... "attr0":"foo", ... "attr1":"foo bar", ... "attr2":"value with long ...
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" ...
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 slight...
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 ...
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 ...
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 ...
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 &gt;&gt;&gt;func1...
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 no...
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 &gt;&gt;&gt;func1...
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>&gt;&gt;&gt; a = 'hallo' &gt;&gt;&gt; a 'hallo' </code></pre> <p>The last statement has the value o...
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 &gt;&gt;&gt;func1...
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 ...
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 &gt;&gt;&gt;func1...
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&gt;copy con test.py def func1(): list = [1,2,3,4,5] print list return list ^Z 1 file(s) copied. H:\test&gt;python -i test.py &gt;&gt;&gt; func1() [1, 2, 3, 4, 5] [1, 2, 3, 4, 5] &gt;&g...
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/lan...
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.s...
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 ...
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=Non...
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 ...
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></pr...
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&lt;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 ...
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. T...
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&lt;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 ...
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>...
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&lt;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 ...
0
2009-06-24T22:29:36Z
1,041,398
<p>Here's a functional factorial, which you almost asked for:</p> <pre><code>&gt;&gt;&gt; def fact(n): return reduce (lambda x,y: x*y, range(1,n+1)) ... &gt;&gt;&gt; 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>M...
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&lt;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 ...
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 ...
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&lt;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 ...
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>&gt;&gt;&gt; import math &gt;&gt;&gt; math.factorial(5) 120 </code>...
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&lt;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 ...
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...
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&lt;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 ...
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 wa...
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" tutorial...
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 wha...
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" tutorial...
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 b...
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" tutorial...
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...
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" tutorial...
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 ne...
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" tutorial...
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" tutorial...
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....
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" tutorial...
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" tutorial...
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 framewor...
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" tutorial...
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 b...
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 co...
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 hav...
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 co...
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 ...
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 co...
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><...
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 co...
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 co...
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 t...
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 co...
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 le...
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>&gt;&gt;&gt; re.split('-\d', 'foo-bar-1.23-4', 1) ['foo-bar', '.23-4'] </code></pre> <p>and</p> <pre><code>&gt;&gt;&gt...
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 charac...
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>&gt;&gt;&gt; re.split('-\d', 'foo-bar-1.23-4', 1) ['foo-bar', '.23-4'] </code></pre> <p>and</p> <pre><code>&gt;&gt;&gt...
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>&gt;&gt;&gt; re.split('-\d', 'foo-bar-1.23-4', 1) ['foo-bar', '.23-4'] </code></pre> <p>and</p> <pre><code>&gt;&gt;&gt...
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...
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>...
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...
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...
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...
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 c...
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...
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....
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...
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....
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 ...
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....
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...
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....
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 ...
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 addition...
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 urllib...
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 <c...
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 b...
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 <c...
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 <c...
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...
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 <c...
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 <c...
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 <c...
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(se...
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, min...
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>&gt;&gt;&gt; pat = r"(\d{4})-(\d\d)-(\d\d) (\d\d):(\d\d):(\d\d)" &gt;&gt;&gt; m = re.match(pat,'0000-00-00 00:00:00') &gt;&gt;&gt; m.groups() ('0000', '00', '00', '00', '00', '00') &gt;&gt;&gt; </code></pre> <p>A more verbose option, na...
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>&gt;&gt;&gt; from time import strptime &gt;&gt;&gt; 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) &gt;&gt;&gt; </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> s...
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 mo...
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...
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...
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 username...
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 username...
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> <o...
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() &gt; self.date_end </code></pre> <p>I wan...
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 secre...
-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() &gt; self.date_end </code></pre> <p>I wan...
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...
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() &gt; self.date_end </code></pre> <p>I wan...
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> </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() &gt; self.date_end </code></pre> <p>I wan...
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 &gt; 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() &gt; self.date_end </code></pre> <p>I wan...
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 ...
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() &gt; self.date_end </code></pre> <p>I wan...
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> <pr...
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() &gt; self.date_end </code></pre> <p>I wan...
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 abso...
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...
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 ...
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('Choo...
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> ...
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 sec...
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> ...
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> ...
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 perfec...
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> ...
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> ...
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 transl...
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 langu...
-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 transl...
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 ...
1
2009-06-25T15:05:52Z
[ "python", "internationalization", "multilingual", "gettext" ]