prefix
stringclasses
1 value
input_text
stringlengths
10
172
target_text
stringlengths
18
33.9k
QA:
How can I find the full path to a font from its display name on a Mac?
<p>open up a terminal (Applications-&gt;Utilities-&gt;Terminal) and type this in:</p> <pre><code>locate InsertFontHere<br></code></pre> <p>This will spit out every file that has the name you want.</p> <p>Warning: there may be alot to wade through.</p>
QA:
How can I find the full path to a font from its display name on a Mac?
<p>I haven't been able to find anything that does this directly. I think you'll have to iterate through the various font folders on the system: <code>/System/Library/Fonts</code>, <code>/Library/Fonts</code>, and there can probably be a user-level directory as well <code>~/Library/Fonts</code>.</p>
QA:
Get a preview JPEG of a PDF on Windows?
<p>You can use ImageMagick's convert utility for this, see some examples in <a href="https://web.archive.org/web/20120413111338/http://studio.imagemagick.org/pipermail/magick-users/2002-May/002636.html" rel="nofollow">http://studio.imagemagick.org/pipermail/magick-users/2002-May/002636.html</a> :</p> <blockquote> <pre><code>Convert taxes.pdf taxes.jpg </code></pre> <p>Will convert a two page PDF file into [2] jpeg files: taxes.jpg.0, taxes.jpg.1</p> <p>I can also convert these JPEGS to a thumbnail as follows:</p> <pre><code>convert -size 120x120 taxes.jpg.0 -geometry 120x120 +profile '*' thumbnail.jpg </code></pre> <p>I can even convert the PDF directly to a jpeg thumbnail as follows:</p> <pre><code>convert -size 120x120 taxes.pdf -geometry 120x120 +profile '*' thumbnail.jpg </code></pre> <p>This will result in a thumbnail.jpg.0 and thumbnail.jpg.1 for the two pages.</p> </blockquote>
QA:
Continuous Integration System for a Python Codebase
<p>One possibility is Hudson. It's written in Java, but there's integration with Python projects:</p> <blockquote> <p><a href="http://redsolo.blogspot.com/2007/11/hudson-embraces-python.html" rel="nofollow">Hudson embraces Python</a></p> </blockquote> <p>I've never tried it myself, however.</p> <p>(<strong>Update</strong>, Sept. 2011: After a trademark dispute Hudson has been renamed to <a href="http://jenkins-ci.org/" rel="nofollow">Jenkins</a>.)</p>
QA:
Continuous Integration System for a Python Codebase
<p>We run <a href="http://buildbot.net/trac">Buildbot - Trac</a> at work, I haven't used it too much since my code base isn't part of the release cycle yet. But we run the tests on different environments (OSX/Linux/Win) and it sends emails --and it's written in python.</p>
QA:
cx_Oracle: How do I iterate over a result set?
<p>The canonical way is to use the built-in cursor iterator.</p> <pre><code>curs.execute('select * from people') for row in curs: print row </code></pre> <hr> <p>You can use <code>fetchall()</code> to get all rows at once.</p> <pre><code>for row in curs.fetchall(): print row </code></pre> <p>It can be convenient to use this to create a Python list containing the values returned:</p> <pre><code>curs.execute('select first_name from people') names = [row[0] for row in curs.fetchall()] </code></pre> <p>This can be useful for smaller result sets, but can have bad side effects if the result set is large.</p> <ul> <li><p>You have to wait for the entire result set to be returned to your client process.</p></li> <li><p>You may eat up a lot of memory in your client to hold the built-up list.</p></li> <li><p>It may take a while for Python to construct and deconstruct the list which you are going to immediately discard anyways.</p></li> </ul> <hr> <p>If you know there's a single row being returned in the result set you can call <code>fetchone()</code> to get the single row.</p> <pre><code>curs.execute('select max(x) from t') maxValue = curs.fetchone()[0] </code></pre> <hr> <p>Finally, you can loop over the result set fetching one row at a time. In general, there's no particular advantage in doing this over using the iterator.</p> <pre><code>row = curs.fetchone() while row: print row row = curs.fetchone() </code></pre>
QA:
Continuous Integration System for a Python Codebase
<p>Second the Buildbot - Trac integration. You can find more information about the integration on the <a href="http://buildbot.net/trac/wiki/BuildbotAndTrac">Buildbot website</a>. At my previous job, we wrote and used the plugin they mention (tracbb). What the plugin does is rewriting all of the Buildbot urls so you can use Buildbot from within Trac. (http://example.com/tracbb).</p> <p>The really nice thing about Buildbot is that the configuration is written in Python. You can integrate your own Python code directly to the configuration. It's also very easy to write your own BuildSteps to execute specific tasks.</p> <p>We used BuildSteps to get the source from SVN, pull the dependencies, publish test results to WebDAV, etcetera.</p> <p>I wrote an X10 interface so we could send signals with build results. When the build failed, we switched on a red lava lamp. When the build succeeded, a green lava lamp switched on. Good times :-)</p>
QA:
Using 'in' to match an attribute of Python objects in an array
<p>No, you were not dreaming. Python has a pretty excellent list comprehension system that lets you manipulate lists pretty elegantly, and depending on exactly what you want to accomplish, this can be done a couple of ways. In essence, what you're doing is saying "For item in list if criteria.matches", and from that you can just iterate through the results or dump the results into a new list.</p> <p>I'm going to crib an example from <a href="http://diveintopython.net/functional_programming/filtering_lists.html" rel="nofollow">Dive Into Python</a> here, because it's pretty elegant and they're smarter than I am. Here they're getting a list of files in a directory, then filtering the list for all files that match a regular expression criteria.</p> <blockquote> <pre><code> files = os.listdir(path) test = re.compile("test\.py$", re.IGNORECASE) files = [f for f in files if test.search(f)] </code></pre> </blockquote> <p>You could do this without regular expressions, for your example, for anything where your expression at the end returns true for a match. There are other options like using the filter() function, but if I were going to choose, I'd go with this.</p> <p>Eric Sipple</p>
QA:
Using 'in' to match an attribute of Python objects in an array
<p>I think:</p> <pre><code>#!/bin/python<br>bar in dict(Foo)<br></code></pre> <p>Is what you are thinking of. When trying to see if a certain key exists within a dictionary in python (python's version of a hash table) there are two ways to check. First is the <strong><code>has_key()</code></strong> method attached to the dictionary and second is the example given above. It will return a boolean value.</p> <p>That should answer your question.</p> <p>And now a little off topic to tie this in to the <em>list comprehension</em> answer previously given (for a bit more clarity). <em>List Comprehensions</em> construct a list from a basic <em>for loop</em> with modifiers. As an example (to clarify slightly), a way to use the <code>in dict</code> language construct in a _list comprehension_:</p> <p>Say you have a two dimensional dictionary <strong><code>foo</code></strong> and you only want the second dimension dictionaries which contain the key <strong><code>bar</code></strong>. A relatively straightforward way to do so would be to use a <em>list comprehension</em> with a conditional as follows:</p> <pre><code>#!/bin/python<br>baz = dict([(key, value) for key, value in foo if bar in value])<br></code></pre> <p>Note the <strong><code>if bar in value</code></strong> at the end of the statement<strong>, this is a modifying clause which tells the <em>list comprehension</em> to only keep those key-value pairs which meet the conditional.</strong> In this case <strong><code>baz</code></strong> is a new dictionary which contains only the dictionaries from foo which contain bar (Hopefully I didn't miss anything in that code example... you may have to take a look at the list comprehension documentation found in <a href="http://docs.python.org/tut/node7.html#SECTION007140000000000000000" rel="nofollow">docs.python.org tutorials</a> and at <a href="http://www.secnetix.de/olli/Python/list_comprehensions.hawk" rel="nofollow">secnetix.de</a>, both sites are good references if you have questions in the future.).</p>
QA:
Using 'in' to match an attribute of Python objects in an array
<p>Are you looking to get a list of objects that have a certain attribute? If so, a <a href="http://docs.python.org/tut/node7.html#SECTION007140000000000000000">list comprehension</a> is the right way to do this.</p> <pre><code>result = [obj for obj in listOfObjs if hasattr(obj, 'attributeName')]<br></code></pre>
QA:
Using 'in' to match an attribute of Python objects in an array
<p>What I was thinking of can be achieved using list comprehensions, but I thought that there was a function that did this in a slightly neater way.</p> <p>i.e. 'bar' is a list of objects, all of which have the attribute 'id'</p> <p>The mythical functional way:</p> <pre><code>foo = 12<br>foo in iter_attr(bar, 'id')</code></pre> <p>The list comprehension way:</p> <pre><code>foo = 12<br>foo in [obj.id for obj in bar]</code></pre> <p>In retrospect the list comprehension way is pretty neat anyway.</p>
QA:
Class views in Django
<p>Sounds to me like you're trying to combine things that shouldn't be combined. If you need to do different processing in your view depending on if it's a User or Group object you're trying to look at then you should use two different view functions.</p> <p>On the other hand there can be common idioms you'd want to extract out of your object_detail type views... perhaps you could use a decorator or just helper functions?</p> <p>-Dan</p>
QA:
Python and MySQL
<p>I don't have any experience with <a href="http://www.SiteGround.com" rel="nofollow">http://www.SiteGround.com</a> as a web host personally. </p> <p>This is just a guess, but it's common for a shared host to support Python and MySQL with the MySQLdb module (e.g., GoDaddy does this). Try the following CGI script to see if MySQLdb is installed.</p> <pre><code>#!/usr/bin/python<br><br>module_name = 'MySQLdb'<br>head = '''Content-Type: text/html<br><br>%s is ''' % module_name<br><br>try:<br> __import__(module_name)<br> print head + 'installed'<br>except ImportError:<br> print head + 'not installed'<br></code></pre>
QA:
How do I use Python's itertools.groupby()?
<p>Can you show us your code?</p> <p>The example on the Python docs is quite straightforward:</p> <pre><code>groups = [] uniquekeys = [] for k, g in groupby(data, keyfunc): groups.append(list(g)) # Store group iterator as a list uniquekeys.append(k) </code></pre> <p>So in your case, data is a list of nodes, keyfunc is where the logic of your criteria function goes and then <code>groupby()</code> groups the data.</p> <p>You must be careful to <strong>sort the data</strong> by the criteria before you call <code>groupby</code> or it won't work. <code>groupby</code> method actually just iterates through a list and whenever the key changes it creates a new group.</p>
QA:
Python and MySQL
<p>I uploaded it and got an internal error</p> <pre><code>Premature end of script headers<br></code></pre> <p>After much playing around, I found that if I had</p> <pre><code>import cgi<br>import cgitb; cgitb.enable()<br>import MySQLdb<br></code></pre> <p>It would give me a much more useful answer and say that it was not installed, you can see it yourself -> <a href="http://woarl.com/db.py" rel="nofollow">http://woarl.com/db.py</a></p> <p>Oddly enough, this would produce an error</p> <pre><code>import MySQLdb<br>import cgi<br>import cgitb; cgitb.enable()<br></code></pre> <p>I looked at some of the other files I had up there and it seems that library was one of the ones I had already tried.</p>
QA:
Adding a Method to an Existing Object Instance
<p>In Python monkey patching generally works by overwriting a class or functions signature with your own. Below is an example from the <a href="http://wiki.zope.org/zope2/MonkeyPatch">Zope Wiki</a>:</p> <pre><code>from SomeOtherProduct.SomeModule import SomeClass<br>def speak(self):<br> return "ook ook eee eee eee!"<br>SomeClass.speak = speak<br></code></pre> <p>That code will overwrite/create a method called speak on the class. In Jeff Atwood's <a href="http://www.codinghorror.com/blog/archives/001151.html">recent post on monkey patching</a>. He shows an example in C# 3.0 which is the current language I use for work.</p>
QA:
Adding a Method to an Existing Object Instance
<p>I don't know Python syntax, but I know Ruby can do it, and it is rather trivial. Let's say you want to add a method to Array that prints the length to standard out:</p> <pre><code>class Array<br> def print_length<br> puts length<br> end<br>end<br></code></pre> <p>If you don't want to modify the whole class, you can just add the method to a single instance of the array, and no other arrays will have the method:</p> <pre><code>array = [1, 2, 3]<br>def array.print_length<br> puts length<br>end<br></code></pre> <p>Just be aware of the issues involved in using this feature. Jeff Atwood actually <a href="http://www.codinghorror.com/blog/archives/001151.html" rel="nofollow">wrote about it</a> not too long ago.</p>
QA:
How do you express binary literals in Python?
<p>As far as I can tell Python, up through 2.5, only supports hexadecimal &amp; octal literals. I did find some discussions about adding binary to future versions but nothing definite.</p>
QA:
How do you express binary literals in Python?
<p>I am pretty sure this is one of the things due to change in Python 3.0 with perhaps bin() to go with hex() and oct().</p> <p>EDIT: lbrandy's answer is correct in all cases.</p>
QA:
How do you express binary literals in Python?
<pre><code>&gt;&gt;&gt; print int('01010101111',2) 687 &gt;&gt;&gt; print int('11111111',2) 255 </code></pre> <p>Another way.</p>
QA:
Python and MySQL
<p>MySQLdb is what I have used before.</p> <p>If you host is using Python version 2.5 or higher, support for sqlite3 databases is built in (sqlite allows you to have a relational database that is simply a file in your filesystem). But buyer beware, sqlite is not suited for production, so it may depend what you are trying to do with it.</p> <p>Another option may be to call your host and complain, or change hosts. Honestly these days, any self respecting web host that supports python and mysql ought to have MySQLdb pre installed.</p>
QA:
Any experiences with Protocol Buffers?
<P>If you are looking for user facing interaction, stick with xml. It has more support, understanding, and general acceptance currently. If it's internal, I would say that protocol buffers are a great idea.</P> <P>Maybe in a few years as more tools come out to support protocol buffers, then start looking towards that for a public facing api. Until then... <A href="http://en.wikipedia.org/wiki/JSON">JSON</A>?</P>
QA:
How do I make a menu that does not require the user to press [enter] to make a selection?
<p><strong>On Linux:</strong></p> <ul> <li>set raw mode</li> <li>select and read the keystroke</li> <li>restore normal settings</li> </ul> <pre> import sys import select import termios import tty def getkey(): old_settings = termios.tcgetattr(sys.stdin) tty.setraw(sys.stdin.fileno()) select.select([sys.stdin], [], [], 0) answer = sys.stdin.read(1) termios.tcsetattr(sys.stdin, termios.TCSADRAIN, old_settings) return answer print """Menu 1) Say Foo 2) Say Bar""" answer=getkey() if "1" in answer: print "foo" elif "2" in answer: print "bar" </pre>
QA:
How do I make a menu that does not require the user to press [enter] to make a selection?
<p><strong>On Windows:</strong></p> <pre><code>import msvcrt answer=msvcrt.getch() </code></pre>
QA:
How to check what OS am I running on in Python?
<pre><code>&gt;&gt;&gt; import os &gt;&gt;&gt; print os.name posix &gt;&gt;&gt; import platform &gt;&gt;&gt; platform.system() 'Linux' &gt;&gt;&gt; platform.release() '2.6.22-15-generic' </code></pre> <p>See: <a href="https://docs.python.org/2/library/platform.html">platform — Access to underlying platform’s identifying data</a></p>
QA:
How do I make a menu that does not require the user to press [enter] to make a selection?
<p>Wow, that took forever. Ok, here's what I've ended up with </p> <pre><code>#!C:\python25\python.exe<br>import msvcrt<br>print """Menu<br>1) Say Foo <br>2) Say Bar"""<br>while 1:<br> char = msvcrt.getch()<br> if char == chr(27): #escape<br> break<br> if char == "1":<br> print "foo"<br> break<br> if char == "2":<br> print "Bar"<br> break<br></code></pre> <p>It fails hard using IDLE, the python...thing...that comes with python. But once I tried it in DOS (er, CMD.exe), as a real program, then it ran fine.</p> <p>No one try it in IDLE, unless you have Task Manager handy.</p> <p>I've already forgotten how I lived with menus that arn't super-instant responsive.</p>
QA:
How to check what OS am I running on in Python?
<p>Dang -- lbrandy beat me to the punch, but that doesn't mean I can't provide you with the system results for Vista!</p> <pre><code>&gt;&gt;&gt; import os &gt;&gt;&gt; os.name 'nt' &gt;&gt;&gt; import platform &gt;&gt;&gt; platform.system() 'Windows' &gt;&gt;&gt; platform.release() 'Vista' </code></pre>
QA:
How to check what OS am I running on in Python?
<p>For the record here's the results on Mac:</p> <pre><code>&gt;&gt;&gt; import os &gt;&gt;&gt; os.name 'posix' &gt;&gt;&gt; import platform &gt;&gt;&gt; platform.system() 'Darwin' &gt;&gt;&gt; platform.release() '8.11.1' </code></pre>
QA:
How do I make a menu that does not require the user to press [enter] to make a selection?
<p>The reason msvcrt fails in IDLE is because IDLE is not accessing the library that runs msvcrt. Whereas when you run the program natively in cmd.exe it works nicely. For the same reason that your program blows up on Mac and Linux terminals.</p> <p>But I guess if you're going to be using this specifically for windows, more power to ya.</p>
QA:
Python: what is the difference between (1,2,3) and [1,2,3], and when should I use each?
<p>The list [1,2,3] is dynamic and flexible but that flexibility comes at a speed cost.</p> <p>The tuple (1,2,3) is fixed (immutable) and therefore faster.</p>
QA:
Python: what is the difference between (1,2,3) and [1,2,3], and when should I use each?
<p>From the <a href="http://www.python.org/doc/faq/general/#why-are-there-separate-tuple-and-list-data-types">Python FAQ</a>:</p> <blockquote> <p>Lists and tuples, while similar in many respects, are generally used in fundamentally different ways. Tuples can be thought of as being similar to Pascal records or C structs; they're small collections of related data which may be of different types which are operated on as a group. For example, a Cartesian coordinate is appropriately represented as a tuple of two or three numbers.</p> <p>Lists, on the other hand, are more like arrays in other languages. They tend to hold a varying number of objects all of which have the same type and which are operated on one-by-one.</p> </blockquote> <p>Generally by convention you wouldn't choose a list or a tuple just based on its (im)mutability. You would choose a tuple for small collections of completely different pieces of data in which a full-blown class would be too heavyweight, and a list for collections of any reasonable size where you have a homogeneous set of data.</p>
QA:
File size differences after copying a file to a server vía FTP
<p>Do you need to open the locfile in binary using <code>rb</code>?</p> <pre><code>f = open (locfile, "rb") </code></pre>
QA:
File size differences after copying a file to a server vía FTP
<p>Well if you go under the properties of your file in Windows or a *nix environment, you will notice two sizes. One is the sector size, and one is the actual size. The sector size is the number of sectors in bytes that are used up on your hard disk. That is because two files cannot be in the same sector with most modern file systems, so if your file fills up half of the sector the whole sector is marked as filled.</p> <p>So you might be comparing the sector file size to the actual file size on the FTP server or vice versa.</p>
QA:
File size differences after copying a file to a server vía FTP
<p>Small files take up a whole node on the filesystem whatever size that is.</p> <p>My host tends to report all small files as 4kb in ftp but in a shell gives an accurate size so it might be a 'feature' common to ftp clients.</p>
QA:
How can I create a directly-executable cross-platform GUI app using Python?
<p>First you will need some GUI library with Python bindings and then (if you want) some program that will convert your python scripts into standalone executables.</p> <p><strong>Cross-platform GUI libraries with Python bindings (Windows, Linux, Mac)</strong></p> <p>Of course, there are many, but the most popular that I've seen in wild are:</p> <ul> <li><a href="http://wiki.python.org/moin/TkInter">Tkinter</a> - based on <a href="http://www.tcl.tk/">Tk GUI toolkit</a> (de-facto standard GUI library for python, free for commercial projects)</li> <li><a href="http://www.wxpython.org/">WxPython</a> - based on <a href="http://www.wxwidgets.org/">WxWidgets</a> (very popular, free for commercial projects)</li> <li><a href="http://www.riverbankcomputing.co.uk/news">PyQt</a> - based on <a href="http://trolltech.com/products/qt/">Qt</a> (also very popular and more stable than WxWidgets but costly license for commercial projects)</li> </ul> <p>Complete list is at <a href="http://wiki.python.org/moin/GuiProgramming">http://wiki.python.org/moin/GuiProgramming</a></p> <p><strong>Single executable (Windows)</strong></p> <ul> <li><a href="http://www.py2exe.org/">py2exe</a> - Probably the most popular out there (<a href="http://stackoverflow.com/questions/2933/an-executable-python-app/31859#31859">PyInstaller</a> is also gaining in popularity)</li> </ul> <p><strong>Single executable (Linux)</strong></p> <ul> <li><a href="http://wiki.python.org/moin/Freeze">Freeze</a> - works the same way like py2exe but targets Linux platform</li> </ul> <p><strong>Single executable (Mac)</strong></p> <ul> <li><a href="https://pythonhosted.org/py2app/">py2app</a> - again, works like py2exe but targets Mac OS</li> </ul>
QA:
How can I create a directly-executable cross-platform GUI app using Python?
<p>You don't need to <em>compile</em> python for Mac/Windows/Linux. It is an interpreted language, so you simply need to have the Python interpreter installed on the system of your choice (it is available for all three platforms).</p> <p>As for a GUI library that works cross platform, Python's <a href="http://www.tcl.tk/" rel="nofollow">Tk/Tcl</a> widget library works very well, and I believe is sufficiently cross platform.</p> <p><a href="http://docs.python.org/lib/module-Tkinter.html" rel="nofollow">Tkinter</a> is the python interface to Tk/Tcl</p> <p>From the python project webpage: </p> <blockquote> <p>Tkinter is not the only GuiProgramming toolkit for Python. It is however the most commonly used one, and almost the only one that is portable between Unix, Mac and Windows</p> </blockquote>
QA:
How can I create a directly-executable cross-platform GUI app using Python?
<p>Since python is installed on nearly every non-Windows OS by default now, the only thing you really need to make sure of is that all of the non-standard libraries you use are installed.</p> <p>Having said that, it is possible to build executables that include the python interpreter, and any libraries you use. This is likely to create a large executable, however.</p> <p>MacOS X even includes support in the Xcode IDE for creating full standalone GUI apps. These can be run by any user running OS X.</p>
QA:
Adding a Method to an Existing Object Instance
<p>In Python, there is a difference between functions and bound methods.</p> <pre><code>&gt;&gt;&gt; def foo(): ... print "foo" ... &gt;&gt;&gt; class A: ... def bar( self ): ... print "bar" ... &gt;&gt;&gt; a = A() &gt;&gt;&gt; foo &lt;function foo at 0x00A98D70&gt; &gt;&gt;&gt; a.bar &lt;bound method A.bar of &lt;__main__.A instance at 0x00A9BC88&gt;&gt; &gt;&gt;&gt; </code></pre> <p>Bound methods have been "bound" (how descriptive) to an instance, and that instance will be passed as the first argument whenever the method is called.</p> <p>Callables that are attributes of a class (as opposed to an instance) are still unbound, though, so you can modify the class definition whenever you want:</p> <pre><code>&gt;&gt;&gt; def fooFighters( self ): ... print "fooFighters" ... &gt;&gt;&gt; A.fooFighters = fooFighters &gt;&gt;&gt; a2 = A() &gt;&gt;&gt; a2.fooFighters &lt;bound method A.fooFighters of &lt;__main__.A instance at 0x00A9BEB8&gt;&gt; &gt;&gt;&gt; a2.fooFighters() fooFighters </code></pre> <p>Previously defined instances are updated as well (as long as they haven't overridden the attribute themselves):</p> <pre><code>&gt;&gt;&gt; a.fooFighters() fooFighters </code></pre> <p>The problem comes when you want to attach a method to a single instance:</p> <pre><code>&gt;&gt;&gt; def barFighters( self ): ... print "barFighters" ... &gt;&gt;&gt; a.barFighters = barFighters &gt;&gt;&gt; a.barFighters() Traceback (most recent call last): File "&lt;stdin&gt;", line 1, in &lt;module&gt; TypeError: barFighters() takes exactly 1 argument (0 given) </code></pre> <p>The function is not automatically bound when it's attached directly to an instance:</p> <pre><code>&gt;&gt;&gt; a.barFighters &lt;function barFighters at 0x00A98EF0&gt; </code></pre> <p>To bind it, we can use the <a href="http://docs.python.org/library/types.html?highlight=methodtype#module-types">MethodType function in the types module</a>:</p> <pre><code>&gt;&gt;&gt; import types &gt;&gt;&gt; a.barFighters = types.MethodType( barFighters, a ) &gt;&gt;&gt; a.barFighters &lt;bound method ?.barFighters of &lt;__main__.A instance at 0x00A9BC88&gt;&gt; &gt;&gt;&gt; a.barFighters() barFighters </code></pre> <p>This time other instances of the class have not been affected:</p> <pre><code>&gt;&gt;&gt; a2.barFighters() Traceback (most recent call last): File "&lt;stdin&gt;", line 1, in &lt;module&gt; AttributeError: A instance has no attribute 'barFighters' </code></pre> <p>More information can be found by reading about <a href="http://users.rcn.com/python/download/Descriptor.htm">descriptors</a> and <a href="http://www.onlamp.com/pub/a/python/2003/04/17/metaclasses.html">metaclass</a> <a href="http://www.gnosis.cx/publish/programming/metaclass_2.html">programming</a>.</p>
QA:
How can I find the full path to a font from its display name on a Mac?
<p>Unfortunately the only API that isn't deprecated is located in the ApplicationServices framework, which doesn't have a bridge support file, and thus isn't available in the bridge. If you're wanting to use ctypes, you can use ATSFontGetFileReference after looking up the ATSFontRef.</p> <p>Cocoa doesn't have any native support, at least as of 10.5, for getting the location of a font.</p>
QA:
Calling a function of a module from a string with the function's name in Python
<p>Assuming module <code>foo</code> with method <code>bar</code>:</p> <pre><code>import foo methodToCall = getattr(foo, 'bar') result = methodToCall() </code></pre> <p>As far as that goes, lines 2 and 3 can be compressed to:</p> <pre><code>result = getattr(foo, 'bar')() </code></pre> <p>if that makes more sense for your use case. You can use <code>getattr</code> in this fashion on class instance bound methods, module-level methods, class methods... the list goes on.</p>
QA:
Programmatically talking to a Serial Port in OS X or Linux
<p>have you tried watching the traffic between the GUI and the serial port to see if there is some kind of special command being sent across? Also just curious, Python is sending ASCII and not UTF-8 or something else right? The reason I ask is because I noticed your quote changes for the strings and in some languages that actually is the difference between ASCII and UTF-8.</p>
QA:
Programmatically talking to a Serial Port in OS X or Linux
<p><code>/dev/cu.xxxxx</code> is the "callout" device, it's what you use when you establish a connection to the serial device and start talking to it. <code>/dev/tty.xxxxx</code> is the "dialin" device, used for monitoring a port for incoming calls for e.g. a fax listener.</p>
QA:
Class views in Django
<p>If you're simply displaying data from models, why not use the <a href="https://docs.djangoproject.com/en/1.2/ref/generic-views/" rel="nofollow">Django Generic Views</a>? They're designed to let you easy show data from a model without having to write your own view and stuff about mapping URL paramaters to views, fetching data, handling edge cases, rendering output, etc.</p>
QA:
Python: what is the difference between (1,2,3) and [1,2,3], and when should I use each?
<p>Tuples are a quick\flexible way to create <em>composite</em> data-types. Lists are containers for, well, lists of objects.</p> <p>For example, you would use a List to store a list of student details in a class.</p> <p>Each student detail in that list may be a 3-tuple containing their roll number, name and test score.</p> <pre><code> `[(1,'Mark',86),(2,'John',34)...]`<br></code></pre> <p>Also, because tuples are immutable they can be used as keys in dictionaries.</p>
QA:
Adding a Method to an Existing Object Instance
<p>What you're looking for is <code>setattr</code> I believe. Use this to set an attribute on an object.</p> <pre><code>&gt;&gt;&gt; def printme(s): print repr(s)<br>&gt;&gt;&gt; class A: pass<br>&gt;&gt;&gt; setattr(A,'printme',printme)<br>&gt;&gt;&gt; a = A()<br>&gt;&gt;&gt; a.printme() # s becomes the implicit 'self' variable<br>&lt; __ main __ . A instance at 0xABCDEFG&gt;<br></code></pre>
QA:
Calling a function of a module from a string with the function's name in Python
<p>Patrick's solution is probably the cleanest. If you need to dynamically pick up the module as well, you can import it like:</p> <pre><code>m = __import__ ('foo') func = getattr(m,'bar') func() </code></pre>
QA:
How to sell Python to a client/boss/person with lots of cash
<p>Focus on the shorter time needed for development/prototype and possibly easier maintenance (none of this may apply against Ruby).</p>
QA:
How to sell Python to a client/boss/person with lots of cash
<p>This is one of those cases that really boil down to personal preference or situational details. If you're more comfortable and experienced with Python, then say so. Are they asking you to justify it because they're more comfortable with one of the other environments? After you're done, will the system be passed off to someone else for long-term maintenance?</p> <p>If they ask you to use a technology or language that you're not as familiar with, then make sure they know up-front that it's going to take you longer.</p>
QA:
How to sell Python to a client/boss/person with lots of cash
<p>I would consider that using python on a new project is completely dependent on what problem you are trying to solve with python. If you want someone to agree with you that you should use python, then show them how python's features apply specifically to that problem.</p> <p>In the case of web development with python, talk about WSGI and other web libraries and frameworks you could use that would make your life easier. One note for python is that most of the frameworks for python web development can be plugged right into any current project. With ruby on rails, you're practically working in a DSL that anyone who uses your project will have to learn. If they know python, then they can figure out what you are doing with django, etc in a day.</p> <p>I'm only talking about web development because it appears that's what you are going to be working on seeing ruby, python and PHP in the same list. The real message that's important is applying to whatever it is you like about python <em>directly</em> to some problem you are trying to solve.</p>
QA:
How do you set up Python scripts to work in Apache 2.0?
<p>There are two main ways of running Python on Apache. The simplest would be to use CGI and write normal Python scripts while the second is using a web framework like Django or Pylons.</p> <p>Using CGI is straightforward. Make sure your Apache config file has a cgi-bin set up. If not, follow their documentation (<a href="http://httpd.apache.org/docs/2.0/howto/cgi.html" rel="nofollow">http://httpd.apache.org/docs/2.0/howto/cgi.html</a>). At that point all you need to do is place your Python scripts in the cgi-bin directory and the standard output will become the HTTP response. Refer to Python's documentation for further info (<a href="https://docs.python.org/library/cgi.html" rel="nofollow">https://docs.python.org/library/cgi.html</a>).</p> <p>If you want to use a web framework you'll need to setup mod_python or FastCGI. These steps are dependent on which framework you want to use. Django provides clear instructions on how to setup mod_python and Django with Apache (<a href="http://www.djangoproject.com/documentation/modpython/" rel="nofollow">http://www.djangoproject.com/documentation/modpython/</a>)</p>
QA:
How do you set up Python scripts to work in Apache 2.0?
<p>Yes, mod_python is pretty confusing to set up. Here's how I did it.</p> <p>In httpd.conf:</p> <pre><code>LoadModule python_module modules/mod_python.so<br><br>&lt;Directory "/serverbase/htdocs/myapp"&gt;<br> AddHandler mod_python .py<br> PythonHandler myapp<br> PythonDebug On<br></code></pre> <p>and in your application directory:</p> <pre><code>$ /serverbase/htdocs/myapp$ ls -l<br>total 16<br>-r-xr-xr-x 1 root sys 6484 May 21 15:54 myapp.py<br></code></pre> <p>Repeat the configuration for each python program you wish to have running under mod_python.</p>
QA:
How do you set up Python scripts to work in Apache 2.0?
<p>Are you running Python on UNIX or Windows?</p> <p>An alternative to mod_python and FastCGI is mod_wsgi. You can find out more at <a href="http://code.google.com/p/modwsgi/" rel="nofollow">modwsgi</a></p> <p>I have built and installed this on Solaris without problems. I had previously tried mod_python but ran into problems with shared libraries as part of the build. There are <a href="http://code.google.com/p/modwsgi/wiki/InstallationInstructions" rel="nofollow">good install docs</a> available.</p>
QA:
Does anyone have experience creating a shared library in MATLAB?
<p>I won't help much but I remember that I was able to wrap MATLAB simulation into DLL and then call it from Delphi app. It work really well.</p> <p>Anyway: good luck!!!</p>
QA:
Cross Platform, Language Agnostic GUI Markup Language?
<p>erm.. HTML? (trying to be funny here... while we wait for real answers..)</p>
QA:
Cross Platform, Language Agnostic GUI Markup Language?
<p>The <a href="http://www.wxwidgets.org/" rel="nofollow" title="wxWidgets">wxWidgets</a> (formerly known as wxWindows) library might be what you're looking for. There's a particularly good port for Python, <a href="http://wxpython.org/" rel="nofollow" title="wxPython">wxPython</a>, as well as versions for different languages -- C#, C++, Perl and Ruby come to mind -- and for various GUIs: Win32, Mac OS X, GTK+, X11, Motif, WinCE. The library's been around for a while and is pretty solid.</p>
QA:
Cross Platform, Language Agnostic GUI Markup Language?
<P>Not sure if this is what you're looking for, but there's <A href="http://glade.gnome.org/" rel="nofollow">Glade</A> (or <A href="http://gladewin32.sourceforge.net/" rel="nofollow">Windows download</A>) which is a designer for GTK+. It generates an XML file which can then be used to build the GUI in a number of different languages.</P>
QA:
Cross Platform, Language Agnostic GUI Markup Language?
<p><a href="http://en.wikipedia.org/wiki/Qt_%28toolkit%29">Qt</a> (pronounced "cute" by its creators[1]) is a cross-platform application development framework, widely used for the development of GUI programs.</p> <p>Qt uses <strong>C++</strong> with several non-standard extensions implemented by an additional pre-processor that generates standard C++ code before compilation. Qt can also be used in several other programming languages; bindings exist for <strong>Ada</strong> (QtAda)[4], C<strong>#</strong> (Qyoto/Kimono)[5], <strong>Java</strong> (Qt Jambi)[6], <strong>Pascal</strong>, <strong>Perl</strong>, <strong>PHP</strong> (PHP-Qt), <strong>Ruby</strong> (RubyQt), and <strong>Python</strong> (PyQt). It runs on all major platforms, and has extensive internationalization support. Non-GUI features include SQL database access, XML parsing, thread management, network support and a unified cross-platform API for file handling.</p>
QA:
Python, Unicode, and the Windows console
<p><strong>Note:</strong> This answer is sort of outdated (from 2008). Please use the solution below with care!!</p> <hr> <p>Here is a page that details the problem and a solution (search the page for the text <em>Wrapping sys.stdout into an instance</em>):</p> <p><a href="http://wiki.python.org/moin/PrintFails">PrintFails - Python Wiki</a></p> <p>Here's a code excerpt from that page:</p> <pre><code>$ python -c 'import sys, codecs, locale; print sys.stdout.encoding; \ sys.stdout = codecs.getwriter(locale.getpreferredencoding())(sys.stdout); \ line = u"\u0411\n"; print type(line), len(line); \ sys.stdout.write(line); print line' UTF-8 &lt;type 'unicode'&gt; 2 Б Б $ python -c 'import sys, codecs, locale; print sys.stdout.encoding; \ sys.stdout = codecs.getwriter(locale.getpreferredencoding())(sys.stdout); \ line = u"\u0411\n"; print type(line), len(line); \ sys.stdout.write(line); print line' | cat None &lt;type 'unicode'&gt; 2 Б Б </code></pre> <p>There's some more information on that page, well worth a read.</p>
QA:
Convert Bytes to Floating Point Numbers in Python
<p>You'll want the <a href="https://docs.python.org/3.4/library/struct.html" rel="nofollow">struct</a> package.</p>
QA:
Python: what is the difference between (1,2,3) and [1,2,3], and when should I use each?
<P>As others have mentioned, Lists and tuples are both containers which can be used to store python objects. Lists are extensible and their contents can change by assignment, on the other hand tuples are immutable.</P> <P>Also, lists cannot be used as keys in a dictionary whereas tuples can. </P>
QA:
Python: what is the difference between (1,2,3) and [1,2,3], and when should I use each?
<p>If you can find a solution that works with tuples, use them, as it forces immutability which kind of drives you down a more functional path. You almost never regret going down the functional/immutable path.</p>
QA:
Get size of a file before downloading in Python
<p>The size of the file is sent as the Content-Length header. Here is how to get it with urllib:</p> <pre><code>&gt;&gt;&gt; site = urllib.urlopen("http://python.org")<br>&gt;&gt;&gt; meta = site.info()<br>&gt;&gt;&gt; print meta.getheaders("Content-Length")<br>['16535']<br>&gt;&gt;&gt;<br></code></pre>
QA:
Get size of a file before downloading in Python
<p>Using the returned-urllib-object method <code>info()</code>, you can get various information on the retrived document. Example of grabbing the current Google logo:</p> <pre><code>&gt;&gt;&gt; import urllib<br>&gt;&gt;&gt; d = urllib.urlopen("http://www.google.co.uk/logos/olympics08_opening.gif")<br>&gt;&gt;&gt; print d.info()<br><br>Content-Type: image/gif<br>Last-Modified: Thu, 07 Aug 2008 16:20:19 GMT <br>Expires: Sun, 17 Jan 2038 19:14:07 GMT <br>Cache-Control: public <br>Date: Fri, 08 Aug 2008 13:40:41 GMT <br>Server: gws <br>Content-Length: 20172 <br>Connection: Close<br></code></pre> <p>It's a dict, so to get the size of the file, you do <code>urllibobject.info()['Content-Length']</code></p> <pre><code>print f.info()['Content-Length']<br></code></pre> <p>And to get the size of the local file (for comparison), you can use the os.stat() command:</p> <pre><code>os.stat("/the/local/file.zip").st_size<br></code></pre>
QA:
Get size of a file before downloading in Python
<p>Also if the server you are connecting to supports it, look at <a href="http://en.wikipedia.org/wiki/HTTP_ETag" rel="nofollow">Etags</a> and the <a href="http://en.wikipedia.org/wiki/List_of_HTTP_headers#Requests" rel="nofollow">If-Modified-Since</a> and <a href="http://en.wikipedia.org/wiki/List_of_HTTP_headers#Requests" rel="nofollow">If-None-Match</a> headers.</p> <p>Using these will take advantage of the webserver's caching rules and will return a <a href="http://en.wikipedia.org/wiki/List_of_HTTP_status_codes#3xx_Redirection" rel="nofollow">304 Not Modified</a> status code if the content hasn't changed.</p>
QA:
Get size of a file before downloading in Python
<p>I have reproduced what you are seeing:</p> <pre><code>import urllib, os<br>link = "http://python.org"<br>print "opening url:", link<br>site = urllib.urlopen(link)<br>meta = site.info()<br>print "Content-Length:", meta.getheaders("Content-Length")[0]<br><br>f = open("out.txt", "r")<br>print "File on disk:",len(f.read())<br>f.close()<br><br><br>f = open("out.txt", "w")<br>f.write(site.read())<br>site.close()<br>f.close()<br><br>f = open("out.txt", "r")<br>print "File on disk after download:",len(f.read())<br>f.close()<br><br>print "os.stat().st_size returns:", os.stat("out.txt").st_size<br></code></pre> <p>Outputs this:</p> <pre><code>opening url: http://python.org<br>Content-Length: 16535<br>File on disk: 16535<br>File on disk after download: 16535<br>os.stat().st_size returns: 16861<br></code></pre> <p>What am I doing wrong here? Is os.stat().st_size not returning the correct size?</p> <hr> <p>Edit: OK, I figured out what the problem was:</p> <pre><code>import urllib, os<br>link = "http://python.org"<br>print "opening url:", link<br>site = urllib.urlopen(link)<br>meta = site.info()<br>print "Content-Length:", meta.getheaders("Content-Length")[0]<br><br>f = open("out.txt", "rb")<br>print "File on disk:",len(f.read())<br>f.close()<br><br><br>f = open("out.txt", "wb")<br>f.write(site.read())<br>site.close()<br>f.close()<br><br>f = open("out.txt", "rb")<br>print "File on disk after download:",len(f.read())<br>f.close()<br><br>print "os.stat().st_size returns:", os.stat("out.txt").st_size<br></code></pre> <p>this outputs:</p> <pre><code>$ python test.py<br>opening url: http://python.org<br>Content-Length: 16535<br>File on disk: 16535<br>File on disk after download: 16535<br>os.stat().st_size returns: 16535<br></code></pre> <p>Make sure you are opening both files for binary read/write.</p> <pre><code>// open for binary write<br>open(filename, "wb")<br>// open for binary read<br>open(filename, "rb")<br></code></pre>
QA:
Best way to abstract season/show/episode data
<p>Why not use SQLite? There is good support in Python and you can write SQL queries to get the data out. Here is the Python docs for <a href="http://docs.python.org/lib/module-sqlite3.html" rel="nofollow">sqlite3</a></p> <hr> <p>If you don't want to use SQLite you could do an array of dicts.</p> <pre><code>episodes = []<br>episodes.append({'season':1, 'episode': 2, 'name':'Something'})<br>episodes.append({'season':1, 'episode': 2, 'name':'Something', 'actors':['Billy Bob', 'Sean Penn']})<br></code></pre> <p>That way you add metadata to any record and search it very easily</p> <pre><code>season_1 = [e for e in episodes if e['season'] == 1]<br>billy_bob = [e for e in episodes if 'actors' in e and 'Billy Bob' in e['actors']]<br><br>for episode in billy_bob:<br> print "Billy bob was in Season %s Episode %s" % (episode['season'], episode['episode'])<br></code></pre>
QA:
Any experiences with Protocol Buffers?
<p>Protocol buffers are intended to optimize communications between machines. They are really not intended for human interaction. Also, the format is binary, so it could not replace XML in that use case. </p> <p>I would also recommend <a href="http://en.wikipedia.org/wiki/JSON">JSON</a> as being the most compact text-based format.</p>
QA:
Cross Platform, Language Agnostic GUI Markup Language?
<p><a href="http://www.mozilla.org/projects/xul/" rel="nofollow">XML User Interface Language</a>. Don't know much about it so not sure if it meets your desires. Post back with your experience if you play with it.</p>
QA:
Best way to abstract season/show/episode data
<P>I have done something similar in the past and used an in-memory XML document as a quick and dirty hierachical database for storage. You can store each show/season/episode as an element (nested appropriately) and attributes of these things as xml attributes on the elements. Then you can use XQuery to get info back out.</P> <P><STRONG>NOTE:</STRONG> I'm not a Python guy so I don't know what your xml support is like.</P> <P><STRONG>NOTE 2:</STRONG> You'll want to profile this because it'll be bigger and slower than the solution you've already got. Likely enough if you are doing some high-volume processing then XML is probably not going to be your friend.</P>
QA:
Get a preview JPEG of a PDF on Windows?
<p>Is the PC likely to have Acrobat installed? I think Acrobat installs a shell extension so previews of the first page of a PDF document appear in Windows Explorer's thumbnail view. You can get thumbnails yourself via the IExtractImage COM API, which you'll need to wrap. <a href="http://www.vbaccelerator.com/home/net/code/libraries/shell_projects/Thumbnail_Extraction/article.asp" rel="nofollow" title="Domain Specific Development with Visual Studio DSL Tools.">VBAccelerator has an example in C#</a> that you could port to Python.</p>
QA:
Get a preview JPEG of a PDF on Windows?
<p>ImageMagick delegates the PDF->bitmap conversion to GhostScript anyway, so here's a command you can use (it's based on the actual command listed by the <code>ps:alpha</code> delegate in ImageMagick, just adjusted to use JPEG as output):</p> <pre><code>gs -q -dQUIET -dPARANOIDSAFER -dBATCH -dNOPAUSE -dNOPROMPT \ -dMaxBitmap=500000000 -dLastPage=1 -dAlignToPixels=0 -dGridFitTT=0 \ -sDEVICE=jpeg -dTextAlphaBits=4 -dGraphicsAlphaBits=4 -r72x72 \ -sOutputFile=$OUTPUT -f$INPUT </code></pre> <p>where <code>$OUTPUT</code> and <code>$INPUT</code> are the output and input filenames. Adjust the <code>72x72</code> to whatever resolution you need. (Obviously, strip out the backslashes if you're writing out the whole command as one line.)</p> <p>This is good for two reasons:</p> <ol> <li>You don't need to have ImageMagick installed anymore. Not that I have anything against ImageMagick (I love it to bits), but I believe in simple solutions.</li> <li>ImageMagick does a two-step conversion. First PDF->PPM, then PPM->JPEG. This way, the conversion is one-step.</li> </ol> <p>Other things to consider: with the files I've tested, PNG compresses better than JPEG. If you want to use PNG, change the <code>-sDEVICE=jpeg</code> to <code>-sDEVICE=png16m</code>.</p>
QA:
How do I use Python's itertools.groupby()?
<p>As Sebastjan said, <strong>you first have to sort your data. This is important.</strong></p> <p>The part I didn't get is that in the example construction</p> <pre><code>groups = [] uniquekeys = [] for k, g in groupby(data, keyfunc): groups.append(list(g)) # Store group iterator as a list uniquekeys.append(k) </code></pre> <p><code>k</code> is the current grouping key, and <code>g</code> is an iterator that you can use to iterate over the group defined by that grouping key. In other words, the <code>groupby</code> iterator itself returns iterators.</p> <p>Here's an example of that, using clearer variable names:</p> <pre><code>from itertools import groupby things = [("animal", "bear"), ("animal", "duck"), ("plant", "cactus"), ("vehicle", "speed boat"), ("vehicle", "school bus")] for key, group in groupby(things, lambda x: x[0]): for thing in group: print "A %s is a %s." % (thing[1], key) print " " </code></pre> <p>This will give you the output:</p> <blockquote> <p>A bear is a animal.<br> A duck is a animal.</p> <p>A cactus is a plant.</p> <p>A speed boat is a vehicle.<br> A school bus is a vehicle.</p> </blockquote> <p>In this example, <code>things</code> is a list of tuples where the first item in each tuple is the group the second item belongs to. </p> <p>The <code>groupby()</code> function takes two arguments: (1) the data to group and (2) the function to group it with. </p> <p>Here, <code>lambda x: x[0]</code> tells <code>groupby()</code> to use the first item in each tuple as the grouping key.</p> <p>In the above <code>for</code> statement, <code>groupby</code> returns three (key, group iterator) pairs - once for each unique key. You can use the returned iterator to iterate over each individual item in that group.</p> <p>Here's a slightly different example with the same data, using a list comprehension:</p> <pre><code>for key, group in groupby(things, lambda x: x[0]): listOfThings = " and ".join([thing[1] for thing in group]) print key + "s: " + listOfThings + "." </code></pre> <p>This will give you the output:</p> <blockquote> <p>animals: bear and duck.<br> plants: cactus.<br> vehicles: speed boat and school bus.</p> </blockquote>
QA:
Cross Platform, Language Agnostic GUI Markup Language?
<p>I read a little on XML User Interface Language (XUL) and it looks really robust and well supported. The main problem for me is it's tied to the Gecko rendering engine so it's cross platform the way wxWidgets, QT and GTK+ are cross platform. Also, there Python bindings don't seem as good as those other libraries.</p> <p>GladeXML and XRC seem like better markups</p>
QA:
Python, Unicode, and the Windows console
<p>The cause of your problem is <strong>NOT</strong> the Win console not willing to accept Unicode (as it does this since I guess Win2k by default). It is the default system encoding. Try this code and see what it gives you:</p> <pre><code>import sys sys.getdefaultencoding() </code></pre> <p>if it says ascii, there's your cause ;-) You have to create a file called sitecustomize.py and put it under python path (I put it under /usr/lib/python2.5/site-packages, but that is differen on Win - it is c:\python\lib\site-packages or something), with the following contents:</p> <pre><code>import sys sys.setdefaultencoding('utf-8') </code></pre> <p>and perhaps you might want to specify the encoding in your files as well:</p> <pre><code># -*- coding: UTF-8 -*- import sys,time </code></pre> <p>Edit: more info can be found <a href="http://www.diveintopython.net/xml_processing/unicode.html" rel="nofollow">in excellent the Dive into Python book</a></p>
QA:
Cross Platform, Language Agnostic GUI Markup Language?
<p>@Cristian and Antony Cramp: while XUL is a nice choice for UI development (cross-platform, open-source licensed, used in Firefox and other major software), it's certainly not language agnostic. You're tied to Gecko, with JS for scripting. There is experimental support for Python scripting, but it's only experimental, AFAIK.</p> <p>You can define the UI in XUL+JS and use back-end components written in C++ though (there are Python and Java bridges available too).</p>
QA:
Cross Platform, Language Agnostic GUI Markup Language?
<p>I seriously doubt you're going to find a markup language for GIU's that's <em>not</em> tied to a specific library. For such a thing to exist, there would need to be a standardized GUI markup language, with several implementations.</p>
QA:
Best way to abstract season/show/episode data
<p>I don't get this part here:</p> <blockquote> <p>This worked okay, but there was no easy way of checking if x[3][24] was supposed to exist or not (so I couldn't raise the season<em>not</em>found exception)</p> </blockquote> <p>There is a way to do it - called <strong>in</strong>:</p> <pre><code>&gt;&gt;&gt;x={} &gt;&gt;&gt;x[1]={} &gt;&gt;&gt;x[1][2]={} &gt;&gt;&gt;x {1: {2: {}}} &gt;&gt;&gt; 2 in x[1] True &gt;&gt;&gt; 3 in x[1] False </code></pre> <p>what seems to be the problem with that?</p>
QA:
Class views in Django
<p>Unless you want to do something a little complex, using the generic views are the way to go. They are far more powerful than their name implies, and if you are just displaying model data generic views will do the job.</p>
QA:
Python and MySQL
<p>You could try setting up your own python installation using <a href="http://peak.telecommunity.com/DevCenter/EasyInstall#creating-a-virtual-python" rel="nofollow">Virtual Python</a>. Check out how to setup Django using it <a href="http://forums.site5.com/showthread.php?t=10236" rel="nofollow">here</a>. That was written a long time ago, but it shows how I got MySQLdb setup without having root access or anything like it. Once you've got the basics going, you can install any python library you want.</p>
QA:
How to use Xpath in Python?
<p>The <a href="http://lxml.de/">lxml package</a> supports xpath. It seems to work pretty well, although I've had some trouble with the self:: axis. There's also <a href="http://pypi.python.org/pypi/Amara/1.1.6">Amara</a>, but I haven't used it personally.</p>
QA:
Accessing mp3 Meta-Data with Python
<p><a href="http://www.dotfunk.com/projects/mp3/" rel="nofollow">This toolkit</a> may do what you need. I can't say if it's the "best", but really, if it does what you need, that's all that matters, right?</p> <p>HTH</p>
QA:
Accessing mp3 Meta-Data with Python
<p>A simple example from the book Dive Into Python works ok for me, <a href="http://www.diveintopython.org/download/diveintopython-examples-5.4.zip" rel="nofollow">this</a> is the download link, the example is fileinfo.py. Don't know if it's the best, but it can do the basic job.</p> <p>The entire book is available online <a href="http://www.diveintopython.org/" rel="nofollow">here</a>.</p>
QA:
Accessing mp3 Meta-Data with Python
<p>It can depend on exactly what you want to do in addition to reading the metadata. If it is just simply the bitrate / name etc. that you need, and nothing else, something lightweight is probably best.</p> <p>If you're manipulating the mp3 past that PyMedia may be suitable.</p> <p>There are quite a few, whatever you do get, make sure and test it out on plenty of sample media. There are a few different versions of ID3 tags in particular, so make sure it's not too out of date. </p> <p>Personally I've used this small MP3Info class with luck. It is quite old though.</p> <p><a href="http://www.omniscia.org/~vivake/python/MP3Info.py" rel="nofollow">http://www.omniscia.org/~vivake/python/MP3Info.py</a></p>
QA:
Best way to abstract season/show/episode data
<p>Bartosz/To clarify "This worked okay, but there was no easy way of checking if x[3][24] was supposed to exist or not"</p> <p><code>x['some show'][3][24]</code> would return season 3, episode 24 of "some show". If there was no season 3, I want the pseudo-dict to raise tvdb<em>seasonnotfound, if "some show" doesn't exist, then raise tvdb</em>shownotfound</p> <p>The current system of a series of classes, each with a <code>__getitem__</code> - Show checks <code>if self.seasons.has_key(requested_season_number)</code>, the Season class checks <code>if self.episodes.has_key(requested_episode_number)</code> and so on.</p> <p>It works, but it there seems to be a lot of repeated code (each class is basically the same, but raises a different error)</p>
QA:
How to use Xpath in Python?
<p><a href="http://pyxml.sourceforge.net" rel="nofollow" title="PyXML">PyXML</a> works well. </p> <p>You didn't say what platform you're using, however if you're on Ubuntu you can get it with <code>sudo apt-get install python-xml</code>. I'm sure other Linux distros have it as well. </p> <p>If you're on a Mac, xpath is already installed but not immediately accessible. You can set <code>PY_USE_XMLPLUS</code> in your environment or do it the Python way before you import xml.xpath:</p> <pre><code>if sys.platform.startswith('darwin'): os.environ['PY_USE_XMLPLUS'] = '1' </code></pre> <p>In the worst case you may have to build it yourself. This package is no longer maintained but still builds fine and works with modern 2.x Pythons. Basic docs are <a href="http://pyxml.sourceforge.net/topics/howto/section-XPath.html" rel="nofollow">here</a>.</p>
QA:
Accessing mp3 Meta-Data with Python
<p>What you're after is the <a href="http://id3-py.sourceforge.net/">ID3</a> module. It's very simple and will give you exactly what you need. Just copy the ID3.py file into your site-packages directory and you'll be able to do something like the following:</p> <pre><code>from ID3 import * try: id3info = ID3('file.mp3') print id3info # Change the tags id3info['TITLE'] = "Green Eggs and Ham" id3info['ARTIST'] = "Dr. Seuss" for k, v in id3info.items(): print k, ":", v except InvalidTagError, message: print "Invalid ID3 tag:", message </code></pre>
QA:
How do I treat an integer as an array of bytes in Python?
<p>This will do what you want:</p> <pre><code>signum = status &amp; 0xff exitstatus = (status &amp; 0xff00) &gt;&gt; 8 </code></pre>
QA:
How do I treat an integer as an array of bytes in Python?
<p>You can unpack the status using <a href="http://docs.python.org/ref/shifting.html" rel="nofollow">bit-shifting</a> and <a href="http://docs.python.org/ref/bitwise.html" rel="nofollow">masking</a> operators.</p> <pre><code>low = status &amp; 0x00FF high = (status &amp; 0xFF00) &gt;&gt; 8 </code></pre> <p>I'm not a Python programmer, so I hope got the syntax correct.</p>
QA:
How do I treat an integer as an array of bytes in Python?
<p>The folks before me've nailed it, but if you really want it on one line, you can do this:</p> <pre><code>(signum, exitstatus) = (status &amp; 0xFF, (status &gt;&gt; 8) &amp; 0xFF) </code></pre> <p>EDIT: Had it backwards.</p>
QA:
How do I treat an integer as an array of bytes in Python?
<p>To answer your general question, you can use <a href="http://en.wikipedia.org/wiki/Bit_twiddling" rel="nofollow">bit manipulation</a> techniques:</p> <pre><code>pid, status = os.wait() exitstatus, signum = status &amp; 0xFF, (status &amp; 0xFF00) &gt;&gt; 8 </code></pre> <p>However, there are also <a href="http://docs.python.org/lib/os-process.html#l2h-2780" rel="nofollow">built-in functions</a> for interpreting exit status values:</p> <pre><code>pid, status = os.wait() exitstatus, signum = os.WEXITSTATUS( status ), os.WTERMSIG( status ) </code></pre> <p>See also:</p> <ul> <li>os.WCOREDUMP()</li> <li>os.WIFCONTINUED()</li> <li>os.WIFSTOPPED()</li> <li>os.WIFSIGNALED()</li> <li>os.WIFEXITED()</li> <li>os.WSTOPSIG()</li> </ul>
QA:
Best way to abstract season/show/episode data
<p>OK, what you need is <code>classobj</code> from new module. That would allow you to construct exception classes dynamically (<code>classobj</code> takes a string as an argument for the class name). </p> <pre><code>import new myexc=new.classobj("ExcName",(Exception,),{}) i=myexc("This is the exc msg!") raise i </code></pre> <p>this gives you:</p> <pre><code>Traceback (most recent call last): File "&lt;stdin&gt;", line 1, in &lt;module&gt; __main__.ExcName: This is the exc msg! </code></pre> <p>remember that you can always get the class name through:</p> <pre><code>self.__class__.__name__ </code></pre> <p>So, after some string mangling and concatenation, you should be able to obtain appropriate exception class name and construct a class object using that name and then raise that exception.</p> <p>P.S. - you can also raise strings, but this is deprecated.</p> <pre><code>raise(self.__class__.__name__+"Exception") </code></pre>
QA:
Accessing mp3 Meta-Data with Python
<p>I've used <a href="https://bitbucket.org/lazka/mutagen">mutagen</a> to edit tags in media files before. The nice thing about mutagen is that it can handle other formats, such as mp4, FLAC etc. I've written several scripts with a lot of success using this API.</p>
QA:
How to use Xpath in Python?
<p>The latest version of <a href="http://effbot.org/zone/element-xpath.htm">elementtree</a> supports XPath pretty well. Not being an XPath expert I can't say for sure if the implementation is full but it has satisfied most of my needs when working in Python. I've also use lxml and PyXML and I find etree nice because it's a standard module.</p> <p>NOTE: I've since found lxml and for me it's definitely the best XML lib out there for Python. It does XPath nicely as well (though again perhaps not a full implementation).</p>
QA:
How should I unit test a code-generator?
<p>I started writing up a summary of my experience with my own code generator, then went back and re-read your question and found you had already touched upon the same issues yourself, focus on the execution results instead of the code layout/look.</p> <p>Problem is, this is hard to test, the generated code might not be suited to actually run in the environment of the unit test system, and how do you encode the expected results?</p> <p>I've found that you need to break down the code generator into smaller pieces and unit test those. Unit testing a full code generator is more like integration testing than unit testing if you ask me.</p>
QA:
How should I unit test a code-generator?
<p>Yes, results are the ONLY thing that matters. The real chore is writing a framework that allows your generated code to run independently... spend your time there.</p>
QA:
How should I unit test a code-generator?
<p>If you are running on *nux you might consider dumping the unittest framework in favor of a bash script or makefile. on windows you might consider building a shell app/function that runs the generator and then uses the code (as another process) and unittest that.</p> <p>A third option would be to generate the code and then build an app from it that includes nothing but a unittest. Again you would need a shell script or whatnot to run this for each input. As to how to encode the expected behavior, it occurs to me that it could be done in much the same way as you would for the C++ code just using the generated interface rather than the C++ one.</p>
QA:
How should I unit test a code-generator?
<p>Recall that "unit testing" is only one kind of testing. You should be able to unit test the <strong>internal</strong> pieces of your code generator. What you're really looking at here is system level testing (a.k.a. regression testing). It's not just semantics... there are different mindsets, approaches, expectations, etc. It's certainly more work, but you probably need to bite the bullet and set up an end-to-end regression test suite: fixed C++ files -> SWIG interfaces -> python modules -> known output. You really want to check the known input (fixed C++ code) against expected output (what comes out of the final Python program). Checking the code generator results directly would be like diffing object files...</p>
QA:
How can I create a directly-executable cross-platform GUI app using Python?
<p>An alternative tool to py2exe is <a href="http://pypi.python.org/pypi/bbfreeze/">bbfreeze</a> which generates executables for windows and linux. It's newer than py2exe and handles eggs quite well. I've found it magically works better without configuration for a wide variety of applications.</p>
QA:
How can I create a directly-executable cross-platform GUI app using Python?
<p>I'm not sure that this is the best way to do it, but when I'm deploying Ruby GUI apps (not Python, but has the same "problem" as far as .exe's are concerned) on Windows, I just write a short launcher in C# that calls on my main script. It compiles to an executable, and I then have an application executable.</p>
QA:
Python: what is the difference between (1,2,3) and [1,2,3], and when should I use each?
<p>Whenever I need to pass in a collection of items to a function, if I want the function to not change the values passed in - I use tuples. </p> <p>Else if I want to have the function to alter the values, I use list. </p> <p>Always if you are using external libraries and need to pass in a list of values to a function and are unsure about the integrity of the data, use a tuple. </p>

No dataset card yet

New: Create and edit this dataset card directly on the website!

Contribute a Dataset Card
Downloads last month
0
Add dataset card