title
stringlengths
10
172
question_id
int64
469
40.1M
question_body
stringlengths
22
48.2k
question_score
int64
-44
5.52k
question_date
stringlengths
20
20
answer_id
int64
497
40.1M
answer_body
stringlengths
18
33.9k
answer_score
int64
-38
8.38k
answer_date
stringlengths
20
20
tags
list
Querying many to many fields in django
2,559,909
<p>In the models there is a many to many fields as,</p> <p>from emp.models import Name</p> <pre><code> def info(request): name = models.ManyToManyField(Name) </code></pre> <p>And in emp.models the schema is as</p> <pre><code> class Name(models.Model): name = models.CharField(max_length=512) def...
0
2010-04-01T11:09:32Z
2,559,955
<p><code>info.name</code> is <code>ManyToManyField</code> so if you want all <code>Name</code> objects associated with it you have to use <code>.all()</code> method on it. Only then you'll get list (queryset) of <code>Name</code> objects:</p> <pre><code>info_list = info.objects.filter(id=a) for info_object in info_lis...
3
2010-04-01T11:19:22Z
[ "python", "django", "django-models", "django-views" ]
Querying many to many fields in django
2,559,909
<p>In the models there is a many to many fields as,</p> <p>from emp.models import Name</p> <pre><code> def info(request): name = models.ManyToManyField(Name) </code></pre> <p>And in emp.models the schema is as</p> <pre><code> class Name(models.Model): name = models.CharField(max_length=512) def...
0
2010-04-01T11:09:32Z
2,562,214
<p>Lukasz is right, but just so you know, it doesn't make sense to filter on an id unless you use <code>info.object.filet(id__in=a)</code> and a is a list of some sort. If you filter on a single id, you should be using objects.get(**kwargs) first of all, and it will return that specific Info instance instead of a Query...
1
2010-04-01T17:12:08Z
[ "python", "django", "django-models", "django-views" ]
How to implement simple sessions for Google App Engine?
2,560,022
<p>Here is a very basic class for handling sessions on App Engine:</p> <pre><code>"""Lightweight implementation of cookie-based sessions for Google App Engine. Classes: Session """ import os import random import Cookie from google.appengine.api import memcache _COOKIE_NAME = 'app-sid' _COOKIE_PATH = '/' _SESSION_E...
7
2010-04-01T11:36:39Z
2,563,115
<p>Here is a suggestion for simplifying your implementation.</p> <p>You are creating a randomized temporary key that you use as the session's key in the memcache. You note that you will be storing the session in the datastore as well (where it will have another key).</p> <p>Why not randomize the session's datastore ...
5
2010-04-01T19:30:49Z
[ "python", "security", "google-app-engine", "session", "cookies" ]
How to implement simple sessions for Google App Engine?
2,560,022
<p>Here is a very basic class for handling sessions on App Engine:</p> <pre><code>"""Lightweight implementation of cookie-based sessions for Google App Engine. Classes: Session """ import os import random import Cookie from google.appengine.api import memcache _COOKIE_NAME = 'app-sid' _COOKIE_PATH = '/' _SESSION_E...
7
2010-04-01T11:36:39Z
2,563,290
<p>Here are a couple of additional security measures you could add.</p> <p>First, I think it is pretty common to use information stored in the session instance to validate each new request. For example, you could verify that the IP address and user-agent don't change during a session:</p> <pre><code>newip = str( req...
0
2010-04-01T20:02:27Z
[ "python", "security", "google-app-engine", "session", "cookies" ]
How should I use try...except while defining a function?
2,560,137
<p>I find I've been confused by the problem that when I needn't to use <code>try..except</code>.For last few days it was used in almost every function I defined which I think maybe a bad practice.For example:</p> <pre><code>class mongodb(object): def getRecords(self,tname,conditions=''): try: ...
4
2010-04-01T12:04:26Z
2,560,159
<p>This (catching all possible exceptions very broadly) is indeed considered bad practice. You'll mask the real reason for the exception.</p> <p>Catch only '<strong>explicitely named</strong>' types of exceptions (which you expect to happen <strong>and</strong> you can/will handle gracefully). Let the rest (unexpecte...
5
2010-04-01T12:08:41Z
[ "python", "exception", "function" ]
How should I use try...except while defining a function?
2,560,137
<p>I find I've been confused by the problem that when I needn't to use <code>try..except</code>.For last few days it was used in almost every function I defined which I think maybe a bad practice.For example:</p> <pre><code>class mongodb(object): def getRecords(self,tname,conditions=''): try: ...
4
2010-04-01T12:04:26Z
2,560,176
<p>That may not be the best thing to do. Whole point of exceptions is that you can catch them on very different level than it's raised. It's best to handle them in the place where you have enough information to make something useful with them (that is very application and context dependent).</p> <p>For example code be...
5
2010-04-01T12:12:42Z
[ "python", "exception", "function" ]
How should I use try...except while defining a function?
2,560,137
<p>I find I've been confused by the problem that when I needn't to use <code>try..except</code>.For last few days it was used in almost every function I defined which I think maybe a bad practice.For example:</p> <pre><code>class mongodb(object): def getRecords(self,tname,conditions=''): try: ...
4
2010-04-01T12:04:26Z
2,560,224
<p>You must find a balance between several goals:</p> <ol> <li><p>An application should recover from as many errors as possible by itself.</p></li> <li><p>An application should report all unrecoverable errors with enough detail to fix the cause of the problem.</p></li> <li><p>Errors can happen everywhere but you don't...
4
2010-04-01T12:21:14Z
[ "python", "exception", "function" ]
How should I use try...except while defining a function?
2,560,137
<p>I find I've been confused by the problem that when I needn't to use <code>try..except</code>.For last few days it was used in almost every function I defined which I think maybe a bad practice.For example:</p> <pre><code>class mongodb(object): def getRecords(self,tname,conditions=''): try: ...
4
2010-04-01T12:04:26Z
2,561,033
<p>another option is to wrap a large section of code in a try: except: (for instance in a web application, one specific GUI page) and then use sys.exc_info() to print out the error and also the stack where it occurred</p> <pre><code>import sys import traceback try: #some buggy code x = ?? except: print...
1
2010-04-01T14:22:35Z
[ "python", "exception", "function" ]
cannot append Model.objects.all()
2,560,178
<p>I cannot run <code>['abc'].append( MyModel.objects.all() )</code> since it generates exception <code>'NoneType' object is not iterable</code> if MyModel has no entry.</p> <p>any workaround or something like <code>? :</code> in c++</p> <p><strong>edit:</strong> my statement is actually </p> <pre><code>','.join([...
0
2010-04-01T12:13:05Z
2,560,412
<p>Shouldn't it be += instead of append?</p>
0
2010-04-01T12:51:31Z
[ "python", "django", "django-models", "django-queryset" ]
cannot append Model.objects.all()
2,560,178
<p>I cannot run <code>['abc'].append( MyModel.objects.all() )</code> since it generates exception <code>'NoneType' object is not iterable</code> if MyModel has no entry.</p> <p>any workaround or something like <code>? :</code> in c++</p> <p><strong>edit:</strong> my statement is actually </p> <pre><code>','.join([...
0
2010-04-01T12:13:05Z
2,560,712
<p>how about: </p> <pre><code>['abc'].append( MyModel.objects.all() or []) </code></pre>
2
2010-04-01T13:38:44Z
[ "python", "django", "django-models", "django-queryset" ]
cannot append Model.objects.all()
2,560,178
<p>I cannot run <code>['abc'].append( MyModel.objects.all() )</code> since it generates exception <code>'NoneType' object is not iterable</code> if MyModel has no entry.</p> <p>any workaround or something like <code>? :</code> in c++</p> <p><strong>edit:</strong> my statement is actually </p> <pre><code>','.join([...
0
2010-04-01T12:13:05Z
2,560,742
<p><code>Model.objects.all()</code> <a href="http://docs.djangoproject.com/en/dev/ref/models/querysets/#all" rel="nofollow">is a QuerySet</a> and that is iterable (see <a href="http://code.djangoproject.com/browser/django/tags/releases/1.1.1/django/db/models/query.py#L86" rel="nofollow">the source</a>). Passing an iter...
1
2010-04-01T13:42:04Z
[ "python", "django", "django-models", "django-queryset" ]
cannot append Model.objects.all()
2,560,178
<p>I cannot run <code>['abc'].append( MyModel.objects.all() )</code> since it generates exception <code>'NoneType' object is not iterable</code> if MyModel has no entry.</p> <p>any workaround or something like <code>? :</code> in c++</p> <p><strong>edit:</strong> my statement is actually </p> <pre><code>','.join([...
0
2010-04-01T12:13:05Z
2,560,791
<p>It might be best to be explicit rather than implicit (and avoid using the short circuit propoerties of <code>or</code> which can lead to errors:</p> <pre><code>my_objects = MyModel.objects.all() if my_objects: [a,b,c].extend(my_objects) </code></pre>
2
2010-04-01T13:50:13Z
[ "python", "django", "django-models", "django-queryset" ]
cannot append Model.objects.all()
2,560,178
<p>I cannot run <code>['abc'].append( MyModel.objects.all() )</code> since it generates exception <code>'NoneType' object is not iterable</code> if MyModel has no entry.</p> <p>any workaround or something like <code>? :</code> in c++</p> <p><strong>edit:</strong> my statement is actually </p> <pre><code>','.join([...
0
2010-04-01T12:13:05Z
2,563,213
<p>None is returned from the append method, which takes place in place. In other words, your statement is equivalent to </p> <pre><code>[str(e) for e in None] </code></pre> <p>which naturally raises a NoneType exception. The solution is have a separate statement for the append or extend method, then follow blokeley's...
1
2010-04-01T19:48:47Z
[ "python", "django", "django-models", "django-queryset" ]
Added tagging to existing model, now how does its admin work?
2,560,240
<p>I wanted to add a StackOverflow-style tag input to a blog model of mine. This is a model that has a lot of data already in it.</p> <pre><code>class BlogPost(models.Model): # my blog fields try: tagging.register(BlogPost) except tagging.AlreadyRegistered: pass </code></pre> <p>I thought that was all I ...
2
2010-04-01T12:24:00Z
2,561,636
<p>Did you try using TagField() in the model instead of registering the model?</p> <pre><code>from tagging.fields import TagField class BlogPost(models.Model): # ... tags = TagField() </code></pre>
2
2010-04-01T15:39:32Z
[ "python", "django", "django-admin", "django-tagging" ]
Added tagging to existing model, now how does its admin work?
2,560,240
<p>I wanted to add a StackOverflow-style tag input to a blog model of mine. This is a model that has a lot of data already in it.</p> <pre><code>class BlogPost(models.Model): # my blog fields try: tagging.register(BlogPost) except tagging.AlreadyRegistered: pass </code></pre> <p>I thought that was all I ...
2
2010-04-01T12:24:00Z
2,614,135
<p>Like istruble said (sorry I can't comment above): Did you try using TagField() in the model instead of registering the model?</p> <pre><code>from tagging.fields import TagField class BlogPost(models.Model): # ... tags = TagField() </code></pre> <p>But after that, you have to change your database table. I ...
0
2010-04-10T16:49:14Z
[ "python", "django", "django-admin", "django-tagging" ]
Python: re-initialize a function's default value for subsequent calls to the function
2,560,697
<p>I have a function that calls itself to increment and decrement a stack.</p> <p>I need to call it a number of times, and I'd like it to work the same way in subsequent calls</p> <p>but, as expected, it doesn't re-use the default value.</p> <p>I've read that this is a newbie trap and I've seen suggested solutions, ...
1
2010-04-01T13:36:24Z
2,560,707
<pre><code>def a(x, stack = None): if stack is None: stack = [None] ... </code></pre>
3
2010-04-01T13:37:53Z
[ "python", "function" ]
Python: re-initialize a function's default value for subsequent calls to the function
2,560,697
<p>I have a function that calls itself to increment and decrement a stack.</p> <p>I need to call it a number of times, and I'd like it to work the same way in subsequent calls</p> <p>but, as expected, it doesn't re-use the default value.</p> <p>I've read that this is a newbie trap and I've seen suggested solutions, ...
1
2010-04-01T13:36:24Z
2,560,729
<p>This problem happens because you modify the default argument, which is mutable. As in Kai's answer, one usually solves this by not modifying the default argument.</p>
0
2010-04-01T13:40:21Z
[ "python", "function" ]
Python: re-initialize a function's default value for subsequent calls to the function
2,560,697
<p>I have a function that calls itself to increment and decrement a stack.</p> <p>I need to call it a number of times, and I'd like it to work the same way in subsequent calls</p> <p>but, as expected, it doesn't re-use the default value.</p> <p>I've read that this is a newbie trap and I've seen suggested solutions, ...
1
2010-04-01T13:36:24Z
2,560,750
<p>Just pass stack explicitly when doing recursive call:</p> <pre><code>def a(x, stack=None): if stack is None: stack = [None] ... a(x + 1, stack) </code></pre>
4
2010-04-01T13:43:20Z
[ "python", "function" ]
Subprocess statement works in python console but not work in Serverdensity plugin?
2,560,754
<p>in the python console the following statement works perfectly fine (i guess using eval that way is not really good, but its just for testing purpose in this case and will be replaced with proper parsing)</p> <pre><code>$ python &gt;&gt;&gt; import subprocess &gt;&gt;&gt; r = subprocess.Popen(['/pathto/plugin1.rb'],...
2
2010-04-01T13:44:17Z
2,561,261
<p>Do you have subprocess imported in the module? Also what error are you getting could you post the error message ?</p>
0
2010-04-01T14:51:57Z
[ "python", "subprocess", "popen" ]
Subprocess statement works in python console but not work in Serverdensity plugin?
2,560,754
<p>in the python console the following statement works perfectly fine (i guess using eval that way is not really good, but its just for testing purpose in this case and will be replaced with proper parsing)</p> <pre><code>$ python &gt;&gt;&gt; import subprocess &gt;&gt;&gt; r = subprocess.Popen(['/pathto/plugin1.rb'],...
2
2010-04-01T13:44:17Z
2,568,719
<p>After switching my dev box (maybe because of the different python version?) i finally was able to get some proper error output.</p> <p>Then it was rather simple: I really just needed to import the missing subprocess module.</p> <p>For who is interested in the solution:</p> <p><a href="http://github.com/maxigs/Ser...
0
2010-04-02T19:24:49Z
[ "python", "subprocess", "popen" ]
Beginner having a problem with classes
2,560,997
<p>I'm working through O'Reilly's "Learning Python" and having a problem with classes. I think I understand the concept, but in practice have stumbled upon this problem. Fron page 88-89:</p> <pre><code>&gt;&gt;&gt; class Worker: def __innit__(self, name, pay): self.name=name self.pay=pay def lastName(self...
0
2010-04-01T14:17:16Z
2,561,015
<p>David, you've mis-typed <code>__init__</code></p> <p>The correct spelling is this:</p> <pre><code>def __init__(self, name, pay): self.name=name self.pay=pay def lastName(self): return self.name.split()[-1] def giveRaise(self, percent): self.pay*=(1.0+percent) </code></pre>
9
2010-04-01T14:19:10Z
[ "python", "class" ]
Beginner having a problem with classes
2,560,997
<p>I'm working through O'Reilly's "Learning Python" and having a problem with classes. I think I understand the concept, but in practice have stumbled upon this problem. Fron page 88-89:</p> <pre><code>&gt;&gt;&gt; class Worker: def __innit__(self, name, pay): self.name=name self.pay=pay def lastName(self...
0
2010-04-01T14:17:16Z
2,561,018
<p>You wrote <code>__innit__</code> instead of <code>__init__</code>.</p> <p>In this way, you declared just another method in the class, not the special method called the constructor, which is by definition named <code>__init__</code>. This causes Python to generate a default constructor taking no arguments, hence the...
2
2010-04-01T14:19:29Z
[ "python", "class" ]
Beginner having a problem with classes
2,560,997
<p>I'm working through O'Reilly's "Learning Python" and having a problem with classes. I think I understand the concept, but in practice have stumbled upon this problem. Fron page 88-89:</p> <pre><code>&gt;&gt;&gt; class Worker: def __innit__(self, name, pay): self.name=name self.pay=pay def lastName(self...
0
2010-04-01T14:17:16Z
2,561,024
<p>One misspelling: it's <code>__init__</code>, not <code>__innit__</code> -- just one <code>n</code>.</p> <p>You also have some indentation problems but I think those may be due to just copy-and-paste issues, or else you'd be getting <code>SyntaxError</code>s before the <code>TypeError</code> you relate;-).</p> <p>S...
5
2010-04-01T14:20:03Z
[ "python", "class" ]
Python equivalent of mysql_real_escape_string, for getting strings safely into MySQL?
2,561,178
<p>Is there a Python equivalent of PHP's <code>mysql_real_escape_string</code>?</p> <p>I'm trying to insert some strings into a MySQL db direct from Python, and keep getting tripped up by quotes in the strings. </p> <pre><code>mysql_string = "INSERT INTO candidate (name, address) VALUES " for k, v in v_dict.iterite...
12
2010-04-01T14:41:10Z
2,561,250
<p>In this particular case you just need to use executemany method of the cursor.</p> <pre><code>mysql_string = "INSERT INTO candidate (name, address) VALUES (%s,%s);" cursor.executemany(mysql_string, v_dict.iteritems()) </code></pre>
2
2010-04-01T14:51:10Z
[ "python", "mysql" ]
Python equivalent of mysql_real_escape_string, for getting strings safely into MySQL?
2,561,178
<p>Is there a Python equivalent of PHP's <code>mysql_real_escape_string</code>?</p> <p>I'm trying to insert some strings into a MySQL db direct from Python, and keep getting tripped up by quotes in the strings. </p> <pre><code>mysql_string = "INSERT INTO candidate (name, address) VALUES " for k, v in v_dict.iterite...
12
2010-04-01T14:41:10Z
2,561,254
<p>If you are using mysql-python, just try</p> <pre><code>MySQLdb.escape_string(SQL) </code></pre> <p>Example</p> <pre><code>&gt;&gt;&gt; import MySQLdb &gt;&gt;&gt; MySQLdb.escape_string("'") "\\'" </code></pre>
35
2010-04-01T14:51:29Z
[ "python", "mysql" ]
Python equivalent of mysql_real_escape_string, for getting strings safely into MySQL?
2,561,178
<p>Is there a Python equivalent of PHP's <code>mysql_real_escape_string</code>?</p> <p>I'm trying to insert some strings into a MySQL db direct from Python, and keep getting tripped up by quotes in the strings. </p> <pre><code>mysql_string = "INSERT INTO candidate (name, address) VALUES " for k, v in v_dict.iterite...
12
2010-04-01T14:41:10Z
2,561,260
<p><code>MySQLdb.escape_string</code> is equivalent. All of that is described in <a href="http://mysql-python.sourceforge.net/MySQLdb.html#id5" rel="nofollow">documentation</a>.</p>
2
2010-04-01T14:51:53Z
[ "python", "mysql" ]
Python equivalent of mysql_real_escape_string, for getting strings safely into MySQL?
2,561,178
<p>Is there a Python equivalent of PHP's <code>mysql_real_escape_string</code>?</p> <p>I'm trying to insert some strings into a MySQL db direct from Python, and keep getting tripped up by quotes in the strings. </p> <pre><code>mysql_string = "INSERT INTO candidate (name, address) VALUES " for k, v in v_dict.iterite...
12
2010-04-01T14:41:10Z
2,561,275
<pre><code>cursor.executemany('INSERT INTO candidate (name, address) VALUES (%s, %s)', [(v_dict['name'], v_dict['address'])] * len(v_dict)) </code></pre> <p>should do what your code appears to attempt -- inserting the <strong>same</strong> identical values N times (you're looping on <code>v_dict.ite...
10
2010-04-01T14:53:05Z
[ "python", "mysql" ]
Python equivalent of mysql_real_escape_string, for getting strings safely into MySQL?
2,561,178
<p>Is there a Python equivalent of PHP's <code>mysql_real_escape_string</code>?</p> <p>I'm trying to insert some strings into a MySQL db direct from Python, and keep getting tripped up by quotes in the strings. </p> <pre><code>mysql_string = "INSERT INTO candidate (name, address) VALUES " for k, v in v_dict.iterite...
12
2010-04-01T14:41:10Z
2,561,805
<blockquote> <p>Is there a Python equivalent of PHP's mysql_real_escape_string?</p> </blockquote> <p>Yes, it's <code>escape_string</code> on the database <strong>connection</strong> object.</p> <p><strong>Not</strong> <code>escape_string</code> on the <code>MySQLdb</code> module, which is equivalent to <code>mysql_...
6
2010-04-01T16:05:57Z
[ "python", "mysql" ]
Should I mix wxpython and pyobjc?
2,561,188
<p>I have a wxPython based app which I am porting to Mac OS X, in that I need to show some alerts which should look like native mac alerts, so I am using pyobjc for that e.g.</p> <pre><code>import Cocoa import wx app = wx.PySimpleApp() frame = wx.Frame(None, title="mac alert test") app.SetTopWindow(frame) frame.Show...
0
2010-04-01T14:42:53Z
2,561,782
<p>One possible question to ask; I believe you must be using wx version for Mac that rests atop Carbon, because I think the Cocoa version hasn't been released yet. Once the cocoa version is released (for wx) then I would think there would have to be "fewer" issues. A mix of carbon and cocoa sounds problematic to me, ...
0
2010-04-01T16:02:06Z
[ "python", "objective-c", "wxpython", "wxwidgets", "pyobjc" ]
Should I mix wxpython and pyobjc?
2,561,188
<p>I have a wxPython based app which I am porting to Mac OS X, in that I need to show some alerts which should look like native mac alerts, so I am using pyobjc for that e.g.</p> <pre><code>import Cocoa import wx app = wx.PySimpleApp() frame = wx.Frame(None, title="mac alert test") app.SetTopWindow(frame) frame.Show...
0
2010-04-01T14:42:53Z
2,562,076
<p>Any reason you don't just write a custom WX dialog, that inherits from wx.Dialog? <a href="http://svn.wxwidgets.org/svn/wx/wxPython/trunk/demo/Dialog.py" rel="nofollow">The WX demo has a very nice example of that</a>. A little more work, but a cleaner approach.</p>
0
2010-04-01T16:47:36Z
[ "python", "objective-c", "wxpython", "wxwidgets", "pyobjc" ]
Should I mix wxpython and pyobjc?
2,561,188
<p>I have a wxPython based app which I am porting to Mac OS X, in that I need to show some alerts which should look like native mac alerts, so I am using pyobjc for that e.g.</p> <pre><code>import Cocoa import wx app = wx.PySimpleApp() frame = wx.Frame(None, title="mac alert test") app.SetTopWindow(frame) frame.Show...
0
2010-04-01T14:42:53Z
2,570,042
<p>I don't think that will work too well, mixing the event loops...</p> <p>[EDIT: I thought this initially, because the dialog is model and the window behind it is not, and there might be two event loops fighting for control. (Because each window has its own, which is why you can have Carbon and Cocoa windows in (an a...
0
2010-04-03T02:39:28Z
[ "python", "objective-c", "wxpython", "wxwidgets", "pyobjc" ]
Learning Python coming from PHP
2,561,362
<p>My dynamic language experience is solely PHP. I want to learn Python now to broaden my career opportunities and just because I like programming. :)</p> <p>When learning Java, I used a site (lost the URL/real name now), something like "Java for PHP developers" that had all on one side of the page the PHP code, and o...
21
2010-04-01T15:05:31Z
2,561,390
<p>I'm not sure such a thing exists but Python is generally an easy language to learn. Python documentation is generally very clear and easy to follow. From the Python interpreter you can also use the dir() and help() methods to view methods, attributes and documentation which makes it easy to explore what options ar...
5
2010-04-01T15:09:15Z
[ "php", "python" ]
Learning Python coming from PHP
2,561,362
<p>My dynamic language experience is solely PHP. I want to learn Python now to broaden my career opportunities and just because I like programming. :)</p> <p>When learning Java, I used a site (lost the URL/real name now), something like "Java for PHP developers" that had all on one side of the page the PHP code, and o...
21
2010-04-01T15:05:31Z
2,562,788
<p>The OP's question is simple enough, but as @Pekka mentioned (or hijacked), this could be a much deeper question (requiring a more substantial answer). Yes, Python's syntax is easy enough to learn without a book, but like any other language, it still takes quite a bit of time to master.</p> <p>The suggest of Dive In...
14
2010-04-01T18:44:56Z
[ "php", "python" ]
Learning Python coming from PHP
2,561,362
<p>My dynamic language experience is solely PHP. I want to learn Python now to broaden my career opportunities and just because I like programming. :)</p> <p>When learning Java, I used a site (lost the URL/real name now), something like "Java for PHP developers" that had all on one side of the page the PHP code, and o...
21
2010-04-01T15:05:31Z
16,762,468
<p>This basic intro with PHP references is a place to start <br /></p> <p><a href="http://www.ibm.com/developerworks/opensource/library/os-php-pythonbasics/">IBM Developer Works:Python Basics for PHP Programmers</a></p>
5
2013-05-26T18:41:08Z
[ "php", "python" ]
How to comment out a block of Python code in Vim
2,561,418
<p>I was wondering if there was any key mapping in Vim to allow me to indent certain lines of code (whether those lines have been selected in visual mode, or <em>n</em> lines above/below current cursor position).</p> <p>So basically something that converts the following </p> <pre><code>def my_fun(x, y): return x ...
155
2010-04-01T15:14:46Z
2,561,449
<p>one way manually </p> <pre><code>:set number :10,12s/^/# </code></pre>
49
2010-04-01T15:18:10Z
[ "python", "vim", "editor" ]
How to comment out a block of Python code in Vim
2,561,418
<p>I was wondering if there was any key mapping in Vim to allow me to indent certain lines of code (whether those lines have been selected in visual mode, or <em>n</em> lines above/below current cursor position).</p> <p>So basically something that converts the following </p> <pre><code>def my_fun(x, y): return x ...
155
2010-04-01T15:14:46Z
2,561,497
<p><strong>Step 1:</strong> Go to the the first column of the first line you want to comment.</p> <p><img src="http://theosp.github.io/stackoverflow/vim-comment-python/1.png" alt="Initial State"></p> <p><strong>Step 2:</strong> Press: <kbd>Ctrl</kbd>+<kbd>v</kbd> and select the lines you want to comment:</p> <p><img...
323
2010-04-01T15:24:14Z
[ "python", "vim", "editor" ]
How to comment out a block of Python code in Vim
2,561,418
<p>I was wondering if there was any key mapping in Vim to allow me to indent certain lines of code (whether those lines have been selected in visual mode, or <em>n</em> lines above/below current cursor position).</p> <p>So basically something that converts the following </p> <pre><code>def my_fun(x, y): return x ...
155
2010-04-01T15:14:46Z
2,561,523
<p>There are some good plugins to help comment/uncomment lines. For example <a href="http://www.vim.org/scripts/script.php?script_id=1218">The NERD Commenter</a>.</p>
19
2010-04-01T15:26:01Z
[ "python", "vim", "editor" ]
How to comment out a block of Python code in Vim
2,561,418
<p>I was wondering if there was any key mapping in Vim to allow me to indent certain lines of code (whether those lines have been selected in visual mode, or <em>n</em> lines above/below current cursor position).</p> <p>So basically something that converts the following </p> <pre><code>def my_fun(x, y): return x ...
155
2010-04-01T15:14:46Z
2,565,136
<p>I usually sweep out a visual block (<code>&lt;C-V&gt;</code>), then search and replace the first character with:</p> <pre><code>:'&lt;,'&gt;s/^/# </code></pre> <p>(Entering command mode with a visual block selected automatically places '&lt;,'> on the command line) I can then uncomment the block by sweeping out th...
19
2010-04-02T05:30:15Z
[ "python", "vim", "editor" ]
How to comment out a block of Python code in Vim
2,561,418
<p>I was wondering if there was any key mapping in Vim to allow me to indent certain lines of code (whether those lines have been selected in visual mode, or <em>n</em> lines above/below current cursor position).</p> <p>So basically something that converts the following </p> <pre><code>def my_fun(x, y): return x ...
155
2010-04-01T15:14:46Z
2,567,010
<p>I have the following lines in my <code>.vimrc</code>:</p> <pre><code>" comment line, selection with Ctrl-N,Ctrl-N au BufEnter *.py nnoremap &lt;C-N&gt;&lt;C-N&gt; mn:s/^\(\s*\)#*\(.*\)/\1#\2/ge&lt;CR&gt;:noh&lt;CR&gt;`n au BufEnter *.py inoremap &lt;C-N&gt;&lt;C-N&gt; &lt;C-O&gt;mn&lt;C-O&gt;:s/^\(\s*\)#*\(...
7
2010-04-02T14:02:15Z
[ "python", "vim", "editor" ]
How to comment out a block of Python code in Vim
2,561,418
<p>I was wondering if there was any key mapping in Vim to allow me to indent certain lines of code (whether those lines have been selected in visual mode, or <em>n</em> lines above/below current cursor position).</p> <p>So basically something that converts the following </p> <pre><code>def my_fun(x, y): return x ...
155
2010-04-01T15:14:46Z
14,692,524
<p>You could add the following mapping to your .vimrc</p> <pre><code>vnoremap &lt;silent&gt; # :s/^/#/&lt;cr&gt;:noh&lt;cr&gt; vnoremap &lt;silent&gt; -# :s/^#//&lt;cr&gt;:noh&lt;cr&gt; </code></pre> <p>Highlight your block with:</p> <pre><code>Shift+v </code></pre> <p><code>#</code> to comment your lines from the ...
26
2013-02-04T17:53:46Z
[ "python", "vim", "editor" ]
How to comment out a block of Python code in Vim
2,561,418
<p>I was wondering if there was any key mapping in Vim to allow me to indent certain lines of code (whether those lines have been selected in visual mode, or <em>n</em> lines above/below current cursor position).</p> <p>So basically something that converts the following </p> <pre><code>def my_fun(x, y): return x ...
155
2010-04-01T15:14:46Z
15,155,176
<p>Frankly I use a tcomment plugin for that <a href="http://www.vim.org/scripts/script.php?script_id=1173">link</a>. It can handle almost every syntax. It defines nice movements, using it with some text block matchers specific for python makes it a powerful tool. </p>
5
2013-03-01T10:12:23Z
[ "python", "vim", "editor" ]
How to comment out a block of Python code in Vim
2,561,418
<p>I was wondering if there was any key mapping in Vim to allow me to indent certain lines of code (whether those lines have been selected in visual mode, or <em>n</em> lines above/below current cursor position).</p> <p>So basically something that converts the following </p> <pre><code>def my_fun(x, y): return x ...
155
2010-04-01T15:14:46Z
16,863,673
<p>Highlight your block with: <code>Shift+v</code></p> <p>Comment the selected block out with: <code>:norm i#</code> (lower case i)</p> <p>To uncomment, highlight your block again, and uncomment with: <code>:norm ^x</code></p> <p>The <code>:norm</code> command performs an action for every selected line. Commenting w...
14
2013-05-31T18:34:52Z
[ "python", "vim", "editor" ]
How to comment out a block of Python code in Vim
2,561,418
<p>I was wondering if there was any key mapping in Vim to allow me to indent certain lines of code (whether those lines have been selected in visual mode, or <em>n</em> lines above/below current cursor position).</p> <p>So basically something that converts the following </p> <pre><code>def my_fun(x, y): return x ...
155
2010-04-01T15:14:46Z
20,455,797
<p><a href="https://github.com/scrooloose/nerdcommenter" rel="nofollow">NERDcommenter</a> is an excellent plugin for commenting which automatically detects a number of filetypes and their associated comment characters. Ridiculously easy to install using <a href="https://github.com/tpope/vim-pathogen" rel="nofollow">Pat...
4
2013-12-08T16:32:02Z
[ "python", "vim", "editor" ]
How to comment out a block of Python code in Vim
2,561,418
<p>I was wondering if there was any key mapping in Vim to allow me to indent certain lines of code (whether those lines have been selected in visual mode, or <em>n</em> lines above/below current cursor position).</p> <p>So basically something that converts the following </p> <pre><code>def my_fun(x, y): return x ...
155
2010-04-01T15:14:46Z
27,249,959
<p>There's a lot of comment plugins for vim - a number of which are multi-language - not just python. If you use a plugin manager like <a href="https://github.com/gmarik/Vundle.vim/" rel="nofollow">Vundle</a> then you can search for them (once you've installed Vundle) using e.g.:</p> <pre><code>:PluginSearch comment <...
1
2014-12-02T12:52:08Z
[ "python", "vim", "editor" ]
How to comment out a block of Python code in Vim
2,561,418
<p>I was wondering if there was any key mapping in Vim to allow me to indent certain lines of code (whether those lines have been selected in visual mode, or <em>n</em> lines above/below current cursor position).</p> <p>So basically something that converts the following </p> <pre><code>def my_fun(x, y): return x ...
155
2010-04-01T15:14:46Z
36,128,330
<p><strong>Ctrl + k for comment (Visual Mode):</strong> </p> <pre><code>vnoremap &lt;silent&gt; &lt;C-k&gt; :s#^#\##&lt;cr&gt;:noh&lt;cr&gt; </code></pre> <p><strong>Ctrl + u for uncomment (Visual Mode):</strong> </p> <pre><code>vnoremap &lt;silent&gt; &lt;C-u&gt; :s#^\###&lt;cr&gt;:noh&lt;cr&gt; </code></pre>
1
2016-03-21T10:19:43Z
[ "python", "vim", "editor" ]
Problem with python class
2,561,469
<p>Hi I am new to Python and as a part of my assignment I have written the following class </p> <pre><code>import nltk.stem.api class BanglaStemmer(nltk.stem.api.StemmerI): suffixList = ['\xef\xbb\xbf\xe0\xa6\xbf\xe0\xa7\x9f\xe0\xa7\x87\xe0\xa6\x9b\xe0\xa6\xbf\xe0\xa6\xb2\xe0\xa6\xbe\xe0\xa6\xae\n', '\xe0\xa6\xb...
0
2010-04-01T15:20:21Z
2,561,482
<p>You can use <code>BanglaStemmer.suffixList</code> or <code>self.suffixList</code> to access the variable. Plain <code>suffixList</code> would only work on a local (defined in the function) or a global (defined in the module) variable.</p>
2
2010-04-01T15:21:50Z
[ "python" ]
Problem with python class
2,561,469
<p>Hi I am new to Python and as a part of my assignment I have written the following class </p> <pre><code>import nltk.stem.api class BanglaStemmer(nltk.stem.api.StemmerI): suffixList = ['\xef\xbb\xbf\xe0\xa6\xbf\xe0\xa7\x9f\xe0\xa7\x87\xe0\xa6\x9b\xe0\xa6\xbf\xe0\xa6\xb2\xe0\xa6\xbe\xe0\xa6\xae\n', '\xe0\xa6\xb...
0
2010-04-01T15:20:21Z
2,561,490
<pre><code>for suffix in suffixList: </code></pre> <p>should be</p> <pre><code>for suffix in self.suffixList: </code></pre> <p>Unlike a lot of OOP languages, Python requires you to qualify class members inside the class methods.</p>
6
2010-04-01T15:23:22Z
[ "python" ]
Problem with python class
2,561,469
<p>Hi I am new to Python and as a part of my assignment I have written the following class </p> <pre><code>import nltk.stem.api class BanglaStemmer(nltk.stem.api.StemmerI): suffixList = ['\xef\xbb\xbf\xe0\xa6\xbf\xe0\xa7\x9f\xe0\xa7\x87\xe0\xa6\x9b\xe0\xa6\xbf\xe0\xa6\xb2\xe0\xa6\xbe\xe0\xa6\xae\n', '\xe0\xa6\xb...
0
2010-04-01T15:20:21Z
2,561,519
<p>In Python, unlike most other languages, you always have to explicitely reference the instance of which you want to access a member (or "attribute" in Python). This instance is always passed as the first parameter to your methods; this is the reason why this first parameter is called <code>self</code> by convention.<...
0
2010-04-01T15:25:56Z
[ "python" ]
fabric and svn password
2,561,472
<p>Assuming that I cannot run something like this with Fabric:</p> <p><code>run("svn update --password 'password' .")</code> </p> <p>how's the proper way to pass to Fabric the password for the remote interactive command line?</p> <p>The problem is that the repo is checked out as svn+ssh and I don't have a http/https...
7
2010-04-01T15:20:36Z
2,561,630
<p>You might need to supply the user as well? If not, you may have better luck exporting your repo and making a tar of it (locally) to upload+deploy on the server. If you run the svn commands locally, you'll be able to get prompted for your username and/or password.</p>
0
2010-04-01T15:39:12Z
[ "python", "svn", "fabric" ]
fabric and svn password
2,561,472
<p>Assuming that I cannot run something like this with Fabric:</p> <p><code>run("svn update --password 'password' .")</code> </p> <p>how's the proper way to pass to Fabric the password for the remote interactive command line?</p> <p>The problem is that the repo is checked out as svn+ssh and I don't have a http/https...
7
2010-04-01T15:20:36Z
2,583,856
<p>We had a problem similar to this a while back and actually proposed a new feature for Fabric, but the developer we spoke to suggested this instead.</p> <pre><code>import getpass password = getpass.getpass('Enter SVN Password: ') run("svn update --password '%s'" % password) </code></pre> <p>This will prompt you for...
2
2010-04-06T09:41:44Z
[ "python", "svn", "fabric" ]
fabric and svn password
2,561,472
<p>Assuming that I cannot run something like this with Fabric:</p> <p><code>run("svn update --password 'password' .")</code> </p> <p>how's the proper way to pass to Fabric the password for the remote interactive command line?</p> <p>The problem is that the repo is checked out as svn+ssh and I don't have a http/https...
7
2010-04-01T15:20:36Z
2,588,682
<p>My standard answer for automating interactive command lines is "use Expect", but you're using Python, so I will slightly refine that to "use <a href="http://pexpect.sourceforge.net/pexpect.html" rel="nofollow">Pexpect</a>". </p> <p>It might take a bit of thought to integrate Pexpect within Fabric, or perhaps you w...
2
2010-04-06T22:04:36Z
[ "python", "svn", "fabric" ]
fabric and svn password
2,561,472
<p>Assuming that I cannot run something like this with Fabric:</p> <p><code>run("svn update --password 'password' .")</code> </p> <p>how's the proper way to pass to Fabric the password for the remote interactive command line?</p> <p>The problem is that the repo is checked out as svn+ssh and I don't have a http/https...
7
2010-04-01T15:20:36Z
2,593,618
<p>Try SSHkey. It allows you to connect to the server without password. In this case, you will have to setup a sshkey between your remote server and the repo.</p> <p>At remote server: Generate key pair</p> <pre><code> $ ssh-keygen -t dsa </code></pre> <p>Leave the passphase empty! This will generate 2 files </p> <...
7
2010-04-07T15:13:26Z
[ "python", "svn", "fabric" ]
fabric and svn password
2,561,472
<p>Assuming that I cannot run something like this with Fabric:</p> <p><code>run("svn update --password 'password' .")</code> </p> <p>how's the proper way to pass to Fabric the password for the remote interactive command line?</p> <p>The problem is that the repo is checked out as svn+ssh and I don't have a http/https...
7
2010-04-01T15:20:36Z
2,601,145
<p>You should take a look at the <a href="http://docs.fabfile.org/0.9.0/usage/env.html" rel="nofollow">Fabric's env documentation</a>. There states that you should make something like this:</p> <pre><code>from fabric.api import env env.user = 'your_user' env.password = 'your_password' </code></pre> <p>Hope it helps!...
0
2010-04-08T15:23:26Z
[ "python", "svn", "fabric" ]
fabric and svn password
2,561,472
<p>Assuming that I cannot run something like this with Fabric:</p> <p><code>run("svn update --password 'password' .")</code> </p> <p>how's the proper way to pass to Fabric the password for the remote interactive command line?</p> <p>The problem is that the repo is checked out as svn+ssh and I don't have a http/https...
7
2010-04-01T15:20:36Z
4,808,605
<p>If yout just want to hide your password from log, you can use something like this:</p> <pre><code>from fabric.state import output def xrun(command, hidden='', *args, **kwargs): old_state = output.running output.running = False print '[%s] run: %s' % (env.host_string, command) run(command + hidden, ...
3
2011-01-26T18:47:43Z
[ "python", "svn", "fabric" ]
Configuring Eclipse with wxPython
2,561,542
<p>I've been browsing documentation, but haven't been able to find a straightforward tutorial, so I apologize if this is a really simple question.</p> <p>Anyway, I have eclipse with pydev installed on MAC OSX, and I want configure wxPython to work with eclipse, how do I do this? Once I've downloaded wxpython, what ste...
2
2010-04-01T15:28:36Z
2,562,061
<p>You don't need to do anything special. I'm on Ubuntu rather than Mac, and I've installed wxPython, so that</p> <pre><code>python -c "import wx" </code></pre> <p>works at a shell prompt. Then, just fire up Eclipse and create a PyDev project, do <code>import wx</code> in your code and start using the wxPython API. Y...
4
2010-04-01T16:45:41Z
[ "python", "eclipse", "wxpython" ]
Configuring Eclipse with wxPython
2,561,542
<p>I've been browsing documentation, but haven't been able to find a straightforward tutorial, so I apologize if this is a really simple question.</p> <p>Anyway, I have eclipse with pydev installed on MAC OSX, and I want configure wxPython to work with eclipse, how do I do this? Once I've downloaded wxpython, what ste...
2
2010-04-01T15:28:36Z
2,562,141
<p>Vinay's answer above is correct. However, if code completion is not picking it up, you might need to add the WX directory to the Pydev's interpreter library path.</p> <blockquote> <p>Window | Preferences | Pydev | Interpreter - Python | Libraries</p> </blockquote> <p>If wx is not present, New Folder and selec...
7
2010-04-01T16:59:04Z
[ "python", "eclipse", "wxpython" ]
Configuring Eclipse with wxPython
2,561,542
<p>I've been browsing documentation, but haven't been able to find a straightforward tutorial, so I apologize if this is a really simple question.</p> <p>Anyway, I have eclipse with pydev installed on MAC OSX, and I want configure wxPython to work with eclipse, how do I do this? Once I've downloaded wxpython, what ste...
2
2010-04-01T15:28:36Z
12,983,874
<p>wxPython install by default to the following path /usr/local/lib/wxPython-2.9.4.0</p> <p>When adding a path to the Interpreter libraries section in the eclipse preferences add this path: /usr/local/lib/wxPython-2.9.4.0/lib/python2.7/site-packages/wx-2.9.4-osx_cocoa</p>
3
2012-10-19T23:43:52Z
[ "python", "eclipse", "wxpython" ]
Cassandra database, which python interface?
2,561,804
<p>I'm going to write the web portal using Cassandra databases. Can you advise me which python interface to use? <strong>thrift, lazygal or pycassa</strong>? Are there any benefits to use more complicated thrift then cleaner pycassa? What about performace - is the same (all of them are just the layer)?</p> <p>Thanks f...
5
2010-04-01T16:05:47Z
2,567,396
<p>Use pycassa if you don't know what to use.</p> <p>Use lazyboy if you want it to maintain indexes for you. It's significantly more complex.</p>
4
2010-04-02T15:13:24Z
[ "python", "database", "cassandra", "thrift" ]
Python - Execute Process -> Block till it exits & Supress Output
2,561,902
<p>I'm using the following to execute a process and hide its output from Python. It's in a loop though, and I need a way to block until the sub process has terminated before moving to the next iteration.</p> <pre><code>subprocess.Popen(["scanx", "--udp", host], stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=sub...
9
2010-04-01T16:20:25Z
2,561,918
<p>Use <a href="http://docs.python.org/library/subprocess.html#subprocess.call"><code>subprocess.call()</code></a>. From the docs:</p> <blockquote> <p>subprocess.call(*popenargs, **kwargs)<br> Run command with arguments. Wait for command to complete, then return the returncode attribute. The arguments are the ...
7
2010-04-01T16:24:07Z
[ "python", "subprocess" ]
Python - Execute Process -> Block till it exits & Supress Output
2,561,902
<p>I'm using the following to execute a process and hide its output from Python. It's in a loop though, and I need a way to block until the sub process has terminated before moving to the next iteration.</p> <pre><code>subprocess.Popen(["scanx", "--udp", host], stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=sub...
9
2010-04-01T16:20:25Z
2,562,292
<p>If you don't need output at all you can pass devnull to <code>stdout</code> and <code>stderr</code>. I don't know if this can make a difference but pass a bufsize. Using devnull now <code>subprocess.call</code> doesn't suffer of deadlock anymore</p> <pre><code>import os import subprocess null = open(os.devnull, 'w...
6
2010-04-01T17:26:20Z
[ "python", "subprocess" ]
What should I use - Mako or Django?
2,562,167
<p>I'm making a website that mail users when a movie or a pc game has released. It isn't too complex - users can sign up, choose movies/music or a genre and save the settings. When the movie/music is released - it mails the user. Some other functionality too but this is the jist.</p> <p>Now, I've been working with Pyt...
4
2010-04-01T17:03:22Z
2,562,185
<p>Django. Because it takes care for all bits and pieces (url mapping, request object handling etc) and hides the DB access from you as well. If you want you can use SQLite DB so no need for MysQL or other "proper" DBs. If you were using just template engine you'd have to take care of HTTP layer yourself. And the DB st...
2
2010-04-01T17:06:08Z
[ "python", "django", "template-engine", "mako" ]
What should I use - Mako or Django?
2,562,167
<p>I'm making a website that mail users when a movie or a pc game has released. It isn't too complex - users can sign up, choose movies/music or a genre and save the settings. When the movie/music is released - it mails the user. Some other functionality too but this is the jist.</p> <p>Now, I've been working with Pyt...
4
2010-04-01T17:03:22Z
2,562,356
<p>Ask yourself this question: What are you getting out of this project? What do you want to learn?</p> <p>If you want to know the nuts and bolts of a web server the hard way: concoct your own web framework using Mako and other useful building blocks as needed. As @pulegium says, you'll have to choose how to handle th...
4
2010-04-01T17:38:22Z
[ "python", "django", "template-engine", "mako" ]
What should I use - Mako or Django?
2,562,167
<p>I'm making a website that mail users when a movie or a pc game has released. It isn't too complex - users can sign up, choose movies/music or a genre and save the settings. When the movie/music is released - it mails the user. Some other functionality too but this is the jist.</p> <p>Now, I've been working with Pyt...
4
2010-04-01T17:03:22Z
5,249,036
<p>I have used mako for some time and have also tried to get to grips with django in google appengine. </p> <p><strong>If you are a python whizz... definitely opt for Mako</strong>. I'm finding django frustrating as the syntax doesn't allow me to do really nice pythonic code. I'm going to drop Mako into my appengine p...
0
2011-03-09T16:41:03Z
[ "python", "django", "template-engine", "mako" ]
Integer to byte conversion
2,562,308
<p>Say I've got an integer, 13941412, that I wish to separate into bytes (the number is actually a color in the form 0x00bbggrr). How would you do that? In c, you'd cast the number to a BYTE and then shift the bits. How do you cast to byte in Python?</p>
2
2010-04-01T17:29:22Z
2,562,328
<p>You can bitwise <code>&amp;</code> with 0xff to get the first byte, then shift 8 bits and repeat to get the other 3 bytes.</p> <p>Edit: For colors, you know you need the least significant three bytes. So, you can use a nicer approach:</p> <pre><code>r = num &amp; 0x0000ff g = (num &amp; 0x00ff00) &gt;&gt; 8 b = (...
2
2010-04-01T17:33:45Z
[ "python", "byte", "casting" ]
Integer to byte conversion
2,562,308
<p>Say I've got an integer, 13941412, that I wish to separate into bytes (the number is actually a color in the form 0x00bbggrr). How would you do that? In c, you'd cast the number to a BYTE and then shift the bits. How do you cast to byte in Python?</p>
2
2010-04-01T17:29:22Z
2,562,340
<p>Use bitwise mathematical operators, the "bytes" are already there:</p> <pre><code>def int_to_rgb(n): b = (n &amp; 0xff0000) &gt;&gt; 16 g = (n &amp; 0x00ff00) &gt;&gt; 8 r = (n &amp; 0x0000ff) return (r, g, b) </code></pre>
12
2010-04-01T17:35:40Z
[ "python", "byte", "casting" ]
Integer to byte conversion
2,562,308
<p>Say I've got an integer, 13941412, that I wish to separate into bytes (the number is actually a color in the form 0x00bbggrr). How would you do that? In c, you'd cast the number to a BYTE and then shift the bits. How do you cast to byte in Python?</p>
2
2010-04-01T17:29:22Z
2,564,105
<p>Here's an optimisation suggestion that applies in any language, and doesn't harm legibility.</p> <p>Instead of this:</p> <pre><code>b = (n &amp; 0xff0000) &gt;&gt; 16 g = (n &amp; 0xff00) &gt;&gt; 8 r = (n &amp; 0xff) </code></pre> <p>use this:</p> <pre><code>b = (n &gt;&gt; 16) &amp; 0xff g = (n &gt;&gt; ...
0
2010-04-01T22:35:31Z
[ "python", "byte", "casting" ]
python: send a list/dict over network
2,562,359
<p>I'm looking for an easy way of packing/unpacking data structures for sending over the network:</p> <p>on client just before sending:</p> <pre><code>a = ((1,2),(11,22,),(111,222)) message = pack(a) </code></pre> <p>and then on server:</p> <pre><code>a = unpack(message) </code></pre> <p>Is there a library that co...
4
2010-04-01T17:39:00Z
2,562,371
<p>Looks like <a href="http://www.json.org/">JSON</a> might fit the bill. It's simple, and <a href="http://docs.python.org/library/json.html">it's in the Python standard library</a>.</p> <p>It might not be too happy about the tuples, though:</p> <pre><code>&gt;&gt;&gt; import json &gt;&gt;&gt; a = ((1,2),(11,22,),(11...
11
2010-04-01T17:40:17Z
[ "python", "serialization" ]
python: send a list/dict over network
2,562,359
<p>I'm looking for an easy way of packing/unpacking data structures for sending over the network:</p> <p>on client just before sending:</p> <pre><code>a = ((1,2),(11,22,),(111,222)) message = pack(a) </code></pre> <p>and then on server:</p> <pre><code>a = unpack(message) </code></pre> <p>Is there a library that co...
4
2010-04-01T17:39:00Z
2,562,382
<p>See <a href="http://docs.python.org/library/pickle.html" rel="nofollow">pickle</a> - Python object serialization:</p> <blockquote> <p>The <code>pickle</code> module implements a fundamental, but powerful algorithm for serializing and de-serializing a Python object structure. “Pickling” is the process whereby ...
2
2010-04-01T17:42:23Z
[ "python", "serialization" ]
python: send a list/dict over network
2,562,359
<p>I'm looking for an easy way of packing/unpacking data structures for sending over the network:</p> <p>on client just before sending:</p> <pre><code>a = ((1,2),(11,22,),(111,222)) message = pack(a) </code></pre> <p>and then on server:</p> <pre><code>a = unpack(message) </code></pre> <p>Is there a library that co...
4
2010-04-01T17:39:00Z
2,830,511
<p>In your example, I'm not sure why you even need JSON:</p> <pre><code>&gt;&gt;&gt; a = ((1,2),(11,22,),(111,222)) &gt;&gt;&gt; print str(a) ((1, 2), (11, 22), (111, 222)) &gt;&gt;&gt; b = eval(str(a)) &gt;&gt;&gt; b ((1, 2), (11, 22), (111, 222)) </code></pre>
-1
2010-05-13T21:38:25Z
[ "python", "serialization" ]
python: send a list/dict over network
2,562,359
<p>I'm looking for an easy way of packing/unpacking data structures for sending over the network:</p> <p>on client just before sending:</p> <pre><code>a = ((1,2),(11,22,),(111,222)) message = pack(a) </code></pre> <p>and then on server:</p> <pre><code>a = unpack(message) </code></pre> <p>Is there a library that co...
4
2010-04-01T17:39:00Z
2,832,659
<p><a href="http://docs.python.org/library/ast.html#ast.literal_eval" rel="nofollow"><code>ast.literal_eval()</code></a> preserves tuples:</p> <pre><code>&gt;&gt;&gt; a = ((1,2),(11,22,),(111,222)) &gt;&gt;&gt; s = repr(a) &gt;&gt;&gt; import ast &gt;&gt;&gt; ast.literal_eval(s) ((1, 2), (11, 22), (111, 222)) </code><...
0
2010-05-14T08:05:09Z
[ "python", "serialization" ]
mysql-python stopped working
2,562,673
<p>This is a rather dumb question but i'am looking at a bizarre situation.</p> <p>I am running fedora and have python 2.6.5 installed. The other day i installed MySQL-python using yum (because i do not have the setuptools module so i cannot build it from source).</p> <p>Anyway yesterday i wrote my entire data access ...
1
2010-04-01T18:28:19Z
2,562,886
<p>If all else fails, go to <a href="http://sourceforge.net/projects/mysql-python/" rel="nofollow">http://sourceforge.net/projects/mysql-python/</a> and install the package manually. This should work reliably.</p>
1
2010-04-01T19:00:58Z
[ "python", "configuration", "installation", "mysql" ]
mysql-python stopped working
2,562,673
<p>This is a rather dumb question but i'am looking at a bizarre situation.</p> <p>I am running fedora and have python 2.6.5 installed. The other day i installed MySQL-python using yum (because i do not have the setuptools module so i cannot build it from source).</p> <p>Anyway yesterday i wrote my entire data access ...
1
2010-04-01T18:28:19Z
2,564,463
<p>Well it seems to be working if i run or debug something from within eclipse. As it has the 2.5 version set as the python interpreter.</p> <p>Does anyone know how i can set which python version to use in general on fedora. I'm sure i just have to set some path variable somewhere but not sure what!</p>
0
2010-04-02T00:29:50Z
[ "python", "configuration", "installation", "mysql" ]
Python UTF-8 can't decode byte on 32-bit machine
2,562,674
<p>it works fine on 64 bit machines but for some reason will not work on python 2.4.3 on a 32-bit instance.</p> <p>i get the error </p> <pre><code>'utf8' codec can't decode bytes in position 76-79: invalid data </code></pre> <p>for the code</p> <pre><code>try: str(sourceresult.sourcename).encode('utf8',...
4
2010-04-01T18:28:28Z
2,562,752
<p>"Invalid Data" usually means that the incoming data contained characters outside its character set. </p> <p>This is often caused by, at some point, some data being encoded in a character set different than UTF-8. </p> <p>For example, if the file a string is stored in was not converted into UTF-8 when you made UTF-...
0
2010-04-01T18:39:38Z
[ "python", "encoding", "string", "utf-8" ]
Python UTF-8 can't decode byte on 32-bit machine
2,562,674
<p>it works fine on 64 bit machines but for some reason will not work on python 2.4.3 on a 32-bit instance.</p> <p>i get the error </p> <pre><code>'utf8' codec can't decode bytes in position 76-79: invalid data </code></pre> <p>for the code</p> <pre><code>try: str(sourceresult.sourcename).encode('utf8',...
4
2010-04-01T18:28:28Z
2,562,881
<p>We need the following, and we need the <em>exact</em> output:</p> <pre><code>type(sourceresult.sourcename) # I suspect it's already a UTF-8 encoded string repr(sourceresult.sourcename) </code></pre> <p>Like I said, I'm almost certain that your <code>sourceresult.sourcename</code> is already a UTF-8 encoded string...
7
2010-04-01T19:00:03Z
[ "python", "encoding", "string", "utf-8" ]
Python UTF-8 can't decode byte on 32-bit machine
2,562,674
<p>it works fine on 64 bit machines but for some reason will not work on python 2.4.3 on a 32-bit instance.</p> <p>i get the error </p> <pre><code>'utf8' codec can't decode bytes in position 76-79: invalid data </code></pre> <p>for the code</p> <pre><code>try: str(sourceresult.sourcename).encode('utf8',...
4
2010-04-01T18:28:28Z
2,562,912
<p>I think the problem is with your use of the str() function. Keep in mind that str() returns narrow, i.e. 1-byte-per-character strings. If the input, sourceresult.sourcename, is unicode, then Python automatically encodes it in order to return a narrow string. By default it uses the system encoding, which is likely...
0
2010-04-01T19:04:44Z
[ "python", "encoding", "string", "utf-8" ]
Python UTF-8 can't decode byte on 32-bit machine
2,562,674
<p>it works fine on 64 bit machines but for some reason will not work on python 2.4.3 on a 32-bit instance.</p> <p>i get the error </p> <pre><code>'utf8' codec can't decode bytes in position 76-79: invalid data </code></pre> <p>for the code</p> <pre><code>try: str(sourceresult.sourcename).encode('utf8',...
4
2010-04-01T18:28:28Z
4,596,880
<p>Make sure you don't have an odd number of bytes in your varchar field; I had a varchar(255) that blew up when someone entered a long string in Arabic. I then got the "unexpected end of data" error (as one might expect...!)</p>
0
2011-01-04T18:11:13Z
[ "python", "encoding", "string", "utf-8" ]
MATLAB-like variable editor in Python
2,562,697
<p>Is there a data viewer in Python/IPython like the variable editor in MATLAB?</p>
4
2010-04-01T18:31:19Z
2,566,285
<p>No, because python is not an integrated environment, but "only" a programming language. You can use <code>locals</code> or <code>globals</code> to give the defined variables. You can filter them with something like this:</p> <pre><code>filter(lambda x: not x.startswith("__"), locals()) </code></pre>
0
2010-04-02T11:03:49Z
[ "python", "matlab", "numpy", "ipython" ]
MATLAB-like variable editor in Python
2,562,697
<p>Is there a data viewer in Python/IPython like the variable editor in MATLAB?</p>
4
2010-04-01T18:31:19Z
2,567,042
<p>You should try spiderlib:</p> <p><a href="http://code.google.com/p/spyderlib/">http://code.google.com/p/spyderlib/</a></p> <p>it's a dev environment a la matlab.</p>
8
2010-04-02T14:10:25Z
[ "python", "matlab", "numpy", "ipython" ]
MATLAB-like variable editor in Python
2,562,697
<p>Is there a data viewer in Python/IPython like the variable editor in MATLAB?</p>
4
2010-04-01T18:31:19Z
2,569,226
<p>in ipython, <code>ipipe.igrid()</code> can be used to view tabular data.</p>
0
2010-04-02T21:10:08Z
[ "python", "matlab", "numpy", "ipython" ]
MATLAB-like variable editor in Python
2,562,697
<p>Is there a data viewer in Python/IPython like the variable editor in MATLAB?</p>
4
2010-04-01T18:31:19Z
28,463,696
<p>Even Pycharm will be a good option if you are looking for MATLAB like editor.</p>
0
2015-02-11T20:17:57Z
[ "python", "matlab", "numpy", "ipython" ]
How to sort a list alphabetically and have additional lists sorted in the same order
2,562,714
<p>I have 3 lists, each with equal elements: email addresses, salaries and IDs</p> <p>I'd like to sort the email addresses alphabetically and <i>in some way</i> sort the other 2 lists (salaries and IDs).</p> <pre><code>E.g., Emails: z@company.com a@company.com Salaries: 50000 60000 IDs: 2 1 </code></pre> <p>The pu...
1
2010-04-01T18:34:00Z
2,562,797
<p>Try:</p> <pre><code>emails = ["z@c.com", "a@c.com"] salaries = [50, 60] ids = [2, 1] intermediate = zip(emails, salaries, ids) intermediate.sort() result = zip(*intermediate) </code></pre>
5
2010-04-01T18:46:22Z
[ "python", "list", "sorting" ]
How to sort a list alphabetically and have additional lists sorted in the same order
2,562,714
<p>I have 3 lists, each with equal elements: email addresses, salaries and IDs</p> <p>I'd like to sort the email addresses alphabetically and <i>in some way</i> sort the other 2 lists (salaries and IDs).</p> <pre><code>E.g., Emails: z@company.com a@company.com Salaries: 50000 60000 IDs: 2 1 </code></pre> <p>The pu...
1
2010-04-01T18:34:00Z
2,562,808
<p>Assuming that each email ID is unique, then this will work:</p> <pre><code>sortedEmails = emails[:] sortedEmails.sort() sortedSalaries = [] for email in sortedEmails: i = emails.index(email) sortedSalaries.append(salaries[i]) </code></pre> <p>Hope that helps</p>
0
2010-04-01T18:47:50Z
[ "python", "list", "sorting" ]
How to sort a list alphabetically and have additional lists sorted in the same order
2,562,714
<p>I have 3 lists, each with equal elements: email addresses, salaries and IDs</p> <p>I'd like to sort the email addresses alphabetically and <i>in some way</i> sort the other 2 lists (salaries and IDs).</p> <pre><code>E.g., Emails: z@company.com a@company.com Salaries: 50000 60000 IDs: 2 1 </code></pre> <p>The pu...
1
2010-04-01T18:34:00Z
2,562,866
<p>This is essentially ebo's solution, made to a one-liner with the user of sorted() rather than list.sort, and multiple lvalues in the assignement to get the individual list (named as the original but with an <code>s_</code> prefix) directly.</p> <pre><code>&gt;&gt;&gt; email = ['z@company.com', 'a@company.com'] &gt;...
3
2010-04-01T18:57:38Z
[ "python", "list", "sorting" ]
Is there a multithreaded map() function?
2,562,757
<p>I have a function that is side effect free and I would like to run for every element in an array and return an array with all of the results. I'm wondering if python has something built into to generate all of the values.</p> <p>Thank you.</p>
10
2010-04-01T18:40:07Z
2,562,799
<p>Try the Pool.map function from multiprocessing:</p> <p><a href="http://docs.python.org/library/multiprocessing.html#using-a-pool-of-workers">http://docs.python.org/library/multiprocessing.html#using-a-pool-of-workers</a></p> <p>It's not multithreaded per-se, but that's actually good since multithreading is severel...
10
2010-04-01T18:47:06Z
[ "python", "multithreading" ]
Is there a multithreaded map() function?
2,562,757
<p>I have a function that is side effect free and I would like to run for every element in an array and return an array with all of the results. I'm wondering if python has something built into to generate all of the values.</p> <p>Thank you.</p>
10
2010-04-01T18:40:07Z
2,562,810
<p>You can use the multiprocessing python package (http://docs.python.org/library/multiprocessing.html). The cloud python package, available from PiCloud (http://www.picloud.com), offers a multi-processing map() function as well, which can offload your map to the cloud.</p>
2
2010-04-01T18:48:02Z
[ "python", "multithreading" ]
Is there a multithreaded map() function?
2,562,757
<p>I have a function that is side effect free and I would like to run for every element in an array and return an array with all of the results. I'm wondering if python has something built into to generate all of the values.</p> <p>Thank you.</p>
10
2010-04-01T18:40:07Z
2,562,823
<p>This functionality is not built in. However, <a href="http://honeypot.net/multi-processing-map-python" rel="nofollow">someone has already implemented it</a>.</p>
0
2010-04-01T18:49:33Z
[ "python", "multithreading" ]
Is there a multithreaded map() function?
2,562,757
<p>I have a function that is side effect free and I would like to run for every element in an array and return an array with all of the results. I'm wondering if python has something built into to generate all of the values.</p> <p>Thank you.</p>
10
2010-04-01T18:40:07Z
2,562,828
<p>I would think there would be no reason to have such a function. All Python threads have to execute on the same CPU. Assuming your map function has no I/O component, you would not see any speedup in processing (and would probably see a slowdown due to context switching).</p> <p>Other posters have mentioned multipr...
0
2010-04-01T18:49:54Z
[ "python", "multithreading" ]
Is there a multithreaded map() function?
2,562,757
<p>I have a function that is side effect free and I would like to run for every element in an array and return an array with all of the results. I'm wondering if python has something built into to generate all of the values.</p> <p>Thank you.</p>
10
2010-04-01T18:40:07Z
2,564,022
<p>Maybe try the <a href="http://www.python.org/dev/peps/pep-3146/" rel="nofollow">Unladen Swallow Python 3</a> implementation? That might be a major project, and not guaranteed to be stable, but if you're inclined it could work. Then <a href="http://docs.python.org/py3k/tutorial/datastructures.html#tut-listcomps" re...
0
2010-04-01T22:12:42Z
[ "python", "multithreading" ]
Is there a multithreaded map() function?
2,562,757
<p>I have a function that is side effect free and I would like to run for every element in an array and return an array with all of the results. I'm wondering if python has something built into to generate all of the values.</p> <p>Thank you.</p>
10
2010-04-01T18:40:07Z
28,867,015
<p>Python now has the concurrent.futures module, which is the simplest way of getting map to work with either multiple threads or multiple processes. </p> <p><a href="https://docs.python.org/3/library/concurrent.futures.html" rel="nofollow">https://docs.python.org/3/library/concurrent.futures.html</a></p>
0
2015-03-04T23:18:37Z
[ "python", "multithreading" ]
SequenceMatcher for multiple inputs, not just two?
2,562,893
<p>wondering about the best way to approach this particular problem and if any libraries (python preferably, but I can be flexible if need be).</p> <p>I have a file with a string on each line. I would like to find the longest common patterns and their locations in each line. I know that I can use SequenceMatcher to ...
3
2010-04-01T19:01:52Z
2,567,164
<p>Is your problem performance?</p> <p>How big is your input?</p> <p>Is the minimum strings length to match 2?</p> <p>Note that your example is not correct I think as the results you expect do not match the sample strings you provided.</p>
0
2010-04-02T14:33:49Z
[ "python", "compression", "sequencematcher" ]
SequenceMatcher for multiple inputs, not just two?
2,562,893
<p>wondering about the best way to approach this particular problem and if any libraries (python preferably, but I can be flexible if need be).</p> <p>I have a file with a string on each line. I would like to find the longest common patterns and their locations in each line. I know that I can use SequenceMatcher to ...
3
2010-04-01T19:01:52Z
6,364,887
<p>If all you want is to find common substrings that are at the same offset in each line, all you need is something like this:</p> <pre><code>matches = [] zipped_strings = zip(s1,s2,s3) startpos = -1 for i in len(zipped_strings): c1,c2,c3 = zipped_strings[i] # if you're not inside a match, # look for matching ...
1
2011-06-15T21:56:41Z
[ "python", "compression", "sequencematcher" ]
Python creating a dictionary and swapping these into another file
2,563,088
<p>I have two tab delimited .csv file. From one.csv I have created a dictionary which looks like:</p> <pre><code>'EB2430': ' "\t"idnD "\t"yjgV "\t"b4267 "\n', 'EB3128': ' "\t"yagE "\t\t"b0268 "\n', 'EB3945': ' "\t"maeB "\t"ypfF "\t"b2463 "\n', 'EB3944': ' "\t"eutS "\t"ypfE "\t"b2462 "\n', </code></pre> <p>I would lik...
3
2010-04-01T19:26:32Z
2,563,313
<p>It looks like you could more usefully use the Python standard library <a href="http://docs.python.org/library/csv.html?highlight=csv#module-csv" rel="nofollow">csv</a> module here. rather than perform the text processing parts youself "manually". E.g.:</p> <pre><code>import csv with open("one.csv", "r") as f: ro...
2
2010-04-01T20:06:44Z
[ "python", "dictionary" ]
Python creating a dictionary and swapping these into another file
2,563,088
<p>I have two tab delimited .csv file. From one.csv I have created a dictionary which looks like:</p> <pre><code>'EB2430': ' "\t"idnD "\t"yjgV "\t"b4267 "\n', 'EB3128': ' "\t"yagE "\t\t"b0268 "\n', 'EB3945': ' "\t"maeB "\t"ypfF "\t"b2463 "\n', 'EB3944': ' "\t"eutS "\t"ypfE "\t"b2462 "\n', </code></pre> <p>I would lik...
3
2010-04-01T19:26:32Z
2,563,346
<p>May I suggest, instead of hand-parsing CSV file use <a href="http://docs.python.org/dev/library/csv.html" rel="nofollow">csv</a> that is built-in. It takes care of delimiters, character escaping etc. It's API is simple, too:</p> <pre><code>import csv # Auto-detector of this particular CSV dialect (delimiters and s...
0
2010-04-01T20:10:56Z
[ "python", "dictionary" ]
Python creating a dictionary and swapping these into another file
2,563,088
<p>I have two tab delimited .csv file. From one.csv I have created a dictionary which looks like:</p> <pre><code>'EB2430': ' "\t"idnD "\t"yjgV "\t"b4267 "\n', 'EB3128': ' "\t"yagE "\t\t"b0268 "\n', 'EB3945': ' "\t"maeB "\t"ypfF "\t"b2463 "\n', 'EB3944': ' "\t"eutS "\t"ypfE "\t"b2462 "\n', </code></pre> <p>I would lik...
3
2010-04-01T19:26:32Z
2,563,415
<p>Have a look to <a href="http://docs.python.org/library/csv.html" rel="nofollow">csv</a> module:</p> <pre><code>import csv reader1 = csv.reader(open('input1.csv'), delimiter = '\t') reader2 = csv.reader(open('input2.csv'), delimiter = '\t') csvwriter = csv.writer(open('output.csv', 'w'),delimiter = '\t') while True:...
0
2010-04-01T20:23:34Z
[ "python", "dictionary" ]
Regex matching very slow
2,563,329
<p>I am trying to parse a PDF to extract the text from it (please don't suggest any libraries to do this, as this is part of learning the format).<br /> I have already handled deflating it to put it in the alphanumeric format. I now need to extract the text from the text blocks.<br /> So, my current pattern is <code>BT...
1
2010-04-01T20:08:58Z
2,563,366
<p>How many of these blocks might appear in a document?</p> <p>Often slow Regex execution is the result of catastrophic backtracking, as described here: <a href="http://www.regular-expressions.info/catastrophic.html" rel="nofollow">http://www.regular-expressions.info/catastrophic.html</a></p> <p>I don't know what reg...
3
2010-04-01T20:16:17Z
[ "python", "regex", "pdf" ]
Regex matching very slow
2,563,329
<p>I am trying to parse a PDF to extract the text from it (please don't suggest any libraries to do this, as this is part of learning the format).<br /> I have already handled deflating it to put it in the alphanumeric format. I now need to extract the text from the text blocks.<br /> So, my current pattern is <code>BT...
1
2010-04-01T20:08:58Z
2,563,408
<p>Are you sure the regex is correct and pulls out ABC as a match? What language's regex engine is this? Using my regular expression debugger shows that:</p> <p><code>"BT.*?((.*?)).*?ET"</code> doesn't pull out ABC and in fact must find the string 'ET' then backtrack back to find everything else.</p> <p><code>"BT.*?\...
1
2010-04-01T20:21:54Z
[ "python", "regex", "pdf" ]
Regex matching very slow
2,563,329
<p>I am trying to parse a PDF to extract the text from it (please don't suggest any libraries to do this, as this is part of learning the format).<br /> I have already handled deflating it to put it in the alphanumeric format. I now need to extract the text from the text blocks.<br /> So, my current pattern is <code>BT...
1
2010-04-01T20:08:58Z
2,566,131
<p>You can't just parse the PDF with a regex to extract the text. In most cases the text in inside compressed binary blobs or encoded. A PDF with the text shown like this is very much the exception.</p>
0
2010-04-02T10:22:57Z
[ "python", "regex", "pdf" ]
Regex matching very slow
2,563,329
<p>I am trying to parse a PDF to extract the text from it (please don't suggest any libraries to do this, as this is part of learning the format).<br /> I have already handled deflating it to put it in the alphanumeric format. I now need to extract the text from the text blocks.<br /> So, my current pattern is <code>BT...
1
2010-04-01T20:08:58Z
2,566,336
<p>There's not really enough info for a definite answer--or maybe you're assuming we know more about PDF than you do. Are there always parenthesized chunks inside these <code>BT...ET</code> sections? Is there always only one of them? Is the <code>BT</code> or <code>ET</code> always at the beginning of a line? If so...
0
2010-04-02T11:19:04Z
[ "python", "regex", "pdf" ]
Regex matching very slow
2,563,329
<p>I am trying to parse a PDF to extract the text from it (please don't suggest any libraries to do this, as this is part of learning the format).<br /> I have already handled deflating it to put it in the alphanumeric format. I now need to extract the text from the text blocks.<br /> So, my current pattern is <code>BT...
1
2010-04-01T20:08:58Z
2,566,860
<p>here's one without regex. simple string parsing using Python internals.</p> <pre><code>&gt;&gt;&gt; xtract=""" ... BT ... /F13 12 Tf ... 288 720 Td ... (ABC) Tj ... ET ... ... """ &gt;&gt;&gt; for chunk in xtract.split("ET"): ... if "BT" in chunk: ... for brace in chunk.split(")"): ... ...
0
2010-04-02T13:32:48Z
[ "python", "regex", "pdf" ]
Regex matching very slow
2,563,329
<p>I am trying to parse a PDF to extract the text from it (please don't suggest any libraries to do this, as this is part of learning the format).<br /> I have already handled deflating it to put it in the alphanumeric format. I now need to extract the text from the text blocks.<br /> So, my current pattern is <code>BT...
1
2010-04-01T20:08:58Z
2,567,777
<p>Since there will be only one bracketed expression between a <code>BT</code> and an <code>ET</code>, you could try the following regular expression for speed:</p> <pre><code>r"(?s)\bBT\b[^(]*\(([^)]*)\).*?\bET\b" </code></pre>
0
2010-04-02T16:25:04Z
[ "python", "regex", "pdf" ]