Dataset Viewer
Auto-converted to Parquet Duplicate
input_text
stringlengths
54
40.1k
target_text
stringlengths
5
29.4k
How can I find the full path to a font from its display name on a Mac? I am using the Photoshop's javascript API to find the fonts in a given PSD Given a font name returned by the API I want to find the actual physical font file that that font name corresponds to on the disc This is all happening in a python program...
open up a terminal (Applications>Utilities>Terminal) and type this in: ````locate InsertFontHere ```` This will spit out every file that has the name you want Warning: there may be alot to wade through
Get a preview JPEG of a PDF on Windows? I have a cross-platform (Python) application which needs to generate a JPEG preview of the first page of a PDF On the Mac I am spawning <a href="http://developer apple com/documentation/Darwin/Reference/ManPages/man1/sips 1 html">sips</a> Is there something similarly simple I c...
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> : <blockquote> ````Convert ...
Continuous Integration System for a Python Codebase I am starting work on a hobby project with a python codebase and would like to set up some form of continuous integration (i e running a battery of test-cases each time a check-in is made and sending nag e-mails to responsible persons when the tests fail) similar to ...
One possibility is Hudson It is written in Java but there is integration with Python projects: <blockquote> <a href="http://redsolo blogspot com/2007/11/hudson-embraces-python html" rel="nofollow">Hudson embraces Python</a> </blockquote> I have never tried it myself however (<strong>Update</strong> Sept 2011: Aft...
cx_Oracle: How do I iterate over a result set? There are several ways to iterate over a result set What are the tradeoff of each?
The canonical way is to use the built-in cursor iterator ````curs execute('select * from people') for row in curs: print row ```` <hr> You can use `fetchall()` to get all rows at once ````for row in curs fetchall(): print row ```` It can be convenient to use this to create a Python list containing the values returned...
Using 'in' to match an attribute of Python objects in an array I do not remember whether I was dreaming or not but I seem to recall there being a function which allowed something like ````foo in iter_attr(array of python objects attribute name)```` I have looked over the docs but this kind of thing does not fall unde...
No you were not dreaming Python has a pretty excellent list comprehension system that let us 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 are doing is saying "For item in list if criteria matches" and from that yo...
Class views in Django <a href="http://www djangoproject com/">Django</a> view points to a function which can be a problem if you want to change only a bit of functionality Yes I could have million keyword arguments and even more if statements in the function but I was thinking more of an object oriented approach F...
Sounds to me like you are trying to combine things that should not be combined If you need to do different processing in your view depending on if it is a User or Group object you are trying to look at then you should use two different view functions On the other hand there can be common idioms you would want to extr...
Python and MySQL I can get Python to work with Postgresql but I cannot get it to work with MySQL The main problem is that on the shared hosting account I have I do not have the ability to install things such as Django or PySQL I generally fail when installing them on my computer so maybe it is good I cannot install o...
I do not have any experience with <a href="http://www SiteGround com" rel="nofollow">http://www SiteGround com</a> as a web host personally This is just a guess but it is 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 MySQ...
How do I use Python's itertools groupby()? I have not been able to find an understandable explanation of how to actually use Python's `itertools groupby()` function What I am trying to do is this: - Take a list - in this case the children of an objectified `lxml` element - Divide it into groups based on some criteria...
Can you show us your code? The example on the Python docs is quite straightforward: ````groups = [] uniquekeys = [] for k g in groupby(data keyfunc): groups append(list(g)) # Store group iterator as a list uniquekeys append(k) ```` So in your case data is a list of nodes keyfunc is where the logic of your criteria ...
Adding a Method to an Existing Object Instance I have read that it is possible to add a method to an existing object (e g not in the class definition) in <strong>Python</strong> I think this is called <them>Monkey Patching</them> (or in some cases <them>Duck Punching</them>) I understand that it is not always a good...
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>: ````from SomeOtherProduct SomeModule import SomeClass def speak(self): return "ook ook eee eee eee!" SomeClass speak = speak...
How do you express binary literals in Python? How do you express an integer as a binary number with Python literals? I was easily able to find the answer for hex: ```` &gt;&gt;&gt; 0x12AF 4783 &gt;&gt;&gt; 0x100 256 ```` and octal: ```` &gt;&gt;&gt; 01267 695 &gt;&gt;&gt; 0100 64 ```` <strong>How do you use literals to...
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
Any experiences with Protocol Buffers? I was just looking through some information about Google's <a href="http://code google com/apis/protocolbuffers/">protocol buffers</a> data interchange format Has anyone played around with the code or even created a project around it? I am currently using XML in a Python project ...
<P>If you are looking for user facing interaction stick with xml It has more support understanding and general acceptance currently If it is 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 ...
How do I make a menu that does not require the user to press [enter] to make a selection? I have got a menu in Python That part was easy I am using `raw_input()` to get the selection from the user The problem is that `raw_input` (and input) require the user to press <kbd>Enter</kbd> after they make a selection Is t...
<strong>On Linux:</strong> - set raw mode - select and read the keystroke - restore normal settings ``` 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 tcs...
How to check what OS am I running on in Python? What do I need to look at to see if I am on Windows Unix etc?
````&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' ```` See: <a href="https://docs python org/2/library/platform html">platform — Access to underlying platform’s identifying data</a>
Python: what is the difference between (1 2 3) and [1 2 3] and when should I use each? In many places `(1 2 3)` and `[1 2 3]` can be used interchangeably When should I use one or the other and why?
The list [1 2 3] is dynamic and flexible but that flexibility comes at a speed cost The tuple (1 2 3) is fixed (immutable) and therefore faster
File size differences after copying a file to a server vía FTP I have created a PHP-script to update a webserver that is live inside a local directory I am migrating the script into Python It works fine for the most part but after a PUT command the size of the file appears to change Thus the size of the file is d...
Do you need to open the locfile in binary using `rb`? ````f = open (locfile "rb") ````
How can I create a directly-executable cross-platform GUI app using Python? Python works on multiple platforms and can be used for desktop and web applications thus I conclude that there is some way to compile it into an executable for Mac Windows and Linux The problem being I have no idea where to start or how to w...
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 <strong>Cross-platform GUI libraries with Python bindings (Windows Linux Mac)</strong> Of course there are many but the most popular that I have seen in wi...
Calling a function of a module from a string with the function's name in Python What is the best way to go about calling a function given a string with the function's name in a Python program For example let us say that I have a module `foo` and I have a string whose contents are `"bar"` What is the best way to go ...
Assuming module `foo` with method `bar`: ````import foo methodToCall = getattr(foo 'bar') result = methodToCall() ```` As far as that goes lines 2 and 3 can be compressed to: ````result = getattr(foo 'bar')() ```` if that makes more sense for your use case You can use `getattr` in this fashion on class instance bou...
Programmatically talking to a Serial Port in OS X or Linux I have a Prolite LED sign that I like to set up to show scrolling search queries from a apache logs and other fun statistics The problem is my G5 does not have a serial port so I have to use a usb to serial dongle It shows up as /dev/cu usbserial and /dev/t...
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...
How to sell Python to a client/boss/person with lots of cash When asked to create system XYZ and you ask to do it in Python over PHP or Ruby what are the main features you can mention when they require you to explain it?
Focus on the shorter time needed for development/prototype and possibly easier maintenance (none of this may apply against Ruby)
How do you set up Python scripts to work in Apache 2 0? I tried to follow a couple of googled up tutorials on setting up mod_python but failed every time Do you have a good step-by step rock-solid howto? My dev box is OS X production - Centos
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 Using CGI is straightforward Make sure your Apache config file has a cgi-bin set up If not follow their documentation (<a href="http:/...
Does anyone have experience creating a shared library in MATLAB? A researcher has created a small simulation in MATLAB and we want to make it accessible to others My plan is to take the simulation clean up a few things and turn it into a set of functions Then I plan to compile it into a C library and use SWIG to ...
I will not 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 Anyway: good luck!!!
Cross Platform Language Agnostic GUI Markup Language? I learned Swing back in the day but now I have moved to Python and want to make some apps with GUIs I have not had the time to learn a new GUI API so I have been using Jython but I would prefer to use CPython It would be great if I can have one simple markup tha...
erm HTML? (trying to be funny here while we wait for real answers )
Python Unicode and the Windows console When I try to print a Unicode string in a Windows console I get a `UnicodeEncodeError: 'charmap' codec cannot encode character ` error I assume this is because the Windows console does not accept Unicode-only characters What is the best way around this? Is there any way I...
<strong>Note:</strong> This answer is sort of outdated (from 2008) Please use the solution below with care!! <hr> Here is a page that details the problem and a solution (search the page for the text <them>Wrapping sys stdout into an instance</them>): <a href="http://wiki python org/moin/PrintFails">PrintFails - Python...
Convert Bytes to Floating Point Numbers in Python I have a binary file that I have to parse and I am using Python Is there a way to take 4 bytes and convert it to a single precision floating point number?
You will want the <a href="https://docs python org/3 4/library/struct html" rel="nofollow">struct</a> package
Get size of a file before downloading in Python I am downloading an entire directory from a web server It works OK but I cannot figure how to get the file size before download to compare if it was updated on the server or not Can this be done as if I was downloading the file from a FTP server? ````import urllib impo...
The size of the file is sent as the Content-Length header Here is how to get it with urllib: ````&gt;&gt;&gt; site = urllib urlopen("http://python org") &gt;&gt;&gt; meta = site info() &gt;&gt;&gt; print meta getheaders("Content-Length") ['16535'] &gt;&gt;&gt; ````
Best way to abstract season/show/episode data Basically I have written an API to www thetvdb com in Python The current code can be found <a href="http://github com/dbr/tvdb_api/tree/master/tvdb_api py">here</a> It grabs data from the API as requested and has to store the data somehow and make it available by doing...
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> <hr> If you do not want to use SQLite you could do an array of dicts ````episodes = [] episodes append({...
How to use Xpath in Python? What is the library? Is there a full implementation? How is the library used? Where is its website?
The <a href="http://lxml de/">lxml package</a> supports xpath It seems to work pretty well although I have had some trouble with the self:: axis There is also <a href="http://pypi python org/pypi/Amara/1 1 6">Amara</a> but I have not used it personally
Accessing mp3 Meta-Data with Python What is the best way to retrieve mp3 metadata in python? I have seen a couple frameworks out there but I am unsure as to which would be the best to use Any ideas?
<a href="http://www dotfunk com/projects/mp3/" rel="nofollow">This toolkit</a> may do what you need I cannot say if it is the "best" but really if it does what you need that is all that matters right? HTH
How do I treat an integer as an array of bytes in Python? I am trying to decode the result of the Python os wait() function This returns according to the Python docs: <blockquote> a tuple containing its pid and exit status indication: a 16-bit number whose low byte is the signal number that killed the process and w...
This will do what you want: ````signum = status &amp; 0xff exitstatus = (status &amp; 0xff00) &gt;&gt; 8 ````
How should I unit test a code-generator? This is a difficult and open-ended question I know but I thought I would throw it to the floor and see if anyone had any interesting suggestions I have developed a code-generator that takes our python interface to our C++ code (generated via SWIG) and generates code needed to ...
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 Problem is this is hard to test the generated code might not be suited t...
Can you check that an exception is thrown with doctest in Python? Is it possible to write a doctest unit test that will check that an exception is raised? For example if I have a function `foo(x)` that is supposed to raise an exception if `x<0` how would I write the doctest for that?
Yes You can do it The <a href="https://docs python org/3/library/doctest html">doctest module documentation</a> and Wikipedia has an <a href="http://en wikipedia org/wiki/Doctest#Example_2%3a_doctests_embedded_in_a_README txt_file">example</a> of it ```` &gt;&gt;&gt; x Traceback (most recent call last): NameErro...
Using an XML catalog with Python's lxml? Is there a way when I parse an XML document using lxml to validate that document against its DTD using an external catalog file? I need to be able to work the fixed attributes defined in a document’s DTD
Can you give an example? According to the <a href="http://codespeak net/lxml/validation html" rel="nofollow">lxml validation docs</a> lxml can handle DTD validation (specified in the XML doc or externally in code) and system catalogs which covers most cases I can think of ````f = StringIO("<!ELEMENT b EMPTY&gt;") dt...
Replacement for for if array iteration I love list comprehensions in Python because they concisely represent a transformation of a list However in other languages I frequently find myself writing something along the lines of: ````foreach (int x in intArray) if (x &gt; 3) //generic condition on x x++ //do other p...
Depends on the language and what you need to do a "map" as it is called in many languages could be what you are looking for I do not know C# but according to <a href="http://blogs msdn com/devdev/archive/2006/06/30/652802 aspx" rel="nofollow">this</a> page NET 2 0 calls map "ConvertAll" The meaning of "map" is pr...
Python version of PHP's stripslashes I wrote a piece of code to convert PHP's striplashes into valid Python [backslash] escapes: ````cleaned = stringwithslashes cleaned = cleaned replace('\\n' '\n') cleaned = cleaned replace('\\r' '\n') cleaned = cleaned replace('\\' '') ```` How can I condense it?
You can obviously concatenate everything together: ````cleaned = stringwithslashes replace("\\n" "\n") replace("\\r" "\n") replace("\\" "") ```` Is that what you were after? Or were you hoping for something more terse?
Python Regular Expressions to implement string unescaping I am trying to implement string unescaping with Python regex and backreferences and it does not seem to want to work very well I am sure it is something I am doing wrong but I cannot figure out what ````&gt;&gt;&gt; import re &gt;&gt;&gt; mystring = r"This ...
Well I think you might have missed the r or miscounted the backslashes ````"\\n" == r"\n" &gt;&gt;&gt; import re &gt;&gt;&gt; mystring = r"This is \\n a test \\r" &gt;&gt;&gt; p = re compile( r"[\\][\\]( )" ) &gt;&gt;&gt; print p sub( r"\\\1" mystring ) This is \n a test \are &gt;&gt;&gt; ```` Which if I understo...
Can you explain closures (as they relate to Python)? I have been reading a lot about closures and I think I understand them but without clouding the picture for myself and others I am hoping someone can explain closures as succinctly and clearly as possible I am looking for a simple explanation that might help me un...
It is simple: A function that references variables from a containing scope potentially after flow-of-control has left that scope That last bit is very useful: ````&gt;&gt;&gt; def makeConstantAdder(x): constant = x def adder(y): return y constant return adder &gt;&gt;&gt; f = makeConstantAdder(12)...
Python Sound ("Bell") I would like to have a python program alert me when it has completed its task by making a beep noise Currently I use `import os` and then use a command line speech program to say "Process complete " I much rather it be a simple "bell " I know that there is a function that can be used in Cocoa ap...
Have you tried : ````import sys sys stdout write('\a') sys stdout flush() ```` That works for me here on Mac OS 10 5 Actually I think your original attempt works also with a little modification: ````print('\a') ```` (You just need the single quotes around the character sequence)
Is there a python module for regex matching in zip files I have over a million text files compressed into 40 zip files I also have a list of about 500 model names of phones I want to find out the number of times a particular model was mentioned in the text files Is there any python module which can do a regex match ...
You could loop through the zip files reading individual files using the zipfile module and running your regex on those eliminating to unzip all the files at once I am fairly certain that you cannot run a regex over the zipped data at least not meaningfully
Regex and unicode I have a script that parses the filenames of TV episodes (show name s01e02 avi for example) grabs the episode name (from the www thetvdb com API) and automatically renames them into something nicer (Show Name - [01x02] avi) The script works fine that is until you try and use it on files that have Un...
Use a subrange of [\u0000-\uFFFF] for what you want You can also use the re UNICODE compile flag <a href="http://docs python org/lib/re-syntax html">The docs</a> say that if UNICODE is set \w will match the characters [0-9_] plus whatever is classified as alphanumeric in the Unicode character properties database Se...
Pylons error - 'MySQL server has gone away' [I hope this is not too obscure&hellip; I will ask the newsgroup if nobody knows here] I am using Pylons (a python framework) to serve a simple web application but it seems to die from time to time with this in the error log: `(2006 'MySQL server has gone away')` I did a b...
You might want to check MySQL's timeout variables: ````show variables like '%timeout%'; ```` You are probably interested in `wait_timeout` (less likely but possible: `interactive_timeout`) On Debian and Ubuntu the defaults are 28800 (MySQL kills connections after 8 hours) but maybe the default for your platform is d...
How do I validate xml against a DTD file in Python I need to validate an XML string (and not a file) against a DTD description file How can that be done in `python`?
Another good option is <a href="http://lxml de/validation html" rel="nofollow">lxml's validation</a> which I find quite pleasant to use A simple example taken from the lxml site: ````from StringIO import StringIO from lxml import etree dtd = etree DTD(StringIO("""<!ELEMENT foo EMPTY&gt;""")) root = etree XML("<foo/&gt...
Prototyping with Python code before compiling I have been mulling over writing a peak fitting library for a while I know Python fairly well and plan on implementing everything in Python to begin with but envisage that I may have to re-implement some core routines in a compiled language eventually IIRC one of Python'...
In my experience there are two easy ways to call into C code from Python code There are other approaches all of which are more annoying and/or verbose The first and easiest is to compile a bunch of C code as a separate shared library and then call functions in that library using ctypes Unfortunately passing anyth...
Sanitising user input using Python What is the best way to sanitise user input for a Python-based web application? Is there a single function to remove HTML characters and any other necessary characters combinations to prevent an <a href="http://en wikipedia org/wiki/Cross-site_scripting" rel="nofollow">XSS</a> or SQL ...
If you are using a framework like <a href="http://www djangoproject com/" rel="nofollow">django</a> the framework can easily do this for you using standard filters In fact I am pretty sure django automatically does it unless you tell it not to Otherwise I would recommend using some sort of regex validation before ...
Create an encrypted ZIP file in Python I am creating an ZIP file with ZipFile in Python 2 5 it works ok so far: ````import zipfile os locfile = "test txt" loczip = os path splitext (locfile)[0] " zip" zip = zipfile ZipFile (loczip "w") zip write (locfile) zip close() ```` but I could not find how to encrypt the file...
You can use the <a href="http://www chilkatsoft com/python asp" rel="nofollow">Chilkat</a> library It is commercial but has a free evaluation and seems pretty nice Here is an example I got from <a href="http://www example-code com/python/zip asp" rel="nofollow">here</a>: ````import chilkat # Demonstrates how to crea...
What is the best way to distribute python command-line tools? My current setup py script works okay but it installs tvnamer py (the tool) as "tvnamer py" into site-packages or somewhere similar Can I make setup py install tvnamer py as tvnamer and/or is there a better way of installing command-line applications?
Try the `entry_points console_scripts` parameter in the setup() call As described in the <a href="http://peak telecommunity com/DevCenter/setuptools#automatic-script-creation">setuptools docs</a> this should do what I think you want To reproduce here: ````from setuptools import setup setup( # other arguments here ...
Build a Basic Python Iterator How would one create an iterative function (or iterator object) in python?
First of all the <a href="https://docs python org/3/library/itertools html">itertools module</a> is incredibly useful for all sorts of cases in which an iterator would be useful but here is all you need to create an iterator in python: <blockquote> yield </blockquote> Is not that cool? Yield can be used to replace a n...
A Transpose/Unzip Function in Python (inverse of zip) I have a list of 2-item tuples and I would like to convert them to 2 lists where the first contains the first item in each tuple and the second list holds the second item <strong>For example:</strong> ````original = [('a' 1) ('b' 2) ('c' 3) ( would' 4)] # an...
<a href="http://docs python org/library/functions html#zip">`zip`</a> is its own inverse! Provided you use the special * operator ````&gt;&gt;&gt; zip(*[('a' 1) ('b' 2) ('c' 3) ( would' 4)]) [('a' 'b' 'c' would') (1 2 3 4)] ```` The way this works is by calling `zip` with the arguments: ````zip(('a' 1) ...
How to check set of files conform to a naming scheme I have a bunch of files (TV episodes although that is fairly arbitrary) that I want to check match a specific naming/organisation scheme Currently: I have three arrays of regex one for valid filenames one for files missing an episode name and one for valid path...
maybe you should take the approach of defaulting to: "the filename is correct" and work from there to disprove that statement: with the fact that you only allow filenames with: 'show name' 'season number x episode number' and 'episode name' you know for certain that these items should be separated by a "-" (dash) so ...
Introducing Python The company I used to work with has two developers working fulltime and a handful of freelancers They are in the process of hiring a new lead developer to try to bring order and management to the development But currently one of the developers has seen the light of Django (the company has only d...
Well python is a high level language its not hard to learn and if the guys already have programming knowledge it should be much easier to learn i like django i think it should be a nice try to use django
What is the best way to grab/parse command line arguments passed to a Python script? What is the <strong>easiest tersest and most flexible</strong> method or library for parsing Python command line arguments?
Use `optparse` which comes with the standard library For example: ````#!/usr/bin/env python import optparse def main(): p = optparse OptionParser() p add_option('--person' '-p' default="world") options arguments = p parse_args() print 'Hello %s' % options person if __name__ == '__main__': main() ```` Source: <a hre...
Find broken symlinks with Python If I call `os stat()` on a broken `symlink` python throws an `OSError` exception This makes it useful for finding them However there are a few other reasons that `os stat()` might throw a similar exception Is there a more precise way of detecting broken `symlinks` with Python under...
Can I mention testing for hardlinks without python? /bin/test has the FILE1 -ef FILE2 condition that is true when files share an inode Therefore something like `find -type f -exec test \{} -ef /path/to/file \; -print` works for hard link testing to a specific file Which brings me to reading `man test` and the ment...
updating an auto_now DateTimeField in a parent model w/ Django I have got two models: Message and Attachment Each attachment is attached to a specific message using a ForeignKey on the Attachment model Both models have an auto_now DateTimeField called updated I am trying to make it so that when any attachment is sa...
You would also need to then save the message Then it that should work
Specifying a mySQL ENUM in a Django model How do I go about specifying and using an ENUM in a Django model?
From the <a href="https://docs djangoproject com/en/dev/ref/models/fields/#django db models Field choices" rel="nofollow">Django documentation</a>: ````MAYBECHOICE = ( ('y' 'Yes') ('n' 'No') ('you' 'Unknown') ) ```` And you define a charfield in your model : ````married = models CharField(max_length=1 choices=MA...
Why Java and Python garbage collection methods are different? Python uses the reference count method to handle object life time So an object that has no more use will be immediately destroyed But in Java the GC(garbage collector) destroys objects which are no longer used at a specific time Why does Java choose thi...
I think the article "<a href="http://www ibm com/developerworks/java/library/j-jtp10283/">Java theory and practice: A brief history of garbage collection</a>" from IBM should help explain some of the questions you have
Why does this python date/time conversion seem wrong? ````&gt;&gt;&gt; import time &gt;&gt;&gt; time strptime("01-31-2009" "%m-%d-%Y") (2009 1 31 0 0 0 5 31 -1) &gt;&gt;&gt; time mktime((2009 1 31 0 0 0 5 31 -1)) 1233378000 0 &gt;&gt;&gt; 60*60*24 # seconds in a day 86400 &gt;&gt;&gt; 1233378000 0 / 86...
````mktime( ) mktime(tuple) > floating point number Convert a time tuple in local time to seconds since the Epoch ```` local time fancy that The time tuple: ````The other representation is a tuple of 9 integers giving local time The tuple items are: year (four digits e g 1998) month (1-12) day (1-31) hours (0...
Unicode vs UTF-8 confusion in Python / Django? I stumbled over this passage in the <a href="http://www djangoproject com/documentation/tutorial01/">Django tutorial</a>: <blockquote> Django models have a default <strong>str</strong>() method that calls <strong>unicode</strong>() and converts the result to a UTF-8 bytest...
Python stores Unicode as UTF-16 str() will return the UTF-8 representation of the UTF-16 string
Format numbers to strings in Python I need to find out how to format numbers as strings My code is here: ````return str(hours)+":"+str(minutes)+":"+str(seconds)+" "+ampm ```` Hours and minutes are integers and seconds is a float the str() function will convert all of these numbers to the tenths (0 1) place So inste...
Formatting in Python is done via the <a href="http://docs python org/2/library/stdtypes html#string-formatting">string formatting (`%`) operator</a>: ````"%02d:%02d:%02d" % (hours minutes seconds) ```` /Edit: There is also <a href="https://docs python org/2/library/time html#time strftime">strftime</a>
How do I download a file over HTTP using Python? I have a small utility that I use to download a MP3 from a website on a schedule and then builds/updates a podcast XML file which I have obviously added to iTunes The text processing that creates/updates the XML file is written in Python I use wget inside a Windows ` b...
In Python 2 use urllib2 which comes with the standard library ````import urllib2 response = urllib2 urlopen('http://www example com/') html = response read() ```` This is the most basic way to use the library minus any error handling You can also do more complex stuff such as changing headers The documentation can...
How do content discovery engines like Zemanta and Open Calais work? I was wondering how as semantic service like Open Calais figures out the names of companies or people tech concepts keywords etc from a piece of text Is it because they have a large database that they match the text against? How would a service ...
Open Calais probably use language parsing technology and language statics to guess which words or phrases are Names Places Companies etc Then it is just another step to do some kind of search for those entities and return meta data Zementa probably does something similar but matches the phrases against meta-data...
What is the best way to duplicate fork() in windows? How do I implement some logic that will allow me to reproduce on Windows the functionality that I have on Linux with the `fork()` system call using Python? I am specifically trying to execute a method on the SAPI Com component while continuing the other logic in th...
Possibly a version of spawn() for python? <a href="http://en wikipedia org/wiki/Spawn_(operating_system)" rel="nofollow">http://en wikipedia org/wiki/Spawn_(operating_system)</a>
How can I graph the Lines of Code history for git repo? Basically I want to get the number of lines-of-code in the repository after each commit The only (really crappy) ways I have found is to use git filter-branch to run "wc -l *" and a script that run git reset --hard on each commit then ran wc -l To make it a bit...
The first thing that jumps to mind is the possibility of your git history having a nonlinear history You might have difficulty determining a sensible sequence of commits Having said that it seems like you could keep a log of commit ids and the corresponding lines of code in that commit In a post-commit hook starti...
Python code generator for Visual Studio? I had an idea if I add a python py file to my C# project and tag the file with a custom generator that would execute the python file and treat the output as the result of the code generation ie put it into a C# file that would allow me to do quite a lot of code generation...
I recall that in previous versions of VS there was a way to add custom build steps to the build process I used that a lot to do exactly the kind of automated code generation you describe I imagine the custom build step feature is still there in 2008
How to capture Python interpreter's and/or CMD EXE's output from a Python script? - Is it possible to capture Python interpreter's output from a Python script? - Is it possible to capture Windows CMD's output from a Python script? If so which librar(y|ies) should I look into?
In which context are you asking? Are you trying to capture the output from a program you start on the command line? if so then this is how to execute it: ````somescript py | your-capture-program-here ```` and to read the output just read from standard input If on the other hand you are executing that script or cmd...
Binary buffer in Python In Python you can use <a href="https://docs python org/library/struct html">StringIO</a> for a file-like buffer for character data <a href="https://docs python org/library/mmap html">Memory-mapped file</a> basically does similar thing for binary data but it requires a file that is used as the ...
Look at the struct package: <a href="https://docs python org/library/struct html" rel="nofollow">https://docs python org/library/struct html</a> it allows you to interpret strings as packed binary data Not sure if this will completely answer your question but you can use struct unpack() to convert binary data to pyth...
pyGame within a pyGTK application What is the best way to use PyGame (SDL) within a PyGTK application? I am searching for a method that allows me to have a drawing area in the GTK window and at the same time being able to manage both GTK and SDL events
You may be interested in <a href="http://www daa com au/pipermail/pygtk/2006-September/012888 html" rel="nofollow">this message thread</a> Looks like they recommend against it
Python super class reflection If I have Python code ````class A(): pass class B(): pass class C(A B): pass ```` and I have class `C` is there a way to iterate through it is super classed (`A` and `B`)? Something like pseudocode: ````&gt;&gt;&gt; magicGetSuperClasses(C) (<type 'A'&gt; <type 'B'&gt;) ```` One solution...
`C __bases__` is an array of the super classes so you could implement your hypothetical function like so: ````def magicGetSuperClasses(cls): return cls __bases__ ```` But I imagine it would be easier to just reference `cls __bases__` directly in most cases
Is there any difference between "foo is None" and "foo == None"? Is there any difference between: ````if foo is None: pass ```` and ````if foo == None: pass ```` The convention that I have seen in most Python code (and the code I myself write) is the former but I recently came across code which uses the latter None i...
`is` always returns `True` if it compares the same object instance Whereas `==` is ultimately determined by the `__eq__()` method i e ```` >>> class foo(object): def __eq__(self other): return True >>> f = foo() >>> f == None True >>> f is None False ````
wxpython: How do I examine dragged data in OnDragOver? I am a bit perplexed by drag and drop in wxPython (but perhaps this questions pertains to drag and drop in other GUI frameworks as well) The frameworks provides a couple of callbacks (OnEnter and OnDragOver) that purportedly allow me to inform the system whether t...
One solution which is a hack of limited usefulness is when a drag is initiated store the dragged data in a global or static reference somewhere This way in the OnEnter and OnDragOver handlers it is possible to get a reference to the data being dragged This is of course only useful for drags within the same appli...
Where can I learn more about PyPy's translation function? I have been having a hard time trying to understand PyPy's translation It looks like something absolutely revolutionary from simply reading the description however I am hard-pressed to find good documentation on actually translating a real world piece of code ...
Are you looking for Python specific translation or just the general "how do you compile some code to bytecode"? If the latter is your case check <a href="http://llvm org/docs/tutorial/" rel="nofollow">the LLVM tutorial</a> I especially find chapter two which teaches you to write a compiler for your own language in...
Does PHP have an equivalent to this type of Python string substitution? Python has this wonderful way of handling string substitutions using dictionaries: ````&gt;&gt;&gt; 'The %(site)s site %(adj)s because it %(adj)s' % {'site':'Stackoverflow' 'adj':'rocks'} 'The Stackoverflow site rocks because it rocks' ```` I love...
Some of the user-contributed notes and functions in <a href="http://us3 php net/sprintf" rel="nofollow">PHP's documentation for sprintf</a> come quite close Note: search the page for "sprintf2"
Is "safe_eval" really safe? I am looking for a "safe" eval function to implement spreadsheet-like calculations (using numpy/scipy) The functionality to do this (the <a href="http://docs python org/lib/module-rexec html" rel="nofollow">rexec module</a>) has been removed from Python since 2 3 due to apparently unfixabl...
Writing your own parser could be fun! It might be a better option because people are expecting to use the familiar spreadsheet syntax (Excel etc) and not Python when they are entering formulas I am not familiar with safe_eval but I would imagine that anything like this certainly has the potential for exploitation
Most Pythonic way equivalent for: while ((x = next()) != END) What is the best Python idiom for this C construct? ````while ((x = next()) != END) { } ```` I do not have the ability to recode next() update: and the answer from seems to be: ````for x in iter(next END): ````
Maybe it is not terribly idiomatic but I would be inclined to go with ````x = next() while x != END: do_something_with_x x = next() ```` but that is because I find that sort of thing easy to read
Best way to extract data from a FileMaker Pro database in a script? My job would be easier or at least less tedious if I could come up with an automated way (preferably in a Python script) to extract useful information from a FileMaker Pro database I am working on Linux machine and the FileMaker database is on the sa...
It has been a <strong>really</strong> long time since I did anything with FileMaker Pro but I know that it does have capabilities for an ODBC (and JDBC) connection to be made to it (however I do not know how or if that translates to the linux/perl/python world though) This article shows how to share/expose your Fi...
How do I create an xml document in python Here is my sample code: ````from xml dom minidom import * def make_xml(): doc = Document() node = doc createElement('foo') node innerText = 'bar' doc appendChild(node) return doc if __name__ == '__main__': make_xml() writexml(sys stdout) ```` when I run the above code I get thi...
Setting an attribute on an object will not give a compile-time or a run-time error it will just do nothing useful if the object does not access it (i e "`node noSuchAttr = 'bar'`" would also not give an error) Unless you need a specific feature of `minidom` I would look at `ElementTree`: ````import sys from xml etr...
What refactoring tools do you use for Python? I have a bunch of classes I want to rename Some of them have names that are small and that name is reused in other class names where I do not want that name changed Most of this lives in Python code but we also have some XML code that references class names Simple sear...
Most editors support the "whole word" search option It is usually a checkbox in the search dialog and what it does is only match the search term if it has leading and trailing spaces dots and most other delimiters It will probably work in your case
Python distutils - does anyone know how to use it? I wrote a quick program in python to add a gtk GUI to a cli program I was wondering how I can create an installer using distutils Since it is just a GUI frontend for a command line app it only works in *nix anyway so I am not worried about it being cross platform my...
See the <a href="http://docs python org/dist/simple-example html" rel="nofollow">distutils simple example</a> That is basically what it is like except real install scripts usually contain a bit more information I have not seen any that are fundamentally more complicated though In essence you just give it a list o...
Install Python to match directory layout in OS X 10 5 The default Python install on OS X 10 5 is 2 5 1 with a fat 32 bit (Intel and PPC) client I want to setup apache and mysql to run django In the past I have run apache and mysql to match this install in 32 bit mode (even stripping out the 64 bit stuff from apache t...
Not sure I entirely understand your question but cannot you simply build and install a 64 bit version and then create symbolic links so that /Library/Python/2 5 and below point to your freshly built version of python?
How do threads work in Python and what are common Python-threading specific pitfalls? I have been trying to wrap my head around how threads work in Python and it is hard to find good information on how they operate I may just be missing a link or something but it seems like the official documentation is not very th...
Below is a basic threading sample It will spawn 20 threads; each thread will output its thread number Run it and observe the order in which they print ````import threading class Foo (threading Thread): def __init__(self x): self __x = x threading Thread __init__(self) def run (self): print str(self __x) for x in xra...
What is the best way to use web services in python? I have a medium sized application that runs as a net web-service which I do not control and I want to create a loose pythonic API above it to enable easy scripting I wanted to know what is the best/most practical solution for using web-services in python Edit: I n...
If I have to expose APIs I prefer doing it as JSON Python has excellent support for JSON objects (JSON Objects are infact python dictionaries)
How can I render a tree structure (recursive) using a django template? I have a tree structure in memory that I would like to render in HTML using a Django template ````class Node(): name = "node name" children = [] ```` There will be some object `root` that is a `Node` and `children` is a list of `Node`s `root` wil...
I think the canonical answer is: "Do not" What you should probably do instead is unravel the thing in your <them>view</them> code so it is just a matter of iterating over (in|de)dents in the template I think I would do it by appending indents and dedents to a list while recursing through the tree and then sending th...
Programmatically editing Python source This is something that I think would be very useful Basically I would like there to be a way to edit Python source programmatically without requiring human intervention There are a couple of things I would like to do with this: - Edit the configuration of Python apps that use s...
Python's standard library provides pretty good facilities for working with Python source; note the <a href="https://docs python org/2/library/tokenize html" rel="nofollow">tokenize</a> and <a href="https://docs python org/2/library/parser html" rel="nofollow">parser</a> modules
Is it possible to run a Python script as a service in Windows? If possible how? I am sketching the architecture for a set of programs that share various interrelated objects stored in a database I want one of the programs to act as a service which provides a higher level interface for operations on these objects and...
Yes you can I do it using the pythoncom libraries that come included with <a href="http://www activestate com/Products/activepython/index mhtml" rel="nofollow">ActivePython</a> or can be installed with <a href="https://sourceforge net/projects/pywin32/" rel="nofollow">pywin32</a> (Python for Windows extensions) This ...
How to generate dynamic (parametrized) unit tests in python? I have some kind of test data and want to create an unit test for each item My first idea was to do it like this: ````import unittest l = [["foo" "a" "a" ] ["bar" "a" "b"] ["lee" "b" "b"]] class TestSequence(unittest TestCase): def testsample(self): ...
i use something like this: ````import unittest l = [["foo" "a" "a" ] ["bar" "a" "b"] ["lee" "b" "b"]] class TestSequense(unittest TestCase): pass def test_generator(a b): def test(self): self assertEqual(a b) return test if __name__ == '__main__': for t in l: test_name = 'test_%s' % t[0] test = test_generator(...
ssh hangs when command invoked directly but exits cleanly when run interactive I need to launch a server on the remote machine and retrieve the port number that the server process is lsitening on When invoked the server will listen on a random port and output the port number on stderr I want to automate the process...
<blockquote> ````s = p stderr readline() ```` </blockquote> I suspect it is the above line When you invoke a command directly through ssh you do not get your full pty (assuming Linux) and thus no stderr to read from When you log in interactively stdin stdout and stderr are set up for you and so your script work...
Extending base classes in Python I am trying to extend some "base" classes in Python: ````class xlist (list): def len(self): return len(self) def add(self *args): self extend(args) return None class xint (int): def add(self value): self = value return self x = xlist([1 2 3]) print x len() ## &gt;&gt;&gt; 3 ok print x...
Ints are immutable and you cannot modify them in place so you should go with option #2 (because option #1 is impossible without some trickery)
Find out how much memory is being used by an object in Python How would you go about finding out how much memory is being used by an object? I know it is possible to find out how much is used by a block of code but not by an instantiated object (anytime during its life) which is what I want
I have not any personal experience with either of the following but a simple search for a "Python [memory] profiler" yield: - PySizer "a memory profiler for Python " found at <a href="http://pysizer 8325 org/" rel="nofollow">http://pysizer 8325 org/</a> However the page seems to indicate that the project has not bee...
Are Python threads buggy? A reliable coder friend told me that Python's current multi-threading implementation is seriously buggy - enough to avoid using altogether What can said about this rumor?
I have used it in several applications and have never had nor heard of threading being anything other than 100% reliable as long as you know its limits You cannot spawn 1000 threads at the same time and expect your program to run properly on Windows however you can easily write a worker pool and just feed it 1000 op...
How to specify an authenticated proxy for a python http connection? What is the best way to specify a proxy with username and password for an http connection in python?
This works for me: ````import urllib2 proxy = urllib2 ProxyHandler({'http': 'http:// username:password@proxyurl:proxyport'}) auth = urllib2 HTTPBasicAuthHandler() opener = urllib2 build_opener(proxy auth urllib2 HTTPHandler) urllib2 install_opener(opener) conn = urllib2 urlopen('http://python org') return_str = conn ...
Python descriptor protocol analog in other languages? Is there something like the Python descriptor protocol implemented in other languages? It seems like a nice way to increase modularity/encapsulation without bloating your containing class' implementation but I have never heard of a similar thing in any other langua...
I have not heard of a direct equivalent either You could probably achieve the same effect with macros especially in a language like Lisp which has extremely powerful macros I would not be at all surprised if other languages start to incorporate something similar because it is so powerful
How do I make Windows aware of a service I have written in Python? In <a href="http://stackoverflow com/questions/32404/can-i-run-a-python-script-as-a-service-in-windows-how" rel="nofollow" title="Python scripts as Windows service">another question</a> I posted yesterday I got very good advice on how a Python script c...
Here is code to install a python-script as a service written in python :) <a href="http://code activestate com/recipes/551780/">http://code activestate com/recipes/551780/</a> This post could also help you out: <a href="http://essiene blogspot com/2005/04/python-windows-services html">http://essiene blogspot com/2005/...
Django ImageField core=False in newforms admin In the transition to newforms admin I am having difficulty figuring out how specify core=False for ImageFields I get the following error: ````TypeError: __init__() got an unexpected keyword argument 'core' ```` [Edit] However by just removing the core argument I get a "T...
This is simple I started getting this problems a few revisions ago Basically just remove the "core=True" parameter in the ImageField in the models and then follow the instructions <a href="http://docs djangoproject com/en/dev/ref/contrib/admin/#inlinemodeladmin-objects" rel="nofollow">here</a> to convert to what th...
Finding what methods an object has Given a Python object of any kind is there an easy way to get a list of all methods that this object has? Or if this is not possible is there at least an easy way to check if it has a particular method other than simply checking if an error occurs when the method is called?
It appears you can use this code replacing 'object' with the object you are interested in:- ````[method for method in dir(object) if callable(getattr(object method))] ```` I discovered it at <a href="http://www diveintopython net/power_of_introspection/index html">this site</a> hopefully that should provide some fur...
Scaffolding in pylons Is there anything similar to rails' scaffolding fo pylons? I have been poking around google but fofund only this thing caled dbsprockets which is fine although probably way to much for my needs What i really need is a basic CRUD thas is based on the SQLAlchemy model
I hear you I have followed the Pylons mailing list for a while looking for something similar There have been some attempts in the past (see <a href="http://adminpylon devjavu com/" rel="nofollow">AdminPylon</a> and <a href="http://code google com/p/restin/" rel="nofollow">Restin</a>) but none have really kept up with...
Validate (X)HTML in Python What is the best way to go about validating that a document follows some version of HTML (prefereably that I can specify)? I would like to be able to know where the failures occur as in a web-based validator except in a native Python app
XHTML is easy use <a href="http://lxml de/validation html" rel="nofollow">lxml</a> HTML is harder since there is traditionally not been as much interest in validation among the HTML crowd (run StackOverflow itself through a validator yikes) The easiest solution would be to execute external applications such as <a ...
Why does Python's iter() on a mapping return iterkeys() instead of iteritems()? It seems like if you want to get the keys of a mapping you ask for them; otherwise give me the <them>whole</them> mapping (constituted by a set of key-value pairs) Is there a historical reason for this?
Check out <a href="http://mail python org/pipermail/python-3000/2007-September/010209 html" rel="nofollow">this thread</a> for a discussion on the reasons behind this behavior (including that Guido likes it and it is <a href="http://mail python org/pipermail/python-3000/2007-September/010222 html" rel="nofollow">not l...
Ruby "is" equivalent Is there a Ruby equivalent for Python's "is"? It tests whether two objects are identical (i e have the same memory location)
Use `a equal? b` <a href="http://www ruby-doc org/core/classes/Object html">http://www ruby-doc org/core/classes/Object html</a> <blockquote> Unlike == the equal? method should never be overridden by subclasses: it is used to determine object identity (that is a equal?(b) iff a is the same object as b) </blockquote>...
Is Python good for big software projects (not web based)? Right now I am developing mostly in C/C++ but I wrote some small utilities in Python to automatize some tasks and I really love it as language (especially the productivity) Except for the performances (a problem that could be sometimes solved thanks to the eas...
In my opinion python is more than ready for developing complex applications I see pythons strength more on the server side than writing graphical clients But have a look at <a href="http://www resolversystems com/" rel="nofollow">http://www resolversystems com/</a> They develop a whole spreadsheet in python using th...
Why is my instance variable not in __dict__? If I create a class `A` as follows: ````class A: def __init__(self): self name = 'A' ```` Inspecting the `__dict__` member looks like `{'name': 'A'}` If however I create a class `B`: ````class B: name = 'B' ```` `__dict__` is empty What is the difference between the two an...
`B name` is a class attribute not an instance attribute It shows up in `B __dict__` but not in `b = B(); b __dict__` The distinction is obscured somewhat because when you access an attribute on an instance the class dict is a fallback So in the above example `b name` will give you the value of `B name`
How to escape os system() calls in Python? When using os system() it is often necessary to escape filenames and other arguments passed as parameters to commands How can I do this? Preferably something that would work on multiple operating systems/shells but in particular for bash I am currently doing the following b...
I believe that os system just invokes whatever command she will is configured for the user so I do not think you can do it in a platform independent way My command she will could be anything from bash emacs ruby or even quake3 Some of these programs are not expecting the kind of arguments you are passing to them ...
Django templates and variable attributes I am using Google App Engine and Django templates I have a table that I want to display the objects look something like: ````Object Result: Items = [item1 item2] Users = [{name='username' item1=3 item2=4} ] ```` The Django template is: ````<table&gt; <tr align="center"&gt; <t...
I am assuming that the part the does not work is `{{ user item }}` Django will be trying a dictionary lookup but using the string `"item"` and not the value of the `item` loop variable Django did the same thing when it resolved `{{ user name }}` to the `name` attribute of the `user` object rather than looking for a...
End of preview. Expand in Data Studio

No dataset card yet

Downloads last month
3