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 |
|---|---|---|---|---|---|---|---|---|---|
Controlling mouse with Python | 1,181,464 | <p>How does one control the mouse cursor in Python, i.e. move it to certain position and click, under Windows?</p>
| 101 | 2009-07-25T07:15:30Z | 1,181,539 | <p>You can use <code>win32api</code> or <code>ctypes</code> module to use win32 apis for controlling mouse or any gui</p>
<p>Here is a fun example to control mouse using win32api:</p>
<pre><code>import win32api
import time
import math
for i in range(500):
x = int(500+math.sin(math.pi*i/100)*500)
y = int(500+math.cos(i)*100)
win32api.SetCursorPos((x,y))
time.sleep(.01)
</code></pre>
<p>A click using ctypes:</p>
<pre><code>import ctypes
# see http://msdn.microsoft.com/en-us/library/ms646260(VS.85).aspx for details
ctypes.windll.user32.SetCursorPos(100, 20)
ctypes.windll.user32.mouse_event(2, 0, 0, 0,0) # left down
ctypes.windll.user32.mouse_event(4, 0, 0, 0,0) # left up
</code></pre>
| 60 | 2009-07-25T07:57:19Z | [
"python",
"mouse"
] |
Controlling mouse with Python | 1,181,464 | <p>How does one control the mouse cursor in Python, i.e. move it to certain position and click, under Windows?</p>
| 101 | 2009-07-25T07:15:30Z | 6,600,457 | <p>Check out the cross platform PyMouse: <a href="https://github.com/pepijndevos/PyMouse/">https://github.com/pepijndevos/PyMouse/</a> </p>
| 17 | 2011-07-06T17:24:03Z | [
"python",
"mouse"
] |
Controlling mouse with Python | 1,181,464 | <p>How does one control the mouse cursor in Python, i.e. move it to certain position and click, under Windows?</p>
| 101 | 2009-07-25T07:15:30Z | 17,578,569 | <p>Another option is to use the cross-platform <a href="https://pypi.python.org/pypi/autopy/0.51">AutoPy package</a>. This package has two different options for moving the mouse:</p>
<p>This code snippet will instantly move the cursor to position (200,200):</p>
<pre><code>import autopy
autopy.mouse.move(200,200)
</code></pre>
<p>If you instead want the cursor to visibly move across the screen to a given location, you can use the smooth_move command:</p>
<pre><code>import autopy
autopy.mouse.smooth_move(200,200)
</code></pre>
| 13 | 2013-07-10T18:46:50Z | [
"python",
"mouse"
] |
Controlling mouse with Python | 1,181,464 | <p>How does one control the mouse cursor in Python, i.e. move it to certain position and click, under Windows?</p>
| 101 | 2009-07-25T07:15:30Z | 26,693,987 | <p>Quick and dirty function that'll left click wherever <code>clicks</code> times on Windows 7 using the <a href="https://docs.python.org/2/library/ctypes.html" rel="nofollow"><code>ctypes</code></a> library. No downloads required.</p>
<pre><code>import ctypes
SetCursorPos = ctypes.windll.user32.SetCursorPos
mouse_event = ctypes.windll.user32.mouse_event
def left_click(x, y, clicks=1):
SetCursorPos(x, y)
for i in xrange(clicks):
mouse_event(2, 0, 0, 0, 0)
mouse_event(4, 0, 0, 0, 0)
left_click(200, 200) #left clicks at 200, 200 on your screen. Was able to send 10k clicks instantly.
</code></pre>
| 3 | 2014-11-01T22:37:42Z | [
"python",
"mouse"
] |
Controlling mouse with Python | 1,181,464 | <p>How does one control the mouse cursor in Python, i.e. move it to certain position and click, under Windows?</p>
| 101 | 2009-07-25T07:15:30Z | 27,046,948 | <p>Try with the <a href="https://pypi.python.org/pypi/PyAutoGUI" rel="nofollow">PyAutoGUI</a> module. It's multiplatform. </p>
<pre><code>pip install pyautogui
</code></pre>
<p>And so:</p>
<pre><code>import pyautogui
pyautogui.click(100, 100)
</code></pre>
<p>It also has other features:</p>
<pre><code>import pyautogui
pyautogui.moveTo(100, 150)
pyautogui.moveRel(0, 10) # move mouse 10 pixels down
pyautogui.dragTo(100, 150)
pyautogui.dragRel(0, 10) # drag mouse 10 pixels down
</code></pre>
<p>This is much easier than going through all the win32con stuff.</p>
| 30 | 2014-11-20T18:32:50Z | [
"python",
"mouse"
] |
Controlling mouse with Python | 1,181,464 | <p>How does one control the mouse cursor in Python, i.e. move it to certain position and click, under Windows?</p>
| 101 | 2009-07-25T07:15:30Z | 38,329,875 | <p>Pyautogui does a great job in controlling mouse with python. </p>
<p><a href="http://pyautogui.readthedocs.io/en/latest/mouse.html" rel="nofollow">http://pyautogui.readthedocs.io/en/latest/mouse.html</a> </p>
| 1 | 2016-07-12T13:09:43Z | [
"python",
"mouse"
] |
Python base 36 encoding | 1,181,919 | <p>How can I encode an integer with base 36 in Python and then decode it again?</p>
| 22 | 2009-07-25T11:32:32Z | 1,181,922 | <p>Have you tried Wikipedia's sample code?</p>
<pre><code>def base36encode(number, alphabet='0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ'):
"""Converts an integer to a base36 string."""
if not isinstance(number, (int, long)):
raise TypeError('number must be an integer')
base36 = ''
sign = ''
if number < 0:
sign = '-'
number = -number
if 0 <= number < len(alphabet):
return sign + alphabet[number]
while number != 0:
number, i = divmod(number, len(alphabet))
base36 = alphabet[i] + base36
return sign + base36
def base36decode(number):
return int(number, 36)
print base36encode(1412823931503067241)
print base36decode('AQF8AA0006EH')
</code></pre>
| 23 | 2009-07-25T11:35:25Z | [
"python"
] |
Python base 36 encoding | 1,181,919 | <p>How can I encode an integer with base 36 in Python and then decode it again?</p>
| 22 | 2009-07-25T11:32:32Z | 1,181,924 | <p>I wish I had read this before. Here is the answer:</p>
<pre><code>def base36encode(number):
if not isinstance(number, (int, long)):
raise TypeError('number must be an integer')
if number < 0:
raise ValueError('number must be positive')
alphabet, base36 = ['0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ', '']
while number:
number, i = divmod(number, 36)
base36 = alphabet[i] + base36
return base36 or alphabet[0]
def base36decode(number):
return int(number, 36)
print(base36encode(1412823931503067241))
print(base36decode('AQF8AA0006EH'))
</code></pre>
| 27 | 2009-07-25T11:36:08Z | [
"python"
] |
Python base 36 encoding | 1,181,919 | <p>How can I encode an integer with base 36 in Python and then decode it again?</p>
| 22 | 2009-07-25T11:32:32Z | 11,406,745 | <p>terrible answer, but was just playing around with this an thought i'd share.</p>
<pre><code>import string, math
int2base = lambda a, b: ''.join(
[(string.digits + string.lowercase + string.uppercase)[(a/b**i)%b]
for i in xrange(int(math.log(a, b)), -1, -1)]
)
num = 1412823931503067241
test = int2base(num, 36)
test2 = int(test, 36)
print test2 == num
</code></pre>
| 8 | 2012-07-10T04:43:11Z | [
"python"
] |
Python base 36 encoding | 1,181,919 | <p>How can I encode an integer with base 36 in Python and then decode it again?</p>
| 22 | 2009-07-25T11:32:32Z | 31,746,873 | <p>This works if you only care about positive integers.</p>
<pre><code>def int_to_base36(num):
"""Converts a positive integer into a base36 string."""
assert num >= 0
digits = '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ'
res = ''
while not res or num > 0:
num, i = divmod(num, 36)
res = digits[i] + res
return res
</code></pre>
<p>To convert back to int, just use <code>int(num, 36)</code>. For a conversion of arbitrary bases see <a href="https://gist.github.com/mbarkhau/1b918cb3b4a2bdaf841c" rel="nofollow">https://gist.github.com/mbarkhau/1b918cb3b4a2bdaf841c</a></p>
| 1 | 2015-07-31T13:02:15Z | [
"python"
] |
Python base 36 encoding | 1,181,919 | <p>How can I encode an integer with base 36 in Python and then decode it again?</p>
| 22 | 2009-07-25T11:32:32Z | 33,270,825 | <pre><code>from numpy import base_repr
num = base_repr(num, 36)
num = int(num, 36)
</code></pre>
<p>Here is information about <a href="http://www.numpy.org" rel="nofollow">numpy</a>.</p>
| 3 | 2015-10-21T23:15:30Z | [
"python"
] |
Python base 36 encoding | 1,181,919 | <p>How can I encode an integer with base 36 in Python and then decode it again?</p>
| 22 | 2009-07-25T11:32:32Z | 38,388,352 | <p>You could use <a href="https://github.com/tonyseek/python-base36" rel="nofollow">https://github.com/tonyseek/python-base36</a>.</p>
<pre><code>$ pip install base36
</code></pre>
<p>and then</p>
<pre><code>>>> import base36
>>> assert base36.dumps(19930503) == 'bv6h3'
>>> assert base36.loads('bv6h3') == 19930503
</code></pre>
| 0 | 2016-07-15T05:21:03Z | [
"python"
] |
cx_Oracle MemoryError when reading lob | 1,182,146 | <p>When trying to read data from a lob field using cx_Oralce Iâm receiving âexceptions.MemoryErrorâ. This code has been working, this one lob field seems to be too big.</p>
<pre><code>Example:
xml_cursor = ora_connection.cursor()
xml_cursor.arraysize = 2000
try:
xml_cursor.execute(âselect xml_data from xmlTable where id = 1â)
for row_data in xml_cursor.fetchall():
str_xml = str(row_data[0]) #this throws âexceptions.MemoryErrorâ
</code></pre>
| 4 | 2009-07-25T14:06:27Z | 1,182,444 | <p>Yep, if Python is giving MemoryError it means that just that one field of that just one row takes more memory than you have (quite possible with a LOB of course). You'll have to slice it up and get it in chunks (with <code>select dbms_lob.substr(xml_data, ...</code> repeatedly) and feed it to an incremental XML parser (or write it out to a file, or whatever is it that you're trying to do with that multi-GB LOB). <code>DBMS_LOB</code> is a well-documented Oracle-supplied package, and you can find its docs in many places, e.g. <a href="http://www.stanford.edu/dept/itss/docs/oracle/10g/appdev.101/b10802/d%5Flob.htm">here</a>.</p>
| 5 | 2009-07-25T16:30:27Z | [
"python",
"cx-oracle"
] |
Python: Multicore processing? | 1,182,315 | <p>I've been reading about Python's <a href="http://docs.python.org/library/multiprocessing.html">multiprocessing module</a>. I still don't think I have a very good understanding of what it can do.</p>
<p>Let's say I have a quadcore processor and I have a list with 1,000,000 integers and I want the sum of all the integers. I could simply do:</p>
<pre><code>list_sum = sum(my_list)
</code></pre>
<p>But this only sends it to one core.</p>
<p>Is it possible, using the multiprocessing module, to divide the array up and have each core get the sum of it's part and return the value so the total sum may be computed?</p>
<p>Something like:</p>
<pre><code>core1_sum = sum(my_list[0:500000]) #goes to core 1
core2_sum = sum(my_list[500001:1000000]) #goes to core 2
all_core_sum = core1_sum + core2_sum #core 3 does final computation
</code></pre>
<p>Any help would be appreciated.</p>
| 20 | 2009-07-25T15:31:35Z | 1,182,343 | <p>Welcome the world of concurrent programming.</p>
<p>What Python can (and can't) do depends on two things.</p>
<ol>
<li><p>What the OS can (and can't) do. Most OS's allocate processes to cores. To use 4 cores, you need to break your problem into four processes. This is easier than it sounds. Sometimes.</p></li>
<li><p>What the underlying C libraries can (and can't) do. If the C libraries expose features of the OS AND the OS exposes features of the hardware, you're solid. </p></li>
</ol>
<p>To break a problem into multiple processes -- especially in GNU/Linux -- is easy. Break it into a multi-step pipeline.</p>
<p>In the case of summing a million numbers, think of the following shell script. Assuming some hypothetical <code>sum.py</code> program that sums either a range of numbers or a list of numbers on stdin.</p>
<p>( sum.py 0 500000 & sum.py 50000 1000000 ) | sum.py</p>
<p>This would have 3 concurrent processes. Two are doing sums of a lot of numbers, the third is summing two numbers. </p>
<p>Since the GNU/Linux shells and the OS already handle some parts of concurrency for you, you can design simple (very, very simple) programs that read from stdin, write to stdout, and are designed to do small parts of a large job.</p>
<p>You can try to reduce the overheads by using <a href="http://docs.python.org/library/subprocess.html">subprocess</a> to build the pipeline instead of allocating the job to the shell. You may find, however, that the shell builds pipelines very, very quickly. (It was written directly in C and makes direct OS API calls for you.)</p>
| 17 | 2009-07-25T15:45:49Z | [
"python",
"multicore",
"multiprocessing"
] |
Python: Multicore processing? | 1,182,315 | <p>I've been reading about Python's <a href="http://docs.python.org/library/multiprocessing.html">multiprocessing module</a>. I still don't think I have a very good understanding of what it can do.</p>
<p>Let's say I have a quadcore processor and I have a list with 1,000,000 integers and I want the sum of all the integers. I could simply do:</p>
<pre><code>list_sum = sum(my_list)
</code></pre>
<p>But this only sends it to one core.</p>
<p>Is it possible, using the multiprocessing module, to divide the array up and have each core get the sum of it's part and return the value so the total sum may be computed?</p>
<p>Something like:</p>
<pre><code>core1_sum = sum(my_list[0:500000]) #goes to core 1
core2_sum = sum(my_list[500001:1000000]) #goes to core 2
all_core_sum = core1_sum + core2_sum #core 3 does final computation
</code></pre>
<p>Any help would be appreciated.</p>
| 20 | 2009-07-25T15:31:35Z | 1,182,350 | <p>Yes, it's possible to do this summation over several processes, very much like doing it with multiple threads:</p>
<pre><code>from multiprocessing import Process, Queue
def do_sum(q,l):
q.put(sum(l))
def main():
my_list = range(1000000)
q = Queue()
p1 = Process(target=do_sum, args=(q,my_list[:500000]))
p2 = Process(target=do_sum, args=(q,my_list[500000:]))
p1.start()
p2.start()
r1 = q.get()
r2 = q.get()
print r1+r2
if __name__=='__main__':
main()
</code></pre>
<p>However, it is likely that doing it with multiple processes is likely slower than doing it in a single process, as copying the data forth and back is more expensive than summing them right away.</p>
| 25 | 2009-07-25T15:48:51Z | [
"python",
"multicore",
"multiprocessing"
] |
Python: Multicore processing? | 1,182,315 | <p>I've been reading about Python's <a href="http://docs.python.org/library/multiprocessing.html">multiprocessing module</a>. I still don't think I have a very good understanding of what it can do.</p>
<p>Let's say I have a quadcore processor and I have a list with 1,000,000 integers and I want the sum of all the integers. I could simply do:</p>
<pre><code>list_sum = sum(my_list)
</code></pre>
<p>But this only sends it to one core.</p>
<p>Is it possible, using the multiprocessing module, to divide the array up and have each core get the sum of it's part and return the value so the total sum may be computed?</p>
<p>Something like:</p>
<pre><code>core1_sum = sum(my_list[0:500000]) #goes to core 1
core2_sum = sum(my_list[500001:1000000]) #goes to core 2
all_core_sum = core1_sum + core2_sum #core 3 does final computation
</code></pre>
<p>Any help would be appreciated.</p>
| 20 | 2009-07-25T15:31:35Z | 1,182,364 | <p>Sure, for example:</p>
<pre><code>from multiprocessing import Process, Queue
thelist = range(1000*1000)
def f(q, sublist):
q.put(sum(sublist))
def main():
start = 0
chunk = 500*1000
queue = Queue()
NP = 0
subprocesses = []
while start < len(thelist):
p = Process(target=f, args=(queue, thelist[start:start+chunk]))
NP += 1
print 'delegated %s:%s to subprocess %s' % (start, start+chunk, NP)
p.start()
start += chunk
subprocesses.append(p)
total = 0
for i in range(NP):
total += queue.get()
print "total is", total, '=', sum(thelist)
while subprocesses:
subprocesses.pop().join()
if __name__ == '__main__':
main()
</code></pre>
<p>results in:</p>
<pre><code>$ python2.6 mup.py
delegated 0:500000 to subprocess 1
delegated 500000:1000000 to subprocess 2
total is 499999500000 = 499999500000
</code></pre>
<p>note that this granularity is too fine to be worth spawning processes for -- the overall summing task is small (which is why I can recompute the sum in main as a check;-) and too many data is being moved back and forth (in fact the subprocesses wouldn't need to get copies of the sublists they work on -- indices would suffice). So, it's a "toy example" where multiprocessing isn't really warranted. With different architectures (use a pool of subprocesses that receive multiple tasks to perform from a queue, minimize data movement back and forth, etc, etc) and on less granular tasks you could actually get benefits in terms of performance, however.</p>
| 7 | 2009-07-25T15:55:45Z | [
"python",
"multicore",
"multiprocessing"
] |
How can I launch a background process in Pylons? | 1,182,587 | <p>I am trying to write an application that will allow a user to launch a fairly long-running process (5-30 seconds). It should then allow the user to check the output of the process as it is generated. The output will only be needed for the user's current session so nothing needs to be stored long-term. I have two questions regarding how to accomplish this while taking advantage of the Pylons framework:</p>
<ol>
<li><p>What is the best way to launch a background process such as this with a Pylons controller?</p></li>
<li><p>What is the best way to get the output of the background process back to the user? (Should I store the output in a database, in session data, etc.?)</p></li>
</ol>
<p><strong>Edit:</strong>
The problem is if I launch a command using <code>subprocess</code> in a controller, the controller waits for the subprocess to finish before continuing, showing the user a blank page that is just loading until the process is complete. I want to be able to redirect the user to a status page immediately after starting the subprocess, allowing it to complete on its own.</p>
| 3 | 2009-07-25T17:36:18Z | 1,182,609 | <p>I think this has little to do with pylons. I would do it (in whatever framework) in these steps:</p>
<ul>
<li>generate some ID for the new job, and add a record in the database.</li>
<li>create a new process, e.g. through the subprocess module, and pass the ID on the command line (*).</li>
<li>have the process write its output to <code>/tmp/project/ID</code></li>
<li>in pylons, implement URLs of the form <code>/job/ID</code> or <code>/job?id=ID</code>. That will look into the database whether the job is completed or not, and merge the temporary output into the page.</li>
</ul>
<p>(*) It might be better for the subprocess to create another process immediately, and have the pylons process wait for the first child, so that there will be no zombie processes.</p>
| 1 | 2009-07-25T17:46:42Z | [
"python",
"background",
"pylons"
] |
How can I launch a background process in Pylons? | 1,182,587 | <p>I am trying to write an application that will allow a user to launch a fairly long-running process (5-30 seconds). It should then allow the user to check the output of the process as it is generated. The output will only be needed for the user's current session so nothing needs to be stored long-term. I have two questions regarding how to accomplish this while taking advantage of the Pylons framework:</p>
<ol>
<li><p>What is the best way to launch a background process such as this with a Pylons controller?</p></li>
<li><p>What is the best way to get the output of the background process back to the user? (Should I store the output in a database, in session data, etc.?)</p></li>
</ol>
<p><strong>Edit:</strong>
The problem is if I launch a command using <code>subprocess</code> in a controller, the controller waits for the subprocess to finish before continuing, showing the user a blank page that is just loading until the process is complete. I want to be able to redirect the user to a status page immediately after starting the subprocess, allowing it to complete on its own.</p>
| 3 | 2009-07-25T17:36:18Z | 1,189,797 | <p>I've handled this problem in the past (long-running process invoked over HTTP) by having my invoked 2nd process daemonize. Your Pylons controller makes a system call to your 2nd process (passing whatever data is needed) and the 2nd process immediately becomes a daemon. This ends the system call and your controller can return. </p>
<p>My web-apps usually then issue AJAX requests to "check-on" the daemon process until it has completed. I've used both tmp files (cPickle works well) and databases to share information between the daemon and the web-app.</p>
<p>Excellent python daemon recipe: <a href="http://code.activestate.com/recipes/278731/" rel="nofollow">http://code.activestate.com/recipes/278731/</a></p>
| 6 | 2009-07-27T18:25:18Z | [
"python",
"background",
"pylons"
] |
Python dictionary/list help | 1,183,031 | <p>This is a python application that's supposed to get all the followers from one table and get their latest updates from another table. - All happening in the dashboard. </p>
<p>dashboard.html:
<a href="http://bizteen.pastebin.com/m65c4ae2d" rel="nofollow">http://bizteen.pastebin.com/m65c4ae2d</a></p>
<p>the dashboard function in views.py:
<a href="http://bizteen.pastebin.com/m39798bd5" rel="nofollow">http://bizteen.pastebin.com/m39798bd5</a></p>
<p>result:
<a href="http://bizteen.pastebin.com/mc12d958" rel="nofollow">http://bizteen.pastebin.com/mc12d958</a></p>
<p>NOTE: When you run the the first div is ok cause thats the div from the latest user status so ignore the 1st div in the result..but as u can see all the rest is blank</p>
<p>so i basically get 0 errors..:S</p>
<p>CAN YOU PLEASEEEEE HELP me OUT here???? :D :D I'd reallllly appreciate it!!! :D Thanks!!!! </p>
| -1 | 2009-07-25T20:53:48Z | 1,183,061 | <p>There's far too much code there to try and work out what's going on, and your explanation is not particularly clear.</p>
<p>However, one obvious problem is that you've got a lot of blank <code>except</code> clauses, which is almost always a bad idea as it masks any problems that might be happening outside of what you already expected. Always, always use <code>except</code> with one or more actual exception classes - <code>except Object.DoesNotExist</code> for example.</p>
<p>Secondly, you need to try and debug this by working out what the values are at each point. The simplest way is to put <code>print</code> statements after every assignment. The values should show up in the console. This will help you track down exactly where your logic is going wrong.</p>
| 1 | 2009-07-25T21:06:15Z | [
"python",
"django",
"list"
] |
How to get the distinct value of one of my models in Google App Engine | 1,183,102 | <p>I have a model, below, and I would like to get all the distinct <code>area</code> values. The SQL equivalent is <code>select distinct area from tutorials</code> </p>
<pre><code>class Tutorials(db.Model):
path = db.StringProperty()
area = db.StringProperty()
sub_area = db.StringProperty()
title = db.StringProperty()
content = db.BlobProperty()
rating = db.RatingProperty()
publishedDate = db.DateTimeProperty()
published = db.BooleanProperty()
</code></pre>
<p>I know that in Python I can do </p>
<pre><code> a = ['google.com', 'livejournal.com', 'livejournal.com', 'google.com', 'stackoverflow.com']
b = set(a)
b
>>> set(['livejournal.com', 'google.com', 'stackoverflow.com'])
</code></pre>
<p>But that would require me moving the area items out of the query into another list and then running set against the list (sounds very inefficient) and if I have a distinct item that is in position 1001 in the datastore I wouldnt see it because of the fetch limit of 1000.</p>
<p>I would like to get all the distinct values of area in my datastore to dump it to the screen as links.</p>
| 5 | 2009-07-25T21:22:49Z | 1,183,140 | <p><a href="http://stackoverflow.com/questions/239258/python-distinct-on-gquery-result-set-gql-gae">This has been asked before</a>, and the conclusion was that using sets is fine.</p>
| 0 | 2009-07-25T21:41:14Z | [
"python",
"google-app-engine",
"gae-datastore"
] |
How to get the distinct value of one of my models in Google App Engine | 1,183,102 | <p>I have a model, below, and I would like to get all the distinct <code>area</code> values. The SQL equivalent is <code>select distinct area from tutorials</code> </p>
<pre><code>class Tutorials(db.Model):
path = db.StringProperty()
area = db.StringProperty()
sub_area = db.StringProperty()
title = db.StringProperty()
content = db.BlobProperty()
rating = db.RatingProperty()
publishedDate = db.DateTimeProperty()
published = db.BooleanProperty()
</code></pre>
<p>I know that in Python I can do </p>
<pre><code> a = ['google.com', 'livejournal.com', 'livejournal.com', 'google.com', 'stackoverflow.com']
b = set(a)
b
>>> set(['livejournal.com', 'google.com', 'stackoverflow.com'])
</code></pre>
<p>But that would require me moving the area items out of the query into another list and then running set against the list (sounds very inefficient) and if I have a distinct item that is in position 1001 in the datastore I wouldnt see it because of the fetch limit of 1000.</p>
<p>I would like to get all the distinct values of area in my datastore to dump it to the screen as links.</p>
| 5 | 2009-07-25T21:22:49Z | 1,183,146 | <p>Datastore cannot do this for you in a single query. A datastore request always returns a consecutive block of results from an index, and an index always consists of all the entities of a given type, sorted according to whatever orders are specified. There's no way for the query to skip items just because one field has duplicate values.</p>
<p>One option is to restructure your data. For example introduce a new entity type representing an "area". On adding a Tutorial you create the corresponding "area" if it doesn't already exist, and on deleting a Tutoral delete the corresponding "area" if no Tutorials remain with the same "area". If each area stored a count of Tutorials in that area, this might not be too onerous (although keeping things consistent with transactions etc would actually be quite fiddly). I expect that the entity's key could be based on the area string itself, meaning that you can always do key lookups rather than queries to get area entities.</p>
<p>Another option is to use a queued task or cron job to periodically create a list of all areas, accumulating it over multiple requests if need be, and put the results either in the datastore or in memcache. That would of course mean the list of areas might be temporarily out of date at times (or if there are constant changes, it might never be entirely in date), which may or may not be acceptable to you.</p>
<p>Finally, if there are likely to be very few areas compared with tutorials, you could do it on the fly by requesting the first Tutorial (sorted by area), then requesting the first Tutorial whose area is greater than the area of the first, and so on. But this requires one request per distinct area, so is unlikely to be fast.</p>
| 7 | 2009-07-25T21:42:23Z | [
"python",
"google-app-engine",
"gae-datastore"
] |
How to get the distinct value of one of my models in Google App Engine | 1,183,102 | <p>I have a model, below, and I would like to get all the distinct <code>area</code> values. The SQL equivalent is <code>select distinct area from tutorials</code> </p>
<pre><code>class Tutorials(db.Model):
path = db.StringProperty()
area = db.StringProperty()
sub_area = db.StringProperty()
title = db.StringProperty()
content = db.BlobProperty()
rating = db.RatingProperty()
publishedDate = db.DateTimeProperty()
published = db.BooleanProperty()
</code></pre>
<p>I know that in Python I can do </p>
<pre><code> a = ['google.com', 'livejournal.com', 'livejournal.com', 'google.com', 'stackoverflow.com']
b = set(a)
b
>>> set(['livejournal.com', 'google.com', 'stackoverflow.com'])
</code></pre>
<p>But that would require me moving the area items out of the query into another list and then running set against the list (sounds very inefficient) and if I have a distinct item that is in position 1001 in the datastore I wouldnt see it because of the fetch limit of 1000.</p>
<p>I would like to get all the distinct values of area in my datastore to dump it to the screen as links.</p>
| 5 | 2009-07-25T21:22:49Z | 16,929,212 | <p>The DISTINCT keyword has been introduced in release 1.7.4.</p>
| 1 | 2013-06-04T23:38:41Z | [
"python",
"google-app-engine",
"gae-datastore"
] |
To SHA512-hash a password in MySQL database by Python | 1,183,161 | <p>This question is based <a href="http://stackoverflow.com/questions/1182798/to-improve-a-relation-figure-for-a-database/1182807#1182807">on the answer</a>.</p>
<p>I would like to know how you can hash your password by SHA1 and then remove the clear-text password in a MySQL database by Python.</p>
<p><strong>How can you hash your password in a MySQL database by Python?</strong></p>
| 3 | 2009-07-25T21:49:58Z | 1,183,173 | <p><a href="http://docs.python.org/library/sha.html" rel="nofollow">http://docs.python.org/library/sha.html</a></p>
<p>The python documentation explains this a lot better than I can.</p>
| 4 | 2009-07-25T21:56:34Z | [
"python",
"mysql",
"database",
"hash"
] |
To SHA512-hash a password in MySQL database by Python | 1,183,161 | <p>This question is based <a href="http://stackoverflow.com/questions/1182798/to-improve-a-relation-figure-for-a-database/1182807#1182807">on the answer</a>.</p>
<p>I would like to know how you can hash your password by SHA1 and then remove the clear-text password in a MySQL database by Python.</p>
<p><strong>How can you hash your password in a MySQL database by Python?</strong></p>
| 3 | 2009-07-25T21:49:58Z | 1,183,213 | <p>As the documentation says you should use <a href="http://docs.python.org/library/hashlib.html">hashlib</a> library not the sha since python 2.5.</p>
<p>It is pretty easy to do make a hash.</p>
<pre><code>hexhash = hashlib.sha512("some text").hexdigest()
</code></pre>
<p>This hex number will be easy to store in a database.</p>
| 12 | 2009-07-25T22:15:17Z | [
"python",
"mysql",
"database",
"hash"
] |
To SHA512-hash a password in MySQL database by Python | 1,183,161 | <p>This question is based <a href="http://stackoverflow.com/questions/1182798/to-improve-a-relation-figure-for-a-database/1182807#1182807">on the answer</a>.</p>
<p>I would like to know how you can hash your password by SHA1 and then remove the clear-text password in a MySQL database by Python.</p>
<p><strong>How can you hash your password in a MySQL database by Python?</strong></p>
| 3 | 2009-07-25T21:49:58Z | 1,183,227 | <p>You don't remove the clear-text password when you hash the password. What you do is accept an input from the user, hash the input, and compare the hash of the input to the hash stored in the database. You should never store or send the plain-text password that the user has.</p>
<p>That said, you can use the sha library <a href="http://stackoverflow.com/questions/1183161/to-sha1-hash-a-password-in-mysql-database-by-python/1183173#1183173">as scrager said</a> (pre-Python 2.5) and the hashlib library <a href="http://stackoverflow.com/questions/1183161/to-sha1-hash-a-password-in-mysql-database-by-python/1183213#1183213">as David Raznick said</a> in newer versions of Python.</p>
| 1 | 2009-07-25T22:23:40Z | [
"python",
"mysql",
"database",
"hash"
] |
To SHA512-hash a password in MySQL database by Python | 1,183,161 | <p>This question is based <a href="http://stackoverflow.com/questions/1182798/to-improve-a-relation-figure-for-a-database/1182807#1182807">on the answer</a>.</p>
<p>I would like to know how you can hash your password by SHA1 and then remove the clear-text password in a MySQL database by Python.</p>
<p><strong>How can you hash your password in a MySQL database by Python?</strong></p>
| 3 | 2009-07-25T21:49:58Z | 1,183,439 | <p>If you're storing passwords in a database, a recommended article to read is Jeff's <a href="http://www.codinghorror.com/blog/archives/000953.html">You're Probably Storing Passwords Incorrectly</a>. This article describes the use of <em>salt</em> and some of the things about storing passwords that are deceptively easy to get wrong.</p>
| 7 | 2009-07-26T00:37:23Z | [
"python",
"mysql",
"database",
"hash"
] |
Is there something like Python's 'with' in C#? | 1,183,233 | <p>Python has a nice keyword since 2.6 called <strong>with</strong>. Is there something similar in C#?</p>
| 8 | 2009-07-25T22:27:18Z | 1,183,236 | <p>The equivalent is the <code>using</code> statement</p>
<p>An example would be </p>
<pre><code> using (var reader = new StreamReader(path))
{
DoSomethingWith(reader);
}
</code></pre>
<p>The restriction is that the type of the variable scoped by the using clause must implement <code>IDisposable</code> and it is its <code>Dispose()</code> method that gets called on exit from the associated code block.</p>
| 21 | 2009-07-25T22:29:24Z | [
"c#",
"python",
"exception"
] |
Is there something like Python's 'with' in C#? | 1,183,233 | <p>Python has a nice keyword since 2.6 called <strong>with</strong>. Is there something similar in C#?</p>
| 8 | 2009-07-25T22:27:18Z | 1,184,079 | <p>C# has the <code>using</code> statement, as mentioned in another answer and documented here:</p>
<ul>
<li><a href="http://msdn.microsoft.com/en-us/library/yh598w02(VS.80).aspx" rel="nofollow">using Statement</a></li>
</ul>
<p>However, it's <strong>not equivalent</strong> to Python's <code>with</code> statement, in that there is no analog of the <code>__enter__</code> method.</p>
<p>In C#:</p>
<pre><code>using (var foo = new Foo()) {
// ...
// foo.Dispose() is called on exiting the block
}
</code></pre>
<p>In Python:</p>
<pre><code>with Foo() as foo:
# foo.__enter__() called on entering the block
# ...
# foo.__exit__() called on exiting the block
</code></pre>
<p>More on the <code>with</code> statement here:</p>
<ul>
<li><a href="http://effbot.org/zone/python-with-statement.htm" rel="nofollow">http://effbot.org/zone/python-with-statement.htm</a></li>
</ul>
| 4 | 2009-07-26T09:00:22Z | [
"c#",
"python",
"exception"
] |
Python: Zope's BTree OOSet, IISet, etc... Effective for this requirement? | 1,183,428 | <p>I asked another question:
<a href="http://stackoverflow.com/questions/1180240/best-way-to-sort-1m-records-in-python" rel="nofollow" title="StackOverflow Python Sorting question">http://stackoverflow.com/questions/1180240/best-way-to-sort-1m-records-in-python</a>
where I was trying to determine the best approach for sorting 1 million records. In my case I need to be able to add additional items to the collection and have them resorted. It was suggested that I try using Zope's BTrees for this task. After doing some reading I am a little stumped as to what data I would put in a set. </p>
<p>Basically, for each record I have two pieces of data. 1. A unique ID which maps to a user and 2. a value of interest for sorting on.</p>
<p>I see that I can add the items to an OOSet as tuples, where the value for sorting on is at index 0. So, <code>(200, 'id1'),(120, 'id2'),(400, 'id3')</code> and the resulting set would be sorted with <code>id2, id1 and id3</code> in order.</p>
<p>However, part of the requirement for this is that each id appear only once in the set. I will be adding additional data to the set periodically and the new data may or may not include duplicated 'ids'. If they are duplicated I want to update the value and not add an additional entry. So, based on the tuples above, I might add <code>(405, 'id1'),(10, 'id4')</code> to the set and would want the output to have <code>id4, id2, id3, id1</code> in order.</p>
<p>Any suggestions on how to accomplish this. Sorry for my newbness on the subject. </p>
<p><strong>* EDIT - additional info *</strong></p>
<p>Here is some actual code from the project:</p>
<pre><code>for field in lb_fields:
t = time.time()
self.data[field] = [ (v[field], k) for k, v in self.foreign_keys.iteritems() ]
self.data[field].sort(reverse=True)
print "Added %s: %03.5f seconds" %(field, (time.time() - t))
</code></pre>
<p>foreign_keys is the original data in a dictionary with each id as the key and a dictionary of the additional data as the value. data is a dictionary containing the lists of sorted data.</p>
<p>As a side note, as each itereation of the for field in lb_fields runs, the time to sort increases - not by much... but it is noticeable. After 1 million records have been sorted for each of the 16 fields it is using about 4 Gigs or RAM. Eventually this will run on a machine with 48 Gigs. </p>
| 0 | 2009-07-26T00:30:01Z | 1,183,587 | <p>I don't think BTrees or other traditional sorted data structures (red-black trees, etc) will help you, because they keep order by key, not by corresponding value -- in other words, the field they guarantee as unique is the same one they order by. Your requirements are different, because you want uniqueness along one field, but sortedness by the other.</p>
<p>What are your performance requirements? With a rather simple pure Python implementation based on Python dicts for uniqueness and Python sorts, on a not-blazingly-fast laptop, I get 5 seconds for the original construction (essentially a sort over the million elements, starting with them as a dict), and about 9 seconds for the "update" with 20,000 new id/value pairs of which half "overlap" (thus overwrite) an existing id and half are new (I can implement the update in a faster way, about 6.5 seconds, but that implementation has an anomaly: if one of the "new" pairs is exactly identical to one of the "old" ones, both id and value, it's duplicated -- warding against such "duplication of identicals" is what pushes me from 6.5 seconds to 9, and I imagine you would need the same kind of precaution).</p>
<p>How far are these 5-and-9 seconds times from your requirements (taking into account the actual speed of the machine you'll be running on vs the 2.4 GHz Core Duo, 2GB of RAM, and typical laptop performance issues of this laptop I'm using)? IOW, is it close enough to "striking distance" to be worth tinkering and trying to squeeze a last few cycles out of, or do you need orders of magnitude faster performance?</p>
<p>I've tried several other approaches (with a SQL DB, with C++ and its std::sort &c, ...) but they're all slower, so if you need much higher performance I'm not sure what you could do.</p>
<p><strong>Edit</strong>: since the OP says this performance would be fine but he can't achieve anywhere near it, I guess I'd best show the script I used to measure these times...:</p>
<pre><code>import gc
import operator
import random
import time
nk = 1000
def popcon(d):
for x in xrange(nk*1000):
d['id%s' % x] = random.randrange(100*1000)
def sorted_container():
ctr = dict()
popcon(ctr)
start = time.time()
ctr_sorted = ctr.items()
ctr_sorted.sort(key=operator.itemgetter(1))
stend = time.time()
return stend-start, ctr_sorted
def do_update(ctr, newones):
start = time.time()
dicol = dict(ctr)
ctr.extend((k,v) for (k,v) in newones if v!=dicol.get(k,None))
dicnu = dict(newones)
ctr.sort(key=operator.itemgetter(1))
newctr = [(k,v) for (k,v) in ctr if v==dicnu.get(k,v)]
stend = time.time()
return stend-start, newctr
def main():
random.seed(12345)
for x in range(3):
duration, ctr = sorted_container()
print 'dict-to-sorted, %d: %.2f sec, len=%d' % (x, duration, len(ctr))
newones = [('id%s' % y, random.randrange(nk*100))
for y in xrange(nk*990,nk*1010)]
duration, ctr = do_update(ctr, newones)
print 'updt-to-sorted, %d: %.2f sec, len=%d' % (x, duration, len(ctr))
del ctr
gc.collect()
main()
</code></pre>
<p>and this is a typical run:</p>
<pre><code>$ time python som.py
dict-to-sorted, 0: 5.01 sec, len=1000000
updt-to-sorted, 0: 9.78 sec, len=1010000
dict-to-sorted, 1: 5.02 sec, len=1000000
updt-to-sorted, 1: 9.12 sec, len=1010000
dict-to-sorted, 2: 5.03 sec, len=1000000
updt-to-sorted, 2: 9.12 sec, len=1010000
real 0m54.073s
user 0m52.464s
sys 0m1.258s
</code></pre>
<p>the overall elapsed time being a few seconds more than the totals I'm measuring, obviously, because it includes the time needed to populate the container with random numbers, generate the "new data" also randomly, destroy and garbage-collect things at the end of each run, and so forth.</p>
<p>This is with the system-supplied Python 2.5.2 on a Macbook with Mac OS X 10.5.7, 2.4 GHz Intel Core Duo, and 2GB of RAM (times don't change much when I use different versions of Python).</p>
| 1 | 2009-07-26T02:26:44Z | [
"python",
"zope"
] |
Python: Zope's BTree OOSet, IISet, etc... Effective for this requirement? | 1,183,428 | <p>I asked another question:
<a href="http://stackoverflow.com/questions/1180240/best-way-to-sort-1m-records-in-python" rel="nofollow" title="StackOverflow Python Sorting question">http://stackoverflow.com/questions/1180240/best-way-to-sort-1m-records-in-python</a>
where I was trying to determine the best approach for sorting 1 million records. In my case I need to be able to add additional items to the collection and have them resorted. It was suggested that I try using Zope's BTrees for this task. After doing some reading I am a little stumped as to what data I would put in a set. </p>
<p>Basically, for each record I have two pieces of data. 1. A unique ID which maps to a user and 2. a value of interest for sorting on.</p>
<p>I see that I can add the items to an OOSet as tuples, where the value for sorting on is at index 0. So, <code>(200, 'id1'),(120, 'id2'),(400, 'id3')</code> and the resulting set would be sorted with <code>id2, id1 and id3</code> in order.</p>
<p>However, part of the requirement for this is that each id appear only once in the set. I will be adding additional data to the set periodically and the new data may or may not include duplicated 'ids'. If they are duplicated I want to update the value and not add an additional entry. So, based on the tuples above, I might add <code>(405, 'id1'),(10, 'id4')</code> to the set and would want the output to have <code>id4, id2, id3, id1</code> in order.</p>
<p>Any suggestions on how to accomplish this. Sorry for my newbness on the subject. </p>
<p><strong>* EDIT - additional info *</strong></p>
<p>Here is some actual code from the project:</p>
<pre><code>for field in lb_fields:
t = time.time()
self.data[field] = [ (v[field], k) for k, v in self.foreign_keys.iteritems() ]
self.data[field].sort(reverse=True)
print "Added %s: %03.5f seconds" %(field, (time.time() - t))
</code></pre>
<p>foreign_keys is the original data in a dictionary with each id as the key and a dictionary of the additional data as the value. data is a dictionary containing the lists of sorted data.</p>
<p>As a side note, as each itereation of the for field in lb_fields runs, the time to sort increases - not by much... but it is noticeable. After 1 million records have been sorted for each of the 16 fields it is using about 4 Gigs or RAM. Eventually this will run on a machine with 48 Gigs. </p>
| 0 | 2009-07-26T00:30:01Z | 1,252,510 | <p>It is perfectly possible to solve your problem. For this you should just note that the container types in Python <strong>always</strong> compare objects by calling their methods. Therefore you should do something like:</p>
<pre><code>class Record:
'Combination of unique part and sort part.'
def __init__(self, unique, sort):
self.unique = unique
self.sort = sort
def __hash__(self):
# Hash should be implemented if __eq__ is implemented.
return hash(self.unique)
def __eq__(self, other):
return self.unique == other.unique
def __lt__(self, other):
return self.sort < other.sort
records = btree((Record(u, s) for u, s in zip(unique_data, sort_data)))
print(records.pop())
</code></pre>
<p>Notes:</p>
<ul>
<li>depending on how your favorite container type is implemented, you might need to add methods for !=, <=, >, >= as well</li>
<li>this will not break the relationship between == and <= as long as <code>x.unique == y.unique</code> ==> <code>x.sort == y.sort</code></li>
</ul>
| 1 | 2009-08-09T22:40:32Z | [
"python",
"zope"
] |
Unbuffered read from process using subprocess in Python | 1,183,643 | <p>I am trying to read from a process that produces long and time-consuming output. However, I want to catch it's output <em>as and when</em> it is produced. But using something like the following seems to be buffering the command's output, so I end up getting the output lines all at once:</p>
<pre><code>p = subprocess.Popen(cmd, shell=True, stdout=subprocess.PIPE, bufsize=0)
for line in p.stdout:
print line
</code></pre>
<p>I am trying this on MacOS 10.5</p>
| 20 | 2009-07-26T03:21:35Z | 1,183,654 | <p>The file iterator is doing some internal buffering <a href="http://docs.python.org/library/stdtypes.html#file.next">on its own</a>. Try this:</p>
<pre><code>line = p.stdout.readline()
while line:
print line
line = p.stdout.readline()
</code></pre>
| 27 | 2009-07-26T03:30:39Z | [
"python",
"subprocess"
] |
Unbuffered read from process using subprocess in Python | 1,183,643 | <p>I am trying to read from a process that produces long and time-consuming output. However, I want to catch it's output <em>as and when</em> it is produced. But using something like the following seems to be buffering the command's output, so I end up getting the output lines all at once:</p>
<pre><code>p = subprocess.Popen(cmd, shell=True, stdout=subprocess.PIPE, bufsize=0)
for line in p.stdout:
print line
</code></pre>
<p>I am trying this on MacOS 10.5</p>
| 20 | 2009-07-26T03:21:35Z | 1,183,784 | <p>Usually, every program will do more buffering on its input and/or output channels than you appear to desire... unless it's fooled into believing said channel's actually a terminal!</p>
<p>For that "fooling in a good cause" purpose, use <a href="http://pexpect.sourceforge.net/pexpect.html">pexpect</a> -- it works just fine on a Mac (life is harder on Windows, though there are solutions that might help even there - fortunately we don't need to dwell on those as you use a Mac instead).</p>
| 6 | 2009-07-26T05:08:32Z | [
"python",
"subprocess"
] |
Unbuffered read from process using subprocess in Python | 1,183,643 | <p>I am trying to read from a process that produces long and time-consuming output. However, I want to catch it's output <em>as and when</em> it is produced. But using something like the following seems to be buffering the command's output, so I end up getting the output lines all at once:</p>
<pre><code>p = subprocess.Popen(cmd, shell=True, stdout=subprocess.PIPE, bufsize=0)
for line in p.stdout:
print line
</code></pre>
<p>I am trying this on MacOS 10.5</p>
| 20 | 2009-07-26T03:21:35Z | 9,069,527 | <p>This was actually a bug that's fixed in Python 2.6: <a href="http://bugs.python.org/issue3907" rel="nofollow">http://bugs.python.org/issue3907</a></p>
| 3 | 2012-01-30T19:26:19Z | [
"python",
"subprocess"
] |
Python Properties & Swig | 1,183,716 | <p>I am attempting to create python bindings for some C++ code using swig. I seem have run into a problem trying to create python properties from some accessor functions I have for methods like the following:</p>
<pre><code>class Player {
public:
void entity(Entity* entity);
Entity* entity() const;
};
</code></pre>
<p>I tried creating a property using the python property function but it seems that the wrapper classes swig generates are not compatible with it at least for setters.</p>
<p>How do you create properties using swig?</p>
| 14 | 2009-07-26T04:17:48Z | 1,186,340 | <p>Ooh, this is tricky (and fun). SWIG <em>doesn't</em> recognize this as an opportunity to generate @property: I imagine it'd be all too easy to slip up and recognize lots of false positives if it weren't done really carefully. However, since SWIG won't do it in generating C++, it's still entirely possible to do this in Python using a small metaclass.</p>
<p>So, below, let's say we have a Math class that lets us set and get an integer variable named "pi". Then we can use this code:</p>
<h2>example.h</h2>
<pre><code>#ifndef EXAMPLE_H
#define EXAMPLE_H
class Math {
public:
int pi() const {
return this->_pi;
}
void pi(int pi) {
this->_pi = pi;
}
private:
int _pi;
};
#endif
</code></pre>
<h2>example.i</h2>
<pre><code>%module example
%{
#define SWIG_FILE_WITH_INIT
#include "example.h"
%}
[essentially example.h repeated again]
</code></pre>
<h2>example.cpp</h2>
<pre><code>#include "example.h"
</code></pre>
<h2>util.py</h2>
<pre><code>class PropertyVoodoo(type):
"""A metaclass. Initializes when the *class* is initialized, not
the object. Therefore, we are free to muck around the class
methods and, specifically, descriptors."""
def __init__(cls, *a):
# OK, so the list of C++ properties using the style described
# in the OP is stored in a __properties__ magic variable on
# the class.
for prop in cls.__properties__:
# Get accessor.
def fget(self):
# Get the SWIG class using super. We have to use super
# because the only information we're working off of is
# the class object itself (cls). This is not the most
# robust way of doing things but works when the SWIG
# class is the only superclass.
s = super(cls, self)
# Now get the C++ method and call its operator().
return getattr(s, prop)()
# Set accessor.
def fset(self, value):
# Same as above.
s = super(cls, self)
# Call its overloaded operator(int value) to set it.
return getattr(s, prop)(value)
# Properties in Python are descriptors, which are in turn
# static variables on the class. So, here we create the
# static variable and set it to the property.
setattr(cls, prop, property(fget=fget, fset=fset))
# type() needs the additional arguments we didn't use to do
# inheritance. (Parent classes are passed in as arguments as
# part of the metaclass protocol.) Usually a = [<some swig
# class>] right now.
super(PropertyVoodoo, cls).__init__(*a)
# One more piece of work: SWIG selfishly overrides
# __setattr__. Normal Python classes use object.__setattr__,
# so that's what we use here. It's not really important whose
# __setattr__ we use as long as we skip the SWIG class in the
# inheritance chain because SWIG's __setattr__ will skip the
# property we just created.
def __setattr__(self, name, value):
# Only do this for the properties listed.
if name in cls.__properties__:
object.__setattr__(self, name, value)
else:
# Same as above.
s = super(cls, self)
s.__setattr__(name, value)
# Note that __setattr__ is supposed to be an instance method,
# hence the self. Simply assigning it to the class attribute
# will ensure it's an instance method; that is, it will *not*
# turn into a static/classmethod magically.
cls.__setattr__ = __setattr__
</code></pre>
<h2>somefile.py</h2>
<pre><code>import example
from util import PropertyVoodoo
class Math(example.Math):
__properties__ = ['pi']
__metaclass__ = PropertyVoodoo
m = Math()
print m.pi
m.pi = 1024
print m.pi
m.pi = 10000
print m.pi
</code></pre>
<p>So the end result is just that you have to create a wrapper class for every SWIG Python class and then type two lines: one to mark which methods should be converted in properties and one to bring in the metaclass.</p>
| 2 | 2009-07-27T03:53:22Z | [
"c++",
"python",
"properties",
"swig"
] |
Python Properties & Swig | 1,183,716 | <p>I am attempting to create python bindings for some C++ code using swig. I seem have run into a problem trying to create python properties from some accessor functions I have for methods like the following:</p>
<pre><code>class Player {
public:
void entity(Entity* entity);
Entity* entity() const;
};
</code></pre>
<p>I tried creating a property using the python property function but it seems that the wrapper classes swig generates are not compatible with it at least for setters.</p>
<p>How do you create properties using swig?</p>
| 14 | 2009-07-26T04:17:48Z | 2,725,454 | <p>I had the same problem and the advice to use %pythoncode worked for me. Here is what I did:</p>
<pre><code>class Foo {
// ...
std::string get_name();
bool set_name(const std::string & name);
};
</code></pre>
<p>In the wrapper:</p>
<pre><code>%include "foo.h"
%pythoncode %{
def RaiseExceptionOnFailure(mutator):
def mutator(self, v):
if not mutator(self, v):
raise ValueError("cannot set property")
return wrapper
Foo.name = property(Foo.get_name, RaiseExceptionOnFailure(Foo.set_name))
%}
</code></pre>
| 1 | 2010-04-27T21:57:11Z | [
"c++",
"python",
"properties",
"swig"
] |
Python Properties & Swig | 1,183,716 | <p>I am attempting to create python bindings for some C++ code using swig. I seem have run into a problem trying to create python properties from some accessor functions I have for methods like the following:</p>
<pre><code>class Player {
public:
void entity(Entity* entity);
Entity* entity() const;
};
</code></pre>
<p>I tried creating a property using the python property function but it seems that the wrapper classes swig generates are not compatible with it at least for setters.</p>
<p>How do you create properties using swig?</p>
| 14 | 2009-07-26T04:17:48Z | 3,530,173 | <p>The problem with Hao's ProperyVoodoo metaclass is that when there are multiple properties in the properties list, all the properties behave the same as the last one in the list. For example, if I had a list or property names ["x", "y", "z"], then the properties generated for all three would use the same accessors as "z".</p>
<p>After a little experimentation I believe I've determined that this problem is caused by the way Python handles closures (ie. names within nested functions that refer to variables in the containing scope). To solve the problem, you need to get local copies of the property name variable into the fget and fset methods. It's easy enough to sneak them in using default arguments:</p>
<pre><code># (NOTE: Hao's comments removed for brevity)
class PropertyVoodoo(type):
def __init__(cls, *a):
for prop in cls.__properties__:
def fget(self, _prop = str(prop)):
s = super(cls, self)
return getattr(s, _prop)()
def fset(self, value, _prop = str(prop)):
s = super(cls, self)
return getattr(s, _prop)(value)
setattr(cls, prop, property(fget=fget, fset=fset))
super(PropertyVoodoo, cls).__init__(*a)
def __setattr__(self, name, value):
if name in cls.__properties__:
object.__setattr__(self, name, value)
else:
s = super(cls, self)
s.__setattr__(name, value)
cls.__setattr__ = __setattr__
</code></pre>
<p>Note that it is, in fact, completely safe to give fget and fset the extra _prop parameters because the property() class will never explicitly pass values to them, which means they will always be the default value (that being a copy of the string referenced by prop at the time each fget and fset method was created).</p>
| 3 | 2010-08-20T10:51:34Z | [
"c++",
"python",
"properties",
"swig"
] |
Python Properties & Swig | 1,183,716 | <p>I am attempting to create python bindings for some C++ code using swig. I seem have run into a problem trying to create python properties from some accessor functions I have for methods like the following:</p>
<pre><code>class Player {
public:
void entity(Entity* entity);
Entity* entity() const;
};
</code></pre>
<p>I tried creating a property using the python property function but it seems that the wrapper classes swig generates are not compatible with it at least for setters.</p>
<p>How do you create properties using swig?</p>
| 14 | 2009-07-26T04:17:48Z | 4,750,081 | <p>There is an easy way to make python properties from methods with swig.<br>
Suppose C++ code Example.h:</p>
<p><strong>C++ header</strong></p>
<pre><code>class Example{
public:
void SetX(int x);
int GetX() const;
};
</code></pre>
<p>Lets convert this setter and getter to python propery 'x'. The trick is in .i file. We add some "swiggy" inline python code (with %pythoncode) that is inserted in a body of a resulting python class (in the auto-generated python code).</p>
<p><strong>Swig wrapping Example.i</strong></p>
<pre><code>%module example
%{
#include "example.h"
%}
class Example{
public:
void SetX(int x);
int GetX() const;
%pythoncode %{
__swig_getmethods__["x"] = GetX
__swig_setmethods__["x"] = SetX
if _newclass: x = property(GetX, SetX)
%}
};
</code></pre>
<p>Check the python code:</p>
<p><strong>python test code</strong></p>
<pre><code>import example
test = example.Example()
test.x = 5
print "Ha ha ha! It works! X = ", repr(test.x)
</code></pre>
<p>That is it!</p>
<hr>
<hr>
<h2>Make it simplier!</h2>
<p>There is no need to rewrite a class definition. Thanks to Joshua advice, one could use SWIG directive %extend ClassName { }. </p>
<p><strong>Swig wrapping Example.i</strong></p>
<pre><code>%module example
%{
#include "example.h"
%}
%extend Example{
%pythoncode %{
__swig_getmethods__["x"] = GetX
__swig_setmethods__["x"] = SetX
if _newclass: x = property(GetX, SetX)
%}
};
</code></pre>
<h2>Hiding setter and getter functions</h2>
<p>As one may see, test.GetX() and test.SetX() are still in place after conversion. One can hide them by:</p>
<p>a) Rename functions by using %rename, add '_' in the beginning thus making methods "private" for python. In the a SWIG interface .i
Example.i</p>
<pre><code>...
class Example{
%rename(_SetX) SetX(int);
%rename(_GetX) GetX();
...
</code></pre>
<p>(%rename may be placed in some separated place to save the possibility to convert this class to other languages, which don't need these '_')</p>
<p>b) or one can play with %feature("shadow")</p>
<h2>Why is it so?</h2>
<p>Why do we have to use such things to convert methods to a property by using SWIG?
As it was said, SWIG selfishly overrides <strong>_<em>setattr</em>_</strong>, so one have to use <strong>_swig_getmethods_</strong> and <strong>_swig_setmethods_</strong> to register functions and stay in the swig way. </p>
<h2>Why may one prefer this way?</h2>
<p>The methods listed above, especially with PropertyVoodoo are... It is like burning the house to fry an egg. Also it breaks the classes layout, as one have to create inherited classes to make python properties from C++ methods. I mean if class Cow returns class Milk and the inherited class is MilkWithProperties(Milk), how to make Cow to produce MilkWithProperties?</p>
<p>This approach allows one to:</p>
<ol>
<li><strong>explicitly control what C++ methods to convert to python properties</strong></li>
<li>conversion rules are located in swig interface(*.i) files, the place where they are supposed to be</li>
<li>one resulting autogenerated .py file</li>
<li>stay in the swig syntax of insertions in swig generated .py file</li>
<li>%pythoncode is ignored if one wraps library to other languages</li>
</ol>
<p><strong>Update</strong>
In a newer version SWIG abandoned <strong>_swig_property</strong> so just use <strong>property</strong>. It works with old version of swig the same. I've changed the post. </p>
| 27 | 2011-01-20T16:55:31Z | [
"c++",
"python",
"properties",
"swig"
] |
Python Properties & Swig | 1,183,716 | <p>I am attempting to create python bindings for some C++ code using swig. I seem have run into a problem trying to create python properties from some accessor functions I have for methods like the following:</p>
<pre><code>class Player {
public:
void entity(Entity* entity);
Entity* entity() const;
};
</code></pre>
<p>I tried creating a property using the python property function but it seems that the wrapper classes swig generates are not compatible with it at least for setters.</p>
<p>How do you create properties using swig?</p>
| 14 | 2009-07-26T04:17:48Z | 11,250,032 | <p>From <a href="http://www.swig.org/Doc2.0/SWIGDocumentation.html#SWIG_adding_member_functions" rel="nofollow">http://www.swig.org/Doc2.0/SWIGDocumentation.html#SWIG_adding_member_functions</a>: </p>
<blockquote>
<p>A little known feature of the %extend directive is that it can also be
used to add synthesized attributes or to modify the behavior of
existing data attributes. For example, suppose you wanted to make
magnitude a read-only attribute of Vector instead of a method.</p>
</blockquote>
<p>So in your example the following should work:</p>
<pre><code>%extend Player {
Entity entity;
}
%{
Entity* Player_entity_get(Player* p) {
return p->get_entity();
}
void Player_entityProp_set(Player* p, Entity* e) {
p->set_entity(e);
}
%}
</code></pre>
| 1 | 2012-06-28T17:38:11Z | [
"c++",
"python",
"properties",
"swig"
] |
Python Properties & Swig | 1,183,716 | <p>I am attempting to create python bindings for some C++ code using swig. I seem have run into a problem trying to create python properties from some accessor functions I have for methods like the following:</p>
<pre><code>class Player {
public:
void entity(Entity* entity);
Entity* entity() const;
};
</code></pre>
<p>I tried creating a property using the python property function but it seems that the wrapper classes swig generates are not compatible with it at least for setters.</p>
<p>How do you create properties using swig?</p>
| 14 | 2009-07-26T04:17:48Z | 11,386,066 | <h1>Use Attributes.i</h1>
<p>In the SWIG Lib folder is a file called "attributes.i" which is not discussed in the documentation but that contains inline documentation.</p>
<p>All you have to do is add the following line to your interface file. </p>
<pre><code>%include <attributes.i>
</code></pre>
<p>You then receive a number of macros (such as %attribute) for defining attributes from existing methods.</p>
<p>An excerpt from the documentation in the attributes.i file: </p>
<blockquote>
<p>The following macros convert a pair of set/get methods into a
"native" attribute. Use %attribute when you have a pair of get/set methods to a
primitive type like in:</p>
</blockquote>
<pre><code> %attribute(A, int, a, get_a, set_a);
struct A
{
int get_a() const;
void set_a(int aa);
};
</code></pre>
| 13 | 2012-07-08T19:40:20Z | [
"c++",
"python",
"properties",
"swig"
] |
How can I use Facebook Connect with Google App Engine without using Django? | 1,183,863 | <p>I'm developing on the Google App Engine and I would like to integrate Facebook Connect into my site as a means for registering and authenticating. In the past, I relied on Google's Accounts API for user registration. I'm trying to use Google's webapp framework instead of Django but it seems that all the resources regarding Facebook connect and GAE are very Django oriented. I have tried messing around with pyfacebook and miniFB found <a href="http://wiki.developers.facebook.com/index.php/Python" rel="nofollow">here</a> at the Facebook docs but I haven't been able to make things work with the webapp framework. I'm having trouble seeing the big picture as far as how I can make this work. What advice can you give me on how to make this work or what I should be considering instead? Should I be focusing on using <a href="http://wiki.developers.facebook.com/index.php/How%5FConnect%5FAuthentication%5FWorks" rel="nofollow">Javascript</a> instead of client libraries?</p>
<p><a href="http://wiki.developers.facebook.com/index.php/Account%5FLinking" rel="nofollow">Account Linking</a></p>
<p><a href="http://wiki.developers.facebook.com/index.php/How%5FTo%5FWrite%5FA%5FGood%5FConnect%5FApp" rel="nofollow">How to write a good connect app</a></p>
| 10 | 2009-07-26T06:06:54Z | 1,214,441 | <p>This tutorial might be useful:</p>
<p><a href="http://dollarmani-facebook.blogspot.com/2008/09/facebook-applications.html" rel="nofollow">http://dollarmani-facebook.blogspot.com/2008/09/facebook-applications.html</a></p>
| 1 | 2009-07-31T19:31:45Z | [
"python",
"google-app-engine",
"authentication",
"facebook"
] |
How can I use Facebook Connect with Google App Engine without using Django? | 1,183,863 | <p>I'm developing on the Google App Engine and I would like to integrate Facebook Connect into my site as a means for registering and authenticating. In the past, I relied on Google's Accounts API for user registration. I'm trying to use Google's webapp framework instead of Django but it seems that all the resources regarding Facebook connect and GAE are very Django oriented. I have tried messing around with pyfacebook and miniFB found <a href="http://wiki.developers.facebook.com/index.php/Python" rel="nofollow">here</a> at the Facebook docs but I haven't been able to make things work with the webapp framework. I'm having trouble seeing the big picture as far as how I can make this work. What advice can you give me on how to make this work or what I should be considering instead? Should I be focusing on using <a href="http://wiki.developers.facebook.com/index.php/How%5FConnect%5FAuthentication%5FWorks" rel="nofollow">Javascript</a> instead of client libraries?</p>
<p><a href="http://wiki.developers.facebook.com/index.php/Account%5FLinking" rel="nofollow">Account Linking</a></p>
<p><a href="http://wiki.developers.facebook.com/index.php/How%5FTo%5FWrite%5FA%5FGood%5FConnect%5FApp" rel="nofollow">How to write a good connect app</a></p>
| 10 | 2009-07-26T06:06:54Z | 1,726,735 | <p>It's not Facebook Connect, really, but at least it's webapp FBML handling:
<a href="http://github.com/WorldMaker/pyfacebook/blob/35b6e4dbb83ca14fbb23046bd675fa4d80d568c9/facebook/webappfb.py">http://github.com/WorldMaker/pyfacebook/.../facebook/webappfb.py</a></p>
<p><a href="http://forum.developers.facebook.com/viewtopic.php?pid=164613">This guy made a post</a> about Facebook Connect on Google AppEngine via webapp framework. (It's stickied in <a href="http://forum.developers.facebook.com/viewforum.php?id=32">the Connect Authentication forum</a>, with 8515 views.)</p>
<p>Here's an example from May 15: <a href="http://myzope.kedai.com.my/blogs/kedai/236">http://myzope.kedai.com.my/blogs/kedai/236</a>
It's based on the Guestbook example webapp, but with Facebook for authentication instead. The author does note that, "there's code duplication (when instantiating pyfacebook) in different classes," and that there should be a better way to do this.</p>
<p>Django sounds like it's better integrated. There's a presentation from 4 months ago on Slideshare called <a href="http://www.slideshare.net/web2ireland/build-facebook-connect-enabled-applications-with-google-apps-engine">Where Facebook Connects Google App Engine</a> (Robert Mao's talk at Facebook Garage Ireland). It looks like an interesting talk, though no videos of it have been posted at the moment. On slide 13, the following tools are mentioned, <em>including Django</em>: Google App Engine SDK, Eclipse, PyDev, Django, <a href="http://code.google.com/p/app-engine-patch/">App Engine Patch</a> and pyFacebook. Sample application given: <a href="http://github.com/mave99a/fb-guinness/">http://github.com/mave99a/fb-guinness/</a></p>
<p>If you merely want authentication, <a href="http://appengine-cookbook.appspot.com/recipe/accept-google-aol-yahoo-myspace-facebook-and-openid-logins/">this Recipe suggests using RPXnow.com</a> for Google, AOL, Yahoo, MySpace, Facebook and OpenID logins with the Webapp Framework. Might be helpful, though doesn't appear at first glance to use Connect, is <a href="http://code.google.com/appengine/articles/shelftalkers.html">a contributed howto article on GAE's site</a> for creating a Facebook App with Best Buy Remix.</p>
| 10 | 2009-11-13T02:21:00Z | [
"python",
"google-app-engine",
"authentication",
"facebook"
] |
How can I use Facebook Connect with Google App Engine without using Django? | 1,183,863 | <p>I'm developing on the Google App Engine and I would like to integrate Facebook Connect into my site as a means for registering and authenticating. In the past, I relied on Google's Accounts API for user registration. I'm trying to use Google's webapp framework instead of Django but it seems that all the resources regarding Facebook connect and GAE are very Django oriented. I have tried messing around with pyfacebook and miniFB found <a href="http://wiki.developers.facebook.com/index.php/Python" rel="nofollow">here</a> at the Facebook docs but I haven't been able to make things work with the webapp framework. I'm having trouble seeing the big picture as far as how I can make this work. What advice can you give me on how to make this work or what I should be considering instead? Should I be focusing on using <a href="http://wiki.developers.facebook.com/index.php/How%5FConnect%5FAuthentication%5FWorks" rel="nofollow">Javascript</a> instead of client libraries?</p>
<p><a href="http://wiki.developers.facebook.com/index.php/Account%5FLinking" rel="nofollow">Account Linking</a></p>
<p><a href="http://wiki.developers.facebook.com/index.php/How%5FTo%5FWrite%5FA%5FGood%5FConnect%5FApp" rel="nofollow">How to write a good connect app</a></p>
| 10 | 2009-07-26T06:06:54Z | 1,726,792 | <p>Most of Facebook Connect (as it was formerly called, now it's "Facebook for Websites") is Javascript. The only serverside thing you really need (assuming you want to integrate it into your own usersystem) is validation of the user's Facebook login. Either minifb or pyfacebook should accomplish this task.</p>
| 4 | 2009-11-13T02:38:34Z | [
"python",
"google-app-engine",
"authentication",
"facebook"
] |
Permalinks with Russian/Cyrillic news articles | 1,183,956 | <p>I basically am working with an oldschool php cms based site in Russian, one of the many new functionalities requested is permalinks.</p>
<p>As of now, currently the website just uses the standard non-mvc 'article.php?id=50'. I was browsing the <a href="http://ru.wikipedia.org/wiki/%D0%97%D0%B0%D0%B3%D0%BB%D0%B0%D0%B2%D0%BD%D0%B0%D1%8F%5F%D1%81%D1%82%D1%80%D0%B0%D0%BD%D0%B8%D1%86%D0%B0" rel="nofollow">Russian wiki</a> and this was really the only Russian site I've seen that made use of native Russian permalinks. I'm wondering:</p>
<ol>
<li>Are there any kind of limitations in regards to character usage? Does this require any type of special setup on the server-side or anything?</li>
<li>What kind of characters should I look out for in general for permalinks? Any gotchas I need?</li>
<li>Any tips on how I should store the permalinks in my database? As of now, the table structure is relatively simple.. just an articles table with:</li>
</ol>
<p>id article_title article_snippet article_whole date_time</p>
<p>I was thinking of adding a new column in this table named 'permalink' which will basically store a modified version of the article_title ( so far the only character I can think of with special treatment is the space which I'll convert to an underscore ).</p>
<ol>
<li>How should I have my new clean urls formatted? I was thinking something like:</li>
</ol>
<p>/articles/2009/ÐаглавнаÑ_ÑÑÑаниÑа</p>
<p>for example.</p>
<p>By the way, I'll be using Pylons ( a python framework ) and MySQL 5 though I'm open to PostgreSQL if there are any weird UTF8 restrictions ( I converted the whole database which was previously Latin1 to UTF8 by the way with iconv ).</p>
| 1 | 2009-07-26T07:16:13Z | 1,183,965 | <p>The current convention is to encode URLs in UTF-8, and then URL-escape (i.e. %-escape) them:</p>
<pre><code>py> urllib.quote(u"articles/2009/ÐаглавнаÑ_ÑÑÑаниÑа".encode("utf-8"))
'articles/2009/%D0%97%D0%B0%D0%B3%D0%BB%D0%B0%D0%B2%D0%BD%D0%B0%D1%8F_%D1%81%D1%82%D1%80%D0%B0%D0%BD%D0%B8%D1%86%D0%B0'
</code></pre>
<p>After this, there won't be any restrictions - i.e. browsers will either recognize it as UTF-8 or not, but they will certainly be able to follow the link.</p>
| 2 | 2009-07-26T07:22:45Z | [
"python",
"mysql",
"model-view-controller"
] |
why __builtins__ is both module and dict | 1,184,016 | <p>I am using the built-in module to insert a few instances, so they can be accessed globally for debugging purposes. The problem with the <code>__builtins__</code> module is that it is a module in a main script and is a dict in modules, but as my script depending on cases can be a main script or a module, I have to do this:</p>
<pre><code>if isinstance(__builtins__, dict):
__builtins__['g_frame'] = 'xxx'
else:
setattr(__builtins__, 'g_frame', 'xxx')
</code></pre>
<p>Is there a workaround, shorter than this? More importantly, why does <code>__builtins__</code> behave this way?</p>
<p>Here is a script to see this. Create a module a.py:</p>
<pre><code>#module-a
import b
print 'a-builtin:',type(__builtins__)
</code></pre>
<p>Create a module b.py:</p>
<pre><code>#module-b
print 'b-builtin:',type(__builtins__)
</code></pre>
<p>Now run python a.py:</p>
<pre><code>$ python a.py
b-builtin: <type 'dict'>
a-builtin: <type 'module'>
</code></pre>
| 8 | 2009-07-26T08:05:17Z | 1,184,036 | <p>I think you want the <code>__builtin__</code> module (note the singular).</p>
<p>See the docs:</p>
<blockquote>
<p><a href="http://docs.python.org/library/__builtin__.html" rel="nofollow">27.3. <code>__builtin__</code> â Built-in objects</a></p>
<p><strong>CPython implementation detail:</strong> Most modules have the name <code>__builtins__</code> (note the <code>'s'</code>) made available as part of their globals. The value of <code>__builtins__</code> is normally either this module or the value of this modulesâs [sic] <strong><code>__dict__</code></strong> attribute. Since this is an implementation detail, it may not be used by alternate implementations of Python.</p>
</blockquote>
| 10 | 2009-07-26T08:25:03Z | [
"python",
"python-module",
"built-in"
] |
Getting the name & extension of an uploaded file using python (google app engine) | 1,184,110 | <p>I am using a form to upload files to the google app engine and store them in the datastore. l would also like to store the original file name and extension for presentation purposes.</p>
<p>Is there a way of retrieving this data from the post sever side or can it only be gathered client side and sent as separate fields (e.g. <a href="http://www.tinyurl.com/5jybfq" rel="nofollow">http://www.tinyurl.com/5jybfq</a>)?</p>
<p>Many thanks.</p>
<p><strong>For those that follow the solution dased on the answer below:</strong> </p>
<pre><code>this_file = self.request.params["file_upload_form_field_name"].filename
(this_file_name, this_file_extension) = os.path.splitext(this_file)
self.response.out.write("File name: " + this_file_name + "<br>")
self.response.out.write("File extension: " + this_file_extension + "<br>")
</code></pre>
| 4 | 2009-07-26T09:15:19Z | 1,184,127 | <p>Does the snippet from <a href="http://osdir.com/ml/GoogleAppEngine/2009-06/msg00287.html" rel="nofollow">this email</a> work?</p>
<pre><code> self.request.params[<form element name with file>].filename
</code></pre>
| 3 | 2009-07-26T09:25:59Z | [
"python",
"google-app-engine",
"upload",
"filenames"
] |
Getting the name & extension of an uploaded file using python (google app engine) | 1,184,110 | <p>I am using a form to upload files to the google app engine and store them in the datastore. l would also like to store the original file name and extension for presentation purposes.</p>
<p>Is there a way of retrieving this data from the post sever side or can it only be gathered client side and sent as separate fields (e.g. <a href="http://www.tinyurl.com/5jybfq" rel="nofollow">http://www.tinyurl.com/5jybfq</a>)?</p>
<p>Many thanks.</p>
<p><strong>For those that follow the solution dased on the answer below:</strong> </p>
<pre><code>this_file = self.request.params["file_upload_form_field_name"].filename
(this_file_name, this_file_extension) = os.path.splitext(this_file)
self.response.out.write("File name: " + this_file_name + "<br>")
self.response.out.write("File extension: " + this_file_extension + "<br>")
</code></pre>
| 4 | 2009-07-26T09:15:19Z | 4,787,610 | <p>Try this...</p>
<p>If your form looks like this:</p>
<pre><code>self.response.out.write('''<form action="/upload" enctype="multipart/form-data" method="post"><input type="file" name="file"/><input type="submit" /></form>''')
</code></pre>
<p>Then in your post handler, try this:</p>
<pre><code>class UploadHandler(webapp.RequestHandler):
def post(self):
obj = MyModel()
obj.filename = self.request.get("file")
obj.blob = self.request.get("contents")
obj.put()
self.redirect('/')
</code></pre>
<p>The filename is stored in the "file" parameter. The actual file contents are in the "contents" parameter.</p>
| 0 | 2011-01-24T21:53:05Z | [
"python",
"google-app-engine",
"upload",
"filenames"
] |
Storing files for testbin/pastebin in Python | 1,184,116 | <p>I'm basically trying to setup my own private pastebin where I can save html files on my private server to test and fool around - have some sort of textarea for the initial input, save the file, and after saving I'd like to be able to view all the files I saved.</p>
<p>I'm trying to write this in python, just wondering what the most practical way would be of storing the file(s) or the code? SQLite? Straight up flat files? </p>
<p>One other thing I'm worried about is the uniqueness of the files, obviously I don't want conflicting filenames ( maybe save using 'title' and timestamp? ) - how should I structure it?</p>
| 0 | 2009-07-26T09:23:29Z | 1,184,162 | <p>I wrote something similar a while back in Django to test jQuery snippets. See:</p>
<p><a href="http://jquery.nodnod.net/" rel="nofollow">http://jquery.nodnod.net/</a></p>
<p>I have the code available on GitHub at <a href="http://github.com/dz/jquerytester/tree/master" rel="nofollow">http://github.com/dz/jquerytester/tree/master</a> if you're curious.</p>
<p>If you're using straight Python, there are a couple ways to approach naming:</p>
<ol>
<li><p>If storing as files, ask for a name, salt with current time, and generate a hash for the filename.</p></li>
<li><p>If using mysqlite or some other database, just use a numerical unique ID.</p></li>
</ol>
<p>Personally, I'd go for #2. It's easy, ensures uniqueness, and allows you to easily fetch various sets of 'files'.</p>
| 1 | 2009-07-26T09:44:57Z | [
"python",
"web-applications"
] |
Storing files for testbin/pastebin in Python | 1,184,116 | <p>I'm basically trying to setup my own private pastebin where I can save html files on my private server to test and fool around - have some sort of textarea for the initial input, save the file, and after saving I'd like to be able to view all the files I saved.</p>
<p>I'm trying to write this in python, just wondering what the most practical way would be of storing the file(s) or the code? SQLite? Straight up flat files? </p>
<p>One other thing I'm worried about is the uniqueness of the files, obviously I don't want conflicting filenames ( maybe save using 'title' and timestamp? ) - how should I structure it?</p>
| 0 | 2009-07-26T09:23:29Z | 1,184,165 | <p>Have you considered trying <a href="http://dev.pocoo.org/projects/lodgeit/" rel="nofollow">lodgeit</a>. Its a free pastbin which you can host yourself. I do not know how hard it is to set up.</p>
<p>Looking at their code they have gone with a database for storage (sqllite will do). They have structured there paste table like, (this is sqlalchemy table declaration style). The code is just a text field.</p>
<pre><code>pastes = Table('pastes', metadata,
Column('paste_id', Integer, primary_key=True),
Column('code', Text),
Column('parent_id', Integer, ForeignKey('pastes.paste_id'),
nullable=True),
Column('pub_date', DateTime),
Column('language', String(30)),
Column('user_hash', String(40), nullable=True),
Column('handled', Boolean, nullable=False),
Column('private_id', String(40), unique=True, nullable=True)
)
</code></pre>
<p>They have also made a hierarchy (see the self join) which is used for versioning. </p>
| 1 | 2009-07-26T09:47:11Z | [
"python",
"web-applications"
] |
Storing files for testbin/pastebin in Python | 1,184,116 | <p>I'm basically trying to setup my own private pastebin where I can save html files on my private server to test and fool around - have some sort of textarea for the initial input, save the file, and after saving I'd like to be able to view all the files I saved.</p>
<p>I'm trying to write this in python, just wondering what the most practical way would be of storing the file(s) or the code? SQLite? Straight up flat files? </p>
<p>One other thing I'm worried about is the uniqueness of the files, obviously I don't want conflicting filenames ( maybe save using 'title' and timestamp? ) - how should I structure it?</p>
| 0 | 2009-07-26T09:23:29Z | 1,184,170 | <p>Plain files are definitely more effective. Save your database for more complex queries.</p>
<p>If you need some formatting to be done on files, such as highlighting the code properly, it is better to do it <em>before</em> you save the file with that code. That way you don't need to apply formatting every time the file is shown.</p>
<p>You definitely would need somehow ensure all file names are unique, but this task is trivial, since you can just check, if the file already exists on the disk and if it does, add some number to its name and check again and so on.</p>
<p>Don't store them all in one directory either, since filesystem can perform much worse if there are A LOT (~ 1 million) files in the single directory, so you can structure your storage like this:</p>
<p>FILE_DIR/YEAR/MONTH/FileID.html and store the "YEAR/MONTH/FileID" Part in the database as a unique ID for the file.</p>
<p>Of course, if you don't worry about performance (not many users, for example) you can just go with storing everything in the database, which is much easier to manage.</p>
| 0 | 2009-07-26T09:51:26Z | [
"python",
"web-applications"
] |
python string search replace | 1,184,119 | <pre><code>SSViewer::set_theme('bullsorbit');
</code></pre>
<p>this my string. I want search in string <code>"SSViewer::set_theme('bullsorbit'); "</code> and replace <code>'bullsorbit'</code> with another string. <code>'bullsorbit'</code> string is dynamically changing.</p>
| 2 | 2009-07-26T09:23:55Z | 1,184,148 | <p>Not in a situation to be able to test this so you may need to fiddle with the Regular Expression (they may be errors in it.)</p>
<pre><code>import re
re.sub("SSViewer::set_theme\('[a-z]+'\)", "SSViewer::set_theme('whatever')", my_string)
</code></pre>
<p>Is this what you want?</p>
<p>Just tested it, this is some sample output:</p>
<pre><code>my_string = """Some file with some other junk
SSViewer::set_theme('bullsorbit');
SSViewer::set_theme('another');
Something else"""
import re
replaced = re.sub("SSViewer::set_theme\('[a-z]+'\)", "SSViewer::set_theme('whatever')", my_string)
print replaced
</code></pre>
<p>produces:</p>
<pre><code>Some file with some other junk
SSViewer::set_theme('whatever');
SSViewer::set_theme('whatever');
Something else
</code></pre>
<p>if you want to do it to a file:</p>
<pre><code>my_string = open('myfile', 'r').read()
</code></pre>
| 3 | 2009-07-26T09:34:02Z | [
"python",
"string",
"search",
"replace"
] |
python string search replace | 1,184,119 | <pre><code>SSViewer::set_theme('bullsorbit');
</code></pre>
<p>this my string. I want search in string <code>"SSViewer::set_theme('bullsorbit'); "</code> and replace <code>'bullsorbit'</code> with another string. <code>'bullsorbit'</code> string is dynamically changing.</p>
| 2 | 2009-07-26T09:23:55Z | 1,184,166 | <pre><code>>> my_string = "SSViewer::set_theme('bullsorbit');"
>>> import re
>>> change = re.findall(r"SSViewer::set_theme\('(\w*)'\);",my_string)
>>> my_string.replace(change[0],"blah")
"SSViewer::set_theme('blah');"
</code></pre>
<p>its not elegant but it works. the findall will return a dictionary of items that are inside the ('') and then replaces them. If you can get sub to work then that may look nicer but this will definitely work</p>
| 1 | 2009-07-26T09:47:38Z | [
"python",
"string",
"search",
"replace"
] |
python string search replace | 1,184,119 | <pre><code>SSViewer::set_theme('bullsorbit');
</code></pre>
<p>this my string. I want search in string <code>"SSViewer::set_theme('bullsorbit'); "</code> and replace <code>'bullsorbit'</code> with another string. <code>'bullsorbit'</code> string is dynamically changing.</p>
| 2 | 2009-07-26T09:23:55Z | 1,184,239 | <pre><code>st = "SSViewer::set_theme('"
for line in open("file.txt"):
line=line.strip()
if st in line:
a = line[ :line.index(st)+len(st)]
b = line [line.index(st)+len(st): ]
i = b.index("')")
b = b[i:]
print a + "newword" + b
</code></pre>
| 0 | 2009-07-26T10:36:06Z | [
"python",
"string",
"search",
"replace"
] |
python string search replace | 1,184,119 | <pre><code>SSViewer::set_theme('bullsorbit');
</code></pre>
<p>this my string. I want search in string <code>"SSViewer::set_theme('bullsorbit'); "</code> and replace <code>'bullsorbit'</code> with another string. <code>'bullsorbit'</code> string is dynamically changing.</p>
| 2 | 2009-07-26T09:23:55Z | 1,184,254 | <p>while your explanation is not entirely clear, I think you might make some use of the following:</p>
<pre><code>open(fname).read().replace('bullsorbit', 'new_string')
</code></pre>
| 0 | 2009-07-26T10:43:26Z | [
"python",
"string",
"search",
"replace"
] |
Python: extending int and MRO for __init__ | 1,184,337 | <p>In Python, I'm trying to extend the builtin 'int' type. In doing so I want to pass in some keywoard arguments to the constructor, so I do this:</p>
<pre><code>class C(int):
def __init__(self, val, **kwargs):
super(C, self).__init__(val)
# Do something with kwargs here...
</code></pre>
<p>However while calling <code>C(3)</code> works fine, <code>C(3, a=4)</code> gives: </p>
<pre><code>'a' is an invalid keyword argument for this function`
</code></pre>
<p>and <code>C.__mro__</code> returns the expected:</p>
<pre><code>(<class '__main__.C'>, <type 'int'>, <type 'object'>)
</code></pre>
<p>But it seems that Python is trying to call <code>int.__init__</code> first... Anyone know why? Is this a bug in the interpreter?</p>
| 10 | 2009-07-26T11:27:59Z | 1,184,369 | <p>You should be overriding
<code>"__new__"</code>, not <code>"__init__"</code> as ints are immutable.</p>
| 3 | 2009-07-26T11:44:27Z | [
"python",
"class-design",
"override"
] |
Python: extending int and MRO for __init__ | 1,184,337 | <p>In Python, I'm trying to extend the builtin 'int' type. In doing so I want to pass in some keywoard arguments to the constructor, so I do this:</p>
<pre><code>class C(int):
def __init__(self, val, **kwargs):
super(C, self).__init__(val)
# Do something with kwargs here...
</code></pre>
<p>However while calling <code>C(3)</code> works fine, <code>C(3, a=4)</code> gives: </p>
<pre><code>'a' is an invalid keyword argument for this function`
</code></pre>
<p>and <code>C.__mro__</code> returns the expected:</p>
<pre><code>(<class '__main__.C'>, <type 'int'>, <type 'object'>)
</code></pre>
<p>But it seems that Python is trying to call <code>int.__init__</code> first... Anyone know why? Is this a bug in the interpreter?</p>
| 10 | 2009-07-26T11:27:59Z | 1,184,377 | <p>The docs for the Python data model advise using <code>__new__</code>:</p>
<p><a href="http://docs.python.org/reference/datamodel.html#object.%5F%5Fnew%5F%5F">object.<strong>new</strong>(cls[, ...])</a></p>
<blockquote>
<p><strong>new</strong>() is intended mainly to allow subclasses of immutable types (like int, str, or tuple) to customize instance creation. It is also commonly overridden in custom metaclasses in order to customize class creation.</p>
</blockquote>
<p>Something like this should do it for the example you gave:</p>
<pre><code>class C(int):
def __new__(cls, val, **kwargs):
inst = super(C, cls).__new__(cls, val)
inst.a = kwargs.get('a', 0)
return inst
</code></pre>
| 7 | 2009-07-26T11:49:20Z | [
"python",
"class-design",
"override"
] |
Python: extending int and MRO for __init__ | 1,184,337 | <p>In Python, I'm trying to extend the builtin 'int' type. In doing so I want to pass in some keywoard arguments to the constructor, so I do this:</p>
<pre><code>class C(int):
def __init__(self, val, **kwargs):
super(C, self).__init__(val)
# Do something with kwargs here...
</code></pre>
<p>However while calling <code>C(3)</code> works fine, <code>C(3, a=4)</code> gives: </p>
<pre><code>'a' is an invalid keyword argument for this function`
</code></pre>
<p>and <code>C.__mro__</code> returns the expected:</p>
<pre><code>(<class '__main__.C'>, <type 'int'>, <type 'object'>)
</code></pre>
<p>But it seems that Python is trying to call <code>int.__init__</code> first... Anyone know why? Is this a bug in the interpreter?</p>
| 10 | 2009-07-26T11:27:59Z | 1,184,416 | <p>What everyone else (so far) said. Int are immutable, so you have to use <strong>new</strong>.</p>
<p>Also see (the accepted answers to):</p>
<ul>
<li><a href="http://stackoverflow.com/questions/1135335/increment-int-object">http://stackoverflow.com/questions/1135335/increment-int-object</a></li>
<li><a href="http://stackoverflow.com/questions/399022/why-cant-i-subclass-datetime-date">http://stackoverflow.com/questions/399022/why-cant-i-subclass-datetime-date</a></li>
</ul>
| 3 | 2009-07-26T12:14:16Z | [
"python",
"class-design",
"override"
] |
Is there a library which handles the parsing of BIND zone files in Python? | 1,184,803 | <p>This is related to <a href="http://stackoverflow.com/questions/236859/any-python-libs-for-parsing-bind-config-files">a similar question</a> about BIND, but in this case I'm trying to see if there's any easy way to parse various zone files into a dictionary, list, or some other manageable data structure, with the final goal being committing the data to a database. </p>
<p>I'm using BIND 8.4.7 and Python 2.4. I <em>may</em> be able to convince management to use a later Python version if needed, but the BIND version is non-negotiable at the moment. </p>
| 0 | 2009-07-26T15:09:54Z | 1,184,861 | <p>ISTM, <a href="http://pypi.python.org/pypi/easyzone/" rel="nofollow">easyzone</a> might meet your needs. It sits on top of dnspython, which would be an alternative API.</p>
| 1 | 2009-07-26T15:38:18Z | [
"python",
"database",
"parsing",
"bind",
"python-2.4"
] |
Downloading text files with Python and ftplib.FTP from z/os | 1,184,844 | <p>I'm trying to automate downloading of some text files from a z/os PDS, using Python and ftplib.</p>
<p>Since the host files are EBCDIC, I can't simply use FTP.retrbinary(). </p>
<p>FTP.retrlines(), when used with open(file,w).writelines as its callback, doesn't, of course, provide EOLs.</p>
<p>So, for starters, I've come up with this piece of code which "looks OK to me", but as I'm a relative Python noob, can anyone suggest a better approach? Obviously, to keep this question simple, this isn't the final, bells-and-whistles thing.</p>
<p>Many thanks.</p>
<pre><code>#!python.exe
from ftplib import FTP
class xfile (file):
def writelineswitheol(self, sequence):
for s in sequence:
self.write(s+"\r\n")
sess = FTP("zos.server.to.be", "myid", "mypassword")
sess.sendcmd("site sbd=(IBM-1047,ISO8859-1)")
sess.cwd("'FOO.BAR.PDS'")
a = sess.nlst("RTB*")
for i in a:
sess.retrlines("RETR "+i, xfile(i, 'w').writelineswitheol)
sess.quit()
</code></pre>
<p>Update: Python 3.0, platform is MingW under Windows XP.</p>
<p>z/os PDSs have a fixed record structure, rather than relying on line endings as record separators. However, the z/os FTP server, when transmitting in text mode, provides the record endings, which retrlines() strips off. </p>
<p><strong>Closing update:</strong></p>
<p>Here's my revised solution, which will be the basis for ongoing development (removing built-in passwords, for example):</p>
<pre><code>import ftplib
import os
from sys import exc_info
sess = ftplib.FTP("undisclosed.server.com", "userid", "password")
sess.sendcmd("site sbd=(IBM-1047,ISO8859-1)")
for dir in ["ASM", "ASML", "ASMM", "C", "CPP", "DLLA", "DLLC", "DLMC", "GEN", "HDR", "MAC"]:
sess.cwd("'ZLTALM.PREP.%s'" % dir)
try:
filelist = sess.nlst()
except ftplib.error_perm as x:
if (x.args[0][:3] != '550'):
raise
else:
try:
os.mkdir(dir)
except:
continue
for hostfile in filelist:
lines = []
sess.retrlines("RETR "+hostfile, lines.append)
pcfile = open("%s/%s"% (dir,hostfile), 'w')
for line in lines:
pcfile.write(line+"\n")
pcfile.close()
print ("Done: " + dir)
sess.quit()
</code></pre>
<p>My thanks to both John and Vinay</p>
| 1 | 2009-07-26T15:31:40Z | 1,184,866 | <p>You should be able to download the file as a binary (using <code>retrbinary</code>) and use the <code>codecs</code> module to convert from EBCDIC to whatever output encoding you want. You should know the specific EBCDIC code page being used on the z/OS system (e.g. cp500). If the files are small, you could even do something like (for a conversion to UTF-8):</p>
<pre><code>file = open(ebcdic_filename, "rb")
data = file.read()
converted = data.decode("cp500").encode("utf8")
file = open(utf8_filename, "wb")
file.write(converted)
file.close()
</code></pre>
<p><strong>Update:</strong> If you need to use <code>retrlines</code> to get the lines and your lines are coming back in the correct encoding, your approach will not work, because the callback is called once for each line. So in the callback, <code>sequence</code> will be the line, and your for loop will write individual characters in the line to the output, <em>each on its own line</em>. So you probably want to do <code>self.write(sequence + "\r\n")</code> rather than the <code>for</code> loop. It still doesn' feel especially right to subclass <code>file</code> just to add this utility method, though - it probably needs to be in a different class in your <code>bells-and-whistles</code> version.</p>
| 3 | 2009-07-26T15:39:56Z | [
"python",
"ftp",
"mainframe",
"zos"
] |
Downloading text files with Python and ftplib.FTP from z/os | 1,184,844 | <p>I'm trying to automate downloading of some text files from a z/os PDS, using Python and ftplib.</p>
<p>Since the host files are EBCDIC, I can't simply use FTP.retrbinary(). </p>
<p>FTP.retrlines(), when used with open(file,w).writelines as its callback, doesn't, of course, provide EOLs.</p>
<p>So, for starters, I've come up with this piece of code which "looks OK to me", but as I'm a relative Python noob, can anyone suggest a better approach? Obviously, to keep this question simple, this isn't the final, bells-and-whistles thing.</p>
<p>Many thanks.</p>
<pre><code>#!python.exe
from ftplib import FTP
class xfile (file):
def writelineswitheol(self, sequence):
for s in sequence:
self.write(s+"\r\n")
sess = FTP("zos.server.to.be", "myid", "mypassword")
sess.sendcmd("site sbd=(IBM-1047,ISO8859-1)")
sess.cwd("'FOO.BAR.PDS'")
a = sess.nlst("RTB*")
for i in a:
sess.retrlines("RETR "+i, xfile(i, 'w').writelineswitheol)
sess.quit()
</code></pre>
<p>Update: Python 3.0, platform is MingW under Windows XP.</p>
<p>z/os PDSs have a fixed record structure, rather than relying on line endings as record separators. However, the z/os FTP server, when transmitting in text mode, provides the record endings, which retrlines() strips off. </p>
<p><strong>Closing update:</strong></p>
<p>Here's my revised solution, which will be the basis for ongoing development (removing built-in passwords, for example):</p>
<pre><code>import ftplib
import os
from sys import exc_info
sess = ftplib.FTP("undisclosed.server.com", "userid", "password")
sess.sendcmd("site sbd=(IBM-1047,ISO8859-1)")
for dir in ["ASM", "ASML", "ASMM", "C", "CPP", "DLLA", "DLLC", "DLMC", "GEN", "HDR", "MAC"]:
sess.cwd("'ZLTALM.PREP.%s'" % dir)
try:
filelist = sess.nlst()
except ftplib.error_perm as x:
if (x.args[0][:3] != '550'):
raise
else:
try:
os.mkdir(dir)
except:
continue
for hostfile in filelist:
lines = []
sess.retrlines("RETR "+hostfile, lines.append)
pcfile = open("%s/%s"% (dir,hostfile), 'w')
for line in lines:
pcfile.write(line+"\n")
pcfile.close()
print ("Done: " + dir)
sess.quit()
</code></pre>
<p>My thanks to both John and Vinay</p>
| 1 | 2009-07-26T15:31:40Z | 1,186,010 | <p>Your writelineswitheol method appends '\r\n' instead of '\n' and then writes the result to a file opened in text mode. The effect, no matter what platform you are running on, will be an unwanted '\r'. Just append '\n' and you will get the appropriate line ending.</p>
<p>Proper error handling should not be relegated to a "bells and whistles" version. You should set up your callback so that your file open() is in a try/except and retains a reference to the output file handle, your write call is in a try/except, and you have a callback_obj.close() method which you use when retrlines() returns to explicitly file_handle.close() (in a try/except) -- that way you get explict error handling e.g. messages "can't (open|write to|close) file X because Y" AND you save having to think about when your files are going to be implicitly closed and whether you risk running out of file handles.</p>
<p>Python 3.x ftplib.FTP.retrlines() should give you str objects which are in effect Unicode strings, and you will need to encode them before you write them -- unless the default encoding is latin1 which would be rather unusual for a Windows box. You should have test files with (1) all possible 256 bytes (2) all bytes that are valid in the expected EBCDIC codepage.</p>
<p>[a few "sanitation" remarks]</p>
<ol>
<li><p>You should consider upgrading your Python from 3.0 (a "proof of concept" release) to 3.1. </p></li>
<li><p>To facilitate better understanding of your code, use "i" as an identifier only as a sequence index and only if you irredeemably acquired the habit from FORTRAN 3 or more decades ago :-)</p></li>
<li><p>Two of the problems discovered so far (appending line terminator to each character, wrong line terminator) would have shown up the first time you tested it.</p></li>
</ol>
| 1 | 2009-07-27T00:54:17Z | [
"python",
"ftp",
"mainframe",
"zos"
] |
Downloading text files with Python and ftplib.FTP from z/os | 1,184,844 | <p>I'm trying to automate downloading of some text files from a z/os PDS, using Python and ftplib.</p>
<p>Since the host files are EBCDIC, I can't simply use FTP.retrbinary(). </p>
<p>FTP.retrlines(), when used with open(file,w).writelines as its callback, doesn't, of course, provide EOLs.</p>
<p>So, for starters, I've come up with this piece of code which "looks OK to me", but as I'm a relative Python noob, can anyone suggest a better approach? Obviously, to keep this question simple, this isn't the final, bells-and-whistles thing.</p>
<p>Many thanks.</p>
<pre><code>#!python.exe
from ftplib import FTP
class xfile (file):
def writelineswitheol(self, sequence):
for s in sequence:
self.write(s+"\r\n")
sess = FTP("zos.server.to.be", "myid", "mypassword")
sess.sendcmd("site sbd=(IBM-1047,ISO8859-1)")
sess.cwd("'FOO.BAR.PDS'")
a = sess.nlst("RTB*")
for i in a:
sess.retrlines("RETR "+i, xfile(i, 'w').writelineswitheol)
sess.quit()
</code></pre>
<p>Update: Python 3.0, platform is MingW under Windows XP.</p>
<p>z/os PDSs have a fixed record structure, rather than relying on line endings as record separators. However, the z/os FTP server, when transmitting in text mode, provides the record endings, which retrlines() strips off. </p>
<p><strong>Closing update:</strong></p>
<p>Here's my revised solution, which will be the basis for ongoing development (removing built-in passwords, for example):</p>
<pre><code>import ftplib
import os
from sys import exc_info
sess = ftplib.FTP("undisclosed.server.com", "userid", "password")
sess.sendcmd("site sbd=(IBM-1047,ISO8859-1)")
for dir in ["ASM", "ASML", "ASMM", "C", "CPP", "DLLA", "DLLC", "DLMC", "GEN", "HDR", "MAC"]:
sess.cwd("'ZLTALM.PREP.%s'" % dir)
try:
filelist = sess.nlst()
except ftplib.error_perm as x:
if (x.args[0][:3] != '550'):
raise
else:
try:
os.mkdir(dir)
except:
continue
for hostfile in filelist:
lines = []
sess.retrlines("RETR "+hostfile, lines.append)
pcfile = open("%s/%s"% (dir,hostfile), 'w')
for line in lines:
pcfile.write(line+"\n")
pcfile.close()
print ("Done: " + dir)
sess.quit()
</code></pre>
<p>My thanks to both John and Vinay</p>
| 1 | 2009-07-26T15:31:40Z | 7,964,999 | <p>Just came across this question as I was trying to figure out how to recursively download datasets from z/OS. I've been using a simple python script for years now to download ebcdic files from the mainframe. It effectively just does this:</p>
<pre><code>def writeline(line):
file.write(line + "\n")
file = open(filename, "w")
ftp.retrlines("retr " + filename, writeline)
</code></pre>
| 1 | 2011-11-01T10:13:45Z | [
"python",
"ftp",
"mainframe",
"zos"
] |
Error importing external library within Django template tag library | 1,185,084 | <p>So I'm attempting to write a Django reusable app that provides a method for displaying your Twitter feed on your page. I know well that it already exists 20 times. It's an academic exercise. :)</p>
<p>Directory structure is pretty simple:</p>
<pre><code>myproject
|__ __init__.py
|__ manage.py
|__ settings.py
|__ myapp
|__ __init__.py
|__ admin.py
|__ conf
|__ __init__.py
|__ appsettings.py
|__ feedparser.py
|__ models.py
|__ templates
|__ __init__.py
|__ templatetags
|__ __init__.py
|__ twitterfeed.py
|__ views.py
|__ templates
|__ base.html
|__ urls.py
</code></pre>
<p>When running the Django shell, the functions defined in twitterfeed.py work perfectly. I also believe that I have the template tags properly named and registered.</p>
<p>As you can see, I use the excellent <a href="http://www.feedparser.org/" rel="nofollow">Universal Feed Parser</a>. My problem is not within UFP itself, but in UFP's inability to be called while importing the template tag library. When I <code>{% load twitterfeed %}</code> in base.py, I get the following error:</p>
<blockquote>
<p>'twitterfeed' is not a valid tag
library: Could not load template
library from
django.templatetags.twitterfeed, No
module named feedparser</p>
</blockquote>
<p>I import feedparser using the following statement:</p>
<pre><code>import re, datetime, time, myapp.feedparser
</code></pre>
<p>The best I can tell, this error message is slightly deceiving. I think there's an ImportError going on when the template library is loaded, and this is Django's interpretation of it.</p>
<p>Is there any way I can import feedparser.py within my reusable app without requiring users of the app to place feedparser somewhere in their PythonPath?</p>
<p>Thanks!</p>
| 3 | 2009-07-26T17:36:06Z | 1,185,115 | <p>I solve this kind of problem (shipping libraries that are dependencies for my overall project) in the following way. First, I create an "ext" directory in the root of my project (in your case that would be <code>myproject/ext</code>). Then I place dependencies such as feedparser in that ext directory - <code>myproject/ext/feedparser</code></p>
<p>Finally, I change my manage.py script to insert the ext/ directory at the front of sys.path. This means both <code>./manage.py runserver</code> and <code>./manage.py shell</code> will pick up the correct path:</p>
<pre><code># manage.py
import os, sys
sys.path.insert(0, os.path.join(os.path.dirname(__file__), 'ext'))
# ... rest of manage.py
</code></pre>
<p>I find this works really well if you don't want to mess around with things like virtualenvs. When you deploy your project you have to make sure the path is correct as well - I usually solve this by adding the same <code>sys.path.insert</code> line to the start of my mod_wsgi app.wsgi file.</p>
| 5 | 2009-07-26T17:52:37Z | [
"python",
"django",
"feedparser",
"templatetags"
] |
Error importing external library within Django template tag library | 1,185,084 | <p>So I'm attempting to write a Django reusable app that provides a method for displaying your Twitter feed on your page. I know well that it already exists 20 times. It's an academic exercise. :)</p>
<p>Directory structure is pretty simple:</p>
<pre><code>myproject
|__ __init__.py
|__ manage.py
|__ settings.py
|__ myapp
|__ __init__.py
|__ admin.py
|__ conf
|__ __init__.py
|__ appsettings.py
|__ feedparser.py
|__ models.py
|__ templates
|__ __init__.py
|__ templatetags
|__ __init__.py
|__ twitterfeed.py
|__ views.py
|__ templates
|__ base.html
|__ urls.py
</code></pre>
<p>When running the Django shell, the functions defined in twitterfeed.py work perfectly. I also believe that I have the template tags properly named and registered.</p>
<p>As you can see, I use the excellent <a href="http://www.feedparser.org/" rel="nofollow">Universal Feed Parser</a>. My problem is not within UFP itself, but in UFP's inability to be called while importing the template tag library. When I <code>{% load twitterfeed %}</code> in base.py, I get the following error:</p>
<blockquote>
<p>'twitterfeed' is not a valid tag
library: Could not load template
library from
django.templatetags.twitterfeed, No
module named feedparser</p>
</blockquote>
<p>I import feedparser using the following statement:</p>
<pre><code>import re, datetime, time, myapp.feedparser
</code></pre>
<p>The best I can tell, this error message is slightly deceiving. I think there's an ImportError going on when the template library is loaded, and this is Django's interpretation of it.</p>
<p>Is there any way I can import feedparser.py within my reusable app without requiring users of the app to place feedparser somewhere in their PythonPath?</p>
<p>Thanks!</p>
| 3 | 2009-07-26T17:36:06Z | 1,185,334 | <p>This looks like one of those annoying relative path issues - solved in Python 2.6 and higher (where you can do import ..feedparser etc) but often a bit tricky on older versions. One cheap and cheerful way to fix this could be just to move feedparser.py in to your templatetags directory, as a sibling to twitterfeed.py</p>
| 2 | 2009-07-26T19:24:37Z | [
"python",
"django",
"feedparser",
"templatetags"
] |
Should I use thread local storage for variables that only exist in a {class,method}? | 1,185,117 | <p>I am implementing a relatively simple thread pool with Python's <code>Queue.Queue</code> class. I have one producer class that contains the <code>Queue</code> instance along with some convenience methods, along with a consumer class that subclasses <code>threading.Thread</code>. I instantiate that object for every thread I want in my pool ("worker threads," I think they're called) based on an integer.</p>
<p>Each worker thread takes <code>flag, data</code> off the queue, processes it using its own database connection, and places the GUID of the row onto a list so that the producer class knows when a job is done.</p>
<p>While I'm aware that other modules implement the functionality I'm coding, the reason I'm coding this is to gain a better understanding of how Python threading works. This brings me to my question.</p>
<p>If I store anything in a function's namespace or in the class's <code>__dict__</code> object, will it be thread safe?</p>
<pre><code>class Consumer(threading.Thread):
def __init__(self, producer, db_filename):
self.producer = producer
self.conn = sqlite3.connect(db_filename) # Is this var thread safe?
def run(self):
flag, data = self.producer.queue.get()
while flag != 'stop':
# Do stuff with data; Is `data` thread safe?
</code></pre>
<p>I am thinking that both would be thread safe, here's my rationale:</p>
<ul>
<li>Each time a class is instantiated, a new <code>__dict__</code> gets created. Under the scenario I outline above, I don't think any other object would have a reference to this object. (Now, perhaps the situation might get more complicated if I used <code>join()</code> functionality, but I'm not...)</li>
<li>Each time a function gets called, it creates its own name space which exists for the lifetime of the function. I'm not making any of my variables <code>global</code>, so I don't understand how any other object would have a reference to a function variable.</li>
</ul>
<p><a href="http://stackoverflow.com/questions/104983/please-explain-thread-local-storage-for-python">This post</a> addresses my question somewhat, but is still a little abstract for me.</p>
<p>Thanks in advance for clearing this up for me.</p>
| 4 | 2009-07-26T17:53:08Z | 1,185,249 | <p>You are right; this is thread-safe. Local variables (the ones you call "function namespace") are always thread-safe, since only the thread executing the function can access them. Instance attributes are thread-safe as long as the instance is not shared across threads. As the consumer class inherits from Thread, its instances certainly won't be shared across threads.</p>
<p>The only "risk" here is the value of the data object: in theory, the producer might hold onto the data object after putting it into the queue, and (if the data object itself is mutable - make sure you understand what "mutable" means) may change the object while the Consumer is using it. If the producer leaves the data object alone after putting it into the queue, this is thread-safe.</p>
| 5 | 2009-07-26T18:47:44Z | [
"python",
"concurrency",
"namespaces",
"multithreading"
] |
Should I use thread local storage for variables that only exist in a {class,method}? | 1,185,117 | <p>I am implementing a relatively simple thread pool with Python's <code>Queue.Queue</code> class. I have one producer class that contains the <code>Queue</code> instance along with some convenience methods, along with a consumer class that subclasses <code>threading.Thread</code>. I instantiate that object for every thread I want in my pool ("worker threads," I think they're called) based on an integer.</p>
<p>Each worker thread takes <code>flag, data</code> off the queue, processes it using its own database connection, and places the GUID of the row onto a list so that the producer class knows when a job is done.</p>
<p>While I'm aware that other modules implement the functionality I'm coding, the reason I'm coding this is to gain a better understanding of how Python threading works. This brings me to my question.</p>
<p>If I store anything in a function's namespace or in the class's <code>__dict__</code> object, will it be thread safe?</p>
<pre><code>class Consumer(threading.Thread):
def __init__(self, producer, db_filename):
self.producer = producer
self.conn = sqlite3.connect(db_filename) # Is this var thread safe?
def run(self):
flag, data = self.producer.queue.get()
while flag != 'stop':
# Do stuff with data; Is `data` thread safe?
</code></pre>
<p>I am thinking that both would be thread safe, here's my rationale:</p>
<ul>
<li>Each time a class is instantiated, a new <code>__dict__</code> gets created. Under the scenario I outline above, I don't think any other object would have a reference to this object. (Now, perhaps the situation might get more complicated if I used <code>join()</code> functionality, but I'm not...)</li>
<li>Each time a function gets called, it creates its own name space which exists for the lifetime of the function. I'm not making any of my variables <code>global</code>, so I don't understand how any other object would have a reference to a function variable.</li>
</ul>
<p><a href="http://stackoverflow.com/questions/104983/please-explain-thread-local-storage-for-python">This post</a> addresses my question somewhat, but is still a little abstract for me.</p>
<p>Thanks in advance for clearing this up for me.</p>
| 4 | 2009-07-26T17:53:08Z | 1,185,250 | <p>I think you are on the whole correct with your assumptions and in your case you are most probably correct.</p>
<p>However it slightly more difficult to tell if something is thread safe or not then you say.</p>
<p>Calls such as <code>self.conn = sqlite3.connect(db_filename)</code> may not be, as sqlite3 module could be sharing some state and calling the function may have some side effects. However, I doubt that this is the case and like you I would assume it was producing a totally new variable.</p>
<p>It is not just global variables that could be a problem, getting mutable variables from outer scopes is also an issue.</p>
<p>So the data in </p>
<pre><code>flag, data = self.producer.queue.get()
</code></pre>
<p>may or may not be thread safe, depending on where the data was produced originally. However, I assume that this data would consist of independent (preferably immutable) information. So if thats the case then all should be thread safe.</p>
| 1 | 2009-07-26T18:48:11Z | [
"python",
"concurrency",
"namespaces",
"multithreading"
] |
Should I use thread local storage for variables that only exist in a {class,method}? | 1,185,117 | <p>I am implementing a relatively simple thread pool with Python's <code>Queue.Queue</code> class. I have one producer class that contains the <code>Queue</code> instance along with some convenience methods, along with a consumer class that subclasses <code>threading.Thread</code>. I instantiate that object for every thread I want in my pool ("worker threads," I think they're called) based on an integer.</p>
<p>Each worker thread takes <code>flag, data</code> off the queue, processes it using its own database connection, and places the GUID of the row onto a list so that the producer class knows when a job is done.</p>
<p>While I'm aware that other modules implement the functionality I'm coding, the reason I'm coding this is to gain a better understanding of how Python threading works. This brings me to my question.</p>
<p>If I store anything in a function's namespace or in the class's <code>__dict__</code> object, will it be thread safe?</p>
<pre><code>class Consumer(threading.Thread):
def __init__(self, producer, db_filename):
self.producer = producer
self.conn = sqlite3.connect(db_filename) # Is this var thread safe?
def run(self):
flag, data = self.producer.queue.get()
while flag != 'stop':
# Do stuff with data; Is `data` thread safe?
</code></pre>
<p>I am thinking that both would be thread safe, here's my rationale:</p>
<ul>
<li>Each time a class is instantiated, a new <code>__dict__</code> gets created. Under the scenario I outline above, I don't think any other object would have a reference to this object. (Now, perhaps the situation might get more complicated if I used <code>join()</code> functionality, but I'm not...)</li>
<li>Each time a function gets called, it creates its own name space which exists for the lifetime of the function. I'm not making any of my variables <code>global</code>, so I don't understand how any other object would have a reference to a function variable.</li>
</ul>
<p><a href="http://stackoverflow.com/questions/104983/please-explain-thread-local-storage-for-python">This post</a> addresses my question somewhat, but is still a little abstract for me.</p>
<p>Thanks in advance for clearing this up for me.</p>
| 4 | 2009-07-26T17:53:08Z | 14,969,556 | <p>To make the data thread safe use copy.deepcopy() to create a new copy of the data before putting it on the queue. Then the producer can modify the data in the next loop without modifying the consumers copy before he gets to it.</p>
| 1 | 2013-02-19T23:27:37Z | [
"python",
"concurrency",
"namespaces",
"multithreading"
] |
Creating child frames of main frame in wxPython | 1,185,156 | <p>I am trying create a new frame in wxPython that is a child of the main frame so that when the main frame is closed, the child frame will also be closed.</p>
<p>Here is a simplified example of the problem that I am having:</p>
<pre><code>#! /usr/bin/env python
import wx
class App(wx.App):
def OnInit(self):
frame = MainFrame()
frame.Show()
self.SetTopWindow(frame)
return True
class MainFrame(wx.Frame):
title = "Main Frame"
def __init__(self):
wx.Frame.__init__(self, None, 1, self.title) #id = 5
menuFile = wx.Menu()
menuAbout = wx.Menu()
menuAbout.Append(2, "&About...", "About this program")
menuBar = wx.MenuBar()
menuBar.Append(menuAbout, "&Help")
self.SetMenuBar(menuBar)
self.CreateStatusBar()
self.Bind(wx.EVT_MENU, self.OnAbout, id=2)
def OnQuit(self, event):
self.Close()
def OnAbout(self, event):
AboutFrame().Show()
class AboutFrame(wx.Frame):
title = "About this program"
def __init__(self):
wx.Frame.__init__(self, 1, -1, self.title) #trying to set parent=1 (id of MainFrame())
if __name__ == '__main__':
app = App(False)
app.MainLoop()
</code></pre>
<p>If I set AboutFrame's parent frame to None (on line 48) then the About frame is succesfully created and displayed but it stays open when the main frame is closed.</p>
<p>Is this the approach that I should be taking to create child frames of the main frame or should I be doing it differently, eg. using the onClose event of the main frame to close any child frames (this way sounds very 'hackish').</p>
<p>If I am taking the correct approach, why is it not working?</p>
| 12 | 2009-07-26T18:08:57Z | 1,185,226 | <pre><code>class AboutFrame(wx.Frame):
title = "About this program"
def __init__(self):
wx.Frame.__init__(self, wx.GetApp().TopWindow, title=self.title)
</code></pre>
| 10 | 2009-07-26T18:37:56Z | [
"python",
"wxpython"
] |
Passing expressions to functions in python? | 1,185,199 | <p>I'm not quite sure what i mean here, so please bear with me..</p>
<p>In sqlalchemy, it appears i'm supposed to pass an expression? to <a href="http://www.sqlalchemy.org/docs/05/ormtutorial.html#common-filter-operators" rel="nofollow">filter()</a> in certain cases. When i try to implement something like this myself, i end up with:</p>
<pre><code>>>> def someFunc(value):
... print(value)
>>> someFunc(5 == 5)
True
</code></pre>
<p><strong>How do i get the values passed to == from inside the function?</strong></p>
<p>Edit: I'm trying to achieve something like this</p>
<pre><code> >>> def magic(left, op, right):
... print(left+" "+op+" "+right)
>>> magic(5 == 5)
5 == 5
</code></pre>
<p>Edit: What about if one of the paramaters was an object?</p>
| 5 | 2009-07-26T18:26:21Z | 1,185,208 | <p>You can't. The expression <code>5 == 5</code> is evaluated and only then is the result passed to someFunc. The function just gets <code>True</code> (the <code>True</code> object, to be precise), no matter what the expression was.</p>
<p>Edit: Concerning your edit, <a href="http://stackoverflow.com/questions/1179096/suggestions-for-python-assert-function">this question</a> is kind of close.</p>
<p>Edit 2: You could just pass the expression as a string and use eval, like this:</p>
<pre><code>>>> def someFunc(expression_string):
... print(expression_string, "evaluates to", eval(expression_string))
>>> someFunc("5 == 5")
5 == 5 evaluates to True
</code></pre>
<p>Don't know whether that helps you. Keep in mind that <code>eval</code> is a powerful tool, so it's dangerous to pass arbitrary (and possibly even user-generated) input to it.</p>
| 1 | 2009-07-26T18:29:36Z | [
"python",
"parameters",
"sqlalchemy"
] |
Passing expressions to functions in python? | 1,185,199 | <p>I'm not quite sure what i mean here, so please bear with me..</p>
<p>In sqlalchemy, it appears i'm supposed to pass an expression? to <a href="http://www.sqlalchemy.org/docs/05/ormtutorial.html#common-filter-operators" rel="nofollow">filter()</a> in certain cases. When i try to implement something like this myself, i end up with:</p>
<pre><code>>>> def someFunc(value):
... print(value)
>>> someFunc(5 == 5)
True
</code></pre>
<p><strong>How do i get the values passed to == from inside the function?</strong></p>
<p>Edit: I'm trying to achieve something like this</p>
<pre><code> >>> def magic(left, op, right):
... print(left+" "+op+" "+right)
>>> magic(5 == 5)
5 == 5
</code></pre>
<p>Edit: What about if one of the paramaters was an object?</p>
| 5 | 2009-07-26T18:26:21Z | 1,185,210 | <p>You need to wrap the whole thing as a literal string. You're trying to print that out as a string I assume, correct?</p>
| 0 | 2009-07-26T18:30:31Z | [
"python",
"parameters",
"sqlalchemy"
] |
Passing expressions to functions in python? | 1,185,199 | <p>I'm not quite sure what i mean here, so please bear with me..</p>
<p>In sqlalchemy, it appears i'm supposed to pass an expression? to <a href="http://www.sqlalchemy.org/docs/05/ormtutorial.html#common-filter-operators" rel="nofollow">filter()</a> in certain cases. When i try to implement something like this myself, i end up with:</p>
<pre><code>>>> def someFunc(value):
... print(value)
>>> someFunc(5 == 5)
True
</code></pre>
<p><strong>How do i get the values passed to == from inside the function?</strong></p>
<p>Edit: I'm trying to achieve something like this</p>
<pre><code> >>> def magic(left, op, right):
... print(left+" "+op+" "+right)
>>> magic(5 == 5)
5 == 5
</code></pre>
<p>Edit: What about if one of the paramaters was an object?</p>
| 5 | 2009-07-26T18:26:21Z | 1,185,211 | <p>Short answer: You can't. The result of the expression evaluation is passed to the function rather than the expression itself.</p>
| 0 | 2009-07-26T18:31:11Z | [
"python",
"parameters",
"sqlalchemy"
] |
Passing expressions to functions in python? | 1,185,199 | <p>I'm not quite sure what i mean here, so please bear with me..</p>
<p>In sqlalchemy, it appears i'm supposed to pass an expression? to <a href="http://www.sqlalchemy.org/docs/05/ormtutorial.html#common-filter-operators" rel="nofollow">filter()</a> in certain cases. When i try to implement something like this myself, i end up with:</p>
<pre><code>>>> def someFunc(value):
... print(value)
>>> someFunc(5 == 5)
True
</code></pre>
<p><strong>How do i get the values passed to == from inside the function?</strong></p>
<p>Edit: I'm trying to achieve something like this</p>
<pre><code> >>> def magic(left, op, right):
... print(left+" "+op+" "+right)
>>> magic(5 == 5)
5 == 5
</code></pre>
<p>Edit: What about if one of the paramaters was an object?</p>
| 5 | 2009-07-26T18:26:21Z | 1,185,228 | <p>It appears you can return tuples from <strong>eq</strong>:</p>
<pre><code>class Foo:
def __init__(self, value):
self.value = value
def __eq__(self, other):
return (self.value, other.value)
f1 = Foo(5)
f2 = Foo(10)
print(f1 == f2)
</code></pre>
| 1 | 2009-07-26T18:38:21Z | [
"python",
"parameters",
"sqlalchemy"
] |
Passing expressions to functions in python? | 1,185,199 | <p>I'm not quite sure what i mean here, so please bear with me..</p>
<p>In sqlalchemy, it appears i'm supposed to pass an expression? to <a href="http://www.sqlalchemy.org/docs/05/ormtutorial.html#common-filter-operators" rel="nofollow">filter()</a> in certain cases. When i try to implement something like this myself, i end up with:</p>
<pre><code>>>> def someFunc(value):
... print(value)
>>> someFunc(5 == 5)
True
</code></pre>
<p><strong>How do i get the values passed to == from inside the function?</strong></p>
<p>Edit: I'm trying to achieve something like this</p>
<pre><code> >>> def magic(left, op, right):
... print(left+" "+op+" "+right)
>>> magic(5 == 5)
5 == 5
</code></pre>
<p>Edit: What about if one of the paramaters was an object?</p>
| 5 | 2009-07-26T18:26:21Z | 1,185,254 | <p>You can achieve your example if you make "op" a function:</p>
<pre>
>>> def magic(left, op, right):
... return op(left, right)
...
>>> magic(5, (lambda a, b: a == b), 5)
True
>>> magic(5, (lambda a, b: a == b), 4)
False
</pre>
<p>This is more Pythonic than passing a String. It's how functions like <a href="http://wiki.python.org/moin/HowTo/Sorting">sort()</a> work.</p>
<p>Those SQLAlchemy examples with filter() are puzzling. I don't know the internals about SQLAlchemy, but I'm guessing in an example like query.filter(User.name == 'ed') what's going on is that User.name is a SQLAlchemy-specific type, with an odd implementation of the __eq() function that generates SQL for the filter() function instead of doing a comparison. Ie: they've made special classes that let you type Python expressions that emit SQL code. It's an unusual technique, one I'd avoid unless building something that's bridging two languages like an ORM.</p>
| 11 | 2009-07-26T18:50:41Z | [
"python",
"parameters",
"sqlalchemy"
] |
Passing expressions to functions in python? | 1,185,199 | <p>I'm not quite sure what i mean here, so please bear with me..</p>
<p>In sqlalchemy, it appears i'm supposed to pass an expression? to <a href="http://www.sqlalchemy.org/docs/05/ormtutorial.html#common-filter-operators" rel="nofollow">filter()</a> in certain cases. When i try to implement something like this myself, i end up with:</p>
<pre><code>>>> def someFunc(value):
... print(value)
>>> someFunc(5 == 5)
True
</code></pre>
<p><strong>How do i get the values passed to == from inside the function?</strong></p>
<p>Edit: I'm trying to achieve something like this</p>
<pre><code> >>> def magic(left, op, right):
... print(left+" "+op+" "+right)
>>> magic(5 == 5)
5 == 5
</code></pre>
<p>Edit: What about if one of the paramaters was an object?</p>
| 5 | 2009-07-26T18:26:21Z | 1,191,181 | <p>An even more pythonic variant of Nelson's solution is to use the operator functions from the <a href="http://docs.python.org/library/operator.html" rel="nofollow">operator</a> module in the standard library; there is no need to create your own lambdas.</p>
<pre><code>>>> from operator import eq
>>> def magic(left, op, right):
... return op(left, right)
...
>>> magic(5, eq, 5)
True
</code></pre>
| 4 | 2009-07-27T23:24:34Z | [
"python",
"parameters",
"sqlalchemy"
] |
Passing expressions to functions in python? | 1,185,199 | <p>I'm not quite sure what i mean here, so please bear with me..</p>
<p>In sqlalchemy, it appears i'm supposed to pass an expression? to <a href="http://www.sqlalchemy.org/docs/05/ormtutorial.html#common-filter-operators" rel="nofollow">filter()</a> in certain cases. When i try to implement something like this myself, i end up with:</p>
<pre><code>>>> def someFunc(value):
... print(value)
>>> someFunc(5 == 5)
True
</code></pre>
<p><strong>How do i get the values passed to == from inside the function?</strong></p>
<p>Edit: I'm trying to achieve something like this</p>
<pre><code> >>> def magic(left, op, right):
... print(left+" "+op+" "+right)
>>> magic(5 == 5)
5 == 5
</code></pre>
<p>Edit: What about if one of the paramaters was an object?</p>
| 5 | 2009-07-26T18:26:21Z | 30,208,467 | <p>You have to implement <code>__eq__()</code> . For example ::</p>
<pre><code>class A(object):
def __eq__(self, other):
return (self, '==', other)
</code></pre>
<p>Then, for the function, which you want to get the expression, like ::</p>
<pre><code>def my_func(expr):
# deal with the expression
print(expr)
>>> a = A()
>>> my_func(a == 1)
(<__main__.A object at 0x1015eb978>, '==', 1)
</code></pre>
| 0 | 2015-05-13T07:34:46Z | [
"python",
"parameters",
"sqlalchemy"
] |
Which python tools for building a database-backed webapp | 1,185,248 | <p>I am <a href="http://stackoverflow.com/questions/1168701/to-make-a-plan-for-my-first-mysql-project">completing my first database project</a> which aims to build a simple discussion site.</p>
<p>The <a href="http://superuser.com/questions/13238/is-python-only-for-building-backends-in-making-websites">answers which I got at Superuser</a> suggests me that Python is difficult to use in building a database webapp without any other tools. </p>
<p><strong>Which other tools would you use?</strong></p>
| -1 | 2009-07-26T18:47:09Z | 1,185,255 | <p>Many people would recommend <a href="http://www.sqlalchemy.org/" rel="nofollow">SQLAlchemy</a>.</p>
| 2 | 2009-07-26T18:50:59Z | [
"python",
"orm",
"cheetah"
] |
Which python tools for building a database-backed webapp | 1,185,248 | <p>I am <a href="http://stackoverflow.com/questions/1168701/to-make-a-plan-for-my-first-mysql-project">completing my first database project</a> which aims to build a simple discussion site.</p>
<p>The <a href="http://superuser.com/questions/13238/is-python-only-for-building-backends-in-making-websites">answers which I got at Superuser</a> suggests me that Python is difficult to use in building a database webapp without any other tools. </p>
<p><strong>Which other tools would you use?</strong></p>
| -1 | 2009-07-26T18:47:09Z | 1,185,265 | <p>ORM is not same as templating. Since you want to write your own sql queries and at the same time want to write clean python code, i would suggest you look at <a href="http://webpy.org/" rel="nofollow">web.py</a>. I have used web.py and i must say its really simple and to the point.It has its own templating engine, but you can use a different one too.</p>
<p>If you would like to use ORM you can use SQLAlchemy or SQLObject they seem to be quite popular.</p>
| 1 | 2009-07-26T18:53:33Z | [
"python",
"orm",
"cheetah"
] |
Which python tools for building a database-backed webapp | 1,185,248 | <p>I am <a href="http://stackoverflow.com/questions/1168701/to-make-a-plan-for-my-first-mysql-project">completing my first database project</a> which aims to build a simple discussion site.</p>
<p>The <a href="http://superuser.com/questions/13238/is-python-only-for-building-backends-in-making-websites">answers which I got at Superuser</a> suggests me that Python is difficult to use in building a database webapp without any other tools. </p>
<p><strong>Which other tools would you use?</strong></p>
| -1 | 2009-07-26T18:47:09Z | 1,185,267 | <p>Sorry, your question makes no sense.</p>
<ol>
<li><p>You say you can't use Django because you have to write your SQL queries yourself. Firstly, why do you have to? And secondly, Django certainly doesn't stop you.</p></li>
<li><p>Even though you say you want to write your SQL queries yourself, you then ask what ORM is best. An ORM replaces the need to write SQL, that's the whole point. If you can't use Django for that reason, SQLAlchemy won't help.</p></li>
</ol>
| 5 | 2009-07-26T18:53:54Z | [
"python",
"orm",
"cheetah"
] |
Which python tools for building a database-backed webapp | 1,185,248 | <p>I am <a href="http://stackoverflow.com/questions/1168701/to-make-a-plan-for-my-first-mysql-project">completing my first database project</a> which aims to build a simple discussion site.</p>
<p>The <a href="http://superuser.com/questions/13238/is-python-only-for-building-backends-in-making-websites">answers which I got at Superuser</a> suggests me that Python is difficult to use in building a database webapp without any other tools. </p>
<p><strong>Which other tools would you use?</strong></p>
| -1 | 2009-07-26T18:47:09Z | 1,185,270 | <p>Your question is very strange.</p>
<p>First, Django doesn't force you to use its SQL abstraction. Each part of Django can be use idenpendently of the others. You can use Django together with any other SQL library.</p>
<p>Second, if you need to build your own SQL queries, an ORM is the <i>opposite</i> of what you need.</p>
| 2 | 2009-07-26T18:55:15Z | [
"python",
"orm",
"cheetah"
] |
Which python tools for building a database-backed webapp | 1,185,248 | <p>I am <a href="http://stackoverflow.com/questions/1168701/to-make-a-plan-for-my-first-mysql-project">completing my first database project</a> which aims to build a simple discussion site.</p>
<p>The <a href="http://superuser.com/questions/13238/is-python-only-for-building-backends-in-making-websites">answers which I got at Superuser</a> suggests me that Python is difficult to use in building a database webapp without any other tools. </p>
<p><strong>Which other tools would you use?</strong></p>
| -1 | 2009-07-26T18:47:09Z | 1,185,286 | <p>There are many other options other than Django. However:</p>
<p><strong>You can make your own SQL queries in Django</strong>. <a href="http://docs.djangoproject.com/en/dev/ref/models/querysets/#extra-select-none-where-none-params-none-tables-none-order-by-none-select-params-none" rel="nofollow">Here is the documentation for <code>extra()</code></a>. <code>extra()</code> lets you make extra SQL calls on top of the ORM.</p>
<p>If you want to make raw SQL queries, bypassing the ORM entirely, you can do so with <code>django.db</code>. <a href="http://blog.doughellmann.com/2007/12/using-raw-sql-in-django.html" rel="nofollow">See this article for examples</a>.</p>
<p>That said, other options aside from Django if you still want to use a framework:</p>
<ul>
<li>Turbogears</li>
<li>Pylons</li>
<li>Web2Py</li>
<li>Zope3</li>
<li>Plone/Zop2</li>
</ul>
<p>See <a href="http://wiki.python.org/moin/WebFrameworks" rel="nofollow">this list</a> for a listing of more frameworks.</p>
<p>Now, if you don't want to use a ORM and just want o make SQL calls directly, Python also has the ability to interact with a database. See <a href="http://wiki.python.org/moin/DatabaseProgramming/" rel="nofollow">this page on the Python wiki</a>.</p>
| 1 | 2009-07-26T19:03:02Z | [
"python",
"orm",
"cheetah"
] |
Algorithms to identify Markov generated content? | 1,185,369 | <p>Markov chains are a (almost standard) way to generate <a href="http://uswaretech.com/blog/2009/06/pseudo-random-text-markov-chains-python/">random gibberish</a> which looks intelligent to untrained eye. How would you go about identifying markov generated text from human written text.</p>
<p>It would be awesome if the resources you point to are Python friendly.</p>
| 11 | 2009-07-26T19:45:13Z | 1,185,394 | <p>If you had several large Markov-generated texts, you could possibly determine that they were so by comparing the word frequencies between each of the samples. Since Markov chains depend on constant word probabilities, the proportions of any given word should be roughly equal from sample to sample.</p>
| 2 | 2009-07-26T19:52:33Z | [
"python",
"algorithm",
"markov"
] |
Algorithms to identify Markov generated content? | 1,185,369 | <p>Markov chains are a (almost standard) way to generate <a href="http://uswaretech.com/blog/2009/06/pseudo-random-text-markov-chains-python/">random gibberish</a> which looks intelligent to untrained eye. How would you go about identifying markov generated text from human written text.</p>
<p>It would be awesome if the resources you point to are Python friendly.</p>
| 11 | 2009-07-26T19:45:13Z | 1,185,431 | <p>One simple approach would be to have a large group of humans read input text for you and see if the text makes sense. I'm only half-joking, this is a tricky problem. </p>
<p>I believe this to be a hard problem, because Markov-chain generated text is going to have a lot of the same properties of real human text in terms of word frequency and simple relationships between the ordering of words. </p>
<p>The differences between real text and text generated by a Markov chain are in higher-level rules of grammar and in semantic meaning, which are hard to encode programmatically. The other problem is that Markov chains are good enough at generating text that they sometimes come up with grammatically and semantically correct statements. </p>
<p>As an example, here's an <a href="http://www.beetleinabox.com/cgi-bin/kant.pl">aphorism from the kantmachine</a>:</p>
<blockquote>
<p>Today, he would feel convinced that
the human will is free; to-morrow,
considering the indissoluble chain of
nature, he would look on freedom as a
mere illusion and declare nature to be
all-in-all.</p>
</blockquote>
<p>While this string was written by a computer program, it's hard to say that a human would never say this. </p>
<p>I think that unless you can give us more specific details about the computer and human-generated text that expose more obvious differences it will be difficult to solve this using computer programming. </p>
| 8 | 2009-07-26T20:11:29Z | [
"python",
"algorithm",
"markov"
] |
Algorithms to identify Markov generated content? | 1,185,369 | <p>Markov chains are a (almost standard) way to generate <a href="http://uswaretech.com/blog/2009/06/pseudo-random-text-markov-chains-python/">random gibberish</a> which looks intelligent to untrained eye. How would you go about identifying markov generated text from human written text.</p>
<p>It would be awesome if the resources you point to are Python friendly.</p>
| 11 | 2009-07-26T19:45:13Z | 1,186,053 | <p>Crowdsourcing. Use Mechanical Turk and get a number of humans to vote on this. There are even some libraries to help you pull this off. For example:</p>
<ul>
<li><a href="http://groups.csail.mit.edu/uid/turkit/" rel="nofollow">TurKit - Iterative Tasks on Mechanical Turk</a></li>
</ul>
<p>Here's a blog post from O'Reilly Radar on tips for using Mechanical Turk to get your work done:</p>
<ul>
<li><a href="http://radar.oreilly.com/2009/06/mechanical-turk-best-practices.html" rel="nofollow">Mechanical Turk Best Practices</a></li>
</ul>
| 2 | 2009-07-27T01:18:56Z | [
"python",
"algorithm",
"markov"
] |
Algorithms to identify Markov generated content? | 1,185,369 | <p>Markov chains are a (almost standard) way to generate <a href="http://uswaretech.com/blog/2009/06/pseudo-random-text-markov-chains-python/">random gibberish</a> which looks intelligent to untrained eye. How would you go about identifying markov generated text from human written text.</p>
<p>It would be awesome if the resources you point to are Python friendly.</p>
| 11 | 2009-07-26T19:45:13Z | 1,186,215 | <p>I suggest a generalization of Evan's answer: make a Markov model of your own and train it with a big chunk of the (very large) sample you're given, reserving the rest of the sample as "test data". Now, see how well the model you've trained does on the test data, e.g. with a chi square test that will suggest situation in which "fit is TOO good" (suggesting the test data is indeed generated by this model) as well as ones in which the fit is very bad (suggesting error in model structure -- an over-trained model with the wrong structure does a notoriously bad job in such cases).</p>
<p>Of course there are still many issues for calibration, such as the structure of the model -- are you suspecting a simple model based on Ntuples of words and little more, or a more sophisticated one with grammar states and the like. Fortunately you can calibrate things pretty well by using large corpora of known-to-be-natural text and also ones you generate yourself with models of various structures.</p>
<p>A different approach is to use <a href="http://www.nltk.org/">nltk</a> to parse the sentences you're given -- a small number of mis-parses is to be expected even in natural text (as humans are imperfect and so is the parser -- it may not know that word X can be used as a verb and only classify it as a noun, etc, etc), but most Markov models (unless they're modeling essentially the same grammar structure your parser happens to be using -- and you can use several parsers to try and counteract that!-) will cause VASTLY more mis-parses than even dyslexic humans. Again, calibrate that on natural vs synthetic texts, and you'll see what I mean!-)</p>
| 5 | 2009-07-27T02:46:20Z | [
"python",
"algorithm",
"markov"
] |
Algorithms to identify Markov generated content? | 1,185,369 | <p>Markov chains are a (almost standard) way to generate <a href="http://uswaretech.com/blog/2009/06/pseudo-random-text-markov-chains-python/">random gibberish</a> which looks intelligent to untrained eye. How would you go about identifying markov generated text from human written text.</p>
<p>It would be awesome if the resources you point to are Python friendly.</p>
| 11 | 2009-07-26T19:45:13Z | 1,187,247 | <p>You could use a "brute force" approach, whereby you compare the generated language to data collected on n-grams of higher order than the Markov model that generated it.</p>
<p>i.e. If the language was generated with a 2nd order Markov model, up to 3-grams are going to have the correct frequencies, but 4-grams probably won't. </p>
<p>You can get up to 5-gram frequencies from Google's public <a href="http://googleresearch.blogspot.com/2006/08/all-our-n-gram-are-belong-to-you.html" rel="nofollow">n-gram dataset.</a> It's huge though - 24G <em>compressed</em> - you need to get it by post on DVDs from <a href="http://www.ldc.upenn.edu" rel="nofollow">LDC</a>. </p>
<p>EDIT: Added some implementation details</p>
<p>The n-grams have already been counted, so you just need to store the counts (or frequencies) in a way that's quick to search. A properly indexed database, or perhaps a Lucene index should work. </p>
<p>Given a piece of text, scan across it and look up the frequency of each 5-gram in your database, and see where it ranks compared to other 5-grams that start with the same 4 words.</p>
<p>Practically, a bigger obstacle might be the licensing terms of the dataset. Using it for a commercial app might be prohibited.</p>
| 6 | 2009-07-27T09:20:32Z | [
"python",
"algorithm",
"markov"
] |
Algorithms to identify Markov generated content? | 1,185,369 | <p>Markov chains are a (almost standard) way to generate <a href="http://uswaretech.com/blog/2009/06/pseudo-random-text-markov-chains-python/">random gibberish</a> which looks intelligent to untrained eye. How would you go about identifying markov generated text from human written text.</p>
<p>It would be awesome if the resources you point to are Python friendly.</p>
| 11 | 2009-07-26T19:45:13Z | 17,794,107 | <p>If you write a program which generates Markovian transition probabilities from any sequence of symbols, and then calculates the entropy rate of the markov matrix. (see <a href="http://en.wikipedia.org/wiki/Entropy_rate#Entropy_rates_for_Markov_chains" rel="nofollow">http://en.wikipedia.org/wiki/Entropy_rate#Entropy_rates_for_Markov_chains</a>) This is basically an estimate of how easily the text could be predicted using just the markov chain (higher entropy means <em>harder</em> to predict). Therefore I would think that the lower the entropy of the markov matrix is, the more likely that the sample of text is controlled by a markov matrix. If you have questions on how to write this code, I happen to have a program in python which does exactly this on my computer, so I can help you out</p>
| 0 | 2013-07-22T17:50:49Z | [
"python",
"algorithm",
"markov"
] |
merge sort implementation to sort by string length - python | 1,185,388 | <p>I've implemented what I believe to be a merge sort algorithm in python. I've never programmed in Python before, so I used several resources with commands that seemed foreign to me, to gain a better understanding. </p>
<p>However, I've also never implemented merge sort in the first place, so I'm not sure if I've even implemented it correctly. Any guidance, tips, or corrections would be greatly appreciated.</p>
<p>Here is my merge method:</p>
<pre><code>def merge(left, right):
result = []
i, j = 0, 0
while(i < len(left) and j< len(right)):
if(len(left[i]) <= len(right[j])):
print(i)
result.append(left[i])
i=i+1
else:
result.append(right[j])
j=j+1
result += left[i:]
result += right[j:]
return result
</code></pre>
<p>meanwhile, here is my mergesort method:</p>
<pre><code>def mergesort(list):
if len(list) < 2:
return list
else:
middle = len(list) / 2
left = mergesort(list[:middle])
right = mergesort(list[middle:])
return merge(left, right)
</code></pre>
<p>Thanks for any possible help! :)</p>
| 0 | 2009-07-26T19:50:35Z | 1,185,421 | <p>Don't name variables "list". That's the name of Python's array type, so using a variable by the same name is confusing.</p>
<p>When you return from a conditional, you don't need to sitck the rest of the function in an else block.</p>
<pre><code>def mergesort(list):
if len(list) < 2:
return list
middle = len(list) / 2
left = mergesort(list[:middle])
right = mergesort(list[middle:])
return merge(left, right)
</code></pre>
<p>Overall, it looks reasonable.</p>
<p>Of course, for anything but an exercise, you should be using list.sort or sorted().</p>
<pre><code>a = ["abc", "de", "f", "ghijkl"]
print sorted(a, lambda a,b: cmp(len(a), len(b)))
</code></pre>
| 3 | 2009-07-26T20:04:39Z | [
"python",
"algorithm",
"mergesort"
] |
merge sort implementation to sort by string length - python | 1,185,388 | <p>I've implemented what I believe to be a merge sort algorithm in python. I've never programmed in Python before, so I used several resources with commands that seemed foreign to me, to gain a better understanding. </p>
<p>However, I've also never implemented merge sort in the first place, so I'm not sure if I've even implemented it correctly. Any guidance, tips, or corrections would be greatly appreciated.</p>
<p>Here is my merge method:</p>
<pre><code>def merge(left, right):
result = []
i, j = 0, 0
while(i < len(left) and j< len(right)):
if(len(left[i]) <= len(right[j])):
print(i)
result.append(left[i])
i=i+1
else:
result.append(right[j])
j=j+1
result += left[i:]
result += right[j:]
return result
</code></pre>
<p>meanwhile, here is my mergesort method:</p>
<pre><code>def mergesort(list):
if len(list) < 2:
return list
else:
middle = len(list) / 2
left = mergesort(list[:middle])
right = mergesort(list[middle:])
return merge(left, right)
</code></pre>
<p>Thanks for any possible help! :)</p>
| 0 | 2009-07-26T19:50:35Z | 1,185,424 | <p>How about using the <code>sorted()</code> function? Like this:</p>
<pre><code>def len_cmp(x, y):
return len(x) - len(y)
my_strings = ["hello", "foo", "bar", "spam"]
print sorted(my_strings, len_cmp)
</code></pre>
| 2 | 2009-07-26T20:06:02Z | [
"python",
"algorithm",
"mergesort"
] |
How do I start a session in a Python web application? | 1,185,406 | <p>This question is based on <a href="http://stackoverflow.com/questions/1184888/to-understand-a-line-about-a-login-variable-in-a-session/1184931#1184931">this answer</a>.</p>
<p>I'm looking for a function similar to PHP's <code>session_start()</code> for Python. I want to access a dictionary like <code>$_SESSION</code> in PHP which becomes available after running the command.</p>
| 4 | 2009-07-26T20:00:26Z | 1,185,418 | <p>Python is not a web language in itself like PHP, so it has not built in web features. There are many modules that add this functionality however, but then you'll have to be specific about which one you're using.</p>
<p>Here's how you could use it with <a href="http://www.djangoproject.com/" rel="nofollow">the Django framework</a>, for example:</p>
<pre><code>def post_comment(request, new_comment):
if request.session.get('has_commented', False):
return HttpResponse("You've already commented.")
c = comments.Comment(comment=new_comment)
c.save()
request.session['has_commented'] = True
return HttpResponse('Thanks for your comment!')
</code></pre>
<p>In simpler web frameworks there might not be session support. Sessions aren't impossible to implement yourself, but you can probably find a stand-alone module that adds support by receiving/sending the session id to it (the session id is stored in a cookie, which almost all web frameworks have some kind of support for.)</p>
| 3 | 2009-07-26T20:04:00Z | [
"python",
"session"
] |
How do I start a session in a Python web application? | 1,185,406 | <p>This question is based on <a href="http://stackoverflow.com/questions/1184888/to-understand-a-line-about-a-login-variable-in-a-session/1184931#1184931">this answer</a>.</p>
<p>I'm looking for a function similar to PHP's <code>session_start()</code> for Python. I want to access a dictionary like <code>$_SESSION</code> in PHP which becomes available after running the command.</p>
| 4 | 2009-07-26T20:00:26Z | 1,185,437 | <p>As someone who comes from PHP and is working his way into Python I can tell you that <a href="http://www.djangoproject.com/">Django</a> is a good way to start dealing with Python on the web. This is especially true if you've been using <a href="http://www.phpwact.org/php/mvc%5Fframeworks">MVC frameworks in PHP</a>. That said, Django has built in support for session management and is documented here:</p>
<p><a href="http://docs.djangoproject.com/en/dev/topics/http/sessions/">http://docs.djangoproject.com/en/dev/topics/http/sessions/</a></p>
<p>And, out of curiousity, I took a look around for session management with plain python and found this:</p>
<p><a href="http://code.activestate.com/recipes/325484/">http://code.activestate.com/recipes/325484/</a></p>
<p>Judging by the comments, it would seem that you're better off using one of the tried and true frameworks to handle this for you. If you're not interested in Django you can also <a href="http://wiki.python.org/moin/WebFrameworks">checkout some of the others</a></p>
| 7 | 2009-07-26T20:13:47Z | [
"python",
"session"
] |
How do I start a session in a Python web application? | 1,185,406 | <p>This question is based on <a href="http://stackoverflow.com/questions/1184888/to-understand-a-line-about-a-login-variable-in-a-session/1184931#1184931">this answer</a>.</p>
<p>I'm looking for a function similar to PHP's <code>session_start()</code> for Python. I want to access a dictionary like <code>$_SESSION</code> in PHP which becomes available after running the command.</p>
| 4 | 2009-07-26T20:00:26Z | 1,185,496 | <p>Let me address some things that might be related to your question...it may not be relevant for you, but I think others might come here with the exact same question and might benefit from my (limited) experience...because I also had this question at one time.</p>
<p>Speaking as someone who went from PHP to Python (and never looked back), I think it's useful to understand how sessions work under the hood. It's probably <em>not</em> a good idea to implement your own session framework unless you (a) want to understand more about sessions management by doing or (b) need something that existing frameworks don't offer.</p>
<p><a href="http://en.wikipedia.org/wiki/Session%5Fcookie">Wikipedia</a> is always a good place to start. Bottom line: session data gets stored somewhere on the server and indexed by a unique identifier (hash of some sort). This identifier gets passed back and forth between the client and server, usually as a cookie or as part of the query string (the URL). For security's sake, you'll want to use an SSL connection or validate the session ID with some other piece of data (e.g. IP address). By default PHP stores sessions as files, but on a shared server that could pose a security risk, so you might want to override the session engine so you store sessions in a database. Python web frameworks have similar functionality.</p>
<p>When I started doing web programming in Python, I noticed two things. First, PHP wrapped a lot of magic into the language, making it easy for a beginning programmer (me in 2003) to learn the language, but not teaching me much about how everything worked. Therefore, I found myself researching many topics about web applications, specifically database connection pooling, URL mapping, sessions, and threading. PHP (and Django, from what I understand) abstract that away for you. Second, PHP is a really crappy language ;) but it gets the job done!!</p>
<p>Personally I use CherryPy for web development. It has session management as a "tool" that you can turn on.</p>
| 8 | 2009-07-26T20:43:45Z | [
"python",
"session"
] |
How do I start a session in a Python web application? | 1,185,406 | <p>This question is based on <a href="http://stackoverflow.com/questions/1184888/to-understand-a-line-about-a-login-variable-in-a-session/1184931#1184931">this answer</a>.</p>
<p>I'm looking for a function similar to PHP's <code>session_start()</code> for Python. I want to access a dictionary like <code>$_SESSION</code> in PHP which becomes available after running the command.</p>
| 4 | 2009-07-26T20:00:26Z | 1,186,016 | <p>You might consider looking into the Beaker library for Python which isn't tied to any one web framework an will work in a WSGI compatible environment:</p>
<blockquote>
<p><a href="http://beaker.groovie.org/">http://beaker.groovie.org/</a></p>
<p>Beaker is a library for caching and sessions for use with web applications and stand-alone Python scripts and applications. It comes with WSGI middleware for easy drop-in use with WSGI based web applications, and caching decorators for ease of use with any Python based application.</p>
</blockquote>
| 5 | 2009-07-27T01:00:05Z | [
"python",
"session"
] |
How to trim whitespace (including tabs)? | 1,185,524 | <p>Is there a function that will trim not only spaces for whitespace, but also tabs?</p>
| 623 | 2009-07-26T20:54:38Z | 1,185,528 | <p>For leading and trailing whitespace:</p>
<pre><code>s = ' foo \t '
print s.strip()
</code></pre>
<p>Otherwise, a regular expression works:</p>
<pre><code>import re
pat = re.compile(r'\s+')
s = ' \t foo \t bar \t '
print pat.sub('', s)
</code></pre>
| 17 | 2009-07-26T20:56:06Z | [
"python",
"string",
"trim",
"strip"
] |
How to trim whitespace (including tabs)? | 1,185,524 | <p>Is there a function that will trim not only spaces for whitespace, but also tabs?</p>
| 623 | 2009-07-26T20:54:38Z | 1,185,529 | <p>Whitespace on the both sides:</p>
<pre><code>s = " \t a string example\t "
s = s.strip()
</code></pre>
<p>Whitespace on the right side:</p>
<pre><code>s = s.rstrip()
</code></pre>
<p>Whitespace on the left side:</p>
<pre><code>s = s.lstrip()
</code></pre>
<p>As <a href="http://stackoverflow.com/users/84380/thedz">thedz</a> points out, you can provide an argument to strip arbitrary characters to any of these functions like this:</p>
<pre><code>s = s.strip(' \t\n\r')
</code></pre>
<p>This will strip any space, \t, \n, or \r characters from the left-hand side, right-hand side, or both sides of the string. </p>
<p>The examples above only remove strings from the left-hand and right-hand sides of strings. If you want to also remove characters from the middle of a string, try re.sub:</p>
<pre><code>import re
print re.sub('[\s+]', '', s)
</code></pre>
<p>That should print out:</p>
<pre><code>astringexample
</code></pre>
| 908 | 2009-07-26T20:56:26Z | [
"python",
"string",
"trim",
"strip"
] |
How to trim whitespace (including tabs)? | 1,185,524 | <p>Is there a function that will trim not only spaces for whitespace, but also tabs?</p>
| 623 | 2009-07-26T20:54:38Z | 9,255,908 | <pre><code>#how to trim a multi line string or a file
s=""" line one
\tline two\t
line three """
#line1 starts with a space, #2 starts and ends with a tab, #3 ends with a space.
s1=s.splitlines()
print s1
[' line one', '\tline two\t', 'line three ']
print [i.strip() for i in s1]
['line one', 'line two', 'line three']
#more details:
#we could also have used a forloop from the begining:
for line in s.splitlines():
line=line.strip()
process(line)
#we could also be reading a file line by line.. e.g. my_file=open(filename), or with open(filename) as myfile:
for line in my_file:
line=line.strip()
process(line)
#moot point: note splitlines() removed the newline characters, we can keep them by passing True:
#although split() will then remove them anyway..
s2=s.splitlines(True)
print s2
[' line one\n', '\tline two\t\n', 'line three ']
</code></pre>
| 9 | 2012-02-13T05:16:24Z | [
"python",
"string",
"trim",
"strip"
] |
How to trim whitespace (including tabs)? | 1,185,524 | <p>Is there a function that will trim not only spaces for whitespace, but also tabs?</p>
| 623 | 2009-07-26T20:54:38Z | 9,326,184 | <p>Python <code>trim</code> method is called <code>strip</code>:</p>
<pre><code>str.strip() #trim
str.lstrip() #ltrim
str.rstrip() #rtrim
</code></pre>
| 39 | 2012-02-17T10:00:00Z | [
"python",
"string",
"trim",
"strip"
] |
How to trim whitespace (including tabs)? | 1,185,524 | <p>Is there a function that will trim not only spaces for whitespace, but also tabs?</p>
| 623 | 2009-07-26T20:54:38Z | 14,824,444 | <p>No one has posted these regex solutions yet.</p>
<p>Matching:</p>
<pre><code>>>> import re
>>> p=re.compile('\\s*(.*\\S)?\\s*')
>>> m=p.match(' \t blah ')
>>> m.group(1)
'blah'
>>> m=p.match(' \tbl ah \t ')
>>> m.group(1)
'bl ah'
>>> m=p.match(' \t ')
>>> print m.group(1)
None
</code></pre>
<p>Searching (you have to handle the "only spaces" input case differently):</p>
<pre><code>>>> p1=re.compile('\\S.*\\S')
>>> m=p1.search(' \tblah \t ')
>>> m.group()
'blah'
>>> m=p1.search(' \tbl ah \t ')
>>> m.group()
'bl ah'
>>> m=p1.search(' \t ')
>>> m.group()
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
AttributeError: 'NoneType' object has no attribute 'group'
</code></pre>
<p>If you use <code>re.sub</code>, you may remove inner whitespace, which could be undesirable.</p>
| 4 | 2013-02-12T02:22:02Z | [
"python",
"string",
"trim",
"strip"
] |
How to trim whitespace (including tabs)? | 1,185,524 | <p>Is there a function that will trim not only spaces for whitespace, but also tabs?</p>
| 623 | 2009-07-26T20:54:38Z | 18,635,055 | <pre><code>content = "this is \nText\r\r\t\n. This is new text"
</code></pre>
<p>To remove <code>\n</code>, <code>\r</code>, <code>\t</code>, the better way is:</p>
<pre><code>data = ""
for i in content:
data += i.strip("\n").strip("\t").strip("\r").replace("\n","").replace("\t","").replace("\r","")
</code></pre>
<p>Output:</p>
<pre><code>>>> data
'this is Text. This is new text'
</code></pre>
<p>This is the easiest way to remove the above characters.
If any python package or library is available, then please let me know and also suggest how to remove character/??, occurs due to pressing Enter.</p>
| -2 | 2013-09-05T11:25:05Z | [
"python",
"string",
"trim",
"strip"
] |
How to trim whitespace (including tabs)? | 1,185,524 | <p>Is there a function that will trim not only spaces for whitespace, but also tabs?</p>
| 623 | 2009-07-26T20:54:38Z | 24,165,293 | <p>You can also use very simple, and basic function: <a href="https://docs.python.org/2/library/stdtypes.html#str.replace">str.replace()</a>, works with the whitespaces and tabs:</p>
<pre><code>>>> whitespaces = " abcd ef gh ijkl "
>>> tabs = " abcde fgh ijkl"
>>> print whitespaces.replace(" ", "")
abcdefghijkl
>>> print tabs.replace(" ", "")
abcdefghijkl
</code></pre>
<p>Simple and easy.</p>
| 13 | 2014-06-11T14:18:09Z | [
"python",
"string",
"trim",
"strip"
] |
How to trim whitespace (including tabs)? | 1,185,524 | <p>Is there a function that will trim not only spaces for whitespace, but also tabs?</p>
| 623 | 2009-07-26T20:54:38Z | 29,641,234 | <p>try translate</p>
<pre><code>>>> import string
>>> print '\t\r\n hello \r\n world \t\r\n'
hello
world
>>> tr = string.maketrans(string.whitespace, ' '*len(string.whitespace))
>>> '\t\r\n hello \r\n world \t\r\n'.translate(tr)
' hello world '
>>> '\t\r\n hello \r\n world \t\r\n'.translate(tr).replace(' ', '')
'helloworld'
</code></pre>
| 0 | 2015-04-15T03:43:54Z | [
"python",
"string",
"trim",
"strip"
] |
How to trim whitespace (including tabs)? | 1,185,524 | <p>Is there a function that will trim not only spaces for whitespace, but also tabs?</p>
| 623 | 2009-07-26T20:54:38Z | 30,929,218 | <pre><code> something = "\t please_ \t remove_ all_ \n\n\n\nwhitespaces\n\t "
something = "".join(something.split())
</code></pre>
<p>output:
please_remove_all_whitespaces</p>
| 1 | 2015-06-19T02:58:48Z | [
"python",
"string",
"trim",
"strip"
] |
How to trim whitespace (including tabs)? | 1,185,524 | <p>Is there a function that will trim not only spaces for whitespace, but also tabs?</p>
| 623 | 2009-07-26T20:54:38Z | 32,907,310 | <p>Generally, I am using the following method:</p>
<pre><code>>>> myStr = "Hi\n Stack Over \r flow!"
>>> charList = [u"\u005Cn",u"\u005Cr",u"\u005Ct"]
>>> import re
>>> for i in charList:
myStr = re.sub(i, r"", myStr)
>>> myStr
'Hi Stack Over flow'
</code></pre>
<p>Note: This is only for removing "\n", "\r" and "\t" only. It does not remove extra spaces.</p>
| 0 | 2015-10-02T12:35:41Z | [
"python",
"string",
"trim",
"strip"
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.