text
stringlengths
226
34.5k
best practice for dealing with common "structural" elements of pages? Question: Very basic question: I am coding a web app that has a handful of pages. These pages have the usual shared elements: eg, the site's header/masthead and a side-bar are present on all pages. The HTML is static (not dynamically generated, its "ajaxy-ness" is done client-side). What is the best way of importing/"including" those common elements into my pages? The solution I am using is to have the HTML files contain empty place- holders <div id="header"></div> <div id="leftSideBar"></div> (...) and then do in jquery's $(document).ready(): $.get("header.html", function(html) { $("#header").html(html); }); // .... Is this the best way to do this? I'm new to web development. : ) I guess I could also dig up a "macro-like" code-generation tool that I would run on the HTML files to replace, eg, "#header" with the contents of header.html. That way loading a page would require a single request for a single HTML file, which sounds better. What is the smart way to achieve this? I am sure this problem has been solved a thousand times. **EDIT:** The server-side is coded in Python+cherrypy. (I am assuming it is reasonable to try to keep away from dynamically generating HTML when doing "web 2.0-ish" web apps. Please correct me if I am wrong. As I said, I am very new to this environment.) Thank you for your insights, lara Answer: If you want to include files, please consider using some backend language such as PHP or ASP. Javascript is not really meant to do this even if this would work. <?php include 'other_file.php'; ?> Using javascript to do this will lead, I think, to a poor SEO and the loading of the page might look weird for the end user. If you really don't want to use a backend language, [some IDE have a way to handle templates](http://www.entheosweb.com/website%5Fdesign/dreamweaver%5Ftemplate.asp), you could look into that. Concerning frameworks, most of them have a way to handle templates. ASP.NET has the master page system, Ruby on Rails has layouts. Here's an example using Rails : <html> ... <div id="content"> <%= yield %> </div> ... </html> Here all the content of a subpage will go into the "yield". Here's a [link](http://guides.rubyonrails.org/layouts%5Fand%5Frendering.html) to learn more about that. Some frameworks can handle multiple place holders.
Python seek on remote file using HTTP Question: How do I seek to a particular position on a remote (HTTP) file so I can download only that part? Lets say the bytes on a remote file were: 1234567890 I wanna seek to 4 and download 3 bytes from there so I would have: 456 and also, how do I check if a remote file exists? I tried, os.path.isfile() but it returns False when I'm passing a remote file url. Answer: If you are downloading the remote file through HTTP, you need to set the `Range` header. Check [in this example](http://code.activestate.com/recipes/83208/) how it can be done. Looks like this: myUrlclass.addheader("Range","bytes=%s-" % (existSize)) **EDIT** : [I just found a better implementation](http://74.125.93.132/search?q=cache:1B4vbPKIz- YJ:linux.duke.edu/projects/urlgrabber/contents/urlgrabber/byterange.py+urllib+range+header&cd=2&hl=en&ct=clnk&client=firefox-a). This class is very simple to use, as it can be seen in the docstring. class HTTPRangeHandler(urllib2.BaseHandler): """Handler that enables HTTP Range headers. This was extremely simple. The Range header is a HTTP feature to begin with so all this class does is tell urllib2 that the "206 Partial Content" reponse from the HTTP server is what we expected. Example: import urllib2 import byterange range_handler = range.HTTPRangeHandler() opener = urllib2.build_opener(range_handler) # install it urllib2.install_opener(opener) # create Request and set Range header req = urllib2.Request('http://www.python.org/') req.header['Range'] = 'bytes=30-50' f = urllib2.urlopen(req) """ def http_error_206(self, req, fp, code, msg, hdrs): # 206 Partial Content Response r = urllib.addinfourl(fp, hdrs, req.get_full_url()) r.code = code r.msg = msg return r def http_error_416(self, req, fp, code, msg, hdrs): # HTTP's Range Not Satisfiable error raise RangeError('Requested Range Not Satisfiable') **Update** : The "better implementation" has moved to [github: excid3/urlgrabber](https://github.com/excid3/urlgrabber) in the "byterange.py" file.
How to render a doctype with Python's xml.dom.minidom? Question: I tried: document.doctype = xml.dom.minidom.DocumentType('html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "DTD/xhtml1-strict.dtd"') There is no doctype in the output. How to fix without inserting it by hand? Answer: You shouldn't instantiate classes from `minidom` directly. It's not a supported part of the API, the `ownerDocument`​s won't tie up and you can get some strange misbehaviours. Instead use the proper DOM Level 2 Core methods: >>> imp= minidom.getDOMImplementation('') >>> dt= imp.createDocumentType('html', '-//W3C//DTD XHTML 1.0 Strict//EN', 'http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd') (‘DTD/xhtml1-strict.dtd’ is a commonly-used but wrong `SystemId`. That relative URL would only be valid inside the xhtml1 folder at w3.org.) Now you've got a `DocumentType` node, you can add it to a document. According to the standard, the only guaranteed way of doing this is at document creation time: >>> doc= imp.createDocument('http://www.w3.org/1999/xhtml', 'html', dt) >>> print doc.toxml() <?xml version="1.0" ?><!DOCTYPE html PUBLIC '-//W3C//DTD XHTML 1.0 Strict//EN' 'http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd'><html/> If you want to change the doctype of an existing document, that's more trouble. The DOM standard doesn't require that `DocumentType` nodes with no `ownerDocument` be insertable into a document. However some DOMs allow it, eg. `pxdom`. `minidom` kind of allows it: >>> doc= minidom.parseString('<html xmlns="http://www.w3.org/1999/xhtml"><head/><body/></html>') >>> dt= minidom.getDOMImplementation('').createDocumentType('html', '-//W3C//DTD XHTML 1.0 Strict//EN', 'http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd') >>> doc.insertBefore(dt, doc.documentElement) <xml.dom.minidom.DocumentType instance> >>> print doc.toxml() <?xml version="1.0" ?><!DOCTYPE html PUBLIC '-//W3C//DTD XHTML 1.0 Strict//EN' 'http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd'><html xmlns="http://www.w3.org/1999/xhtml"><head/><body/></html> but with bugs: >>> doc.doctype # None >>> dt.ownerDocument # None which may or may not matter to you. Technically, the only reliable way per the standard to set a doctype on an existing document is to create a new document and import the whole of the old document into it! def setDoctype(document, doctype): imp= document.implementation newdocument= imp.createDocument(doctype.namespaceURI, doctype.name, doctype) newdocument.xmlVersion= document.xmlVersion refel= newdocument.documentElement for child in document.childNodes: if child.nodeType==child.ELEMENT_NODE: newdocument.replaceChild( newdocument.importNode(child, True), newdocument.documentElement ) refel= None elif child.nodeType!=child.DOCUMENT_TYPE_NODE: newdocument.insertBefore(newdocument.importNode(child, True), refel) return newdocument
How to load modules dynamically on package import? Question: Given the following example layout: test/ test.py formats/ __init__.py format_a.py format_b.py What I try to archive is, that whenever I `import formats`, the `__init__.py` looks for all available modules in the `formats` subdir, loads them and makes them available (right now simply through a variable, `supported_formats`). If theres a better, more pythonic or otherwise approach to dynamically loading stuff on runtime, based on physical available files, please tell. ### My Approach I tried something like this (in `__init__.py`): supported_formats = [__import__(f[:f.index('.py')]) for f in glob.glob('*.py')] So far I just get it to work, when I run `__init__.py` from the command line (from the formats subdir or from other directories) . But when I import it from `test.py`, it bails on me like this: `ImportError: No module named format_a.py` Same when I import it from the python interpreter, when I started the interpreter in an other directory but the `formats` subdir. Here's the whole code. It also looks for a specific class and stores one instance of each class in an dict, but loading the modules dynamically is the main part I don't get: def dload(get_cls=True, get_mod=True, key=None, fstring_mod='*.py', fstring_class=''): if p.dirname(__file__): path = p.split(p.abspath(__file__))[0] fstring_mod = p.join(path, fstring_mod) print >> sys.stderr, 'Path-Glob:', fstring_mod modules = [p.split(fn)[1][:fn.index('.py')] for fn in glob.glob(fstring_mod)] print >> sys.stderr, 'Modules:', ', '.join(modules) modules = [__import__(m) for m in modules] if get_cls: classes = {} if key else [] for m in modules: print >> sys.stderr, "-", m for c in [m.__dict__[c]() for c in m.__dict__ if c.startswith(fstring_class)]: print >> sys.stderr, " ", c if key: classes[getattr(c, key)] = c else: classes.append(c) if get_mod: return (modules, classes) else: return classes elif get_mod: return modules _supported_formats = dload(get_mod=False, key='fid', fstring_mod='format_*.py', fstring_class='Format') ### My Idea The whole messing with filesystem-paths and the like is probably messy anyway. I would like to handle this with module namespaces or something similar, but I'm kinda lost right now on how start and how to address the modules, so they reachable from anywhere. Answer: There are two fixes you need to make to your code: 1. You should call `__import__(m, globals(), locals())` instead of `__import__(m)`. This is needed for Python to locate the modules within the package. 2. Your code doesn't remove the .py extension properly since you call index() on the wrong string. If it will always be a .py extension, you can simply use `p.split(fn)[1][:-3]` instead.
How can I select all of the Sundays for a year using Python? Question: Using Python... How can I select all of the Sundays (or any day for that matter) in a year? [ '01/03/2010','01/10/2010','01/17/2010','01/24/2010', ...] These dates represent the Sundays for 2010. This could also apply to any day of the week I suppose. Answer: You can use `date` from the [`datetime`](http://docs.python.org/library/datetime.html) module to find the first Sunday in a year and then keep adding seven days, generating new Sundays: from datetime import date, timedelta def allsundays(year): d = date(year, 1, 1) # January 1st d += timedelta(days = 6 - d.weekday()) # First Sunday while d.year == year: yield d d += timedelta(days = 7) for d in allsundays(2010): print d
python equivalent of '#define func() ' or how to comment out a function call in python Question: my python code is interlaced with lots of function calls used for (debugging|profiling|tracing etc.) for example: import logging logging.root.setLevel(logging.DEBUG) logging.debug('hello') j = 0 for i in range(10): j += i logging.debug('i %d j %d' % (i,j)) print(j) logging.debug('bye') i want to #define these resource consuming functions out of the code. something like the c equivalent #define logging.debug(val) yes, i know the logging module logging level mechanism can be used to mask out loggings below set log level. but, im asking for a general way to have the python interpreter skip functions (that take time to run even if they dont do much) one idea is to redefine the functions i want to comment out into empty functions: def lazy(*args): pass logging.debug = lazy the above idea still calls a function, and may create a myriad of other problems Answer: Python does not have a preprocessor, although you could run your python source through an external preprocessor to get the same effect - e.g. `sed "/logging.debug/d"` will strip out all the debug logging commands. This is not very elegant though - you will end up needing some sort of build system to run all your modules through the preprocessor and perhaps create a new directory tree of the processed .py files before running the main script. Alternatively if you put all your debug statements in an `if __debug__:` block they will get optimised out when python is run with the -O (optimise) flag. As an aside, I checked the code with the dis module to ensure that it did get optimised away. I discovered that both if __debug__: doStuff() and if 0: doStuff() are optimised, but if False: doStuff() is not. This is because False is a regular Python object, and you can in fact do this: >>> False = True >>> if False: print "Illogical, captain" Illogical, captain Which seems to me a flaw in the language - hopefully it is fixed in Python 3. **Edit:** This is fixed in Python 3: Assigning to True or False [now gives a SyntaxError](http://docs.python.org/dev/3.0/library/constants.html). Since True and False are constants in Python 3, it means that `if False: doStuff()` is now optimised: >>> def f(): ... if False: print( "illogical") ... >>> dis.dis(f) 2 0 LOAD_CONST 0 (None) 3 RETURN_VALUE
pycurl module not available after installation on Snow Leopard Question: I'm running Python 2.6.4 on Mac Snow Leopard. I installed pycurl using: sudo env ARCHFLAGS="-arch x86_64" easy_install setuptools pycurl==7.16.2.1 The installation completes with no issues and says pycurl is installed in subsequent installation attempts. However, when I try to "import pycurl" in a script, I get a message that pycurl isn't found. I'm not sure what else to do to fix this. Answer: I would suspect you have 2 versions of python on your system. How about removing easy install and reinstalling it. Remove the current easy install script by typing `which easy_install` and then `rm [easy install full path]`. To install easy install wget http://peak.telecommunity.com/dist/ez_setup.py python ez_setup.py Then, try your command again: sudo env ARCHFLAGS="-arch x86_64" easy_install setuptools pycurl==7.16.2.1
Deleting files which start with a name Python Question: I have a few files I want to delete, they have the same name at the start but have different version numbers. Does anyone know how to delete files using the start of their name? Eg. version_1.1 version_1.2 Is there a way of delting any file that starts with the name version? Thanks Answer: import os, glob for filename in glob.glob("mypath/version*"): os.remove(filename) Substitute the correct path (or `.` (= current directory)) for `mypath`. And make sure you don't get the path wrong :) This will raise an Exception if a file is currently in use.
Newbie needs help with Python Tutorial Question: I am a newbie going through a byte of python (3.0). This is the first programming language I have ever used. I am stuck at the point where you make a simple program that creates a backup zip file (p.75). I'm running Windows 7 (64 bit) with python 3.1. Prior to this I installed GNUWin32 + sources, and added C:\Program Files(x86)\GnuWin32\bin to my Path enviornmental variable. This is the program: #!C:\Python31\mystuff # Filename : my_backup_v1.py import os import time # backing up a couple small files that I made source = [r'C:\AB\a', r'C:\AB\b'] #my back up directory target_dir = 'C:\\Backup' #name of back up file target = target_dir + os.sep + time.strftime('%Y%m%d%H%M%S') + '.zip' zip_command = "zip -qr {0} {1}".format(target,' '.join(source)) print(zip_command) if os.system(zip_command) == 0: print('Successful backup to', target) else: print('Backup failed!') print('source files are', source) print('target directory is', target_dir) print('target is', target) Output: zip -qr C:\Backup\20100106143030.zip C:\AB\a C:\AB\b Backup failed! source files are ['C:\\AB\\a', 'C:\\AB\\b'] target directory is C:\Backup target is C:\Backup\20100106143030.zip The Tutorial includes a little bit troubleshooting advice: copy and paste the zip_command in the python shell prompt to see if that atleast works: >>> zip -qr C:\Backup\20100106143030.zip C:\AB\a C:\AB\b SyntaxError: invalid syntax (<pyshell#17>, line 1) Since that didn't work, the tutorial said to read the GNUWin32 manual for additional help. I've looked through it and have yet to see anything that will help me out. To see if the zip function is working I did help(zip) and got the following: >>> help(zip) Help on class zip in module builtins: class zip(object) | zip(iter1 [,iter2 [...]]) --> zip object | | Return a zip object whose .__next__() method returns a tuple where | the i-th element comes from the i-th iterable argument. The .__next__() | method continues until the shortest iterable in the argument sequence | is exhausted and then it raises StopIteration. | | Methods defined here: | | __getattribute__(...) | x.__getattribute__('name') <==> x.name | | __iter__(...) | x.__iter__() <==> iter(x) | | __next__(...) | x.__next__() <==> next(x) | | ---------------------------------------------------------------------- | Data and other attributes defined here: | | __new__ = <built-in method __new__ of type object at 0x1E1B8D80> | T.__new__(S, ...) -> a new object with type S, a subtype of T Unfortuneatly I can not really understand the 'help' yet. However I played around a bit with the zip function to see how it works. >>> zip (r'C:AB\a') <zip object at 0x029CE8C8> So it appears that the zip function works, but I guess I'm not using it correctly. Please help me out, and keep in mind I haven't had much experience with programming yet. If you would like to view the tutorial you can find it at www.swaroopch.com/notes/Python . Answer: >>> zip -qr C:\Backup\20100106143030.zip C:\AB\a C:\AB\b sounds like a command you should type in your operating system's shell, not in python's shell. Maybe you can try os.system('zip -qr C:\Backup\20100106143030.zip C:\AB\a C:\AB\b') in the python shell...
sftp using ftplib Question: Hi All I need to download a file from a host using sFTP. Do you know if is it possible to do that using python ftplib? I saw [an example here](http://stackoverflow.com/questions/432385/sftp-in-python- platform-independent), but when I try to connect I receive `EOFError`. I tried this code: import ftplib ftp = ftplib.FTP() ftp.connect( "1.2.3.4", "22" ) This method returns with an error after long time so I cannot perform a call to login. I cannot try the constructor `FTP([host[, user[, passwd[, acct[, timeout]]]]])` because my port is 22 but `ftplib` default is 21. If I follow the example ftp = ftplib.FTP("1.2.3.4") ftp = ftplib.FTP("1.2.3.4","22") I receive a connection refused so I cannot enter any username password. Can you help me? Thank you very much Answer: As [the question you linked to](http://stackoverflow.com/questions/432385/sftp-in-python-platform- independent) states, ftplib doesn't support sftp (which is FTP over SSH and has nothing to do with FTPS, FTP over SSL). Use the [recommended](http://stackoverflow.com/questions/432385/sftp-in-python- platform-independent/432403#432403) [paramiko](http://www.lag.net/paramiko/) instead.
Using 'super' when subclassing python class that is not derived from `object`(old-style?) Question: I'm playing with subclassing `OptionParser` from the std library module `optparser`. (Python 2.5.2) When I attempt it I get the exception: TypeError: super() argument 1 must be type, not classobj Looking at `OptionParser`, it is not derived from `object`. So I added `object` as a parent class, (shown below) and `super` works properly. from optparse import OptionParser, Option class MyOptionParser(OptionParser, object): """Class to change """ def __init__(self, usage=None, option_list=None, option_class=Option, version=None, conflict_handler="error", description=None, formatter=None, add_help_option=True, prog=None, epilog=None, ): super(MyOptionParser, self).__init__(usage, option_list, option_class, version, conflict_handler, description, formatter, add_help_option, prog, epilog) if __name__ == '__main__': """Run a quick test """ parser = MyOptionParser() parser.add_option("-t", "--test", type="string", dest="test") (options, args) = parser.parse_args() print "The test option is: %s" % options.test Is this the correct way to go about it? Answer: Yes I dont see why it would not work. You just need to add couple of spaces right before that super call - as it's written right now, it is not part of your custom **init** method. Also, a shortcut you might want to use is **kwargs - you can do kwargs key check in your method if thats what you desire to do: class MyOptionParser(OptionParser, object): """Class to change """ def __init__(self, **kwargs): # You can limit kwargs keys here super(MyOptionParser, self).__init__(**kwargs)
Python Matplotlib rectangular binning Question: I've got a series of (x,y) values that I want to plot a 2d histogram of using python's matplotlib. Using hexbin, I get something like this: ![alt text](http://img121.imageshack.us/img121/1339/hexbin.png) But I'm looking for something like this: ![alt text](http://img17.imageshack.us/img17/1927/recthist.png) Example Code: from matplotlib import pyplot as plt import random foo = lambda : random.gauss(0.0,1.0) x = [foo() for i in xrange(5000)] y = [foo() for i in xrange(5000)] pairs = zip(x,y) #using hexbin I supply the x,y series and it does the binning for me hexfig = plt.figure() hexplt = hexfig.add_subplot(1,1,1) hexplt.hexbin(x, y, gridsize = 20) #to use imshow I have to bin the data myself def histBin(pairsData,xbins,ybins=None): if (ybins == None): ybins = xbins xdata, ydata = zip(*pairsData) xmin,xmax = min(xdata),max(xdata) xwidth = xmax-xmin ymin,ymax = min(ydata),max(ydata) ywidth = ymax-ymin def xbin(xval): xbin = int(xbins*(xval-xmin)/xwidth) return max(min(xbin,xbins-1),0) def ybin(yval): ybin = int(ybins*(yval-ymin)/ywidth) return max(min(ybin,ybins-1),0) hist = [[0 for x in xrange(xbins)] for y in xrange(ybins)] for x,y in pairsData: hist[ybin(y)][xbin(x)] += 1 extent = (xmin,xmax,ymin,ymax) return hist,extent #plot using imshow imdata,extent = histBin(pairs,20) imfig = plt.figure() implt = imfig.add_subplot(1,1,1) implt.imshow(imdata,extent = extent, interpolation = 'nearest') plt.draw() plt.show() It seems like there should already be a way to do this without writing my own "binning" method and using imshow. Answer: Numpy has a function called [histogram2d](http://docs.scipy.org/doc/numpy/reference/generated/numpy.histogram2d.html), whose docstring also shows you how to visualize it using Matplotlib. Add `interpolation=nearest` to the imshow call to disable the interpolation.
Problem with AuiMDI frames in wxPython Question: I am creating a AuiMDIParent frame and inside that parent frame I have a AuiMDIChild Frame. Inside the child frame I have a panel which displays an image. My problem is that when I run my code (given below) I get the desired result, but when I try to close the main window that is the parent frame, nothing happens. Then when I close the child frame entire application is closed including parent frame (not just the child frame). I do not know why is this happening. Please help me figure out if any one has come across such problem. If you run my code you will have a better idea of the problem. Thanks. import wx import wx.aui class ParentFrame(wx.aui.AuiMDIParentFrame): ''' This is main frame ''' def __init__(self,parent,id,title): ''' Creates a Parent Frame which has child frames into it. ''' wx.aui.AuiMDIParentFrame.__init__(self,parent,id,title, size=(900,700), style=wx.DEFAULT_FRAME_STYLE | wx.NO_FULL_REPAINT_ON_RESIZE) self.SetMinSize((500,500)) self.CreateStatusBar() class NetworkVisualizationFrame(wx.aui.AuiMDIChildFrame): ''' This is a child frame ''' def __init__(self,parent=None,id=-1,title="Network Visualization",image="Default.png"): ''' Creates a child frame inside parent frame. ''' wx.aui.AuiMDIChildFrame.__init__(self,parent,id,title) (frameWidth,frameHeight) = self.GetSizeTuple() #========================================================= # Create an image panel #========================================================= imagePanelHeight = int(frameHeight) imagePanelWidth = int(0.7 * frameWidth) self.imagePanel = wx.Panel(self,id=-1,name="Image Panel", style=wx.BORDER_THEME, size=(imagePanelWidth,imagePanelHeight)) self.loadImage(image) self.Bind(wx.EVT_SIZE, self.onResize) self.Bind(wx.EVT_PAINT, self.onPaint) def loadImage(self,image): #================================================== # Find the aspect ratio of the image #================================================== self.png = wx.Image(image, wx.BITMAP_TYPE_PNG) imageHeight = self.png.GetHeight() imageWidth = self.png.GetWidth() self.aspectRatio = imageWidth/imageHeight self.bitmap = wx.BitmapFromImage(self.png) def onResize(self,event): (frameWidth,frameHeight) = self.GetSizeTuple() imagePanelWidth = int(0.7 * frameWidth) imagePanelHeight = int(frameHeight) self.imagePanel.SetSize((imagePanelWidth,imagePanelHeight)) (w, h) = self.getBestSize() self.imagePanel.SetSize((w,h)) self.scaledPNG = self.png.Scale(w, h) self.bitmap = wx.BitmapFromImage(self.scaledPNG) self.Refresh() def onPaint(self,event): dc = wx.PaintDC(self.imagePanel) dc.DrawBitmap(self.bitmap, 0, 0, useMask=False) def getBestSize(self): (w,h) = self.imagePanel.GetSizeTuple() # Keep the height same and change width of the image according to aspect ratio newWidth = int (self.aspectRatio * h) newSize = (newWidth,h) return newSize app = wx.PySimpleApp() parentFrame = ParentFrame(None,-1,"Main Frame") NetworkVisualizationFrame(parentFrame,-1,"Network Visualization","Artifacts_vs_Elaborations_36855.png") parentFrame.Show() app.MainLoop() Answer: Its probably because you have the child frame parented to 'None' instead of the mdi parent frame.
ValueError in Django Question: I'm getting a strange error and can't figure out why. I'd appreciate any input. I've been stuck on this for a few days. Here is my code: models.py class Employee(models.Model): lastname = models.CharField(max_length=75) firstname = models.CharField(max_length=75) position = models.ForeignKey(Position) jurisdiction = models.ForeignKey(Jurisdiction) basepay = models.FloatField() ot = models.FloatField() benefits = models.FloatField() totalpay = models.FloatField() class Meta: ordering = ['lastname', 'firstname'] def __unicode__(self): return "%s %s" % (self.firstname, self.lastname) def full_name(self): return "%s, %s" % (self.lastname, self.firstname) def get_absolute_url(self): return "/salaries/employee/%s/" % self.id urls.py from django.conf.urls.defaults import * from djangodemo.salaries.models import Employee from django.views.generic import list_detail employee_info = { "queryset" : Employee.objects.all(), "template_name" : "salaries/employee.html", } urlpatterns = patterns('', (r'^salaries/employee/$', list_detail.object_list, 'employee_info'), ) employee.html {{ object_list }} When I run python manage.py runserver and look at `http://127.0.0.1:8000/salaries/employee` in my browser, I get this error: Traceback (most recent call last): File "F:\django\instantdjango\Python26\Lib\site-packages\django\core\servers\basehttp.py", line 279, in run self.result = application(self.environ, self.start_response) File "F:\django\instantdjango\Python26\Lib\site-packages\django\core\servers\basehttp.py", line 651, in __call__ return self.application(environ, start_response) File "F:\django\instantdjango\Python26\Lib\site-packages\django\core\handlers\wsgi.py", line 241, in __call__ response = self.get_response(request) File "F:\django\instantdjango\Python26\Lib\site-packages\django\core\handlers\base.py", line 73, in get_response response = middleware_method(request) File "F:\django\instantdjango\Python26\Lib\site-packages\django\middleware\common.py", line 57, in process_request _is_valid_path("%s/" % request.path_info)): File "F:\django\instantdjango\Python26\Lib\site-packages\django\middleware\common.py", line 142, in _is_valid_path urlresolvers.resolve(path) File "F:\django\instantdjango\Python26\Lib\site-packages\django\core\urlresolvers.py", line 294, in resolve return get_resolver(urlconf).resolve(path) File "F:\django\instantdjango\Python26\Lib\site-packages\django\core\urlresolvers.py", line 218, in resolve sub_match = pattern.resolve(new_path) File "F:\django\instantdjango\Python26\Lib\site-packages\django\core\urlresolvers.py", line 123, in resolve kwargs.update(self.default_args) ValueError: dictionary update sequence element #0 has length 1; 2 is required Answer: urlpatterns = patterns('', (r'^salaries/employee/$', list_detail.object_list, 'employee_info'), ) The third item in the tuple needs to be a dictionary, not a string. Try removing the single quotes around employee_info: urlpatterns = patterns('', (r'^salaries/employee/$', list_detail.object_list, employee_info), )
Searching for individual bipartite networks Question: I have data in the below form, which makes up a bipartite network. A1 - B1 A2 - B2 A2 - B1 A3 - B1 A4 - B2 A5 - B3 A6 - B3 A7 - B3 A7 - B3 A8 - B4 A9 - B3 What I would like to do is write something (ideally in python or C) or use an existing library to identify individual communities within the data. For instance A1,A2,A3,A4 are all part of the same community because they connect to B1,B2 similarly A5,A6,A7,A8,A9 all connected to B3 and B4. I am a bit confused having read lots various articles about network flow and graphs as to exactly where my problem sits. Is this just a form of Breadth- first search or is there a more efficient means of doing this? Thanks Answer: Using Python and the [igraph library](http://igraph.sourceforge.net), you may do the following: import igraph graph = igraph.Graph.Formula("A1-B1, A2-B2, A2-B1, A3-B1, A4-B2, A5-B3, A6-B3, A7-B3, A8-B4, A9-B3") comms = graph.clusters() for comm in comms: print ", ".join(graph.vs[comm]["name"]) A short explanation: `Graph.Formula` constructs a graph out of a string representation like the one above, but you can use any other method provided by igraph to construct your graph. An advantage of using `Graph.Formula` is that it automatically creates a `name` vertex attribute containing the vertex names. `graph.clusters()` searches for the connected components of the network and returns a `VertexClustering` object. This object can be used in a `for` loop to iterate over the components. In the core of the `for` loop, the `comm` variable will always contain the indices of the nodes in the current community. I select the vertices of the community using `graph.vs[comm]`, request their names as a list (`graph.vs[comm]["name"]`) and then join the names by commas.
Django forms: custom error list format Question: New to python and django. Using the forms module and going through the errors one by one (so not just dumping them at the top) I noticed [this solution](http://docs.djangoproject.com/en/dev/ref/forms/api/#customizing-the- error-list-format) to be able to set a custom format for errors, in my case, it'd be: `<dd class="error">errstr</dd>` And more or less copying the example provided, I have the following: **forms.py** ( I expanded it slightly just for my sake) class DefinitionErrorList(forms.util.ErrorList): def __unicode__(self): return self.view_as_dd() def view_as_dd(self): if not self: return u'' return u'<dd class="error">%s</dd>' % '<br />'.join([u'<span>%s</span>' % e for e in self]) **main.py** from poke.forms import PokeForm, DefinitionErrorList def create_new(response, useless): if response.method == 'POST': # They posted something, so collect it (duh) f = PokeForm(response.POST, error_class=DefinitionErrorList) if f.is_valid(): cd = f.cleaned_data **template** for reference <dt>A small message to remind yourself</dt> {{ form.message.errors }} <dd> <span class="input_border" style="width: 75%;"> {{ form.message }}</span> <span class="tooltip_span">{{ tooltip.message }}</span> </dd> The problem is is that with the above, if a field has an error, it still uses the default format (the ), and no matter what I try I can't get my one to be used. I'm pretty sure I missed something small or misunderstood some instructions. Thanks for any help and I'm sorry if I forgot any information! Edit: I'm using Django 1.1, if that helps any. And to make it (possibly) clearer, the errors are displaying fine, they just aren't looking the way I want them to. Answer: there has been a long lasting ticket on this. <http://code.djangoproject.com/ticket/6138> latest update says it's fixed. see if it works in trunk. if not, submit your bug. if it does, get the patch or wait til the next release. (although i thought the latest release was after the date of the last update on the ticket).
Access scanner from Java or Python (or something else if it's technically motivated) in Linux (but Windows would be nice) Question: I want to write a system for handling important documents in my home. This is the user story for getting a new document: 1. I "Add new document" and am prompted to scan it using my combined printer/scanner. 2. I view the scanned copy to see it's of good enough quality. Which it has. 3. The system tells me to mark it with number N, which I do. I also enter title, document type, description and when the document is no longer needed to be stored (could be never to always keep it). The problem is accessing the scanner. I do not know what the smoothest way is. Ideally it would support "all" scanners through some kind of standard interface. I do not know if that even exists. Should I do this in Java, Python or something else? My primary platform is Linux. But if it worked on Windows too, that would be nice. If I manage to create something useful I'll release it as GPL, so it's for a good cause too. ;-) Thank you for reading! Answer: Under Linux, the common interface to scanners is [SANE](http://www.sane- project.org/).
python-re: How do I match an alpha character Question: How can I match an alpha character with a regular expression. I want a character that is in `\w` but is not in `\d`. I want it unicode compatible that's why I cannot use `[a-zA-Z]`. Answer: Your first two sentences contradict each other. "in `\w` but is not in `\d`" includes underscore. I'm assuming from your third sentence that you don't want underscore. Using a Venn diagram on the back of an envelope helps. Let's look at what we DON'T want: (1) characters that are not matched by `\w` (i.e. don't want anything that's not alpha, digits, or underscore) => `\W` (2) digits => `\d` (3) underscore => `_` So what we don't want is anything in the character class `[\W\d_]` and consequently what we do want is anything in the character class `[^\W\d_]` Here's a simple example (Python 2.6). >>> import re >>> rx = re.compile("[^\W\d_]+", re.UNICODE) >>> rx.findall(u"abc_def,k9") [u'abc', u'def', u'k'] Further exploration reveals a few quirks of this approach: >>> import unicodedata as ucd >>> allsorts =u"\u0473\u0660\u06c9\u24e8\u4e0a\u3020\u3021" >>> for x in allsorts: ... print repr(x), ucd.category(x), ucd.name(x) ... u'\u0473' Ll CYRILLIC SMALL LETTER FITA u'\u0660' Nd ARABIC-INDIC DIGIT ZERO u'\u06c9' Lo ARABIC LETTER KIRGHIZ YU u'\u24e8' So CIRCLED LATIN SMALL LETTER Y u'\u4e0a' Lo CJK UNIFIED IDEOGRAPH-4E0A u'\u3020' So POSTAL MARK FACE u'\u3021' Nl HANGZHOU NUMERAL ONE >>> rx.findall(allsorts) [u'\u0473', u'\u06c9', u'\u4e0a', u'\u3021'] U+3021 (HANGZHOU NUMERAL ONE) is treated as numeric (hence it matches \w) but it appears that Python interprets "digit" to mean "decimal digit" (category Nd) so it doesn't match \d U+2438 (CIRCLED LATIN SMALL LETTER Y) doesn't match \w All CJK ideographs are classed as "letters" and thus match \w Whether any of the above 3 points are a concern or not, that approach is the best you will get out of the re module as currently released. Syntax like \p{letter} is in the future.
Using win32com and/or active_directory, how can I access an email folder by name? Question: In python w/ Outlook 2007, using win32com and/or active_directory, how can I get a reference to a sub-folder so that I may move a MailItem to this sub- folder? I have an inbox structure like: Inbox | +-- test | `-- todo I can access the inbox folder like: import win32com.client import active_directory session = win32com.client.gencache.EnsureDispatch("MAPI.session") win32com.client.gencache.EnsureDispatch("Outlook.Application") outlook = win32com.client.Dispatch("Outlook.Application") mapi = outlook.GetNamespace('MAPI') inbox = mapi.GetDefaultFolder(win32com.client.constants.olFolderInbox) print '\n'.join(dir(inbox)) But when I try to get subdirectory `test` per [Microsoft's example](http://msdn.microsoft.com/en-us/library/bb175261.aspx) the `inbox` object doesn't have the `Folders` interface or any way to get a subdirectory. How can I get a `Folder` object which points to `test` subdir? Answer: I realize this is an old question but I've been using the win32com package recently and found the documentation troublesome to say the least...My hope is that someone, someday can be saved the turmoil I experienced trying to wrap my head around MSDN's explanation Here's and example of a python script to traverse through Outlook folders, accessing e-mails where I please. _Disclaimer_ I shifted around the code and took out some sensitive info so if you're trying to copy and paste it and have it run, good luck. import win32com import win32com.client import string import os # the findFolder function takes the folder you're looking for as folderName, # and tries to find it with the MAPIFolder object searchIn def findFolder(folderName,searchIn): try: lowerAccount = searchIn.Folders for x in lowerAccount: if x.Name == folderName: print 'found it %s'%x.Name objective = x return objective return None except Exception as error: print "Looks like we had an issue accessing the searchIn object" print (error) return None def main(): outlook=win32com.client.Dispatch("Outlook.Application") ons = outlook.GetNamespace("MAPI") #this is the initial object you're accessing, IE if you want to access #the account the Inbox belongs too one = '<your account name here>@<your domain>.com' #Retrieves a MAPIFolder object for your account #Object functions and properties defined by MSDN at #https://msdn.microsoft.com/en-us/library/microsoft.office.interop.outlook.mapifolder_members(v=office.14).aspx Folder1 = findFolder(one,ons) #Now pass you're MAPIFolder object to the same function along with the folder you're searching for Folder2 = findFolder('Inbox',Folder1) #Rinse and repeat until you have an object for the folder you're interested in Folder3 = findFolder(<your inbox subfolder>,Folder2) #This call returns a list of mailItem objects refering to all of the mailitems(messages) in the specified MAPIFolder messages = Folder3.Items #Iterate through the messages contained within our subfolder for xx in messages: try: #Treat xx as a singular object, you can print the body, sender, cc's and pretty much every aspect of an e-mail #In my case I was writing the body to .txt files to parse... print xx.Subject,xx.Sender,xx.Body #Using move you can move e-mails around programatically, make sure to pass it a #MAPIFolder object as the destination, use findFolder() to get the object xx.Move(Folder3) except Exception as err: print "Error accessing mailItem" print err if __name__ == "__main__": main() PS Hope this doesn't do more harm than good.
Tab Completion in Python Command Line Interface - how to catch Tab events Question: I'm writing a little CLI in Python (as an extension to Mercurial) and would like to support tab-completion. Specifically, I would like catch tabs in the prompt and show a list of matching options (just like bash). Example: Enter section name: ext*TAB* extensions extras The problem is I'm not sure how to catch the Tab events. I'm using the `ui.prompt()` API of Mercurial, which is just calling `raw_input()` under the hood. As far as I know, `raw_input()` only returns on 'enter' and if a user enters a tab, the string returned simply includes a `"\t"`. Answer: For that you use the [`readline`](http://docs.python.org/library/readline.html) module. Simplest code I can think: import readline COMMANDS = ['extra', 'extension', 'stuff', 'errors', 'email', 'foobar', 'foo'] def complete(text, state): for cmd in COMMANDS: if cmd.startswith(text): if not state: return cmd else: state -= 1 readline.parse_and_bind("tab: complete") readline.set_completer(complete) raw_input('Enter section name: ') Example usage: Enter section name: <tab> email errors extension extra foo foobar stuff Enter section name: e<tab> email errors extension extra Enter section name: ext<tab> extension extra Besides completion, `readline` provides you with: * Line editing * Keybinding configuration (emacs and vi modes included) * History (up arrow to recall previous values) * History searching, saving and loading
Django: Unexpectedly persistent module variables Question: I noticed a strange behaviour today: It seems that, in the following example, the config.CLIENT variable stays persistent accross requests – even if the view gets passed an entirely different client_key, the query that gets the client is only executed once (per many requests), and then the config.CLIENT variable stays assigned. It does not seem to be a database caching issue. It happens with mod_python as well as with the test server (the variable is reassigned when the test server is restarted). What am I missing here? #views.py from my_app import config def get_client(client_key=None): if config.CLIENT == None: config.CLIENT = get_object_or_404(Client, key__exact=client_key, is_active__exact=True) return config.CLIENT def some_view(request, client_key): client = get_client(client_key) ... return some_response # config.py CLIENT = None Answer: Multiple requests are processed by the same process and global variables like your CLIENT live as long, as process does. You shouldn't rely on global variables, when processing requests - use either local ones, when you need to keep a variable for the time of building response or put data into the database, when something must persist across multiple requests. If you need to keep some value through the request you can either add it to thread locals [(here you should some examples, that adds user info to locals)](http://code.djangoproject.com/wiki/CookBookThreadlocalsAndUser) or simply pass it as a variable into other functions.
How to Correctly Use Lists in R? Question: Brief background: Many (most?) contemporary programming languages in widespread use have at least a handful of ADTs [abstract data types] in common, in particular, * **string** (a sequence comprised of characters) * **list** (an ordered collection of values), and * **map-based type** (an unordered array that maps keys to values) In the R programming language, the first two are implemented as `character` and `vector`, respectively. When I began learning R, two things were obvious almost from the start: `list` is the most important data type in R (because it is the parent class for the R `data.frame`), and second, I just couldn't understand how they worked, at least not well enough to use them correctly in my code. For one thing, it seemed to me that R's `list` data type was a straightforward implementation of the map ADT (`dictionary` in Python, `NSMutableDictionary` in Objective C, `hash` in Perl and Ruby, `object literal` in Javascript, and so forth). For instance, you create them just like you would a Python dictionary, by passing key-value pairs to a constructor (which in Python is `dict` not `list`): x = list("ev1"=10, "ev2"=15, "rv"="Group 1") And you access the items of an R List just like you would those of a Python dictionary, e.g., x['ev1']. Likewise, you can retrieve just the 'keys' or just the 'values' by: names(x) # fetch just the 'keys' of an R list # [1] "ev1" "ev2" "rv" unlist(x) # fetch just the 'values' of an R list # ev1 ev2 rv # "10" "15" "Group 1" x = list("a"=6, "b"=9, "c"=3) sum(unlist(x)) # [1] 18 but R `list`s are also **_unlike_** other map-type ADTs (from among the languages I've learned anyway). My guess is that this is a consequence of the initial spec for S, i.e., an intention to design a data/statistics DSL [domain-specific language] from the ground-up. _three_ significant differences between R `list`s and mapping types in other languages in widespread use (e.g,. Python, Perl, JavaScript): _first_ , `list`s in R are an _ordered_ collection, just like vectors, even though the values are keyed (ie, the keys can be any hashable value not just sequential integers). Nearly always, the mapping data type in other languages is _unordered_. _second_ , `list`s can be returned from functions even though you never passed in a `list` when you called the function, and _even though_ the function that returned the `list` doesn't contain an (explicit) `list` constructor (Of course, you can deal with this in practice by wrapping the returned result in a call to `unlist`): x = strsplit(LETTERS[1:10], "") # passing in an object of type 'character' class(x) # returns 'list', not a vector of length 2 # [1] list A _third_ peculiar feature of R's `list`s: it doesn't seem that they can be members of another ADT, and if you try to do that then the primary container is coerced to a `list`. E.g., x = c(0.5, 0.8, 0.23, list(0.5, 0.2, 0.9), recursive=TRUE) class(x) # [1] list my intention here is not to criticize the language or how it is documented; likewise, I'm not suggesting there is anything wrong with the `list` data structure or how it behaves. All I'm after is to correct is my understanding of how they work so I can correctly use them in my code. Here are the sorts of things I'd like to better understand: * What are the rules which determine when a function call will return a `list` (e.g., `strsplit` expression recited above)? * If I don't explicitly assign names to a `list` (e.g., `list(10,20,30,40)`) are the default names just sequential integers beginning with 1? (I assume, but I am far from certain that the answer is yes, otherwise we wouldn't be able to coerce this type of `list` to a vector w/ a call to `unlist`. * why do these two different operators, `[]`, and `[[]]`, return the _same_ result? `x = list(1, 2, 3, 4)` both expressions return "1": `x[1]` `x[[1]]` * why do these two expressions **not** return the same result? `x = list(1, 2, 3, 4)` `x2 = list(1:4)` Please don't point me to the R Documentation ([`?list`](http://www.inside-r.org/r-doc/base/list), [`R-intro`](http://cran.r-project.org/doc/manuals/r-devel/R-intro.html#Lists))--I have read it carefully and it does not help me answer the type of questions I recited just above. (lastly, I recently learned of and began using an R Package (available on CRAN) called [`hash`](http://mran.revolutionanalytics.com/packages/info/?hash) which implements _conventional_ map-type behavior via an S4 class; I can certainly recommend this Package.) Answer: Just to address the last part of your question, since that really points out the difference between a `list` and `vector` in R: > Why do these two expressions not return the same result? > > x = list(1, 2, 3, 4); x2 = list(1:4) A list can contain any other class as each element. So you can have a list where the first element is a character vector, the second is a data frame, etc. In this case, you have created two different lists. x has four vectors, each of length 1. x2 has 1 vector of length 4: > length(x[[1]]) [1] 1 > length(x2[[1]]) [1] 4 So these are completely different lists. R lists are very much like [a hash map](http://en.wikipedia.org/wiki/Hash_table) data structure in that each index value can be associated with any object. Here's a simple example of a list that contains 3 different classes (including a function): > complicated.list <- list("a"=1:4, "b"=1:3, "c"=matrix(1:4, nrow=2), "d"=search) > lapply(complicated.list, class) $a [1] "integer" $b [1] "integer" $c [1] "matrix" $d [1] "function" Given that the last element is the search function, I can call it like so: > complicated.list[["d"]]() [1] ".GlobalEnv" ... As a final comment on this: it should be noted that a `data.frame` is really a list (from the data.frame documentation): > A data frame is a list of variables of the same number of rows with unique > row names, given class ‘"data.frame"’ That's why columns in a data.frame can have different data types, while columns in a matrix cannot. As an example, here I try to create a matrix with numbers and characters: > a <- 1:4 > class(a) [1] "integer" > b <- c("a","b","c","d") > d <- cbind(a, b) > d a b [1,] "1" "a" [2,] "2" "b" [3,] "3" "c" [4,] "4" "d" > class(d[,1]) [1] "character" Note how I cannot change the data type in the first column to numeric because the second column has characters: > d[,1] <- as.numeric(d[,1]) > class(d[,1]) [1] "character"
Get HTML links within a specified <table> using minidom Question: I'm looking to use Python and xml.dom.minidom to get a list of links within a particular `<table>` specified by the table id. Based on some [excellent advice](http://stackoverflow.com/questions/1732348/regex-match-open-tags- except-xhtml-self-contained-tags/1732454#1732454), I'm trying to use the DOM instead of pattern matching. import urllib import xml.dom.minidom url = 'http://www.batstrading.com/market_data/shortsales' page = xml.dom.minidom.parse(urllib.urlopen(url)) I can get all the links by the tag name `page.getElementsByTagName('a')`, but I cannot limit the links returned by those only contained within the table with ID "monthly-short-sale". Using `getElementById` returns None. Is this because the "monthly-short-sale" ID is not defined within the DTD? If so, what would be the best way to extract this information? Here is the code that I'm currently using, which works, but sins against god: import urllib import xml.dom.minidom import datetime url = 'http://www.batstrading.com/market_data/shortsales' def getDownloadLink(alink, prefix = 'BATSsh'): """return (datetime.date, link) for the provided link if the link target starts with the data file prefix""" n = len(prefix) href = alink.getAttribute('href') if href.startswith(prefix) and (len(href) == 25): year = int(href[n:n+4]) month = int(href[n+4:n+6]) day = int(href[n+6:n+8]) date = datetime.date(year, month, day) return (date, url + '/' + href) page = xml.dom.minidom.parse(urllib.urlopen(url)) link = (getDownloadLink(a) for a in page.getElementsByTagName('a')) link = dict(i for i in link if i is not None) Answer: The problem is that minidom is a non-external-entity-reading XML parser. That means it doesn't even look at the DTD, so it doesn't know that in HTML the attribute with the name `id` corresponds to an `ID` schema type. A further consequence of this is that minidom won't know about the HTML- specific entities like `&eacute;` that are defined in the XHTML doctype, so you may lose text that way. If you don't care about this, you can continue using minidom and using an alternative way to get at the table, involving `getElementsByTagName` and checking `element.id` manually. (You could hack up your own `getElementById` function to do it the slow way.) Or you could use an XML parser that does allow external entities such as pxdom. However this means the parser will have to fetch and parse the DTD from W3 each time, which will be unpleasantly slow. Or you could go for an HTML parser, which has the HTML entities and ID-nesses built in, such as BeautifulSoup. This might be a better idea when you are dealing with real-world HTML pages served as `text/html`, which though they may claim to be XHTML often includes naughty bits that aren't well-formed.
Manually raising (throwing) an exception in Python Question: How can I raise an exception in Python so that it can later be caught via an `except` block? Answer: > # How do I manually throw/raise an exception in Python? [Use the most specific Exception constructor that semantically fits your issue](https://docs.python.org/3/library/exceptions.html#exception-hierarchy). Be specific in your message, e.g.: raise ValueError('A very specific bad thing happened') # Don't do this: Avoid raising a generic Exception, to catch it, you'll have to catch all other more specific exceptions that subclass it. ## Hiding bugs raise Exception('I know Python!') # don't, if you catch, likely to hide bugs. For example: def demo_bad_catch(): try: raise ValueError('represents a hidden bug, do not catch this') raise Exception('This is the exception you expect to handle') except Exception as error: print('caught this error: ' + repr(error)) >>> demo_bad_catch() caught this error: ValueError('represents a hidden bug, do not catch this',) ## Won't catch and more specific catches won't catch the general exception: def demo_no_catch(): try: raise Exception('general exceptions not caught by specific handling') except ValueError as e: print('we will not catch e') >>> demo_no_catch() Traceback (most recent call last): File "<stdin>", line 1, in <module> File "<stdin>", line 3, in demo_no_catch Exception: general exceptions not caught by specific handling # Best Practice: [Instead, use the most specific Exception constructor that semantically fits your issue](https://docs.python.org/3/library/exceptions.html#exception- hierarchy). raise ValueError('A very specific bad thing happened') which also handily allows an arbitrary number of arguments to be passed to the constructor. This works in Python 2 and 3. raise ValueError('A very specific bad thing happened', 'foo', 'bar', 'baz') These arguments are accessed by the `args` attribute on the Exception object. For example: try: some_code_that_may_raise_our_value_error() except ValueError as err: print(err.args) prints ('message', 'foo', 'bar', 'baz') In Python 2.5, an actual `message` attribute was added to BaseException in favor of encouraging users to subclass Exceptions and stop using `args`, but [the introduction of `message` and the original deprecation of args has been retracted](http://www.python.org/dev/peps/pep-0352/#retracted-ideas). ## When in `except` clause When inside an except clause, you might want to, e.g. log that a specific type of error happened, and then reraise. The best way to do this while preserving the stack trace is to use a bare raise statement, e.g.: try: do_something_in_app_that_breaks_easily() except AppError as error: logger.error(error) raise # just this! # raise AppError # Don't do this, you'll lose the stack trace! You can preserve the stacktrace (and error value) with `sys.exc_info()`, but this is way more error prone, prefer to use a bare `raise` to reraise. This is the syntax in Python 2: raise AppError, error, sys.exc_info()[2] # avoid this. # Equivalently, as error *is* the second object: raise sys.exc_info()[0], sys.exc_info()[1], sys.exc_info()[2] In [Python 3](https://docs.python.org/3/reference/simple_stmts.html#the-raise- statement): raise error.with_traceback(sys.exc_info()[2]) Again: avoid manually manipulating tracebacks. It's [less efficient](https://docs.python.org/2/reference/simple_stmts.html#the-raise- statement) and more error prone. And if you're using threading and `sys.exc_info` you may even get the wrong traceback (especially if you're using exception handling for control flow - which I'd personally tend to avoid.) ### Python 3, Exception chaining In Python 3, you can chain Exceptions, which preserve tracebacks: raise RuntimeError('specific message') from error But beware, this _does_ change the error type raised. ## Deprecated Methods: These can easily hide and even get into production code. You want to raise an exception/error, and doing them will raise an error, **but not the one intended!** [Valid in Python 2, but not in Python 3](http://www.python.org/dev/peps/pep-3109/) is the following: raise ValueError, 'message' # Don't do this, it's deprecated! Only [valid in much older versions of Python](https://docs.python.org/2/whatsnew/2.5.html#pep-352-exceptions-as-new- style-classes) (2.4 and lower), you may still see people raising strings: raise 'message' # really really wrong. don't do this. In all modern versions, this will actually raise a TypeError, because you're not raising a BaseException type. If you're not checking for the right exception and don't have a reviewer that's aware of the issue, it could get into production. # Example Usage: I raise Exceptions to warn consumers of my API if they're using it incorrectly: def api_func(foo): '''foo should be either 'baz' or 'bar'. returns something very useful.''' if foo not in _ALLOWED_ARGS: raise ValueError('{foo} wrong, use "baz" or "bar"'.format(foo=repr(foo))) # Create your own error types when apropos: > **"I want to make an error on purpose, so that it would go into the > except"** You can create your own error types, if you want to indicate something specific is wrong with your application, just subclass the appropriate point in the exception hierarchy: class MyAppLookupError(LookupError): '''raise this when there's a lookup error for my app''' and usage: if important_key not in resource_dict and not ok_to_be_missing: raise MyAppLookupError('resource is missing, and that is not ok.')
is there a way to view the source of a module from within the python console? Question: if I'm in the python console and I want to see how a particular module works, is there an easy way to dump the source? Answer: Some of the methods of [inspect](http://docs.python.org/library/inspect.html) module are well-suited for this purpose: import module import inspect src = inspect.getsource(module)
Installing SUDS in python 2.6.4 Question: I am having real trouble installing SUDS in python 2.6.4. I have tried to install the setup file but it says the location of python cannot be found. This is because I have changed the location of python. I have tried to use easy_install but am having no luck. Does anyone know a simple way to do this or have a link to clear installation instructions. Command that I entered was: python setup.py install The result I recieved was: running install error: cannot create or remove files in install directory The following error occurred while trying to add or remove files in the installation directory: [Errno 13] Permission denied: '/usr/local/lib/python2.6/site-packages/test-easy-install-9203.write-test' The installation directory you specified (via --install-dir, --prefix, or the distutils default setting) was: /usr/local/lib/python2.6/site-packages/ Perhaps your account does not have write access to this directory? If the installation directory is a system-owned directory, you may need to sign in as the administrator or "root" account. If you do not have administrative access to this machine, you may wish to choose a different installation directory, preferably one that is listed in your PYTHONPATH environment variable. For information on other options, you may wish to consult the documentation at: http://peak.telecommunity.com/EasyInstall.html And if I have to change the python path how exactly do you do this. I have tried what one site said to do and it was to first, create an altinstall.pth file in Python's site-packages directory, containing the following line: import os, site; site.addsitedir(os.path.expanduser('~/lib/python2.3')) Then it says modify distutils.cfg in the distutils directory with: [install] install_lib = ~/lib/python2.3 # This next line is optional but often quite useful; it directs EasyInstall # and the distutils to install scripts in the user's "bin" directory. For # Mac OS X framework Python builds, you should use /usr/local/bin instead, # because neither ~/bin nor the default script installation location are on # the system PATH. # install_scripts = ~/bin Answer: Have you tried setting PYTHONPATH to the location of python? Maybe this way it will know, where to install it. You are calling it with `python setup.py install`. Try `sudo python setup.py install`, if you are using some linux and you are sudoer.
Using SUDS to test WSDL Question: Does anyone know about a good SUDS tutorial. I am trying to run tests on WSDL files and I am having trouble finding any imformation on how to do this. Is SUDS much different to SOAPy and would anyone recommend it to run smoke tests on functions stored in WSDL files. I have read that SOAPAy is no longer supported in Python 2.6+. Is this true? I have a WSDL file I have entered: from suds.client import Client client = Client('http://10.51.54.50/ptz.wsdl') client.service.GetNode() I got this error: in open response = self._open(req, data) File "/home/build/workspace/downloads/Python-2.6.4/Lib/urllib2.py", line 407, in _open '_open', req) File "/home/build/workspace/downloads/Python-2.6.4/Lib/urllib2.py", line 367, in _call_chain result = func(*args) File "/home/build/workspace/downloads/Python-2.6.4/Lib/urllib2.py", line 1146, in http_open return self.do_open(httplib.HTTPConnection, req) File "/home/build/workspace/downloads/Python-2.6.4/Lib/urllib2.py", line 1121, in do_open raise URLError(err) urllib2.URLError: <urlopen error [Errno 111] Connection refused> Does anyone know why this is happening? I can connect to this file through my browser. I have installed all the suds packages. Is there any other setup required? Answer: Suds is very simple to use. from suds.client import Client client = Client("http://example.com/foo.wsdl") client.service.someMethod(someParameter) `someMethod` is the name of a method as described in the WSDL.
Does the TCPServer + BaseRequestHandler in Python's SocketServer close the socket after each call to handle()? Question: I'm writing a client/server application in Python and I'm finding it necessary to get a new connection to the server for each request from the client. My server is just inheriting from TCPServer and I'm inheriting from BaseRequestHandler to do my processing. I'm not calling self.request.close() anywhere in the handler, but somehow the server seems to be hanging up on my client. What's up? Answer: _According to the docs_ , neither TCPServer nor BaseRequestHandler close the socket unless prompted to do so. The default implementations of both `handle()` and `finish()` do nothing. A couple of things might be happening: * You are closing the socket itself or the request which wraps it, or calling `server_close` somewhere. * The socket timeout could have been hit and you have implemented a timeout handler which closes the socket. * The client could be actually closing the socket. Code would really help figuring this out. _However_ , my testing confirms your results. Once you return from `handle` on the server, whether connecting through telnet or Python's `socket` module, your connection shows up as being closed by the remote host. Handling socket activity in a loop inside handle seems to work: def handle(self): while 1: try: data = self.request.recv(1024) print self.client_address, "sent", data except: pass A brief Google Code Search confirms that this is a typical way of handling a request: [1](http://www.google.com/codesearch/p?hl=en#kidGrKEZwi0/trunk/bin/stats.py&q=lang%3Apy%20%28BaseRequestHandler%29&sa=N&cd=52&ct=rc) [2](http://www.google.com/codesearch/p?hl=en#EKZaOgYQHwo/unstable/sources/linda-0.6.tar.gz%7Cg33OoHGt0is/linda-0.6/server.py&q=lang%3Apy%20%28BaseRequestHandler%29&l=118) [3](http://www.google.com/codesearch/p?hl=en#93sG5NkuQsA/SoHo/1826/srpsocket.zip%7CH78xpN-0ydY/SRPSocket/SRPSocket.py&q=lang%3Apy%20%28BaseRequestHandler%29&l=77) [4](http://www.google.com/codesearch/p?hl=en#S67yNHIE_f4/authors/id/P/PE/PERRAD/CORBA- Python-0.36.tar.gz%7C1DH3SMWaXOo/CORBA- Python-0.36/rpc1/server.py&q=lang%3Apy%20%28BaseRequestHandler%29&l=10). Honestly, there are plenty of other networking libraries available for Python that I might look to if I were facing a disconnect between the abstraction `SocketServer` provides and my expectations. Code sample that I used to test: from SocketServer import BaseRequestHandler, TCPServer class TestRequestHandler(BaseRequestHandler): def handle(self): data = self.request.recv(1024) print self.client_address, "sent", data self.request.send(data) class TestServer(TCPServer): def __init__(self, server_address, handler_class=TestRequestHandler): TCPServer.__init__(self, server_address, handler_class) if __name__ == "__main__": import socket address = ('localhost', 7734) server = TestServer(address) server.socket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
How to fetch some data conditionally with Python and Beautiful Soup Question: Sorry if you feel like this has been asked but I have read the related questions and being quite new to Python I could not find how to write this request in a clean manner. For now I have this minimal Python code: from mechanize import Browser from BeautifulSoup import BeautifulSoup import re import urllib2 br = Browser() br.open("http://www.atpworldtour.com/Rankings/Singles.aspx") filename = "rankings.html" FILE = open(filename,"w") html = br.response().read(); soup = BeautifulSoup(html); links = soup.findAll('a', href=re.compile("Players")); for link in links: print link['href']; FILE.writelines(html); It retrieves all the link where the href contains the word player. Now the HTML I need to parse looks something like this: <tr> <td>1</td> <td><a href="/Tennis/Players/Top-Players/Roger-Federer.aspx">Federer,&nbsp;Roger</a>&nbsp;(SUI)</td> <td><a href="/Tennis/Players/Top-Players/Roger-Federer.aspx?t=rb">10,550</a></td> <td>0</td> <td><a href="/Tennis/Players/Top-Players/Roger-Federer.aspx?t=pa&m=s">19</a></td> </tr> The 1 contains the rank of the player. I would like to be able to retrieve this data in a dictionary: * rank * name of the player * link to the detailed page (here /Tennis/Players/Top-Players/Roger-Federer.aspx) Could you give me some pointers or if this is easy enough help me to build the piece of code ? I am not sure about how to formulate the request in Beautiful Soup. Anthony Answer: Searching for the players using your method will work, but will return 3 results per player. Easier to search for the table itself, and then iterate over the rows (except the header): table=soup.find('table', 'bioTableAlt') for row in table.findAll('tr')[1:]: cells = row.findAll('td') #retreieve data from cells... To get the data you need: rank = cells[0].string player = cells[1].a.string link = cells[1].a['href']
Implementation limitations of float.as_integer_ratio() Question: Recently, a correspondent mentioned [`float.as_integer_ratio()`](http://docs.python.org/library/stdtypes.html#numeric- types-int-float-long-complex), new in Python 2.6, noting that typical floating point implementations are essentially rational approximations of real numbers. Intrigued, I had to try π: >>> float.as_integer_ratio(math.pi); (884279719003555L, 281474976710656L) I was mildly surprised not to see the more [accurate](http://en.wikipedia.org/wiki/Pi) result due to [Arima](http://en.wikipedia.org/wiki/Arima_Yoriyuki),: (428224593349304L, 136308121570117L) For example, this code: #! /usr/bin/env python from decimal import * getcontext().prec = 36 print "python: ",Decimal(884279719003555) / Decimal(281474976710656) print "Arima: ",Decimal(428224593349304) / Decimal(136308121570117) print "Wiki: 3.14159265358979323846264338327950288" produces this output: python: 3.14159265358979311599796346854418516 Arima: 3.14159265358979323846264338327569743 Wiki: 3.14159265358979323846264338327950288 Certainly, the result is correct given the precision afforded by 64-bit floating-point numbers, but it leads me to ask: How can I find out more about the implementation limitations of `as_integer_ratio()`? Thanks for any guidance. Additional links: [Stern-Brocot](http://en.wikipedia.org/wiki/Stern- Brocot_tree), [Python source](http://svn.python.org/view/python/trunk/Objects/floatobject.c?revision=77139&view=markup), [IronPython source](http://www.google.com/codesearch/p?hl=en#4BXx6j5BqI4/IronPython_Main/Src/IronPython/Runtime/Operations/FloatOps.cs&q=as_integer_ratio&sa=N&cd=2&ct=rc). Answer: The algorithm used by `as_integer_ratio` only [considers powers of 2 in the denominator](http://www.google.com/codesearch/p?hl=en#4BXx6j5BqI4/IronPython_Main/Src/IronPython/Runtime/Operations/FloatOps.cs&q=as_integer_ratio&sa=N&cd=2&ct=rc). Here is a (probably) [better algorithm](http://www.math.niu.edu/~rusin/known- math/95/rationalize).
How to load a C# dll in python? Question: how can I load a c# dll in python? Do I have to put some extra code in the c# files? (like export in c++ files) I don't want to use IronPython. I want to import a module to Python! Answer: The package [Python for.NET](http://pythonnet.sourceforge.net/) and the Python Implementation [IronPython](http://ironpython.net/) now work the same way. Example for a C# DLL `MyDll.dll`: import clr clr.AddReference('MyDll') from MyNamespace import MyClass my_instance = MyClass() See [this post](http://stackoverflow.com/questions/7367976/calling-a-c-sharp- library-from-python) for more details.
Python web hosting: Numpy, Matplotlib, Scientific Computing Question: I write scientific software in Numpy/Scipy/Matplotlib. Having developed applications on my home computer, I am now interested in writing simple web applications. Example: user uploads image or audio file, my program processes it using Numpy/Scipy, and output is displayed on the browser using Matplotlib, or perhaps the user can download a processed file. I already pay for hosting that does have Python 2.4.3 installed, but no Numpy/Scipy. I don't have shell access via command line, either. Just drag- and-drop FTP. Pretty limited, but I can get simple Python/CGI scripts working. Surprisingly, a web search revealed few suitable options for web hosting with these capabilities already built in. (Please guide me if I am wrong.) I am learning about the Google App Engine, but I still don't have a full understanding about its tools and limitations. What the web _did_ tell me is that others have similar concerns. Hoping for solutions, I thought I would ask these simple questions to the awesome SO community: 1. Is there a simple way of installing numpy (or any third-party package/library) onto my already hosted space? I know the Python path on my hosted space, and I know the relevant Python/Numpy directories on my home computer. Can I simply copy files over and have it work? Both local and remote systems run Ubuntu. 2. What hosting sites exist (either free or paid) which have Numpy/Matplotlib installed or, if not installed, the possibility of installing it? Are there any documented sites that you can reference with working applications, no matter how simple? 3. Can Google App Engine help me in any way? Or is it totally for something else? Have you or others used it to write scientific applications in Python/Numpy? If so, could you reference them? Thank you for your help. EDIT: After the useful answers below, I bought the $20 plan at Slicehost, and I love it so far! (I first tried Amazon EC2. I must be stupid, but I just couldn't get it to work.) Setting up the Ubuntu server with Apache took mere hours (and I'm an Apache novice). It allows me to do exactly what I wanted with Python plus much more. I now have my own remote repository for version control, too. Thanks again! EDIT 2: Nearly two years later, I tried Linode and EC2 (again). Linode is great. EC2 seemed easier this time around -- maybe it's just added experience, or maybe it's the improvements that Amazon made to the AWS management console. For those interested in Numpy/Scipy/Matplotlib/Audiolab, here is my Ubuntu cheat sheet whenever I launch an EC2 instance: ec2:~$ sudo aptitude install build-essential python-scipy ipython python-matplotlib python-dev python-setuptools libsndfile-dev libasound2-dev mysql-server python-mysqldb Upload scikits.audiolab-0.11.0 ec2:~/scikits.audiolab-0.11.0$ sudo python setup.py install ec2:~$ sudo rm -rf scikits.audiolab-0.11.0 ec2:~$ nano .ipython/ipy_user_conf.py ip.ex('import matplotlib; matplotlib.use("Agg"); import scipy, pylab, scipy.signal as sig, scipy.linalg as lin, scipy.sparse as spar, os, sys, MySQLdb, boto; from scikits import audiolab') import ipy_greedycompleter import ipy_autoreload Answer: **1: Installing third party packages to hosted spaces** You can indeed install third party packages to your hosted space. If it's a pure python package, all that's needed is to unpack it to a directory and then add that directory to your PYTHONPATH environment variable or `sys.path`. This can be tiring to do often, and won't work easily for compiled modules. If you have shell access to your python host, the excellent [virtualenv](http://pypi.python.org/pypi/virtualenv) package allows you to do set up a private python environment with its own libraries. To set up your virtualenv, you'll do something like this at the shell: $ virtualenv $HOME/my_python $ $HOME/my_python/bin/easy_install numpy You can keep running easy_install for anything else you want to install in your personal python environment. Now, when you write your python scripts, you will want to use your private python interpreter, if that is possible: #!/home/myuser/my_python/bin/python import numpy # script here If your python env cannot be specified (such as if run by mod_wsgi), you will need to add it to the import path: import sys sys.path.insert(0, '/home/myuser/my_python/lib/python2.5/site-packages') import numpy **2: Hosting sites with numpy** I can't think of any hosting sites offhand which offer numpy pre-installed. However, [Dreamhost](http://www.dreamhost.com/)/Bluehost for sharedhosts provide SSH access, and with shell access you can install numpy using the methods I described above. Any Virtual Private Server such as [Linode](http://www.linode.com/)/[Slicehost](http://www.slicehost.com/) will allow you to install whatever you desire, as well. **3: AppEngine** As mentioned above, AppEngine will not allow you to install C extensions (but pure python ones do work) so it's unlikely numpy will work for you on there, since I suspect some of its features use C speedups.
Python multiprocessing and a shared counter Question: I'm having troubles with the multiprocessing module. I'm using a Pool of workers with its map method to load data from lots of files and for each of them I analyze data with with a custom function. Each time a file has been processed I would like to have a counter updated so that I can keep track of how many files remains to be processed. Here is sample code: def analyze_data( args ): # do something counter += 1 print counter if __name__ == '__main__': list_of_files = os.listdir(some_directory) global counter counter = 0 p = Pool() p.map(analyze_data, list_of_files) I can't find a solution for this. Answer: The problem is that the `counter` variable is not shared between your processes: each separate process is creating it's own local instance and incrementing that. See [this section](http://docs.python.org/library/multiprocessing.html#sharing-state- between-processes) of the documentation for some techniques you can employ to share state between your processes. In your case you might want to share a [`Value`](http://docs.python.org/library/multiprocessing.html#multiprocessing.Value) instance between your workers Here's a working version of your example (with some dummy input data). Note it uses global values which I would really try to avoid in practice: from multiprocessing import Pool, Value from time import sleep counter = None def init(args): ''' store the counter for later use ''' global counter counter = args def analyze_data(args): ''' increment the global counter, do something with the input ''' global counter # += operation is not atomic, so we need to get a lock: with counter.value.get_lock(): counter.value += 1 print counter.value return args * 10 if __name__ == '__main__': #inputs = os.listdir(some_directory) # # initialize a cross-process counter and the input lists # counter = Value('i', 0) inputs = [1, 2, 3, 4] # # create the pool of workers, ensuring each one receives the counter # as it starts. # p = Pool(initializer = init, initargs = (counter, )) i = p.map_async(analyze_data, inputs, chunksize = 1) i.wait() print i.get()
"Pre-importing" a variable into a module Question: Python beginner here, so I apologize if this question has a simple answer. (I hope it does.) I am working on a python module--a plugin for a larger program. I'm trying to develop the module using the Eclipse IDE (with pydev), which means I need to be able to run this module stand-alone, i.e. not as a plugin from the larger program. I've actually sorted out a lot of the hairy details of this on my own, much of it involving creating a sort of "harness" that launches the plugin from my IDE in a way that simulates (from the plugin's perspective) being launched from within its real operating environment. But one thing eludes me. When the module is run from within it's "real" environment, it somehow has a certain name (call it "Bob") already defined in its dir() results. When I run it in my own environment, "Bob" doesn't appear in dir() unless I load it manually. Naturally, if I wrote code to load "Bob" manually just so that the plugin will work in my IDE, that interferes with the plugin when it is running "for real". What I need help with is: **how do I get my plugin to start up (via my launching harness) with "Bob" already loaded?** Naively, I'm kind of hoping to somehow be able to "force" the plugin to import "Bob" somehow, without actually having to add "import Bob" to the plugin itself. But I'm open to suggestions on a better way...? Answer: Presumably, when you run it "stand-alone" under Eclipse (or "stand-alone" without Eclipse, for that matter, just as "python foobar.py" at a shell prompt), your module's `__name__` global variable has the value of `'__main__'` (if the module gets imported, instead, that global variable's value will be `'foobar'` \-- or however the module's named). So, just do if __name__ == '__main__': import Bob and you can have Bob imported when your module is run stand-alone, without any ill-effect when your module is instead getting `import`ed.
How to extract links from a webpage using lxml, XPath and Python? Question: I've got this xpath query: /html/body//tbody/tr[*]/td[*]/a[@title]/@href It extracts all the links with the title attribute - and gives the `href` in [FireFox's Xpath checker add-on](https://addons.mozilla.org/en- US/firefox/addon/1095). However, I cannot seem to use it with `lxml`. from lxml import etree parsedPage = etree.HTML(page) # Create parse tree from valid page. # Xpath query hyperlinks = parsedPage.xpath("/html/body//tbody/tr[*]/td[*]/a[@title]/@href") for x in hyperlinks: print x # Print links in <a> tags, containing the title attribute This produces no result from `lxml` (empty list). How would one grab the `href` text (link) of a hyperlink containing the attribute title with `lxml` under Python? Answer: I was able to make it work with the following code: from lxml import html, etree from StringIO import StringIO html_string = '''<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <html lang="en"> <head/> <body> <table border="1"> <tbody> <tr> <td><a href="http://stackoverflow.com/foobar" title="Foobar">A link</a></td> </tr> <tr> <td><a href="http://stackoverflow.com/baz" title="Baz">Another link</a></td> </tr> </tbody> </table> </body> </html>''' tree = etree.parse(StringIO(html_string)) print tree.xpath('/html/body//tbody/tr/td/a[@title]/@href') >>> ['http://stackoverflow.com/foobar', 'http://stackoverflow.com/baz']
Caching non-view returns Question: I have a dozen or so permission lookups on views that make sure users have the right permissions to do something on the system (ie make sure they're in the right group, if they can edit their profile, if they're group administrators, etc). A check might look like this: from django.contrib.auth.decorators import user_passes_test test_canvote = lambda u: u.has_perm('polls.can_vote') @user_passes_test(test_canvote) def my_view(request): # ... This is actually code from the Django tutorial (mine is a little uglier). Sometimes a check is very database intensive, firing off multiple queries. With lots of users hitting permission-checked pages, things can quickly get quite slow. My question is, can I (with your help) build a wrapper (or replacement) for the user_passes_test decorator that searches the cache for a key `'TESTCACHE' + user.pk + 'testname'` and if it doesn't exist, executes the test and saves its result. I've never written a decorator before but I imagine it would look nearly identical to the `user_passes_test` one, just passing the test as a string: @cached_user_passes_test('test_canvote') def my_view(request): # ... And as ever, let me know if I'm mad or if Django already does this for me (so I've problems elsewhere). Edit: The standard decorators can be found here: <http://code.djangoproject.com/browser/django/trunk/django/contrib/auth/decorators.py> I think it might be easier replacing `user_passes_test` than wrapping it so here's the starting point. Of course, if you feel I'm incorrect in that statement, let me know: try: from functools import update_wrapper, wraps except ImportError: from django.utils.functional import update_wrapper, wraps # Python 2.3, 2.4 fallback. from django.contrib.auth import REDIRECT_FIELD_NAME from django.http import HttpResponseRedirect from django.utils.http import urlquote from django.utils.decorators import auto_adapt_to_methods def user_passes_test(test_func, login_url=None, redirect_field_name=REDIRECT_FIELD_NAME): """ Decorator for views that checks that the user passes the given test, redirecting to the log-in page if necessary. The test should be a callable that takes the user object and returns True if the user passes. """ if not login_url: from django.conf import settings login_url = settings.LOGIN_URL def decorator(view_func): def _wrapped_view(request, *args, **kwargs): if test_func(request.user): return view_func(request, *args, **kwargs) path = urlquote(request.get_full_path()) tup = login_url, redirect_field_name, path return HttpResponseRedirect('%s?%s=%s' % tup) return wraps(view_func)(_wrapped_view) return auto_adapt_to_methods(decorator) Answer: You might need to serialize the function (which I'm not doing when I use it as the key to the cache), but something like this should work: from django.core.cache import cache def cached_user_passes_test(test_func, login_url=None, redirect_field_name=REDIRECT_FIELD_NAME): if not login_url: from django.conf import settings login_url = settings.LOGIN_URL def decorator(view_func): def _wrapped_view(request, *args, **kwargs): key = str(test_func) + str(request.user) cached_test_result = cache.get(key) if cached_test_result != None: test_result = cached_test_result else: test_result = test_func(request.user) cache.set(key, test_result, 60) if test_result: return view_func(request, *args, **kwargs) path = urlquote(request.get_full_path()) tup = login_url, redirect_field_name, path return HttpResponseRedirect('%s?%s=%s' % tup) return wraps(view_func)(_wrapped_view) return auto_adapt_to_methods(decorator)
Decode HTML entities in Python string? Question: I'm parsing some HTML with Beautiful Soup 3, but it contains HTML entities which Beautiful Soup 3 doesn't automatically decode for me: >>> from BeautifulSoup import BeautifulSoup >>> soup = BeautifulSoup("<p>&pound;682m</p>") >>> text = soup.find("p").string >>> print text &pound;682m How can I decode the HTML entities in `text` to get `"£682m"` instead of `"&pound;682m"`. Answer: ### Python 3.4+ `HTMLParser.unescape` is deprecated, and [was supposed to be removed in 3.5](https://github.com/python/cpython/blob/3.5/Lib/html/parser.py#L466-L470), although it was left in by mistake. It will be removed from the language soon. Instead, use `html.unescape()`: import html print(html.unescape('&pound;682m')) see <https://docs.python.org/3/library/html.html#html.unescape> * * * ### Python 2.6-3.3 You can use the HTML parser from the standard library: >>> try: ... # Python 2.6-2.7 ... from HTMLParser import HTMLParser ... except ImportError: ... # Python 3 ... from html.parser import HTMLParser ... >>> h = HTMLParser() >>> print(h.unescape('&pound;682m')) £682m See <http://docs.python.org/2/library/htmlparser.html> You can also use the [`six`](https://pythonhosted.org/six/) compatibility library to simplify the import: >>> from six.moves.html_parser import HTMLParser >>> h = HTMLParser() >>> print(h.unescape('&pound;682m')) £682m
How to aggregate over a single queryset in Django? Question: **Short description** : given a queryset `myQueryset`, how do I select `max("myfield")` without actually retrieving all rows and doing `max` in python? The best I can think of is `max([r["myfield"] for r in myQueryset.values("myfield")])`, which isn't very good if there are millions of rows. **Long description** : Say I have two models in my Django app, City and Country. City has a foreign key field to Country: class Country(models.Model): name = models.CharField(max_length = 256) class City(models.Model): name = models.CharField(max_length = 256) population = models.IntegerField() country = models.ForeignKey(Country, related_name = 'cities') This means that a Country instance has `.cities` available. Let's say I now want to write a method for Country called `highest_city_population` that returns the population of the largest city. Coming from a LINQ background, my natural instinct is to try `myCountry.cities.max('population')` or something like that, but this isn't possible. Answer: Use [Aggregation](http://docs.djangoproject.com/en/dev/topics/db/aggregation/) (new in Django 1.1). You use it like this: >>> from django.db.models import Max >>> City.objects.all().aggregate(Max('population')) {'population__max': 28025000} To get the highest population of a `City` for each `Country`, I think you could do something like this: >>> from django.db.models import Max >>> Country.objects.annotate(highest_city_population = Max('city__population'))
Pylons and AuthKit OpenID problem Question: I have troubles setting up the support for openID authentication, using authkit and pylons. I set up everything as described in the [cookbook](http://docs.pythonweb.org/display/authkitcookbook/OpenID+Passurl), but still get the following error: File "/usr/lib/python2.6/dist-packages/authkit/authenticate/open_id.py", line 480, in __call__ return self.app(environ, start_response) File "/usr/lib/python2.6/dist-packages/authkit/authenticate/open_id.py", line 218, in __call__ self.session_middleware AuthKitConfigError: The session middleware 'beaker.session' is not present. Have you set up the session middleware? (The full traceback is quite uninformative, just a chain of middleware calls) My config is the following: authkit.setup.method = openid, cookie # TODO authkit.openid.template.file = authkit.cookie.params.httponly = true authkit.openid.store.type = file authkit.openid.store.config = %(here)s/data authkit.openid.session.middleware = beaker.session authkit.openid.session.key = authkit_openid authkit.openid.baseurl = http://mysite.moc authkit.openid.path.signedin = /main/cabinet authkit.openid.authenticate.user.encrypt = authkit.users:md5 The beaker middleware is definitely loaded, here is my make_app function (yes, the pylons version check is true): | # Configure the Pylons environment | load_environment(global_conf, app_conf) | | # The Pylons WSGI app | app = PylonsApp() | app = UserMiddleware(app) | | if pylons.__version__ >= "0.9.7": |- from beaker.middleware import SessionMiddleware || from routes.middleware import RoutesMiddleware || app = RoutesMiddleware(app, config['routes.map']) || app = SessionMiddleware(app, app_conf) | | | if asbool(full_stack): | # Handle Python exceptions | |- app = authkit.authenticate.middleware(app, app_conf) || # Display error documents for 401, 403, 404 status codes (and || # 500 when debug is disabled) || if pylons.__version__ >= "0.9.7": ||- app = ErrorHandler(app, global_conf, 23- **config['pylons.errorware']) ||| from pylons.middleware import StatusCodeRedirect ||| if asbool(config['debug']): 23- app = StatusCodeRedirect(app) ||| else: 23- app = StatusCodeRedirect(app, [401, 403, 404, 500]) || else: ||- app = ErrorHandler(app, global_conf, error_template = error_template, 23- **config['pylons.errorware']) ||| app = ErrorDocuments(app, global_conf, mapper=error_mapper, **app_conf) | | # Establish the Registry for this application | app = RegistryManager(app) | | # Static files | javascripts_app = StaticJavascripts() | static_app = StaticURLParser(config['pylons.paths']['static_files']) | app = Cascade([static_app, javascripts_app, app]) | return app Does anyone have any idea, what is going on here? Answer: Take this line in your middleware.py: app = authkit.authenticate.middleware(app, app_conf) And move it immediately below this line: app = PylonsApp()
How to check file size in python? Question: I am writing a Python script in Windows. I want to do something based on the file size. For example, if the size is greater than 0, I will send an email to somebody, otherwise continue to other things. How do I check the file size? Answer: Like this (credit <http://www.daniweb.com/forums/thread78629.html>): >>> import os >>> b = os.path.getsize("/path/isa_005.mp3") >>> b 2071611L
What are the advantages of just-in-time compilation versus ahead-of-time compilation? Question: I've been thinking about it lately, and it seems to me that most advantages given to **JIT** compilation should more or less be attributed to the intermediate format instead, and that jitting in itself is not much of a good way to generate code. So these are the main **pro-JIT** compilation arguments I usually hear: 1. **Just-in-time compilation allows for greater portability.** Isn't that attributable to the intermediate format? I mean, nothing keeps you from compiling your virtual bytecode into native bytecode once you've got it on your machine. Portability is an issue in the 'distribution' phase, not during the 'running' phase. 2. **Okay, then what about generating code at runtime?** Well, the same applies. Nothing keeps you from integrating a just-in-time compiler for a real just-in-time need into your native program. 3. **But the runtime compiles it to native code just once anyways, and stores the resulting executable in some sort of cache somewhere on your hard drive.** Yeah, sure. But it's optimized your program under time constraints, and it's not making it better from there on. See the next paragraph. It's not like **ahead-of-time** compilation had no advantages either. **Just- in-time** compilation has time constraints: you can't keep the end user waiting forever while your program launches, so it has a tradeoff to do somewhere. Most of the time they just optimize less. A friend of mine had _profiling evidence_ that inlining functions and unrolling loops "manually" (obfuscating source code in the process) had a positive impact on performance on his **C#** number-crunching program; doing the same on my side, with my **C** program filling the same task, yielded no positive results, and I believe this is due to the extensive transformations my compiler was allowed to make. And yet we're surrounded by jitted programs. **C#** and **Java** are everywhere, Python scripts can compile to some sort of bytecode, and I'm sure a whole bunch of other programming languages do the same. There must be a good reason that I'm missing. So what makes **just-in-time** compilation so superior to **ahead-of-time** compilation? * * * **EDIT** To clear some confusion, maybe it would be important to state that I'm all for an intermediate representation of executables. This has a lot of advantages (and really, most arguments for **just-in-time** compilation are actually arguments for an intermediate representation). My question is about how they should be compiled to native code. Most runtimes (or compilers for that matter) will prefer to either compile them just-in-time or ahead-of-time. As **ahead-of-time** compilation looks like a better alternative to me because the compiler has more time to perform optimizations, I'm wondering why Microsoft, Sun and all the others are going the other way around. I'm kind of dubious about profiling-related optimizations, as my experience with **just-in-time** compiled programs displayed poor basic optimizations. I used an example with C code only because I needed an example of **ahead-of- time** compilation versus **just-in-time** compilation. The fact that **C** code wasn't emitted to an intermediate representation is irrelevant to the situation, as I just needed to show that **ahead-of-time** compilation can yield better immediate results. Answer: 1. Greater portability: The deliverable (byte-code) stays portable 2. At the same time, more platform-specific: Because the JIT-compilation takes place on the same system that the code runs, it can be very, very fine-tuned for that particular system. If you do ahead-of-time compilation (and still want to ship the same package to everyone), you have to compromise. 3. Improvements in compiler technology can have an impact on existing programs. A better C compiler does not help you at all with programs already deployed. A better JIT-compiler will improve the performance of existing programs. The Java code you wrote ten years ago will run faster today. 4. Adapting to run-time metrics. A JIT-compiler can not only look at the code and the target system, but also at how the code is used. It can instrument the running code, and make decisions about how to optimize according to, for example, what values the method parameters usually happen to have. You are right that JIT adds to start-up cost, and so there is a time- constraint for it, whereas ahead-of-time compilation can take all the time that it wants. This makes it more appropriate for server-type applications, where start-up time is not so important and a "warm-up phase" before the code gets really fast is acceptable. I suppose it would be possible to store the result of a JIT compilation somewhere, so that it could be re-used the next time. That would give you "ahead-of-time" compilation for the second program run. Maybe the clever folks at Sun and Microsoft are of the opinion that a fresh JIT is already good enough and the extra complexity is not worth the trouble.
Does Python have a module for parsing HTTP requests and responses? Question: httplib (now http.client) and friends all have conn.getresponse() and an HTTPResponse class, but the server-side operations of conn.getrequest() and an HTTPRequest class seem to be lacking. I understand that BaseHTTPServer and BaseHTTPRequestHandler can perform this functionality, but they don't expose these methods for use outside of the module. Essentially what I want is BaseHTTPRequestHandler#parse_request to be a static method that returns an HTTPRequest object rather than populating member variables. Answer: Jeff, to enable parsing I create a small nine-line subclass of the base HTTP request handler: from BaseHTTPServer import BaseHTTPRequestHandler from StringIO import StringIO class HTTPRequest(BaseHTTPRequestHandler): def __init__(self, request_text): self.rfile = StringIO(request_text) self.raw_requestline = self.rfile.readline() self.error_code = self.error_message = None self.parse_request() def send_error(self, code, message): self.error_code = code self.error_message = message You can now take a string with the text of an HTTP request inside and parse it by instantiating this class: # Simply instantiate this class with the request text request = HTTPRequest(request_text) print request.error_code # None (check this first) print request.command # "GET" print request.path # "/who/ken/trust.html" print request.request_version # "HTTP/1.1" print len(request.headers) # 3 print request.headers.keys() # ['accept-charset', 'host', 'accept'] print request.headers['host'] # "cm.bell-labs.com" # Parsing can result in an error code and message request = HTTPRequest('GET\r\nHeader: Value\r\n\r\n') print request.error_code # 400 print request.error_message # "Bad request syntax ('GET')"
Can someone help clarify my confusion about syncdb and import loops, 'Do you have to be explicit on imports?' Question: I have been having a difficult time building the database with syncdb on Python2.5. I think that some of this issue is because of the use of wildcard* for importing forum.models it seems to be creating a loop. >>> import settings >>> from forum.managers import QuestionManager, TagManager, AnswerManager, VoteManager, FlaggedItemManager, ReputeManager, AwardManager Traceback (most recent call last): File "<console>", line 1, in <module> File "/home/username/webapps/username/sousvide_app/forum/managers.py", line 6, in <module> from forum.models import * File "/home/username/webapps/username/sousvide_app/forum/models.py", line 18, in <module> from forum.managers import QuestionManager, TagManager, AnswerManager, VoteManager, FlaggedItemManager, ReputeManager, AwardManager ImportError: cannot import name QuestionManager >>> from forum.models import Question, Tag >>> from forum.managers import QuestionManager, TagManager, AnswerManager, VoteManager, FlaggedItemManager, ReputeManager, AwardManager >>> import sys, pprint >>> pprint.pprint(sys.path) ['/home/username/webapps/username/sousvide_app', '/home/username/webapps/username/lib/python2.5', '/home/username/lib/python2.5/markdown2-1.0.1.16-py2.5.egg', '/home/username/lib/python2.5/html5lib-0.11.1-py2.5.egg', '/home/username/lib/python2.5', '/usr/local/lib/python25.zip', '/usr/local/lib/python2.5', '/usr/local/lib/python2.5/plat-linux2', '/usr/local/lib/python2.5/lib-tk', '/usr/local/lib/python2.5/lib-dynload', '/usr/local/lib/python2.5/site-packages', '/usr/local/lib/python2.5/site-packages/PIL'] >>> from settings import INSTALLED_APPS >>> pprint.pprint(INSTALLED_APPS) ('sousvide_app.forum', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.sites', 'django.contrib.admin', 'django.contrib.humanize', 'django_authopenid') I had the same issue on another install that I was able to fix by explicitly importing the managers from forum.managers . As you can see, if I load Question and Tag models into the namespace I'm able to import the managers in the shell. I made the from forum.models import * explicit: from forum.models import Question, Tag However, I'm still not able to syncdb. When I try to output the SQL the APP can't be found. $ python2.5 manage.py sql forum Error: App with label forum could not be found. Are you sure your INSTALLED_APPS setting is correct? Can anyone give me an idea what is going wrong? Is there something about Python2.5 that could contribute to this error? Answer: Would you happen to be using `global_settings.py` or `local_settings.py` in addition to `settings.py`? The proper way to import Django's settings is to use the decoupled object `from django.conf import settings`, NOT to `import settings`. See the doc page about it here: [Using settings in Python code](http://docs.djangoproject.com/en/dev/topics/settings/#using-settings-in- python-code) I can't say for certain if that's the fix to your problem, but it's a step in the right direction to make sure your settings are being loaded properly if you say your issue is apps not showing up in `INSTALLED_APPS`.
Trouble using python's gzip/"How do I know what compression is being used?" Question: Ok, so I've got an Open Source Java client/server program that uses packets to communicate. I'm trying to write a python client for said program, but the contents of the packet seem to be compressed. A quick perusal through the source code suggested gzip as the compression schema (since that was the only compression module imported in the code that I could find), but when I saved the data from one of the packets out of wireshark and tried to do import gzip f = gzip.open('compressed_file') f.read() It told me that this wasn't a gzip file because the header was wrong. Can someone advise me what I've done wrong here? Did I change or mess up the format when I saved it out? Do I need to strip away some of the extraneous data from the packet before I try running this block on it? if (zipped) { // XML encode the data and GZIP it. ByteArrayOutputStream baos = new ByteArrayOutputStream(); Writer zipOut = new BufferedWriter(new OutputStreamWriter( new GZIPOutputStream(baos))); PacketEncoder.encodeData(packet, zipOut); zipOut.close(); // Base64 encode the commpressed data. // Please note, I couldn't get anything other than a // straight stream-to-stream encoding to work. byte[] zipData = baos.toByteArray(); ByteArrayOutputStream base64 = new ByteArrayOutputStream( (4 * zipData.length + 2) / 3); Base64.encode(new ByteArrayInputStream(zipData), base64, false); EDIT: Ok, sorry I have the information requested here. This was gathered using Wireshark to listen in on communication between two running copies of the original program on different computers. To get the hex stream below, I used the "Copy -> Hex (Byte Stream)" option in Wireshark. 001321cdc68ff4ce46e4f00d0800450000832a85400080061e51ac102cceac102cb004f8092a9909b32c10e81cb25018f734823e00000100000000000000521f8b08000000000000005bf39681b59c85818121a0b4884138da272bb12c512f27312f5dcf3f292b35b9c47ac2b988f902c59a394c0c0c150540758c250c5c2ea5b9b9950a2e89258900aa4c201a3f000000 I know this will contain the string "Dummy Data" in it. I believe it should also contain "Jonathanb" (the player name I used to send the message) and the integer 80 (80 is the command # for "Chat" as far as I can gather from the code). Answer: You could try using standard library module [zlib](http://docs.python.org/library/zlib.html?highlight=zlib#module-zlib) directly -- that's what [gzip](http://docs.python.org/library/gzip.html?highlight=gzip#module-gzip) uses for the compress/decompress part. If the whole packet isn't liked by the [decompress](http://docs.python.org/library/zlib.html?highlight=zlib#zlib.decompress) function, you can try using different values of `wbits` and/or slicing off a few bytes off the packet's front (if you could "reverse engineer" exactly **how** the Java code is compressing that packet -- even just understand how many `wbits` is using, or whether it's putting out any prefix before the compressed data -- that would help immensely, of course). The only likely "damage" you might have done to the file itself would be, on windows, if you had written it without specifying `'wb'` to use binary mode -- writing it in "text mode" on windows would make the file unusable. Just saying...!-)
Python - Moving entire text between two .doc files Question: I have been having this issue for a while and cannot figure how should I start to do this with python. My OS is windows xp pro. I need the script that moves entire (100% of the text) text from one .doc file to another. But its not so easy as it sounds. The target .doc file is not the only one but can be many of them. All the target .doc files are always in the same folder (same path) but all of them don't have the same name. The .doc file FROM where I want to move entire text is only one, always in the same folder (same path) and always with the same file name. Names of the target are only similar but as I have said before, not the same. Here is the point of whole script: Target .doc files have the names: > HD1.doc HD2.doc HD3.doc HD4.doc and so on What I would like to have is moved the entire (but really all of the text, must be 100% all) text into the .doc file with the highest ( ! ) number. The target .doc files will always start with ''HD'' and always be similar to above examples. It is possible that the doc file (target file) is only one, so only HD1.doc. Therefore ''1'' is the maximum number and the text is moved into this file. Sometimes the target file is empty but usually won't be. If it won't be then the text should be moved to the end of the text, into first new line (no empty lines inbetween). So for example in the target file which has the maximum number in its name is the following text: a b c In the file from which I want to move the text is: d This means I need in the target file this: a b c d But no empty lines anywhere. I have found (showing three different codes): <http://paste.pocoo.org/show/169309/> But neither of them make any sense to me. I know I would need to begin with finding the correct target file (correct HDX file where X is the highest number - again all HD files are and will be in the same folder) but no idea how to do this. I meant microsoft office word .doc files. They have "pure text". What I mean with pure text is that Im also able to see them in notepad (.txt). But I need to work with .doc extensions. Python is because I need this as automated system, so I wouldn't even need to open any file. Why exsactly python and not any other programming language? The reason for this is because recently I have started learning python and need this script for my work - Python is the "only" programming language that Im interested for and thats why I would like to make this script with it. By "really 100%" I meant that entire text (everything in source file - every single line, no matter if there are 2 or several thousands) would be moved to correct (which one is correct is described in my first post) target file. I cannot move the whole file because I need to move entire text (everything gathered - source file will be always the same but contest of text will be always different - different words in lines) and not whole file because I need the text in correct .doc file with correct name and together (with "together" i mean inside the same file) with already exsisting text IF is there anything already in the target file. Because its possible that the correct target file is empty also. If someone could suggest me anything, I would really appreciate it. Thank you, best wishes. I have tried to ask on openoffice forum but they don't answer. Seen the code could be something like this: from time import sleep import win32com.client from win32com.client import Dispatch wordApp = win32com.client.Dispatch('Word.Application') wordApp.Visible=False wordApp.Documents.Open('C:\\test.doc') sleep(5) HD1 = wordApp.Documents.Open('C:\\test.doc') #HD1 word document as object. HD1.Content.Select.Copy() #Selects entire document and copies it. ` But I have no idea what does that mean. Also I cannot use the .doc file like that because I never know what is the correct filename (HDX.doc where X is maximum integer number, all HD are in same directory path) of the file and therefore I cannot use its name - the script should find the correct file. Also ''filename'' = wordApp.Documents.open... would for sure give me syntax error. :-( Answer: Openoffice ships with full python scripting support, have a look: <http://wiki.services.openoffice.org/wiki/Python> Might be easier than trying to mess around with MS Word and COM apis.
Python: Optimizing, or at least getting fresh ideas for a tree generator Question: I have written a program that generates random expressions and then uses genetic techniques to select for fitness. The following part of the program generates the random expression and stores it in a tree structure. As this can get called billions of times during a run, I thought it should be optimized for time. I'm new to programming and I work (play) by myself so, as much as I search on the inernet for ideas, I'd like some input as I feel like I'm doing this in isolation. The bottlenecks seem to be Node.**init** (), (22% of total time) and random.choice(), (14% of total time) import random def printTreeIndented(data, level=0): '''utility to view the tree ''' if data == None: return printTreeIndented(data.right, level+1) print ' '*level + ' '+ str(data.cargo)#+ ' '+ str(data.seq)+ ' '+ str(data.branch) printTreeIndented(data.left, level+1) #These are the global constants used in the Tree.build_nodes() method. Depth = 5 Ratio = .6 #probability of terminating the current branch. Atoms = ['1.0','2.0','3.0','4.0','5.0','6.0','7.0','8.0','9.0','x','x','x','x'] #dict of operators. the structure is: operator: number of arguements Operators = {'+': 2, '-': 2, '*': 2, '/': 2, '**': 2} class KeySeq: '''Iterator to produce sequential integers for keys in Tree.thedict ''' def __init__(self, data = 0): self.data = data def __iter__(self): return self def next(self): self.data = self.data + 1 return self.data KS = KeySeq() class Node(object): ''' ''' def __init__(self, cargo, left=None, right=None): object.__init__(self) self.isRoot = False self.cargo = cargo self.left = left self.right = right self.parent = None self.branch = None self.seq = 0 class Tree(object): def __init__(self): self.thedict = {} #provides access to the nodes for further mutation and # crossbreeding. #When the Tree is instantiated, it comes filled with data. self.data = self.build_nodes() # Uncomment the following lines to see the data and a crude graphic of the tree. # print 'data: ' # for v in self.thedict.itervalues(): # print v.cargo, # print # print # printTreeIndented(self.data) def build_nodes (self, depth = Depth, entry = 1, pparent = None, bbranch = None): ''' ''' r = float() r = random.random() #If r > Ratio, it forces a terminal node regardless of #the value of depth. #If entry = 1, then it's the root node and we don't want # a tree with just a value in the root node. if (depth <= 0) or ((r > Ratio) and (not (entry))): ''' Add a terminal node. ''' this_atom = (random.choice(Atoms)) this_atom = str(this_atom) this_node = Node(this_atom) this_node.parent = pparent this_node.branch = bbranch this_node.seq = KS.next() self.thedict[this_node.seq] = this_node return this_node else: ''' Add a node that has branches. ''' this_operator = (random.choice(Operators.keys())) this_node = Node(this_operator) if entry: this_node.isRoot = True this_node.parent = pparent this_node.branch = bbranch this_node.seq = KS.next() self.thedict[this_node.seq] = this_node #branch as many times as 'number of arguements' # it's only set up for 2 arguements now. for i in range(Operators[this_operator]): depth =(depth - 1) if i == 0: this_node.left = (self.build_nodes(entry = 0, depth =(depth), pparent = this_node, bbranch = 'left')) else: this_node.right = (self.build_nodes(entry = 0, depth =(depth), pparent = this_node, bbranch = 'right')) return this_node def Main(): for i in range(100000): t = Tree() return t if __name__ == '__main__': rresult = Main() Answer: Below, I've summarized some of the more obvious optimization efforts, without really touching the algorithm much. All timings are done with Python 2.6.4 on a Linux x86-64 system. Initial time: **8.3s** ## Low-Hanging Fruits [jellybean](http://stackoverflow.com/questions/2127680/python-optimizing-or- at-least-getting-fresh-ideas-for-a-tree-generator/2127869#2127869) already pointed some out. Just fixing those already improves the runtime a little bit. Replacing the repeated calls to `Operators.keys()` by using the same list again and again also saves some time. Time: **6.6s** ## Using itertools.count Pointed out by [Dave Kirby](http://stackoverflow.com/questions/2127680/python- optimizing-or-at-least-getting-fresh-ideas-for-a-tree- generator/2127975#2127975), simply using [`itertools.count`](http://docs.python.org/library/itertools.html#itertools.count) also saves you some time: from itertools import count KS = count() Time: **6.2s** ## Improving the Constructor Since you're not setting all attributes of `Node` in the ctor, you can just move the attribute declarations into the class body: class Node(object): isRoot = False left = None right = None parent = None branch = None seq = 0 def __init__(self, cargo): self.cargo = cargo This does not change the semantics of the class as far as you're concerned, since all values used in the class body are immutable (`False`, `None`, `0`), if you need other values, read [this answer on class attributes](http://stackoverflow.com/questions/1250779/python-class-vs-module- attributes/1251929#1251929) first. Time: **5.2s** ## Using namedtuple In your code, you're not changing the expression tree any more, so you might as well use an object that is immutable. `Node` also does not have any behavior, so using a [`namedtuple`](http://docs.python.org/library/collections.html?highlight=namedtuple#collections.namedtuple) is a good option. This does have an implication though, since the `parent` member had to be dropped for now. Judging from the fact that you might introduce operators with more than two arguments, you would have to replace left/right with a list of children anyway, which is mutable again and would allow creating the parent node before all the children. from collections import namedtuple Node = namedtuple("Node", ["cargo", "left", "right", "branch", "seq", "isRoot"]) # ... def build_nodes (self, depth = Depth, entry = 1, pparent = None, bbranch = None): r = random.random() if (depth <= 0) or ((r > Ratio) and (not (entry))): this_node = Node( random.choice(Atoms), None, None, bbranch, KS.next(), False) self.thedict[this_node.seq] = this_node return this_node else: this_operator = random.choice(OpKeys) this_node = Node( this_operator, self.build_nodes(entry = 0, depth = depth - 1, pparent = None, bbranch = 'left'), self.build_nodes(entry = 0, depth = depth - 2, pparent = None, bbranch = 'right'), bbranch, KS.next(), bool(entry)) self.thedict[this_node.seq] = this_node return this_node I've kept the original behavior of the operand loop, that decrements the depth at each iteration. I'm not sure this is wanted behavior, but changing it increases runtime and therefore makes comparison impossible. **Final time: 4.1s** ## Where to go from here If you want to have support for more than two operators and/or support for the parent attribute, use something along the lines of the following code: from collections import namedtuple Node = namedtuple("Node", ["cargo", "args", "parent", "branch", "seq", "isRoot"]) def build_nodes (self, depth = Depth, entry = 1, pparent = None, bbranch = None): r = random.random() if (depth <= 0) or ((r > Ratio) and (not (entry))): this_node = Node( random.choice(Atoms), None, pparent, bbranch, KS.next(), False) self.thedict[this_node.seq] = this_node return this_node else: this_operator = random.choice(OpKeys) this_node = Node( this_operator, [], pparent, bbranch, KS.next(), bool(entry)) this_node.args.extend( self.build_nodes(entry = 0, depth = depth - (i + 1), pparent = this_node, bbranch = i) for i in range(Operators[this_operator])) self.thedict[this_node.seq] = this_node return this_node This code also decreases the depth with the operator position.
How can I normalize/collapse paths or URLs in Python in OS independent way? Question: I tried to use `os.normpath` in order to convert `http://example.com/a/b/c/../` to `http://example.com/a/b/` but it doesn't work on Windows because it does convert the slash to backslash. Answer: Here is how to do it >>> import urlparse >>> urlparse.urljoin("ftp://domain.com/a/b/c/d/", "../..") 'ftp://domain.com/a/b/' >>> urlparse.urljoin("ftp://domain.com/a/b/c/d/e.txt", "../..") 'ftp://domain.com/a/b/' Remember that `urljoin` consider a path/directory all until the last `/` \- after this is the filename, if any. Also, do not add a leading `/` to the second parameter, otherwise you will not get the expected result. `os.path` module is platform dependent but for file paths using only slashes but not-URLs you could use `posixpath,normpath`.
Import by file/module name in GAE Question: I am trying to make a simple localization module that takes a key name and returns the localized string based on the language given. The language is one of the constants and maps to a python file that contains the string table. I want to do this dynamically at runtime. Below is my approach, but GAE does not support the imp module. Is there an alternative way to do this? import logging import imp import localizable LANGUAGE_EN = "en" LANGUAGE_JP = "ja" class Localizer(object): """ Returns a localized string corresponding to unique keys """ @classmethod def localize(cls, language = LANGUAGE_EN, key = None): user_language = imp.load_source("localizable.%s" % language, "/") if (user_language): return user_language.Locale.localize(key) else: logging.error("Localizable file was not found") return "" I put the language files in localizable/en.py, etc. Answer: The alternative to the imp module that (I believe) should be available in GAE is `__import__()`. It's in fact what the 'import' statement calls to do the actual importing. user_language = getattr(__import__('localizable.%s' % language), language) or user_language __import__('localizable.%s' % language, {}, globals(), ['']) (passing a non-empty fourth argument to `__import__` causes it to return the right-most module in the first argument, instead of the left-most. It's a little hacky, so people tend to prefer the first solution over the second.)
Can Python's list comprehensions (ideally) do the equivalent of 'count(*)...group by...' in SQL? Question: I think list comprehensions may give me this, but I'm not sure: any elegant solutions in Python (2.6) in general for selecting unique objects in a list and providing a count? (I've defined an `__eq__` to define uniqueness on my object definition). So in RDBMS-land, something like this: CREATE TABLE x(n NUMBER(1)); INSERT INTO x VALUES(1); INSERT INTO x VALUES(1); INSERT INTO x VALUES(1); INSERT INTO x VALUES(2); SELECT COUNT(*), n FROM x GROUP BY n; Which gives: COUNT(*) n ========== 3 1 1 2 So , here's my equivalent list in Python: [1,1,1,2] And I want the same output as the SQL SELECT gives above. EDIT: The example I gave here was simplified, I'm actually processing lists of user-defined object-instances: just for completeness I include the extra code I needed to get the whole thing to work: import hashlib def __hash__(self): md5=hashlib.md5() [md5.update(i) for i in self.my_list_of_stuff] return int(md5.hexdigest(),16) The `__hash__` method was needed to get the `set` conversion to work (I opted for the list-comprehension idea that works in 2.6 [despite the fact that I learnt that involves an inefficiency (see comments) - my data set is small enough for that not be an issue]). `my_list_of_stuff` above is a list of (Strings) on my object definition. Answer: >>> from collections import Counter >>> Counter([1,1,1,2]) Counter({1: 3, 2: 1}) [Counter](http://docs.python.org/3.1/library/collections.html#collections.Counter) only available in py3.1, inherits from the `dict`.
Python's subprocess.Popen object hangs gathering child output when child process does not exit Question: When a process exits abnormally or not at all, I still want to be able to gather what output it may have generated up until that point. The obvious solution to this example code is to kill the child process with an os.kill, but in my real code, the child is hung waiting for NFS and does not respond to a SIGKILL. #!/usr/bin/python import subprocess import os import time import signal import sys child_script = """ #!/bin/bash i=0 while [ 1 ]; do echo "output line $i" i=$(expr $i \+ 1) sleep 1 done """ childFile = open("/tmp/childProc.sh", 'w') childFile.write(child_script) childFile.close() cmd = ["bash", "/tmp/childProc.sh"] finish = time.time() + 3 p = subprocess.Popen(cmd, stdout=subprocess.PIPE, stderr=subprocess.PIPE, stdin=subprocess.PIPE) while p.poll() is None: time.sleep(0.05) if finish < time.time(): print "timed out and killed child, collecting what output exists so far" out, err = p.communicate() print "got it" sys.exit(0) In this case, the print statement about timing out appears and the python script never exits or progresses. Does anybody know how I can do this differently and still get output from my child processe Answer: Problem is that bash doesn't answer to CTRL-C when not connected with a terminal. Switching to SIGHUP or SIGTERM seems to do the trick: cmd = ["bash", 'childProc.sh'] p = subprocess.Popen(cmd, stdout=subprocess.PIPE, stderr=subprocess.STDOUT, close_fds=True) time.sleep(3) print 'killing pid', p.pid os.kill(p.pid, signal.SIGTERM) print "timed out and killed child, collecting what output exists so far" out = p.communicate()[0] print "got it", out Outputs: killing pid 5844 timed out and killed child, collecting what output exists so far got it output line 0 output line 1 output line 2
Python looping: idiomatically comparing successive items in a list Question: I need to loop over a list of objects, comparing them like this: 0 vs. 1, 1 vs. 2, 2 vs. 3, etc. (I'm using pysvn to extract a list of diffs.) I wound up just looping over an index, but I keep wondering if there's some way to do it which is more closely idiomatic. It's Python; shouldn't I be using iterators in some clever way? Simply looping over the index seems pretty clear, but I wonder if there's a more expressive or concise way to do it. for revindex in xrange(len(dm_revisions) - 1): summary = \ svn.diff_summarize(svn_path, revision1=dm_revisions[revindex], revision2 = dm_revisions[revindex+1]) Answer: This is called a sliding window. There's an [example in the `itertools` documentation](http://www.python.org/doc/2.3.5/lib/itertools-example.html) that does it. Here's the code: from itertools import islice def window(seq, n=2): "Returns a sliding window (of width n) over data from the iterable" " s -> (s0,s1,...s[n-1]), (s1,s2,...,sn), ... " it = iter(seq) result = tuple(islice(it, n)) if len(result) == n: yield result for elem in it: result = result[1:] + (elem,) yield result What that, you can say this: for r1, r2 in window(dm_revisions): summary = svn.diff_summarize(svn_path, revision1=r1, revision2=r2) Of course you only care about the case where n=2, so you can get away with something much simpler: def adjacent_pairs(seq): it = iter(seq) a = it.next() for b in it: yield a, b a = b for r1, r2 in adjacent_pairs(dm_revisions): summary = svn.diff_summarize(svn_path, revision1=r1, revision2=r2)
lxml has essentially nothing Question: The `lxml` package for Python seems to absolutely broken on my system. I am not sure of the problem, as all of the files are in place, it seems. My suspicion is that the problem is in `__init__.py`, but I don't have enough practice with the system to make an accurate diagnosis or fix the problem. Here is some code that I think will help diagnose the problem: Python 2.6.4 (r264:75706, Dec 7 2009, 18:45:15) [GCC 4.4.1] on linux2 Type "help", "copyright", "credits" or "license" for more information. >>> import lxml >>> dir(lxml) ['__builtins__', '__doc__', '__file__', '__name__', '__package__', '__path__'] >>> print lxml.__path__ ['/usr/lib/python2.6/dist-packages/lxml'] >>> c = open("/usr/lib/python2.6/dist-packages/lxml/__init__.py", "r") >>> for line in c: ... print line ... # this is a package >>> c.close() >>> import os >>> os.system("ls /usr/lib/python2.6/dist-packages/lxml/") builder.py ElementInclude.py __init__.py sax.pyc builder.pyc ElementInclude.pyc __init__.pyc usedoctest.py cssselect.py _elementpath.py objectify.so usedoctest.pyc cssselect.pyc _elementpath.pyc pyclasslookup.py doctestcompare.py etree.so pyclasslookup.pyc doctestcompare.pyc html sax.py 0 >>> Like I said, my suspicion is that `__init__.py` contains the problem, but I'm not 100% sure. Also, I'm using Linux Mint 8 - the rough equivalent of Ubuntu 9.10. Thanks in advance. Answer: No, you're just doing it wrong! Try, e.g., `from lxml import etree`, and you should be able to use `etree` fully. `import lxml` \-- importing the **package**! -- does **not** give you implicit access to any of the package's **modules**!-)
imports while starting an interactive shell Question: When I start the interactive django shell through manage.py, by executing python -v manage.py shell from the project directory, I see a lot of modules of format django.package.module getting imported in the verbose output but still I have to import them to use it in the shell. The same happens when I just run the Python shell (with the -v argument). For example I see this in the verbose output, import os # precompiled from /usr/local/gdp/lib/python2.4/os.pyc but still i have to do import os to import and use the os module. What is being imported that am seeing in the verbose output and why I have to import them explicitly again to use them in the shell? Does Python load some essential modules while starting the shell or is it some kind of behind-the- scene magic? Answer: `-v` traces the **first** import of a module -- the one that actually **loads** the module (executes its code, and so may take a bit of time) and sticks it into `sys.modules`. That has **nothing** to do whether your interactive session (module `__main__`) gets the module injected into its namespace, of course. To ensure module `'goo'` **does** get into the namespace of module `'X'` (for **any** `X`, so of course _including_ `__main__`... among many, many others), module `'X'` just needs to `import goo` itself (a very fast operation indeed, if `sys.modules['goo']` is already defined!-).
Library like fakeweb for Python Question: I really like the way fakeweb in Ruby can be used to fake http requests when testing. Is there a similar library or an alternative for Python? Answer: See also <http://stackoverflow.com/questions/295438/how-can-one-mock-stub- python-module-like-urllib/295503> . The answer that recommends [Mox](http://code.google.com/p/pymox/) seems the most like fakeweb, but Mox lets you create fake versions of any module, not just urllib. For incoming requests, if your web framework uses WebOb ([repoze.bfg](http://bfg.repoze.org/), [Pylons](http://pylonshq.com/) others), you can use [`webob.Request.blank`](http://pythonpaste.org/webob/reference.html#id1). from webob import Request r = Request.blank('/') a_view_function(r)
Reprojecting polar to cartesian grid Question: I have a polar (r,theta) grid (which means that each cell is an annulus section) containing values of some physical quantity (e.g. temperature), and I would like to re-grid (or re-project) these values onto a cartesian grid. Are there any Python packages that can do this? I am not interested in converting the coordinates of the centers of the cells from polar to cartesian - this is very easy. Instead, I'm looking for a package that can actually re-grid the data properly. Thanks for any suggestions! Answer: Thanks for your answers - after thinking a bit more about this I came up with the following code: import numpy as np import matplotlib matplotlib.use('Agg') import matplotlib.pyplot as mpl from scipy.interpolate import interp1d from scipy.ndimage import map_coordinates def polar2cartesian(r, t, grid, x, y, order=3): X, Y = np.meshgrid(x, y) new_r = np.sqrt(X*X+Y*Y) new_t = np.arctan2(X, Y) ir = interp1d(r, np.arange(len(r)), bounds_error=False) it = interp1d(t, np.arange(len(t))) new_ir = ir(new_r.ravel()) new_it = it(new_t.ravel()) new_ir[new_r.ravel() > r.max()] = len(r)-1 new_ir[new_r.ravel() < r.min()] = 0 return map_coordinates(grid, np.array([new_ir, new_it]), order=order).reshape(new_r.shape) # Define original polar grid nr = 10 nt = 10 r = np.linspace(1, 100, nr) t = np.linspace(0., np.pi, nt) z = np.random.random((nr, nt)) # Define new cartesian grid nx = 100 ny = 200 x = np.linspace(0., 100., nx) y = np.linspace(-100., 100., ny) # Interpolate polar grid to cartesian grid (nearest neighbor) fig = mpl.figure() ax = fig.add_subplot(111) ax.imshow(polar2cartesian(r, t, z, x, y, order=0), interpolation='nearest') fig.savefig('test1.png') # Interpolate polar grid to cartesian grid (cubic spline) fig = mpl.figure() ax = fig.add_subplot(111) ax.imshow(polar2cartesian(r, t, z, x, y, order=3), interpolation='nearest') fig.savefig('test2.png') Which is not strictly re-gridding, but works fine for what I need. Just posting the code in case it is useful to anyone else. Feel free to suggest improvements!
draw hebrew text to an image using Image module (python) Question: Hi I am trying to use Image module in order to make bitmaps with hebrew lettering in it. when printing from the shell (idle) I managed to print hebrew, but when trying to draw text to a bitmap it draws some ascii lettering. this is the code: import Image import ImageDraw a = "אריאל" #or any other hebrew string im=Image.new('RGB',(200,200),(100,100,100)) #type file,size,Background color d=ImageDraw.Draw(im) d.text((0,0),a) #should draw the string im.show() any help will be very appreciated. Answer: Try `a = u"אריאל"`. Failing that, try [PyCairo](http://cairographics.org/documentation/pycairo/). It has advanced typography handling that may work better.
django error ,about django-sphinx Question: from django.db import models from djangosphinx.models import SphinxSearch class MyModel(models.Model): search = SphinxSearch() # optional: defaults to db_table # If your index name does not match MyModel._meta.db_table # Note: You can only generate automatic configurations from the ./manage.py script # if your index name matches. search = SphinxSearch('index_name') # Or maybe we want to be more.. specific searchdelta = SphinxSearch( index='index_name delta_name', weights={ 'name': 100, 'description': 10, 'tags': 80, }, mode='SPH_MATCH_ALL', rankmode='SPH_RANK_NONE', ) queryset = MyModel.search.query('query') results1 = queryset.order_by('@weight', '@id', 'my_attribute') results2 = queryset.filter(my_attribute=5) results3 = queryset.filter(my_other_attribute=[5, 3,4]) results4 = queryset.exclude(my_attribute=5)[0:10] results5 = queryset.count() # as of 2.0 you can now access an attribute to get the weight and similar arguments for result in results1: print result, result._sphinx # you can also access a similar set of meta data on the queryset itself (once it's been sliced or executed in any way) print results1._sphinx and Traceback (most recent call last): File "D:\zjm_code\sphinx_test\models.py", line 1, in <module> from django.db import models File "D:\Python25\Lib\site-packages\django\db\__init__.py", line 10, in <module> if not settings.DATABASE_ENGINE: File "D:\Python25\Lib\site-packages\django\utils\functional.py", line 269, in __getattr__ self._setup() File "D:\Python25\Lib\site-packages\django\conf\__init__.py", line 38, in _setup raise ImportError("Settings cannot be imported, because environment variable %s is undefined." % ENVIRONMENT_VARIABLE) ImportError: Settings cannot be imported, because environment variable DJANGO_SETTINGS_MODULE is undefined. Answer: I know what the problem is :) You are trying to run this script as stand-alone. But since you use django models. all of them have to be imported in your `namespace`. This is what is the error. It clearly days `ImportError`. To solve - go to your django-project directory & then type `python manage.py shell`. This imports all Django-env files. Now import your models & try out the search.
sscanf in Python Question: I'm looking for an equivalent to `sscanf()` in Python. I want to parse `/proc/net/*` files, in C I could do something like this: int matches = sscanf( buffer, "%*d: %64[0-9A-Fa-f]:%X %64[0-9A-Fa-f]:%X %*X %*X:%*X %*X:%*X %*X %*d %*d %ld %*512s\n", local_addr, &local_port, rem_addr, &rem_port, &inode); I thought at first to use `str.split`, however it doesn't split on the given characters, but the `sep` string as a whole: >>> lines = open("/proc/net/dev").readlines() >>> for l in lines[2:]: >>> cols = l.split(string.whitespace + ":") >>> print len(cols) 1 Which should be returning 17, as explained above. Is there a Python equivalent to `sscanf` (not RE), or a string splitting function in the standard library that splits on any of a range of characters that I'm not aware of? Answer: When I'm in a C mood, I usually use zip and list comprehensions for scanf-like behavior. Like this: input = '1 3.0 false hello' (a, b, c, d) = [t(s) for t,s in zip((int,float,bool,str),input.split())] print (a, b, c, d) Note that for more complex format strings, you do need to use regular expressions: import re input = '1:3.0 false,hello' (a, b, c, d) = [t(s) for t,s in zip((int,float,bool,str),re.search('^(\d+):([\d.]+) (\w+),(\w+)$',input).groups())] print (a, b, c, d)
Filter files in a very large folder Question: I have a folder with 100k text files. I want to put files with over 20 lines in another folder. How do I do this in python? I used os.listdir, but of course, there isn't enough memory for even loading the filenames into memory. Is there a way to get maybe 100 filenames at a time? Here's my code: import os import shutil dir = '/somedir/' def file_len(fname): f = open(fname,'r') for i, l in enumerate(f): pass f.close() return i + 1 filenames = os.listdir(dir+'labels/') i = 0 for filename in filenames: flen = file_len(dir+'labels/'+filename) print flen if flen > 15: i = i+1 shutil.copyfile(dir+'originals/'+filename[:-5], dir+'filteredOrigs/'+filename[:-5]) print i And Output: Traceback (most recent call last): File "filterimage.py", line 13, in <module> filenames = os.listdir(dir+'labels/') OSError: [Errno 12] Cannot allocate memory: '/somedir/' Here's the modified script: import os import shutil import glob topdir = '/somedir' def filelen(fname, many): f = open(fname,'r') for i, l in enumerate(f): if i > many: f.close() return True f.close() return False path = os.path.join(topdir, 'labels', '*') i=0 for filename in glob.iglob(path): print filename if filelen(filename,5): i += 1 print i it works on a folder with fewer files, but with the larger folder, all it prints is "0"... Works on linux server, prints 0 on mac... oh well... Answer: you might try using [`glob.iglob`](http://docs.python.org/library/glob.html) that returns an iterator: topdir = os.path.join('/somedir', 'labels', '*') for filename in glob.iglob(topdir): if filelen(filename) > 15: #do stuff Also, please don't use `dir` for a variable name: you're shadowing the built- in. Another major improvement that you can introduce is to your `filelen` function. If you replace it with the following, you'll save a lot of time. Trust me, [what you have now is the slowest alternative](http://stackoverflow.com/questions/845058/how-to-get-line-count- cheaply-in-python): def many_line(fname, many=15): for i, line in enumerate(open(fname)): if i > many: return True return False
How to pass data to another function from a class (in HTMLParser)? Question: I'm beginning to learn python. My python version is 3.1 I've never learnt OOP before, so I'm confused by the HTMLParser. from html.parser import HTMLParser class parser(HTMLParser): def handle_data(self, data): print(data) p = parser() page = """<html><h1>title</h1><p>I'm a paragraph!</p></html>""" p.feed(page) I'll get this: > _title_ > > _I'm a paragraph!_ I want this data passed to a function, what should I do? Sorry for my poor English and Thank you for your help! Answer: I did not look into the HTMLParser module itself, but I can see that feed inherently calls handle_data, which in your derived class does a print. @ron's answer suggests passing the data directly to your function, which is totally OK. However, since you are new to OOP, maybe take a look at this code. This is Python, 2.x, but I think the only thing that would change is the package location, html.parser instead of HTMLParser. from HTMLParser import HTMLParser class MyParser(HTMLParser): def handle_data(self, data): self.output.append(data) def feed(self, data): self.output = [] HTMLParser.feed(self, data) p = MyParser() page = """<html><h1>title</h1><p>I'm a paragraph!</p></html>""" p.feed(page) print p.output output ['title', "I'm a paragraph!"] Here I am overriding the feed method of HTMLParser. Instead, when the call is made `p.feed(page)` it will call my method, which creates / sets an instance variable called output to an empty list and then calls the feed method in the base class (HTMLParser) and proceeds with what it does normally. So, by overriding the feed method I was able to do some extra stuff (added a new output variable). The handle_data method similarly is an override method. In fact, the handle_data method of HTMLParser doesn't even do anything... nothing at all (according to the docs.) So, just to clarify... You call `p.feed(page)` which calls the MyParser.feed method MyParser.feed sets a variable self.output to and empty list then calls HTMLParser.feed The handle_data method adds the line onto the end of the output list. You now have access to the data via a call to p.output.
Installing numpy broke NLTK (OS X 10.6.2, Python 2.6) Question: I had a working installation of NLTK (py26-nltk) on my Mac (OS X 10.6.2). Then I installed numpy. Now when I try to import nltk, I get this: >>> import nltk Traceback (most recent call last): File "<stdin>", line 1, in <module> File "nltk/__init__.py", line 83, in <module> from collocations import * File "nltk/collocations.py", line 39, in <module> from nltk.metrics import ContingencyMeasures, BigramAssocMeasures, TrigramAssocMeasures File "nltk/metrics/__init__.py", line 14, in <module> from scores import * File "nltk/metrics/scores.py", line 15, in <module> from scipy.stats.stats import betai File "/Library/Frameworks/Python.framework/Versions/2.6/lib/python2.6/site-packages/scipy/stats/__init__.py", line 7, in <module> from stats import * File "/Library/Frameworks/Python.framework/Versions/2.6/lib/python2.6/site-packages/scipy/stats/stats.py", line 203, in <module> from morestats import find_repeats #is only reference to scipy.stats File "/Library/Frameworks/Python.framework/Versions/2.6/lib/python2.6/site-packages/scipy/stats/morestats.py", line 7, in <module> import distributions File "/Library/Frameworks/Python.framework/Versions/2.6/lib/python2.6/site-packages/scipy/stats/distributions.py", line 27, in <module> import vonmises_cython File "numpy.pxd", line 30, in scipy.stats.vonmises_cython (scipy/stats/vonmises_cython.c:2939) ValueError: numpy.dtype does not appear to be the correct type object What has gone wrong? How can I fix this? Answer: It seems to be more of a matter of [version] **incompatibility between SciPy and NumPy** versions than between NLTK and Numpy. While SciPy is not required for NLTK, it is an optional import, and will load if available. A few hypothesis regarding your situation: Hyp #1 * you formerly were running under NumPy 1.3 along with a compatible version of SciPy * you recently installed NumPy 1.4 but didn't touch SciPy ==> "Old" SciPy is broken. Remedy : Install newer SciPy or uninstall it altogether (although you may be using/needing SciPy, without knowing it, depending on the modules of NLTK you use) Alternate Remedy: re-install NumPy 1.3 over 1.4. Hyp #2 (less likely) * You never had SciPy and NLTK was happy, working without it. * You recently installed NumPy 1.4 (over 1.3) _and_ SciPy (over nothing) * For some reason NumPy and SciPy don't play nice together Remedy: Uninstall SciPy
Oracle build order and PL/SQL package dependencies Question: I'm trying to build up a list of PL/SQL package dependencies so that I can help set up an automated build script for my packages to run on the test server. Is there a way to start with a single package (a "root" package identified by name, ideally) and then find all of the dependencies, and the order they must be compiled in? Dependencies are already fully resolved in my personal schema (so at least I have somewhere to start - but where do I go next?). (Oracle 10.2) **EDIT:** The build tool that is being used will use the build order and will retreive those files in order from source control, and then pass them to Oracle to compile (the actual build tool itself is written in Python or Java or both - I don't have access to the source). Basically, the build tool needs as input a list of files to compile _in the order they must be compiled in_ , and acces to those files in source control. If it has that, everything will work quite nicely. **EDIT:** Thanks for the neat scripts. Unfortunately, the build process is mostly out of my hands. The process is based around a build tool which was built by the vendor of the product we are integrating with, which is why the only inputs I can give to the build process are a list of files in the order they need to be built in. If there is a compiler error, the build tool fails, we have to manually submit a request for a new build. So a list of files in the order they should be compiled is important. **EDIT:** Found this: <http://www.oracle.com/technology/oramag/code/tips2004/091304.html> Gives me the dependencies of any object. Now I just need to get the ordering right... If I get something working I'll post it here. **EDIT:** (with code!) I know that in general, this sort of thing is not necessary for Oracle, but for anyone who's still interested... I have cobbled together a little script that seems to be able to get a build order such that all packages will be built in the correct order with no dependency-related errors (with respect to pacakges) the first time around: declare type t_dep_list is table of varchar2(40) index by binary_integer; dep_list t_dep_list; i number := 1; cursor c_getObjDepsByNameAndType is --based on a query found here: http://www.oracle.com/technology/oramag/code/tips2004/091304.html select lvl, u.object_id, u.object_type, LPAD(' ', lvl) || object_name obj FROM (SELECT level lvl, object_id FROM SYS.public_dependency s START WITH s.object_id = (select object_id from user_objects where object_name = UPPER(:OBJECT_NAME) and object_type = UPPER(:OBJECT_TYPE)) CONNECT BY s.object_id = PRIOR referenced_object_id GROUP BY level, object_id) tree, user_objects u WHERE tree.object_id = u.object_id and u.object_type like 'PACKAGE%' --only look at packages, not interested in other types of objects ORDER BY lvl desc; function fn_checkInList(in_name in varchar2) return boolean is begin for j in 1 .. dep_list.count loop if dep_list(j) = in_name then return true; end if; end loop; return false; end; procedure sp_getDeps(in_objID in user_objects.object_id%type, in_name in varchar2) is cursor c_getObjDepsByID(in_objID in user_objects.object_id%type) is --based on a query found here: http://www.oracle.com/technology/oramag/code/tips2004/091304.html select lvl, u.object_id, u.object_type, LPAD(' ', lvl) || object_name obj FROM (SELECT level lvl, object_id FROM SYS.public_dependency s START WITH s.object_id = (select uo.object_id from user_objects uo where uo.object_name = (select object_name from user_objects uo where uo.object_id = in_objID) and uo.object_type = 'PACKAGE BODY') CONNECT BY s.object_id = PRIOR referenced_object_id GROUP BY level, object_id) tree, user_objects u WHERE tree.object_id = u.object_id and u.object_id <> in_objID --exclude self (requested Object ID) from list. ORDER BY lvl desc; begin --loop through the dependencies for r in c_getObjDepsByID(in_objID) loop if fn_checkInList(trim(r.obj)) = false and (r.object_type = 'PACKAGE' or r.object_type = 'PACKAGE BODY') and trim(r.obj) <> trim(in_name) then dbms_output.put_line('checking deps of: ' || r.obj || ' ' || r.object_id || ' level: ' || r.lvl); --now for each dependency, check the sub-dependency sp_getDeps(r.object_id, trim(r.obj)); --add the object to the dependency list. dep_list(i) := trim(r.obj); i := i + 1; end if; end loop; exception when NO_DATA_FOUND then dbms_output.put_line('no more data for: ' || in_objID); end; begin for r in c_getObjDepsByNameAndType loop dbms_output.put_line('top-level checking deps of: ' || r.obj || ' ' || r.object_id || ' level: ' || r.lvl); sp_getDeps(r.object_id, trim(r.obj)); end loop; dbms_output.put_line('dep count: ' || dep_list.count); for j in 1 .. dep_list.count loop dbms_output.put_line('obj: ' || j || ' ' || dep_list(j)); end loop; end; I know it's not the prettiest code (globals all over the place, etc... ugh), and I'll probably repost it if I can get a chance this afternoon to clean it up, but right now, it produces a build order that seems to run the first time with no problems. `:OBJECT_NAME` should be the root object that you want to trace all dependencies and build order of. For me, this is a main package with a single method that is the entry point to the rest of the system. `:OBJECT_TYPE` I have mostly restricted to `PACKAGE BODY`, but it shouldn't be too much work to include other types, such as triggers. One last thing, the object specified by `:OBJECT_NAME` will not appear in the output, but it should be the last item, so you'll have to add that to your build list manually. **UPDATE:** I just discovered `user_dependencies` and `all_dependencies`, this code could probably be made much simpler now. Answer: If you're really dealing with just PL/SQL packages you do not need to sweat the build order. Just build all the package specifications first. Then you can deploy all the package bodies and they will compile, because their dependencies are the package specs. If you happen to have some package specs which do depend on other specs - if you have packages which declare, say, constants, subtypes or ref cursors which are used in the signatures of packaged procedures - then you need to build those package specs first. But there should be few enough of them that you can arrange them in the build script by hand. **edit** > It looks like they wil be doing incremental AND "clean-sweep" builds, so the > build order will matter most for when they clean out the environment and > rebuild it. That doesn't alter anything. Here is an extended example. I have a schema with three packages.... SQL> select object_name, object_type, status 2 from user_objects 3 order by 1, 2 4 / OBJECT_NAME OBJECT_TYPE STATUS --------------- --------------- ------- PKG1 PACKAGE VALID PKG1 PACKAGE BODY VALID PKG2 PACKAGE VALID PKG2 PACKAGE BODY VALID PKG3 PACKAGE VALID PKG3 PACKAGE BODY VALID 6 rows selected. SQL> The interesting thing is that a procedure in PKG1 calls a procedure from PKG2, a procedure in PKG2 calls a procedure from PKG3 and a procedure in PKG3 calls a procedure from PKG1. **Q.** How does that circular dependency work? **A.** It's not a circular dependency.... SQL> select name, type, referenced_name, referenced_type 2 from user_dependencies 3 where referenced_owner = user 4 / NAME TYPE REFERENCED_NAME REFERENCED_TYPE --------------- --------------- --------------- --------------- PKG1 PACKAGE BODY PKG1 PACKAGE PKG1 PACKAGE BODY PKG2 PACKAGE PKG2 PACKAGE BODY PKG2 PACKAGE PKG2 PACKAGE BODY PKG3 PACKAGE PKG3 PACKAGE BODY PKG3 PACKAGE PKG3 PACKAGE BODY PKG1 PACKAGE 6 rows selected. SQL> All the dependent objects are the package bodies, all the referenced objects are the packaged specs. Consequently, if I trash'n'rebuild the schema it really doesn't matter what order I use. First we trash ... SQL> drop package pkg1 2 / Package dropped. SQL> drop package pkg2 2 / Package dropped. SQL> drop package pkg3 2 / Package dropped. SQL> Then we rebuild ... SQL> create or replace package pkg3 is 2 procedure p5; 3 procedure p6; 4 end pkg3; 5 / Package created. SQL> create or replace package pkg2 is 2 procedure p3; 3 procedure p4; 4 end pkg2; 5 / Package created. SQL> create or replace package pkg1 is 2 procedure p1; 3 procedure p2; 4 end pkg1; 5 / Package created. SQL> create or replace package body pkg2 is 2 procedure p3 is 3 begin 4 pkg3.p5; 5 end p3; 6 procedure p4 is 7 begin 8 dbms_output.put_line('PKG2.P4'); 9 end p4; 10 end pkg2; 11 / Package body created. SQL> create or replace package body pkg3 is 2 procedure p5 is 3 begin 4 dbms_output.put_line('PKG3.P5'); 5 end p5; 6 procedure p6 is 7 begin 8 pkg1.p1; 9 end p6; 10 end pkg3; 11 / Package body created. SQL> create or replace package body pkg1 is 2 procedure p1 is 3 begin 4 dbms_output.put_line('PKG1.P1'); 5 end p1; 6 procedure p2 is 7 begin 8 pkg2.p4; 9 end p2; 10 end pkg1; 11 / Package body created. SQL> The order of the individual objects is irrelevant. Just build the package specs before the package bodies. Although even that does not really matter... SQL> create or replace package pkg4 is 2 procedure p7; 3 end pkg4; 4 / Package created. SQL> create or replace package body pkg4 is 2 procedure p7 is 3 begin 4 dbms_output.put_line('PKG4.P7::'||constants_pkg.whatever); 5 end p7; 6 end pkg4; 7 / Warning: Package Body created with compilation errors. SQL> show errors Errors for PACKAGE BODY PKG4: LINE/COL ERROR -------- ----------------------------------------------------------------- 4/9 PL/SQL: Statement ignored 4/43 PLS-00201: identifier 'CONSTANTS_PKG.WHATEVER' must be declared SQL> `PKG4` is INVALID because we have not built `CONSTANTS_PKG` yet. SQL> create or replace package constants_pkg is 2 whatever constant varchar2(20) := 'WHATEVER'; 3 end constants_pkg; 4 / Package created. SQL> select object_name, object_type, status 2 from user_objects 3 where status != 'VALID' 4 order by 1, 2 5 / OBJECT_NAME OBJECT_TYPE STATUS --------------- --------------- ------- PKG4 PACKAGE BODY INVALID SQL> SQL> set serveroutput on size unlimited SQL> exec pkg4.p7 PKG4.P7::WHATEVER PL/SQL procedure successfully completed. SQL> select object_name, object_type, status 2 from user_objects 3 where status != 'VALID' 4 order by 1, 2 5 / no rows selected SQL> Anything built using `CREATE OR REPLACE` is always created, it is just marked as INVALID if there are errors. As soon as we execute it, directly or indirectly, the database compiles it for us. So, order does not matter. Really it doesn't. If the idea of finishing a build with invalid objects concerns you - and I have some sympathy with that, we are told not to live with broken windows - you can use the `utlrp` script or in 11g [the UTL_RECOMP package](http://download- west.oracle.com/docs/cd/B19306_01/appdev.102/b14258/u_recomp.htm#i999843); either approach requires a SYSDBA account. **edit 2** > The process is based around a build tool which was built by the vendor of > the product we are integrating with, which is why the only inputs I can give > to the build process are a list of files in the order they need to be built > in. If there is a compiler error, the build tool fails, we have to manually > submit a request for a new build. This is a political problem not a technical one. Which isn't to say that political problems can't be resolved with a technical fix, just that the technical fix is not the best tool for the job. Good luck.
flip bytes using Python's struct module Question: I would like to flip from big to little endian this string: `\x00\x40` to have it like this: `\x40\x00` I guess the proper function to use would be struct.pack, but I can't find a way to make it properly work. A small help would be very appreciated ! Thanks Answer: You're not showing the whole code, so the simplest solution would be: data = data[1] + data[0] If you insist on using `struct`: >>> from struct import pack, unpack >>> unpack('<H', '\x12\x13') (4882,) >>> pack('>H', *unpack('<H', '\x12\x13')) '\x13\x12' Which first unpacks the string as a little-endian unsigned short, and then packs it back as big-endian unsigned short. You can have it the other way around, of course. When converting between BE and LE it doesn't matter which way you're converting - the conversion function is bi-directional.
Python: convert script from procedural to OOP style Question: I wrote this simple Munin plugin to graph average fan speed and I want to redo it to OOP - strictly as a learning exercise. Don't have a clue where to start though. Anyone feel like offering some guidance or even an example of what this script should look like when done. I will use it to redo some other scripts into an OOP style as well; again for learning purposes. import sys import subprocess CMD = "/usr/sbin/omreport chassis fans".split() # Munin populates sys.argv[1] with "" (an empty argument), lets remove it. sys.argv = [x for x in sys.argv if x] if len(sys.argv) > 1: if sys.argv[1].lower() == "autoconfig": print "autoconfig" elif sys.argv[1].lower() == "config": print "graph_title Average Fan Speed" print "graph_args --base 1000 -l 0" print "graph_vlabel speed (RPM)" print "graph_category Chassis" print "graph_info This graph shows the average speed of all fans" print "graph_period second" print "speed.label speed" print "speed.info Average fan speed for the five minutes." else: try: data = subprocess.Popen(CMD,stdout=subprocess.PIPE).stdout.readlines() except OSError, e: print >> sys.stderr, "Error running '%s', %s" % (" ".join(cmd), e) sys.exit(1) count = total = 0 for item in data: if "Reading" in item: # Extract variable length fan speed, without regex. total += int(item.split(":")[1].split()[0]) count += 1 # Sometimes omreport returns zero output if omsa services aren't started. if not count or not total: print >> sys.stderr, 'Error: "omreport chassis fans" returned 0 output.' print >> sys.stderr, 'OMSA running? Try: "srvadmin-services.sh status".' sys.exit(1) avg = (total / count) print "speed.value %s" % avg Answer: You remake it in OOP by identifying code and data that goes together. These you then merge into "classes". You actual data above seems to be the output of a process. The code is iterating over it. I guess you can make a class out of that if you want to, but it's a bit silly. :) So, something like this (obviously completely untested code): import sys import subprocess class Fanspeed(object): def __init__(self, command): self.command = command.split() def average_fan_speed(self): data = subprocess.Popen(CMD,stdout=subprocess.PIPE).stdout.readlines() count = total = 0 for item in data: if "Reading" in item: # Extract variable length fan speed, without regex. total += int(item.split(":")[1].split()[0]) count += 1 # Sometimes omreport returns zero output if omsa services aren't started. if not count or not total: raise ValueError("I found no fans. Is OMSA services started?" avg = (total / count) return % avg if __main__ == '__main__': # Munin populates sys.argv[1] with "" (an empty argument), lets remove it. sys.argv = [x for x in sys.argv if x] if len(sys.argv) > 1: if sys.argv[1].lower() == "autoconfig": print "autoconfig" elif sys.argv[1].lower() == "config": print "graph_title Average Fan Speed" print "graph_args --base 1000 -l 0" print "graph_vlabel speed (RPM)" print "graph_category Chassis" print "graph_info This graph shows the average speed of all fans" print "graph_period second" print "speed.label speed" print "speed.info Average fan speed for the five minutes." else: try: cmd = "/usr/sbin/omreport chassis fans" fanspeed = Fanspeed(cmd) average = fanspeed.average_fan_speed() except OSError, e: print >> sys.stderr, "Error running '%s', %s" % (cmd, e) sys.exit(1) except ValueError, e: # Sometimes omreport returns zero output if omsa services aren't started. print >> sys.stderr, 'Error: "omreport chassis fans" returned 0 output.' print >> sys.stderr, 'OMSA running? Try: "srvadmin-services.sh status".' sys.exit(1) But YMMV. It's perhaps a bit clearer.
Python: How do I force iso-8859-1 file output? Question: How do I force Latin-1 (which I guess means iso-8859-1?) file output in Python? Here's my code at the moment. It works, but trying to import the resulting output file into a Latin-1 MySQL table produces [weird encoding errors](http://stackoverflow.com/questions/2188522/importing-text-to-mysql- strange-format). outputFile = file( "textbase.tab", "w" ) for k, v in textData.iteritems(): complete_line = k + '~~~~~' + v + '~~~~~' + " ENDOFTHELINE" outputFile.write(complete_line) outputFile.write( "\n" ) outputFile.close() The resulting output file seems to be saved in "Western (Mac OS Roman)", but if I then save it in Latin-1, I still get strange encoding problems. How can I make sure that the strings used, and the file itself, are all encoded in Latin-1 as soon as they are generated? The original strings (in the `textData` dictionary) have been parsed in from an RTF file - I don't know if that makes a difference. I'm a bit new to Python and to encoding generally, so apologies if this is a dumb question. I have tried looking at the docs but haven't got very far. I'm using Python 2.6.1. Answer: Simply use the [`codecs`](http://docs.python.org/library/codecs.html) module for writing the file: import codecs outputFile = codecs.open("textbase.tab", "w", "ISO-8859-1") Of course, the strings you write have to be Unicode strings (type `unicode`), they won't be converted if they are plain `str` objects (which are basically just arrays of bytes). I guess you are reading the RTF file with the normal Python file object as well, so you might have to convert that to using `codecs.open` as well.
Determining the unmatched portion of a string using a regex in Python Question: Suppose I have a string "a foobar" and I use "^a\s*" to match "a ". Is there a way to easily get "foobar" returned? (What was NOT matched) I want to use a regex to look for a _command word_ and also use the regex to remove the command word from the string. I know how to do this using something like: mystring[:regexobj.start()] + email[regexobj.end():] But this falls apart if I have multiple matches. Thanks! Answer: Use `re.sub`: import re s = "87 foo 87 bar" r = re.compile(r"87\s*") s = r.sub('', s) print s Result: foo bar
Getting python MySQLdb to run on Ubuntu Question: I created a virtualbox with a fresh install of ubuntu 9.10. I am trying to get MySQLdb to run on python but I'm failing at the `import MySQLdb` I first tried `sudo easy_install MySQL_python-1.2.3c1-py2.6-linux-i686.egg` and then `sudo apt-get install python-mysqldb`. Both apparently installed ok, but gave me the following error message when in python I have the import line: Traceback (most recent call last): File "<stdin>", line 1, in <module> File "/usr/local/lib/python2.6/dist-packages/MySQL_python-1.2.3c1-py2.6-linux-i686.egg/MySQLdb/__init__.py", line 19, in <module> File "/usr/local/lib/python2.6/dist-packages/MySQL_python-1.2.3c1-py2.6-linux-i686.egg/_mysql.py", line 7, in <module> File "/usr/local/lib/python2.6/dist-packages/MySQL_python-1.2.3c1-py2.6-linux-i686.egg/_mysql.py", line 6, in __bootstrap__ ImportError: libmysqlclient_r.so.15: cannot open shared object file: No such file or directory I have already installed MySQL and it is running, if that matters at all. I tried following [this](http://forums.mysql.com/read.php?50,191097,193961#msg-193961), but failed in step 2 Answer: Your MySQLdb egg installation looks like it is not working properly. You should go into /usr/local/lib/python2.6/dist-packages and remove it. The Ubuntu python-mysqldb package should work fine. Unless you have a good reason, you should stick to your distribution's package manager when installing new software.
How to implement an efficient infinite generator of prime numbers in Python? Question: This is not a homework, I am just curious. INFINITE is the key word here. I wish to use it as for p in primes(). I believe that this is a built-in function in Haskell. So, the answer cannot be as naive as "Just do a Sieve". First of all, you do not know how many consecutive primes will be consumed. Well, suppose you could concoct 100 of them at a time. Would you use the same Sieve approach as well as the frequency of prime numbers formula? I prefer non-concurrent approach. Thank you for reading (and writing ;) )! Answer: # “If I have seen further…” The `erat2` function from the cookbook can be further sped up (by about 20-25%): ## erat2a import itertools as it def erat2a( ): D = { } yield 2 for q in it.islice(it.count(3), 0, None, 2): p = D.pop(q, None) if p is None: D[q*q] = q yield q else: # old code here: # x = p + q # while x in D or not (x&1): # x += p # changed into: x = q + 2*p while x in D: x += 2*p D[x] = p The `not (x&1)` check verifies that `x` is odd. However, since _both_ `q` and `p` are odd, by adding `2*p` half of the steps are avoided along with the test for oddity. ## erat3 If one doesn't mind a little extra fanciness, `erat2` can be sped up by 35-40% with the following changes (NB: needs Python 2.7+ or Python 3+ because of the `itertools.compress` function): import itertools as it def erat3( ): D = { 9: 3, 25: 5 } yield 2 yield 3 yield 5 MASK= 1, 0, 1, 1, 0, 1, 1, 0, 1, 0, 0, 1, 1, 0, 0, MODULOS= frozenset( (1, 7, 11, 13, 17, 19, 23, 29) ) for q in it.compress( it.islice(it.count(7), 0, None, 2), it.cycle(MASK)): p = D.pop(q, None) if p is None: D[q*q] = q yield q else: x = q + 2*p while x in D or (x%30) not in MODULOS: x += 2*p D[x] = p The `erat3` function takes advantage of the fact that all primes (except for 2, 3, 5) modulo 30 result to only eight numbers: the ones included in the `MODULOS` frozenset. Thus, after yielding the initial three primes, we start from 7 and work _only_ with the candidates. The candidate filtering uses the `itertools.compress` function; the “magic” is in the `MASK` sequence; `MASK` has 15 elements (there are 15 odd numbers in every 30 numbers, as chosen by the `itertools.islice` function) with a `1` for every possible candidate, starting from 7. The cycle repeats as specified by the `itertools.cycle` function. The introduction of the candidate filtering needs another modification: the `or (x%30) not in MODULOS` check. The `erat2` algorithm processed all odd numbers; now that the `erat3` algorithm processes only r30 candidates, we need to make sure that all `D.keys()` can only be such —false— candidates. ## Benchmarks ### Results On an Atom 330 Ubuntu 9.10 server, versions 2.6.4 and 3.1.1+: $ testit up to 8192 ==== python2 erat2 ==== 100 loops, best of 3: 18.6 msec per loop ==== python2 erat2a ==== 100 loops, best of 3: 14.5 msec per loop ==== python2 erat3 ==== Traceback (most recent call last): … AttributeError: 'module' object has no attribute 'compress' ==== python3 erat2 ==== 100 loops, best of 3: 19.2 msec per loop ==== python3 erat2a ==== 100 loops, best of 3: 14.1 msec per loop ==== python3 erat3 ==== 100 loops, best of 3: 11.7 msec per loop On an AMD Geode LX Gentoo home server, Python 2.6.5 and 3.1.2: $ testit up to 8192 ==== python2 erat2 ==== 10 loops, best of 3: 104 msec per loop ==== python2 erat2a ==== 10 loops, best of 3: 81 msec per loop ==== python2 erat3 ==== Traceback (most recent call last): … AttributeError: 'module' object has no attribute 'compress' ==== python3 erat2 ==== 10 loops, best of 3: 116 msec per loop ==== python3 erat2a ==== 10 loops, best of 3: 82 msec per loop ==== python3 erat3 ==== 10 loops, best of 3: 66 msec per loop ### Benchmark code A `primegen.py` module contains the `erat2`, `erat2a` and `erat3` functions. Here follows the testing script: #!/bin/sh max_num=${1:-8192} echo up to $max_num for python_version in python2 python3 do for function in erat2 erat2a erat3 do echo "==== $python_version $function ====" $python_version -O -m timeit -c \ -s "import itertools as it, functools as ft, operator as op, primegen; cmp= ft.partial(op.ge, $max_num)" \ "next(it.dropwhile(cmp, primegen.$function()))" done done
How to create a scrollable screen in text mode with Python Question: I would like to create a scrollable screen in text mode, like the one obtained when typing help(object) in the interpreter. Is there a cross-platform module I can use to easily implement this? For example: >>> def jhelp(object): >>> text = # get text for object >>> display_text(text) # display a scrollable screen. How do I do this? >>> >>> l = [1,2,3] >>> jhelp(l) Answer: from pydoc import ttypager def jhelp(object): text = # get text for object ttypager(text) # display a scrollable screen.
How can I validate a date in Python 3.x? Question: I would like to have the user input a date, something like: date = input('Date (m/dd/yyyy): ') and then make sure that the input is a valid date. I don't really care that much about the date format. Thanks for any input. Answer: You can use the [`time` module's `strptime()`](http://docs.python.org/library/time.html#time.strptime) function: import time date = input('Date (mm/dd/yyyy): ') try: valid_date = time.strptime(date, '%m/%d/%Y') except ValueError: print('Invalid date!') Note that in Python 2.x you'll need to use `raw_input` instead of `input`.
Django: What's an awesome plugin to maintain images in the admin? Question: I have an articles entry model and I have an excerpt and description field. If a user wants to post an image then I have a separate ImageField which has the default standard file browser. I've tried using `django-filebrowser` but I don't like the fact that it requires `django-grappelli` nor do I necessarily want a flash upload utility - can anyone recommend a tool where I can manage image uploads, and basically replace the file browse provided by django with an imagepicking browser? In the future I'd probably want it to handle image resizing and specify default image sizes for certain article types. **Edit:** I'm trying out [adminfiles](http://bitbucket.org/carljm/django- adminfiles/overview/) now but I'm having issues installing it. I grabbed it and added it to my python path, added it to INSTALLED_APPS, created the databases for it, uploaded an image. I followed the instructions to modify my Model to specify `adminfiles_fields` and registered but it's not applying in my admin, here's my `admin.py` for articles: from django.contrib import admin from django import forms from articles.models import Category, Entry from tinymce.widgets import TinyMCE from adminfiles.admin import FilePickerAdmin class EntryForm( forms.ModelForm ): class Media: js = ['/media/tinymce/tiny_mce.js', '/media/tinymce/load.js']#, '/media/admin/filebrowser/js/TinyMCEAdmin.js'] class Meta: model = Entry class CategoryAdmin(admin.ModelAdmin): prepopulated_fields = { 'slug': ['title'] } class EntryAdmin( FilePickerAdmin ): adminfiles_fields = ('excerpt',) prepopulated_fields = { 'slug': ['title'] } form = EntryForm admin.site.register( Category, CategoryAdmin ) admin.site.register( Entry, EntryAdmin ) Here's my Entry model: class Entry( models.Model ): LIVE_STATUS = 1 DRAFT_STATUS = 2 HIDDEN_STATUS = 3 STATUS_CHOICES = ( ( LIVE_STATUS, 'Live' ), ( DRAFT_STATUS, 'Draft' ), ( HIDDEN_STATUS, 'Hidden' ), ) status = models.IntegerField( choices=STATUS_CHOICES, default=LIVE_STATUS ) tags = TagField() categories = models.ManyToManyField( Category ) title = models.CharField( max_length=250 ) excerpt = models.TextField( blank=True ) excerpt_html = models.TextField(editable=False, blank=True) body_html = models.TextField( editable=False, blank=True ) article_image = models.ImageField(blank=True, upload_to='upload') body = models.TextField() enable_comments = models.BooleanField(default=True) pub_date = models.DateTimeField(default=datetime.datetime.now) slug = models.SlugField(unique_for_date='pub_date') author = models.ForeignKey(User) featured = models.BooleanField(default=False) def save( self, force_insert=False, force_update= False): self.body_html = markdown(self.body) if self.excerpt: self.excerpt_html = markdown( self.excerpt ) super( Entry, self ).save( force_insert, force_update ) class Meta: ordering = ['-pub_date'] verbose_name_plural = "Entries" def __unicode__(self): return self.title Edit #2: To clarify I did move the media files to my media path and they are indeed rendering the image area, I can upload fine, the `<<<image>>>` tag is inserted into my editable MarkItUp w/ Markdown area but it isn't rendering in the MarkItUp preview - perhaps I just need to apply the `|upload_tags` into that preview. I'll try adding it to my template which posts the article as well. Answer: Try [django-adminfiles](http://bitbucket.org/carljm/django- adminfiles/overview/) \- it's awesome. You can upload images or choose existing ones, and insert them anywhere within the text, where they will be displayed as `<<<placeholders>>>`. You fully control how the placeholders are resolved on the actual site, using special templates - allowing you to control how images are displayed on the site (that includes scaling, using for example sorl.thumbnail template tag). The app can easily support inserting files of other types - you just create a templates for a given file type, showing how it should be presented on your website. It even supports inserting from Flicker and YouTube. As you can see I'm still really stoked about finding it :) It will look something like this in your admin panel (although the screenshot is from a really old version): ![django-adminfiles](http://lincolnloop.com/legacy/media/img/django-admin- uploads.png) **Update** : You have full control over when and how images are displayed. Some examples: 1. For the main article page I want the default image display style, so that's what I write in my template (this will render the images according to rules I defined in my default adminfiles/render/image/default.html template): `{{ article.content|render_uploads }}` 2. But let's say in my e-mail newsletter I don't want to embed the image - I just want to link to it. I will write this in the template (this will render the images according to rules I defined in my adminfiles/render_as_link/default.html template): `{{ post.content|render_uploads:"adminfiles/render_as_link" }}` 3. I don't want to have image embed code (or any other HTML for that matter) in my search index, so in my django-haystack template I just do this to remove all HTML: `{{ article.content|render_uploads|striptags }}` 4. Or I can do this to index images' captions (but not images themselves; again, this assumes you've got adminfiles/only_caption/default.html template with the right code in place): `{{ article.content|render_uploads:"adminfiles/only_caption" }}` 5. Ok, but what if I want to preserve all other HTML formatting, but don't want to display the images? I'll create an empty `adminfiles/blank/default.html` file and to this: `{{ article.content|render_uploads:"adminfiles/blank" }}` There are some other ways you could achieve the same effect (for example by choosing right `ADMINFILES_REF_START` and `ADMINFILES_REF_END` and not using the filter at all), but I think this post is too long already ;)
Instantiate a Python class from a name Question: So i have a set of classes and a string with one of the class names. How do I instantiate a class based on that string? class foo: def __init__(self, left, right): self.left = left self.right = right str = "foo" x = Init(str, A, B) I want x to be an instantiation of class foo. Answer: In your case you can use something like get_class = lambda x: globals()[x] c = get_class("foo") And it's even easier no get class from the module import somemodule getattr(somemodule, "SomeClass")
How to transform tuple of string(object locations) to dictionary of objects in python Question: I would like to transform a tuple: TEST_CLASSES = ( 'common.test.TestClass', ) to TEST_CLASSES = { 'test': common.test.TestClass, } How to make a dictionary is simple but I have a problem with conversion from string to object. Could anybody help me please? thanks! Answer: You could use [`eval`](http://docs.python.org/library/functions.html#eval), which can be **evil** if your inputs are not safe: >>> import os >>> eval('os.path.join') <function join at 0x00BBA2B8> if the `common.test.TestClass` doesn't exist in the current namespace a `NameError` will be raised: >>> eval('math.isnan') Traceback (most recent call last): File "<pyshell#5>", line 1, in <module> eval('math.isnan') File "<string>", line 1, in <module> NameError: name 'math' is not defined
How to mount a network directory using python? Question: I need to mount a directory "dir" on a network machine "data" using python on a linux machine I know that I can send the command via command line: mkdir ~/mnt/data_dir mount -t data:/dir/ ~/mnt/data_dir but how would I send those commands from a python script? Answer: I'd recommend you use `subprocess.checkcall`. from subprocess import * #most simply check_call( 'mkdir ~/mnt/data_dir', shell=True ) check_call( 'mount -t whatever data:/dir/ ~/mnt/data_dir', shell=True ) #more securely from os.path import expanduser check_call( [ 'mkdir', expanduser( '~/mnt/data_dir' ) ] ) check_call( [ 'mount', '-t', 'whatever', 'data:/dir/', expanduser( '~/mnt/data_dir' ) ] )
Python regex - r prefix Question: Can anyone explain why example 1 below works, when the r prefix is not used? I thought the r prefix must be used whenever escape sequences are used? Example 2 and example 3 demonstrates this.. # example 1 import re print (re.sub('\s+', ' ', 'hello there there')) # prints 'hello there there' - not expected as r prefix is not used # example 2 import re print (re.sub(r'(\b\w+)(\s+\1\b)+', r'\1', 'hello there there')) # prints 'hello there' - as expected as r prefix is used # example 3 import re print (re.sub('(\b\w+)(\s+\1\b)+', '\1', 'hello there there')) # prints 'hello there there' - as expected as r prefix is not used Answer: Because `\` begin escape sequences only when they are valid escape sequences. >>> '\n' '\n' >>> r'\n' '\\n' >>> print '\n' >>> print r'\n' \n >>> '\s' '\s' >>> r'\s' '\\s' >>> print '\s' \s >>> print r'\s' \s > [Unless](http://docs.python.org/library/re.html) an 'r' or 'R' prefix is > present, [escape > sequences](http://docs.python.org/reference/lexical_analysis.html) in > strings are interpreted according to rules similar to those used by Standard > C. The recognized escape sequences are: > > > Escape Sequence Meaning Notes > \newline Ignored > \\ Backslash (\) > \' Single quote (') > \" Double quote (") > \a ASCII Bell (BEL) > \b ASCII Backspace (BS) > \f ASCII Formfeed (FF) > \n ASCII Linefeed (LF) > \N{name} Character named name in the Unicode database (Unicode only) > \r ASCII Carriage Return (CR) > \t ASCII Horizontal Tab (TAB) > \uxxxx Character with 16-bit hex value xxxx (Unicode only) > \Uxxxxxxxx Character with 32-bit hex value xxxxxxxx (Unicode only) > \v ASCII Vertical Tab (VT) > \ooo Character with octal value ooo > \xhh Character with hex value hh > Never rely on raw strings for path literals, as raw strings have some rather _peculiar_ inner workings, known to have bitten people in the ass: > When an "r" or "R" prefix is present, a character following a backslash is > included in the string without change, and all backslashes are left in the > string. For example, the string literal `r"\n"` consists of two characters: > a backslash and a lowercase "n". String quotes can be escaped with a > backslash, but the backslash remains in the string; for example, `r"\""` is > a valid string literal consisting of two characters: a backslash and a > double quote; `r"\"` is not a valid string literal (even a raw string cannot > end in an odd number of backslashes). Specifically, a raw string cannot end > in a single backslash (since the backslash would escape the following quote > character). Note also that a single backslash followed by a newline is > interpreted as those two characters as part of the string, not as a line > continuation. To better illustrate this last point: >>> r'\' SyntaxError: EOL while scanning string literal >>> r'\'' "\\'" >>> '\' SyntaxError: EOL while scanning string literal >>> '\'' "'" >>> >>> r'\\' '\\\\' >>> '\\' '\\' >>> print r'\\' \\ >>> print r'\' SyntaxError: EOL while scanning string literal >>> print '\\' \
Venn Diagram up to 4 lists - outputting the intersections and unique sets Question: in my work I use a lot of Venn diagrams, and so far I've been relying on the web-based "[Venny](http://bioinfogp.cnb.csic.es/tools/venny/index.html)". This offers the nice option to export the various intersections (i.e., the elements belonging only to that specific intersection). Also, it does diagrams up to 4 lists. Problem is, doing this with large lists (4K+ elements) and more than 3 sets is a chore (copy, paste, save...). Thus, I have decided to focus on generating the lists myself and use it just to plot. This lengthy introduction leads to the crux of the matter. Given 3 or 4 lists which partially contain identical elements, how can I process them in Python to obtain the various sets (unique, common to 4, common to just first and second, etc...) as shown on the Venn diagram ([3 list graphical example](http://www.math.cornell.edu/~numb3rs/lipa/imgs/venn3.png), [4 list graphical example](http://www.math.cornell.edu/~numb3rs/lipa/imgs/venn4.png))? It doesn't look too hard for 3 lists but for 4 it gets somewhat complex. Answer: Assuming you have python 2.6 or better: >>> from itertools import combinations >>> >>> data = dict( ... list1 = set(list("alphabet")), ... list2 = set(list("fiddlesticks")), ... list3 = set(list("geography")), ... list4 = set(list("bovinespongiformencephalopathy")), ... ) >>> >>> variations = {} >>> for i in range(len(data)): ... for v in combinations(data.keys(),i+1): ... vsets = [ data[x] for x in v ] ... variations[tuple(sorted(v))] = reduce(lambda x,y: x.intersection(y), vsets) ... >>> for k,v in sorted(variations.items(),key=lambda x: (len(x[0]),x[0])): ... print "%r\n\t%r" % (k,v) ... ('list1',) set(['a', 'b', 'e', 'h', 'l', 'p', 't']) ('list2',) set(['c', 'e', 'd', 'f', 'i', 'k', 'l', 's', 't']) ('list3',) set(['a', 'e', 'g', 'h', 'o', 'p', 'r', 'y']) ('list4',) set(['a', 'c', 'b', 'e', 'g', 'f', 'i', 'h', 'm', 'l', 'o', 'n', 'p', 's', 'r', 't', 'v', 'y']) ('list1', 'list2') set(['e', 'l', 't']) ('list1', 'list3') set(['a', 'h', 'e', 'p']) ('list1', 'list4') set(['a', 'b', 'e', 'h', 'l', 'p', 't']) ('list2', 'list3') set(['e']) ('list2', 'list4') set(['c', 'e', 'f', 'i', 'l', 's', 't']) ('list3', 'list4') set(['a', 'e', 'g', 'h', 'o', 'p', 'r', 'y']) ('list1', 'list2', 'list3') set(['e']) ('list1', 'list2', 'list4') set(['e', 'l', 't']) ('list1', 'list3', 'list4') set(['a', 'h', 'e', 'p']) ('list2', 'list3', 'list4') set(['e']) ('list1', 'list2', 'list3', 'list4') set(['e'])
How to count both sides of many-to-many relationship in Google App Engine Question: Consider a GAE (python) app that lets users comment on songs. The expected number of users is 1,000,000+. The expected number of songs is 5,000. The app must be able to: * Give the number of songs a user has commented on * Give the number of users who have commented on a song Counter management must be transactional so that they always reflect the underlying data. It seems GAE apps must keep these types of counts calculated at all times since querying for them at request time would be inefficient. **My Data Model** class Song(BaseModel): name = db.StringProperty() # Number of users commenting on the song user_count = db.IntegerProperty('user count', default=0, required=True) date_added = db.DateTimeProperty('date added', False, True) date_updated = db.DateTimeProperty('date updated', True, False) class User(BaseModel): email = db.StringProperty() # Number of songs commented on by the user song_count = db.IntegerProperty('song count', default=0, required=True) date_added = db.DateTimeProperty('date added', False, True) date_updated = db.DateTimeProperty('date updated', True, False) class SongUser(BaseModel): # Will be child of User song = db.ReferenceProperty(Song, required=True, collection_name='songs') comment = db.StringProperty('comment', required=True) date_added = db.DateTimeProperty('date added', False, True) date_updated = db.DateTimeProperty('date updated', True, False) **Code** This handles the user's song count transactionally but not the song's user count. s = Song(name='Hey Jude') s.put() u = User(email='me@example.com') u.put() def add_mapping(song_key, song_comment, user_key): u = User.get(user_key) su = SongUser(parent=u, song=song_key, song_comment=song_comment, user=u); u.song_count += 1 u.put() su.put() # Transactionally add mapping and increase user's song count db.run_in_transaction(add_mapping, s.key(), 'Awesome', u.key()) # Increase song's user count (non-transactional) s.user_count += 1 s.put() **The question is:** How can I manage both counters transactionally? Based on my understanding this would be impossible since User, Song, and SongUser would have to be a part of the same [entity group](http://code.google.com/appengine/docs/python/datastore/keysandentitygroups.html#Entity_Groups_Ancestors_and_Paths). They can't be in one entity group because then all my data would be in one group and it could not be distributed by user. Answer: You really shouldn't have to worry about handling the user's count of songs on which they have commented inside a transaction because it seems unlikely that a User would be able to comment on more than one song at a time, right? Now, it is definitely the case that many users could be commenting on the same song at one time, so that is where you have to worry about making sure that the data isn't made invalid by a race condition. However, if you keep the count of the number of users who have commented on a song inside the Song entity, and lock the entity with a transaction, you are going to get very high contention for that entity and datastore timeouts will make you application have lots of problems. This answer for this problem is [Sharded Counters](http://code.google.com/appengine/articles/sharding_counters.html). In order to make sure that you can create a new SongUser entity and update the related Song's sharded counter, you should consider having the SongUser entity have the related Song as a parent. That will put them in the same entity group and you can both create the SongUser and updated the sharded counter in the same transaction. The SongUser's relationship to the User who created it can be held in a ReferenceProperty. Regarding your concern about the two updates (the transactional one and the User update) not both succeeding, that is always a possibility, but given that either update can fail, you will need to have proper exception-handling to ensure that both succeed. That's an important point: the in-transaction- updates are not guaranteed to succeed. You may get a TransactionfailedError exception if the transaction can not complete for any reason. So, if your transaction completes without raising an exception, run the update to User in a transaction. That will get you automatic retries of the update to User, should some error occur. Unless there's something about possible contention on the User entity that I don't understand, the possiblity that it will not eventually succeed is _surpassingly small_. If that is an unacceptable risk, then I don't think that that AppEngine has a perfect solution to this problem for you. First ask yourself: _is it really that bad if the count of songs that someone has commented on is off by one? Is this as critical as updating a bank account balance or completing a stock sale?_
How does one run Spawning with Django within a virtualenv? Question: Because of the way Eventlet, which Spawning depends on, installs itself, it can't be installed into a virtualenv. The following error (wrapped for readability) illustrates: Running eventlet-0.9.4/setup.py -q bdist_egg --dist-dir \ /tmp/easy_install-m_s75o/eventlet-0.9.4/egg-dist-tmp-fAZK_u error: SandboxViolation: chmod('/home/myuser/.python-eggs/\ greenlet-0.2-py2.6-linux-i686.egg-tmp/tmpgxa_uc.$extract', 493) {} Without patching the Python path beyond all recognition, and installing Spawning globally (which would break the whole point of having a virtualenv anyway), how would one install/run this? Answer: The following five commands worked without any problems. How are you installing spawning? virtualenv test cd test/ . bin/activate easy_install spawning python -c 'import spawning'
How can I filter a pcap file by specific protocol using python? Question: I have some pcap files and I want to filter by protocol, i.e., if I want to filter by HTTP protocol, anything but HTTP packets will remain in the pcap file. There is a tool called [openDPI](http://www.opendpi.org/), and it's perfect for what I need, but there is no wrapper for python language. Does anyone knows any python modules that can do what I need? Thanks **Edit 1:** HTTP filtering was just an example, there is a lot of protocols that I want to filter. **Edit 2:** I tried Scapy, but I don't figure how to filter correctly. The filter only accepts Berkeley Packet Filter expression, i.e., I can't apply a msn, or HTTP, or another specific filter from upper layer. Can anyone help me? Answer: I know this is a super-old question, but I just ran across it thought I'd provide **_my_** answer. This is a problem I've encountered several times over the years, and I keep finding myself falling back to [dpkt](http://code.google.com/p/dpkt/). Originally from the very capable [dugsong](http://monkey.org/~dugsong/), dpkt is primarily a packet creation/parsing library. I get the sense the pcap parsing was an afterthought, but it turns out to be a very useful one, because parsing pcaps, IP, TCP and and TCP headers is straightforward. It's parsing all the higher- level protocols that becomes the time sink! (I wrote my own python pcap parsing library before finding dpkt) The documentation on using the pcap parsing functionality is a little thin. Here's an example from my files: import socket import dpkt import sys pcapReader = dpkt.pcap.Reader(file(sys.argv[1], "rb")) for ts, data in pcapReader: ether = dpkt.ethernet.Ethernet(data) if ether.type != dpkt.ethernet.ETH_TYPE_IP: raise ip = ether.data src = socket.inet_ntoa(ip.src) dst = socket.inet_ntoa(ip.dst) print "%s -> %s" % (src, dst) Hope this helps the next guy to run across this post!
`if __name__ == '__main__'` equivalent in Ruby Question: I am new to Ruby. I'm looking to import functions from a module that contains a tool I want to continue using separately. In Python I would simply do this: def a(): ... def b(): ... if __name__ == '__main__': a() b() This allows me to run the program or import it as a module to use `a()` and/or `b()` separately. What's the equivalent paradigm in Ruby? Answer: From the Ruby I've seen out in the wild (granted, not a ton), this is not a standard Ruby design pattern. Modules and scripts are supposed to stay separate, so I wouldn't be surprised if there isn't really a good, clean way of doing this. **EDIT:** [Found it.](http://gimbo.org.uk/blog/2006/04/18/scripts-in-ruby-a- la-pythons-__name__-__main__-idiom/) if __FILE__ == $0 foo() bar() end But it's definitely not common.
Can someone help me with this JAVA SAXParser? Question: I've been fiddling for 3 hours and I can't get this F* **** parser to work. Sorry for cursing. I don't understand why I can't find **one decent tutorial** that does exactly what I want. I just want to send the function a String/XML. Then, parse it. it's not that hard. In python, I can do it with my eyes closed. Awesome, freaking documentation right here: <http://www.crummy.com/software/BeautifulSoup/documentation.html> import BeautifulSoup soup = BeautifulSoup(the_xml) persons_name = soup.findAll('first_name')[0].string Why can't I find a good, simple, documentation that teaches me how to parse XML????? This is my current code for JAVA SAX, and its not working, and I don't even know why. public static void parseit(String thexml) { SAXParserFactory factory = SAXParserFactory.newInstance(); try { SAXParser saxParser = factory.newSAXParser(); saxParser.parse( thexml , new DefaultHandler() ); } catch (Throwable err) { err.printStackTrace (); } } Can someone just write me the code to parse the XML using SAX parser...please...It's just like 5 lines of code. Answer: You have to extends your default handler DefaultHandler. For example, try this: saxParser.parse( new InputSource(new StringReader(thexml)) , new DefaultHandler() { public void startElement(String uri, String localName, String qName, Attributes attributes) { System.out.println("Hello "+qName); } });
Class Inheritance Question: I am trying to get completely to grips with class inheritence in Python. I have created program's with classes but they are all in one file. I have also created scripts with multiple files containing just functions. I have started using class inheritence in scripts with multiple files and I am hitting problems. I have 2 basic scripts below and I am trying to get the second script to inherit values from the first script. The code is as follow's: First Script: class test(): def q(): a = 20 return a def w(): b = 30 return b if __name__ == '__main__': a = q() b = w() if __name__ == '__main__': (a, b) = test() Second Script: from class1 import test class test2(test): def e(a, b): print a print b e(a, b) if __name__ == '__main__': test2(test) Can anyone explain to me how to get the second file to inherit the first files values? Thanks for any help. Answer: I would say you messed up class definition with function stuff. It should look more like this: class Test(object): def __init__(self): self.a = 20 self.b = 30 if __name__ == '__main__': test_instance = Test() and from class1 import Test class Test2(Test): def e(self): print self.a print self.b if __name__ == '__main__': test_instance = Test2() test_instance.e() # prints 20 and 30 It looks like your problem is not (only) inheritance, but also **how to correctly[define classes in Python](http://docs.python.org/tutorial/classes.html)**. Some notes: * Always use capitalized names for classes. That is more or less convention. * As ruibm pointed out, every (non-static) method of a class has to have a first parameter that is named (by convention) `self`. * You can create instance variables by setting them as `self.variable = value` in the `__init__` method. * If you call `Test()` you get an object back. Unless you assign it to a variable, just calling `test2()` as you did in your second piece of code has no effect. Maybe it had in your case because defined your class in a weird way.
How to parse just the text from a Word Doc using Python? Question: When you try opening a MS Word document or for that matter most Windows file formats, you will see gibberish as given below broken intermittently by the actual text. I need to extract the text that goes in and want to ignore the gibberish -- which is something like given below. How do I extract only the text that matters, and ignore rest of the stuff. Please advise. Here's a sample of `open("sample.doc",r").read()` of a word doc. Thanks 00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00In an Interesting news,his is the first time we polled Indian channel community for their preferred memory supplier. Transcend came a close second, was seen to be more popular among class A city based resellers, was also the most recalled memory brand among customers according to resellers. However Transcend channels complained of parallel imports and constant unavailability of the products in grey x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x Answer: The tool that seems the most viable, particularly if you need an all python solution is [OleFileIO](http://www.decalage.info/en/python/olefileio).
Python - codec encoding ascii to unicode: error Question: :) I am trying to go about the process of reversing transliteration of an input file(currently in english) back to its original form(in hindi) A sample or a part of the input file looks like this: E-k- b-u-d-z*dhi-m-aan- p-ksii# E-k- ghn-e- j-ngg-l- m-e-ng E-k- b-h-u-t- UUNNc-aa p-e-dr thaa# U-s- k-ii p-t-z*t-o-ng s-e- l-d-ii shaakhaay-e-ng m-j-*zb-uut- b-aaj-u-O-ng k-ii t-r-h- pheil-ii h-u-II thiing# w-n- h-NNs-o-ng k-aa E-k- jhu-nhz*D- I-s- p-e-dr p-r- n-i-w-aas- k-r-t-aa thaa# w-e- s-b- y-h-aaNN s-u-r-ksi-t- the- AUr- b-dre- AAr-aam- s-e- r-h-t-e- the-# U-n- m-e-ng s-e- E-k- p-ksii b-h-u-t- b-u-d-z*dhi-m-aan- thaa# I-s- b-u-d-z*dhi-m-aan- p-ksii n-e- E-k- d-i-n- p-e-dr k-ii j-dr m-e-ng s-e- E-k- l-t-aa k-o- U-g-t-e- d-e-khaa# I-s- k-e- b-aar-e- m-e-ng U-s-n-e- d-uus-r-e- p-ksi-y-o-ng s-e- b-aat- k-ii# "k-z*y-aa t-u-m-z*h-e-ng w-h- l-t-aa d-i-khaaII d-e-t-ii h-ei", U-s- n-e- U-n- s-e- p-uuchaa "t-u-m-z*h-e-ng I-s-e- n-Shz*T- k-r- d-e-n-aa c-aah-i-E-"# "I-s-e- k-z*y-o-ng n-Shz*T- k-r- d-e-n-aa c-aah-i-E-?" h-NNs-o-ng n-e- AAshz*c-*ry- s-e- p-uuchaa "y-h- t-o- I-t-n-ii cho-T-ii s-e- h-ei# h-m-e-ng y-h- k-z*y-aa h-aan-i- p-h-u-NNc-aa s-k-t-ii h-ei"# "m-e-r-e- m-i-tro-ng," b-u-d-z*dhi-m-aan- p-ksii n-e- U-t-z*t-r- d-i-y-aa "w-h- cho-T-ii s-ii l-t-aa j-l-z*d-ii h-ii b-drii h-o- j-aay-e-g-ii# y-h- h-m-aar-e- p-e-dr p-r- c-Dh*z k-r- U-s- s-e- l-i-p-T-t-ii j-aay-e-g-ii AUr- phi-r- m-o-T-ii AUr- m-j-*zb-uut- h-o- j-aay-e-g-ii"# "t-o- k-z*y-aa h-u-AA"# Its equivalent meaning in english is: A WISE OLD BIRD. Deep in the forest stood a very tall tree. Its leafy branches spread out like long arms. This was the home of a flock of wild geese. They were safe there. One of the geese was a wild old bird. One day this wise old bird noticed a small creeper growing at the foot of the tree. He spoke to the other birds about it. "Do you see that creeper ?" he said to them. "You must destroy it." "Why must we destroy it ?" asked the geese in surprise. "It is so small. What harm can it do?" "My friends," replied the wise old bird, " that little creeper will soon grow. My script looks like this: #!/usr/bin/python # -*- coding: UTF-8 -*- import sys CODEC = 'utf-8' input_file=sys.argv[1] output_file=sys.argv[2] list1=[] f=open(input_file,'r') f1 = open(output_file,'w') english_hindi_dict={'A' : u'अ' , 'AA' : u'आ ' , 'I' : u'इ' , 'II' : u'ई ' , 'U' : u'उ ' ,\ 'UU' : u'ऊ' , 'r' : u'ऋ' , 'E' : u'ए' , 'ai' : u'ऐ' , 'O' : u'ओ' , 'AU' : u'औ' ,\ 'k' : u'क' , 'kh' : u'ख' , 'g' : u'ग' , 'gh' : u'घ' , 'c' : u'च' , 'ch' : u'छ',\ 'j': u'ज' , 'jh' : u'झ' , 'tr' : u'त्र' , 'T' : u'ट' , 'Th' : u'ठ' , 'D' : u'ड',\ 'dr' : u'ड' , 'Dh' : u'ढ' , 'Na' : u'ण' , 'th' : u'त' , 'tha' : u'थ',\ 'd' : u'द' , 'dh': u'ध' , 'n' : u'न' , 'p' : u'प' , 'ph' : u'फ' ,\ 'b' : u'ब' , 'bh' : u'भ' , 'm' : u'म' , 'y' : u'य' , 'r' : u'र' , 'l' : u'ल' ,\ 'w' : u'व' , 'sh' : u'श' , 'sha' : u'ष', 's' : u'स' , 'h' : u'ह' , 'ks' : u'क्ष' ,\ 'i' : u'ि' , 'ii' : u'ी' , 'u' : u'ु' , 'uu' : u'ू' , 'e' : u'े' ,\ 'aa' : u'ै' , 'o' : u'ो' , 'AU' : u'ौ' ,'H' : u'्' ,'mn' : u'ं' ,\ 'NN' : u'ँ' , 'AW' : u'ॅ' , 'rr' : u'ृ' , '4' : u'४' , '6': u'६' , '8' : u'८',\ '2' : u'२' , '5' : u'५' , '3' : u'३' , '7' : u'७' , '9' : u'९' , '1' : u'१'} for line in f: #line=line.strip() to remove a line from its newline character.... #line=line.rstrip('.') line=line.replace('-','') line=line.replace('#','|') # i am using the or symbol for poornviram #line=line.replace('।','') #line = line.lower() for word in line: for ch in word: if (ch in english_hindi_dict) : translatedToken = english_hindi_dict[ch] else : translatedToken = ch #{ translatedToken = english_hindi_dict[ch] } #for ch in line: f1.write(translatedToken) #print translatedToken #line = line.replace( char,english_hindi_dict[char] ) #list1.append(line) f.close() f1.write(' '.join(list1)) f1.close() the error that I am getting is: python transliterate_eh_nw.py Hstory.txt op1.txt Traceback (most recent call last): File "transliterate_eh_nw.py", line 43, in <module> f1.write(translatedToken) UnicodeEncodeError: 'ascii' codec can't encode character u'\u092f' in position 0: ordinal not in range(128) Could you please tell me how do I deal with this error. Thank you..:) Answer: You have a few problems other than the one which you asked about. (1) A conceptual problem: "E-k- b-u-d-z*dhi-m-aan- p-ksii#" is **not** "english". It is Hindi language written in ASCII using some romanization scheme. It looks like ITRAN but ITRAN doesn't have AA and A, it has only aa and a. Does the scheme have a name? Can you supply a URL? Your object is better described as "transliterate some Hindi text from the unnamed romanization to Devanagari script". (2) Showing the result of translating your text from Hindi to English ("A WISE OLD BIRD" etc) is only moderately useful. The expected Devanagari output would be a better idea. (3) As remarked by @kaiser.se, the transliteration dictionary has multi-byte (up to 3 bytes!) keys, some of which are prefixes of others. Presumably `AA` must be recognised in priority to `A`, `gh` must be recognised before `g`, etc. Iterating over the items of a dictionary happens in an order that is predictable but for your purposes should be regarded as random. In the code that follows, I've given priority to longer "keys". (4) Either the dictionary is missing some letter keys (a S t z) or the transliteration rules are more complicated than any of us has guessed so far (5) The meaning of the characters # * and - is not 100% obvious. It appears from your input text that z and * appear only in combination as z* (6) It would be a good idea if you explained the interpretation of e.g. `shaakhaay-e-ng` ... does it start with `sh` then `aa` or does it start with `sha` then `a`? What are the rules? The answer to the problem that you asked about is of course as several others have pointed out that you need to encode your unicode output using an encoding that is supported by your display device e.g. UTF-8. Here's some code: #!/usr/bin/python # -*- coding: UTF-8 -*- input_data = """ E-k- b-u-d-z*dhi-m-aan- p-ksii# E-k- ghn-e- j-ngg-l- m-e-ng E-k- b-h-u-t- UUNNc-aa p-e-dr thaa# [snip] "t-o- k-z*y-aa h-u-AA"# """ roman_devanagari_dict={'A' : u'अ' , 'AA' : u'आ ' , 'I' : u'इ' , 'II' : u'ई ' , 'U' : u'उ ' ,\ [snip] '2' : u'२' , '5' : u'५' , '3' : u'३' , '7' : u'७' , '9' : u'९' , '1' : u'१'} #Presuming we need to do the 3-letter cases then the 2-letter then the 1-letter replacements = [(-len(k), unicode(k), v) for k, v in roman_devanagari_dict.items()] replacements.sort() data = input_data.decode('ascii') for _junk, from_text, to_text in replacements: data = data.replace(from_text, to_text) # Presuming the '-' are inter-character markers, delete them last, not first data = data.replace(u'-', '') data = data.replace(u'#', '') print "untransliterated:", set(c for c in data if 0x20 < ord(c) < 0x7f) BOM = u'\ufeff' outf = open('devanagari.txt', 'w') outf.write(BOM.encode('utf8')) # for the benefit of clueless Windows s/w outf.write(data.encode('utf8')) outf.close() Output: एक बुदz*धिमैन पक्षी एक घने जनगगल मेनग एक बहुt ऊँचै पेड थa उ स की पtz*tोनग से लदी षaखैयेनग मज*zबूt बैजुओनग की tरह फेिली हुई तीनग वन हँसोनग कै एक झुनहz*ड इस पेड पर निवैस करtै थa वे सब यहैँ सुरक्षिt ते ौर बडे आ रैम से रहtे ते उ न मेनग से एक पक्षी बहुt बुदz*धिमैन थa इस बुदz*धिमैन पक्षी ने एक दिन पेड की जड मेनग से एक लtै को उ गtे देखै इस के बैरे मेनग उ सने दूसरे पक्षियोनग से बैt की "कz*यै tुमz*हेनग वह लtै दिखैई देtी हेि", उ स ने उ न से पूछै "tुमz*हेनग इसे नSहz*ट कर देनै चैहिए" "इसे कz*योनग नSहz*ट कर देनै चैहिए?" हँसोनग ने आ शz*च*रय से पूछै "यह tो इtनी छोटी से हेि हमेनग यह कz*यै हैनि पहुँचै सकtी हेि" "मेरे मित्रोनग," बुदz*धिमैन पक्षी ने उ tz*tर दियै "वह छोटी सी लtै जलz*दी ही बडी हो जैयेगी यह हमैरे पेड पर चढ*z कर उ स से लिपटtी जैयेगी ौर फिर मोटी ौर मज*zबूt हो जैयेगी" "tो कz*यै हुआ " which has only a few recognisable words when shoved through Google Translate. **Update** after examining the transliteration table more closely: * Three of the entries (AA, II, and U) have a space after the Devanagari equivalent. Perhaps the spaces should be removed. * The general pattern for consonants appears to be: DEVANAGARI LETTER XA is represented by x DEVANAGARI LETTER XXA is represented by X DEVANAGARI LETTER XHA is represented by xh DEVANAGARI LETTER XXHA is represented by Xh However 3 entries break the pattern: SSA -> sha but pattern says S TA -> th but pattern says t THA -> tha but pattern says th Note: changing the above 3 entries stopped my code from complaining that S and t were left unchanged when transliterating your sample text, and removed the seemingly-anomalous sha and tha entries. * Entries (D and dr) are mapped to the same character, DEVANAGARI LETTER DDA. D is the expected entry for that character; perhaps dr should be mapped elsewhere. * There is no entry for DEVANAGARI LETTER NGA (U+0919); perhaps it should be encoded as ng -- there are a few words ending in ng in the sample text. * Are the uncatered-for "z*" occurrences in the sample text anything to do with DEVANAGARI LETTER ZA (U+095B)?
Changing default encoding of Python? Question: I have many "can't encode" and "can't decode" problems with [Python](http://en.wikipedia.org/wiki/Python_%28programming_language%29) when I run my applications from the console. But in the [Eclipse](http://en.wikipedia.org/wiki/Eclipse_%28software%29) [PyDev](http://en.wikipedia.org/wiki/PyDev) IDE, the default character encoding is set to [UTF-8](http://en.wikipedia.org/wiki/UTF-8), and I'm fine. I searched around for setting the default encoding, and people say that Python deletes the `sys.setdefaultencoding` function on startup, and we can not use it. So what's the best solution for it? Answer: Here is a simpler method (hack) that gives you back the `setdefaultencoding()` function that was deleted from `sys`: import sys # sys.setdefaultencoding() does not exist, here! reload(sys) # Reload does the trick! sys.setdefaultencoding('UTF8') **PS** : This is obviously a hack, since `sys.setdefaultencoding()` is purposely removed from `sys` when Python starts. Reenabling it and changing the default encoding [can break code that relies on ASCII being the default](https://anonbadger.wordpress.com/2015/06/16/why-sys- setdefaultencoding-will-break-code/) (this code can be third-party, which would generally make fixing it impossible or dangerous).
Automatic transformation from getter/setter to properties Question: I have a big libray written in C++ and someone created an interface to use it in python (2.6) in an automatic way. Now I have a lot of classes with getter and setter methods. Really: I hate them. I want to reimplement the classes with a more pythonic interface using properties. The problem is that every class has hundreds of getters and setters and I have a lot of classes. How can I automatically create properties? For example, if I have a class called MyClass with a GetX() and SetX(x), GetY, SetY, ... methods how can I automatically create a derived class MyPythonicClass with the property X (readable if there is the getter and writable if there is the setter), and so on? I would like a mechanism that let me to choose to skip some getter/setter couples where is better to do the work by hand. Answer: Here's a way to do it with a class decorator def make_properties(c): from collections import defaultdict props=defaultdict(dict) for k,v in vars(c).items(): if k.startswith("Get"): props[k[3:]]['getter']=v if k.startswith("Set"): props[k[3:]]['setter']=v for k,v in props.items(): setattr(c,k,property(v.get('getter'),v.get('setter'))) return c @make_properties class C(object): def GetX(self): print "GetX" return self._x def SetX(self, value): print "SetX" self._x = value c=C() c.X=5 c.X Here is a slightly more complicated version that allows you to specify a list of items to skip def make_properties(skip=None): if skip is None: skip=[] def f(c): from collections import defaultdict props=defaultdict(dict) for k,v in vars(c).items(): if k.startswith("Get"): props[k[3:]]['getter']=v if k.startswith("Set"): props[k[3:]]['setter']=v for k,v in props.items(): if k in skip: continue setattr(c,k,property(v.get('getter'),v.get('setter'))) return c return f @make_properties(skip=['Y']) class C(object): def GetX(self): print "GetX" return self._x def SetX(self, value): print "SetX" self._x = value def GetY(self): print "GetY" return self._y def SetY(self, value): print "SetY" self._y = value c=C() c.X=5 c.X c.Y=5 c.Y
detecting end of tty output Question: Hi I'm writing a psudo-terminal that can live in a tty and spawn a second tty which is filters input and output from I'm writing it in python for now, spawning the second tty and reading and writing is easy but when I read, the read does not end, it waits for more input. import subprocess pfd = subprocess.Popen(['/bin/sh'], shell=True, stdout=subprocess.PIPE, stdin=subprocess.PIPE) cmd = "ls" pfd.stdin.write(cmd + '\n') out = '' while 1: c = pfd.stdout.read(1) if not c: # if end of output (this never happends) break if c == '\n': # print line when found print repr(out) out = '' else: out += c \----------------------------- outputs ------------------------ intty $ python intty.py 'intty.py' 'testA_blank' 'testB_blank' (hangs here does not return) it looks like it's reaching the end of hte buffer and instead of returning None or '' it hangs waiting for more input. what should I be looking for to see if the output has completed? the end of the buffer? a non-printable character? \---------------- edit ------------- this happends also when I run xpcshell instead of ls, I'm assuming these interactive programs have some way of knowing to display the prompt again, strangly the prompt, in this case "js>" never apears Answer: Well, your output actually hasn't completed. Because you spawned `/bin/sh`, the shell is still running after "ls" completes. There is no EOF indicator, because it's still running. Why not simply run `/bin/ls`? You could do something like pfd = subprocess.Popen(['ls'], stdout=subprocess.PIPE, stdin=subprocess.PIPE) out, err_output = pfd.communicate() This also highlights `subprocess.communicate`, which is a safer way to get output (For outputs which fit in memory, anyway) from a single program run. This will return only when the program has finished running. Alternately, you -could- read linewise from the shell, but you'd be looking for a special shell sequence like the `sh~#` line which could easily show up in program output. Thus, running a shell is probably a bad idea all around. * * * **Edit** Here is what I was referring to, but it's still not really the best solution, as it has a LOT of caveats: while 1: c = pfd.stdout.read(1) if not c: break elif c == '\n': # print line when found print repr(out) out = '' else: out += c if out.strip() == 'sh#': break Note that this will break out if any other command outputs 'sh#' at the beginning of the line, and also if for some reason the output is different from expected, you will enter the same blocking situation as before. This is why it's a very sub-optimal situation for a shell.
Help for novice choosing between Java and Python for app with sql db Question: I'm going to write my first non-Access project, and I need advice on choosing the platform. I will be installing it on multiple friends' and family's computers, so (since I'm sure many, many platforms would suffice just fine for my app), my highest priority has two parts: 1) ease of install for the non- technical user and, 2) minimizing compatibility problems. I want to be able to fix bugs and make changes and roll them out without having to troubleshoot OS and program conflicts on their computers (or at least keeping those things to the absolute minimum-this is why these concerns are my highest priority in choosing a platform.) I have narrowed it down to Python or Java. I like Java's use of the JVM, which seems like would serve to protect against incompatibilities on individual computers nicely. And I've heard a lot of good things about Python, but I don't know how much more prone to incompatibilities it is vs Java. In case it is important, I know the app will definitely use some flavor of a free server- enabled SQL db (server-enabled because I want to be able to run the app from multiple computers), but I don't know which to use yet. I thought I could decide that next. My experience level: I've taken a C++ (console app only) class and done some VBA in Access, but mostly I'm going to have to jump in and learn as I go. So of course I don't know much about all of this. I'm not in the computer field, this is just a hobby. So, which would be better for this app, Java or Python? (In case it comes up, I don't want to make it browser-based at all. I've dealt with individual computers' browser settings breaking programs, and that goes against part 2 of my top priority - maximum compatibility.) Thank you. Update: It will need a gui, and I'd like to be able to do a little bit of customization on it (or use a non-standard, or maybe a non-built-in one) to make it pop a little. Update 2: Truthfully, I really am only concerned with Windows computers. I am considering Java only for its reliability as a platform. Answer: The largest issue I can think of is the need to install an interpreter. With Java, a lot of people will already have that interpreter installed, although you won't necessarily know which version. It may be wise to include the installer for Java with the program. With Python, you're going to have to install the interpreter on each computer, too. One commenter mentioned .NET. .NET 2.0 has a fairly high likelyhood of being installed than either Java or Python on Windows machines. The catch is that you can't (easily) install it on OSX or Linux.
Content of file to tree format using python Question: I have a file containing a file "dir.txt" with the below data: /home/abc/a.txt /home/abc/b.txt /home/xyz/test /home/xyz/test/d.txt /home/xyz/test/e.txt /home/xyz/test/f.txt /home/xyz /home/xyz/g.txt I want to parse the file and get the output like /home/abc/a.txt b.txt /home/xyz/test/d.txt e.txt f.txt /home/xyz/g.txt Using python, basically need to print the content in a tree format. How would I process it? Answer: you need to use `os.path.split` on every path, find the first dirname and print path as it is. find it length and print so many spaces before next basename, on change of the dirname repeat as before. >>> import os.path >>> olddir = None >>> for name in open('input.txt'): dirname, fname = os.path.split(name) if olddir != dirname: prefix = ' ' * (len(dirname) +1) olddir = dirname print(name) else: print(prefix + fname) /home/abc/a.txt b.txt /home/xyz/test/d.txt e.txt f.txt /home/xyz/g.txt
Deploying a Django app to Weblogic: Cannot find modjy Question: I'm trying to deploy a django app to Weblogic and it cannot find modjy. I looked in the jython.jar that is included in the generated war file, and the modjy servlet is indeed there. Below is the error the server gets when deploying the app. <Feb 18, 2010 11:18:49 AM EST> <Error> <HTTP> <BEA-101216> <Servlet: "modjy" failed to preload on startup in Web application: "myApp.war". Traceback (innermost last): File "<string>", line 1, in ? ImportError: no module named modjy at org.python.core.Py.ImportError(Unknown Source) at org.python.core.imp.import_first(Unknown Source) at org.python.core.imp.import_name(Unknown Source) at org.python.core.imp.importName(Unknown Source) at org.python.core.ImportFunction.load(Unknown Source) Truncated. see log file for complete stacktrace > <Feb 18, 2010 11:18:49 AM EST> <Error> <Deployer> <BEA-149231> <Unable to set the activation state to true for the application 'myApp'. weblogic.application.ModuleException: [HTTP:101216]Servlet: "modjy" failed to preload on startup in Web application: "myApp.war". Traceback (innermost last): File "<string>", line 1, in ? ImportError: no module named modjy at weblogic.servlet.internal.WebAppModule.startContexts(WebAppModule.java:1399) at weblogic.servlet.internal.WebAppModule.start(WebAppModule.java:460) at weblogic.application.internal.flow.ModuleStateDriver$3.next(ModuleStateDriver.java:425) at weblogic.application.utils.StateMachineDriver.nextState(StateMachineDriver.java:83) at weblogic.application.internal.flow.ModuleStateDriver.start(ModuleStateDriver.java:119) Truncated. see log file for complete stacktrace Caused By: Traceback (innermost last): File "<string>", line 1, in ? ImportError: no module named modjy at org.python.core.Py.ImportError(Unknown Source) at org.python.core.imp.import_first(Unknown Source) at org.python.core.imp.import_name(Unknown Source) at org.python.core.imp.importName(Unknown Source) at org.python.core.ImportFunction.load(Unknown Source) Truncated. see log file for complete stacktrace > Answer: Sorry for getting to this issue so late: I just spotted the URL in my referer logs. The problem here is that modjy is failing to import the "modjy.py" module, which lives in the jython Lib/modjy directory. I have created a "Modjy Troubleshooting" page, and described this problem on it. <http://opensource.xhaus.com/projects/modjy/wiki/ModjyTroubleShooting> If that doesn't solve the problem, then please send an email to the jython- users list.
how to have global variables among different modules in Python Question: I investigated that scope of global variables in python is limited to the module. But I need the scope to be global among different modules. Is there such a thing? I played around `__builtin__` but no luck. thanks in advance! Answer: You can access global variables from other modules by importing them explicitly. In module `foo`: joe = 5 In module `bar`: from foo import joe print joe Note that this isn't recommended, though. It's much better to hide access to a module's variables by using functions.
Do simple things with a Google Wave robot Question: I wanted to add 3 features to the robot from the tutorial here: <http://code.google.com/apis/wave/extensions/robots/python-tutorial.html> Before adding all these features, my robot is working as intended. Now the odd features still shows up (with "v2" at the bck of the blip content), but neither of the new features shows up! I tried different ways alr, still doesn't work. So frustrating... Below is the code tt i think looks more logically. Can someone tell me why none seems to work? Thanks... Feature 1 -- wanted to try out AppendText Feature 2 -- wanted the robot to detect a blip is submitted Feature 3 -- wanted the robot to add a blip with the content of the old blip deleted. from waveapi import events from waveapi import model from waveapi import robot def OnParticipantsChanged(properties, context): """Invoked when any participants have been added/removed.""" added = properties['participantsAdded'] for p in added: Notify(context) def OnRobotAdded(properties, context): """Invoked when the robot has been added.""" root_wavelet = context.GetRootWavelet() """feature 1""" root_wavelet.CreateBlip().GetDocument().SetText("I'm alive! v2").GetDocument().AppendText("xxx") def Notify(context): root_wavelet = context.GetRootWavelet() root_wavelet.CreateBlip().GetDocument().SetText("Hi everybody! v2") """feature 2""" def OnBlipSubmitted(properties, context): blip = context.GetBlipById(properties['blipId']) blip.GetDocument().AppendText("xxx") """feature 3""" def OnBlipDeleted(properties, context): blip = context.GetBlipById(properties['blipId']) contents = blip.GetDocument().GetText() root_wavelet = context.GetRootWavelet() root_wavelet.CreateBlip().GetDocument().SetText(contents) if __name__ == '__main__': myRobot = robot.Robot('appName', image_url='http://appName.appspot.com/icon.png', version='1', profile_url='http://appName.appspot.com/') myRobot.RegisterHandler(events.WAVELET_PARTICIPANTS_CHANGED, OnParticipantsChanged) myRobot.RegisterHandler(events.WAVELET_SELF_ADDED, OnRobotAdded) """myRobot.RegisterHandler(events.BLIP_SUMBITTED, OnBlipSubmitted) myRobot.RegisterHandler(events.BLIP_DELETED, OnBlipDeleted)""" myRobot.Run() **Edit: (Important!)** I just noticed that it seems to hv different behaviour on normal mode vs sandbox mode. In normal mode I see both blips "I'm alive! v2" and "Hi everybody! v2", but in sandbox mode I can only see the 1st one. Werid... In neither case I see the appended text... The reason why i commented this part """myRobot.RegisterHandler(events.BLIP_SUMBITTED, OnBlipSubmitted) myRobot.RegisterHandler(events.BLIP_DELETED, OnBlipDeleted)""" is cos without commenting it, the robot doesn't do anything at all! Answer: `events.BLIP_SUMBITTED` should be `events.BLIP_SUBMITTED`
importerror: No module named django Question: I installed python 2.6 alongside my mac's 2.5.2 version. As soon as I did, python2.6 manage.py runserver failed because it couldn't find django.core.management. From a shell, import django returns importerror: No module named django. Why? Answer: Did you [reinstall Django](http://docs.djangoproject.com/en/dev/topics/install/#installing-an- official-release)? This happens when I install side by side versions of Python on Gentoo. Whenever I install a new version, I have to either reinstall the new ones or make a symlink to the old `site-packages`.
How can I fix the error on this Python code? Question: I have this superclass: import wx class Plugin(wx.Panel): def __init__(self, parent, *args, **kwargs): wx.Panel.__init__(self, parent, *args, **kwargs) self.colorOver = ((89,89,89)) self.colorLeave = ((110,110,110)) self.SetBackgroundColour(self.colorLeave) self.SetForegroundColour(self.colorLeave) self.name = "plugin" wx.StaticText(self, -1, self.getName(), style=wx.ALIGN_LEFT) self.Bind(wx.EVT_ENTER_WINDOW, self.onMouseOver) self.Bind(wx.EVT_LEAVE_WINDOW, self.onMouseLeave) def onMouseOver(self, event): self.SetBackgroundColour(self.colorOver) self.Refresh() def onMouseLeave(self, event): self.SetBackgroundColour(self.colorLeave) self.Refresh() def OnClose(self, event): self.Close() app.Destroy() def getName(self): return self.name and this subclass: import plugin import wx class noisePlugin(plugin.Plugin): self.name = "noise" and it gives me this error compiling the subclass: Traceback (most recent call last): File "C:\Users\André Ferreira\Desktop\Tese\Código Python\SoundLog\Plugins\noisePlugin.py", line 4, in <module> class noisePlugin(plugin.Plugin): File "C:\Users\André Ferreira\Desktop\Tese\Código Python\SoundLog\Plugins\noisePlugin.py", line 5, in noisePlugin self.name = "noise" NameError: name 'self' is not defined What can I do to fix this error? I want getName() method to return the name of the instanciated class! Thanks in advance :) Answer: Make the subclass class noisePlugin(plugin.Plugin): def __init__(self, *a, **k): plugin.Plugin.__init__(self, *a, **k) self.name = "noise" Whenever you want to use `self.`something you have to be **within a method** , not at class level outside of methods!
Error while executing "paster shell example.ini" in reddit.com Question: Friends!!! I am frustated since last five days working on implementing reddit.com on a ubuntu 9.10 machine. Yes, I know that reddit.com has been tested on ubuntu intrepid. But now i want to install it on U9.10 I have installed postgresql database, created user copied the files, and installed all the dependencies. Everything is installed perfectly as described in the document <http://code.reddit.com/wiki/RedditStartToFinishIntrepid> until the line: > $ paster shell example.ini this line gives me a error and i couldnt figure out where the problem lies. Error: /home/ubuntu/reddit/r2/r2/lib/utils/utils.py:29: DeprecationWarning: the sha module is deprecated; use the hashlib module instead import re, datetime, math, random, string, sha, os /home/ubuntu/reddit/r2/r2/lib/contrib/memcache.py:50: DeprecationWarning: the md5 module is deprecated; use hashlib instead from md5 import md5 Traceback (most recent call last): File "/usr/local/bin/paster", line 8, in <module> load_entry_point('PasteScript==1.7.3', 'console_scripts', 'paster') () File "/usr/local/lib/python2.6/dist-packages/PasteScript-1.7.3- py2.6.egg/paste/script/command.py", line 84, in run invoke(command, command_name, options, args[1:]) File "/usr/local/lib/python2.6/dist-packages/PasteScript-1.7.3- py2.6.egg/paste/script/command.py", line 123, in invoke exit_code = runner.run(args) File "/usr/local/lib/python2.6/dist-packages/PasteScript-1.7.3- py2.6.egg/paste/script/command.py", line 218, in run result = self.command() File "/usr/local/lib/python2.6/dist-packages/Pylons-0.9.6.2- py2.6.egg/pylons/commands.py", line 341, in command conf = appconfig(config_name, relative_to=here_dir) File "/usr/local/lib/python2.6/dist-packages/PasteDeploy-1.3.3- py2.6.egg/paste/deploy/loadwsgi.py", line 215, in appconfig global_conf=global_conf) File "/usr/local/lib/python2.6/dist-packages/PasteDeploy-1.3.3- py2.6.egg/paste/deploy/loadwsgi.py", line 248, in loadcontext global_conf=global_conf) File "/usr/local/lib/python2.6/dist-packages/PasteDeploy-1.3.3- py2.6.egg/paste/deploy/loadwsgi.py", line 278, in _loadconfig return loader.get_context(object_type, name, global_conf) File "/usr/local/lib/python2.6/dist-packages/PasteDeploy-1.3.3- py2.6.egg/paste/deploy/loadwsgi.py", line 409, in get_context section) File "/usr/local/lib/python2.6/dist-packages/PasteDeploy-1.3.3- py2.6.egg/paste/deploy/loadwsgi.py", line 431, in _context_from_use object_type, name=use, global_conf=global_conf) File "/usr/local/lib/python2.6/dist-packages/PasteDeploy-1.3.3- py2.6.egg/paste/deploy/loadwsgi.py", line 361, in get_context global_conf=global_conf) File "/usr/local/lib/python2.6/dist-packages/PasteDeploy-1.3.3- py2.6.egg/paste/deploy/loadwsgi.py", line 248, in loadcontext global_conf=global_conf) File "/usr/local/lib/python2.6/dist-packages/PasteDeploy-1.3.3- py2.6.egg/paste/deploy/loadwsgi.py", line 285, in _loadegg return loader.get_context(object_type, name, global_conf) File "/usr/local/lib/python2.6/dist-packages/PasteDeploy-1.3.3- py2.6.egg/paste/deploy/loadwsgi.py", line 561, in get_context object_type, name=name) File "/usr/local/lib/python2.6/dist-packages/PasteDeploy-1.3.3- py2.6.egg/paste/deploy/loadwsgi.py", line 587, in find_egg_entry_point possible.append((entry.load(), protocol, entry.name)) File "/usr/lib/python2.6/dist-packages/pkg_resources.py", line 1913, in load entry = __import__(self.module_name, globals(),globals(), ['__name__']) File "/home/ubuntu/reddit/r2/r2/__init__.py", line 26, in <module> from r2.config.middleware import make_app File "/home/ubuntu/reddit/r2/r2/config/middleware.py", line 30, in <module> from pylons.error import error_template File "/usr/local/lib/python2.6/dist-packages/Pylons-0.9.6.2- py2.6.egg/pylons/error.py", line 18, in <module> from pylons.middleware import media_path File "/usr/local/lib/python2.6/dist-packages/Pylons-0.9.6.2- py2.6.egg/pylons/middleware.py", line 11, in <module> from webhelpers.rails.asset_tag import javascript_path **ImportError: No module named rails.asset_tag** Kindly guys please help me, take me out of my own frustration. Thanks in Advance Answer: Newer version of python-webhelpers doesn't have asset_tag.py, you need to install an older version (0.6.4) for Pylons 0.9.6: wget <http://pypi.python.org/packages/source/W/WebHelpers/WebHelpers-0.6.4.tar.gz> && tar -xf WebHelpers-0.6.4.tar.gz && cd WebHelpers-0.6.4 && python setup.py build && sudo python setup.py install && cd .. && sudo rm -r WebHelpers-0.6.4*
Using Property Builtin with GAE Datastore's Model Question: I want to make attributes of GAE Model properties. The reason is for cases like to turn the value into uppercase before storing it. For a plain Python class, I would do something like: Foo(db.Model): def get_attr(self): return self.something def set_attr(self, value): self.something = value.upper() if value != None else None attr = property(get_attr, set_attr) However, GAE Datastore have their own concept of Property class, I looked into the [documentation](http://code.google.com/appengine/docs/python/datastore/propertyclass.html#Property) and it seems that I could override `get_value_for_datastore(model_instance)` to achieve my goal. Nevertheless, I don't know what `model_instance` is and how to extract the corresponding field from it. Is overriding GAE Property classes the right way to provides getter/setter- like functionality? If so, how to do it? **Added:** One potential issue of overriding `get_value_for_datastore` that I think of is it might not get called before the object was put into datastore. Hence getting the attribute before storing the object would yield an incorrect value. Answer: Subclassing GAE's [Property](http://code.google.com/appengine/docs/python/datastore/propertyclass.html) class is especially helpful if you want more than one "field" with similar behavior, in one or more models. Don't worry, `get_value_for_datastore` and `make_value_from_datastore` **are** going to get called, on any store and fetch respectively -- so if you need to do anything fancy (including but not limited to uppercasing a string, which isn't actually all _that_ fancy;-), overriding these methods in your subclass is just fine. **Edit** : let's see some example code (net of imports and `main`): class MyStringProperty(db.StringProperty): def get_value_for_datastore(self, model_instance): vv = db.StringProperty.get_value_for_datastore(self, model_instance) return vv.upper() class MyModel(db.Model): foo = MyStringProperty() class MainHandler(webapp.RequestHandler): def get(self): my = MyModel(foo='Hello World') k = my.put() mm = MyModel.get(k) s = mm.foo self.response.out.write('The secret word is: %r' % s) This shows you the string's been uppercased in the datastore -- but if you change the `get` call to a simple `mm = my` you'll see the _in-memory_ instance wasn't affected. But, a `db.Property` instance itself is a descriptor -- wrapping it into a built-in `property` (a completely different descriptor) will not work well with the datastore (for example, you can't write GQL queries based on field names that aren't really instances of `db.Property` but instances of `property` \-- those fields are **not** in the datastore!). So if you want to work with both the datastore _and_ for instances of `Model` that have never actually been to the datastore and back, you'll have to choose **two** names for what's logically "the same" field -- one is the name of the attribute you'll use on in-memory model instances, and that one can be a built-in `property`; the other one is the name of the attribute that ends up in the datastore, and that one needs to be an instance of a `db.Property` subclass _and_ it's this second name that you'll need to use in queries. Of course the methods underlying the first name need to read and write the second name, but you can't just "hide" the latter because that's the name that's going to be in the datastore, and so that's the name that will make sense to queries!
How to fix the wxpython events called? Question: with this code: import wx class Plugin(wx.Panel): def __init__(self, parent, *args, **kwargs): panel = wx.Panel.__init__(self, parent, *args, **kwargs) self.colorOver = ((89,89,89)) self.colorLeave = ((110,110,110)) self.colorFont = ((145,145,145)) self.SetBackgroundColour(self.colorLeave) self.SetForegroundColour(self.colorLeave) self.name = "Plugin" self.overPanel = 0 self.overLabel = 0 self.overButton = 0 sizer = wx.BoxSizer(wx.VERTICAL) self.pluginName = wx.StaticText(self, -1, ' ' + self.getName()) self.pluginClose = wx.BitmapButton(self, -1, wx.Bitmap('C:\Users\André Ferreira\Desktop\Tese\Código Python\SoundLog\Images\close.png'), style=wx.NO_BORDER) self.pluginClose.Hide() gs = wx.GridSizer(2, 2, 0, 0) gs.AddMany([(self.pluginName, 0, wx.ALIGN_LEFT), (self.pluginClose, 0, wx.ALIGN_RIGHT|wx.CENTER)]) sizer.Add(gs, 1, wx.EXPAND) self.SetSizer(sizer) self.pluginName.Bind(wx.EVT_LEAVE_WINDOW, self.onLabelMouseLeave) self.pluginName.Bind(wx.EVT_ENTER_WINDOW, self.onLabelMouseOver) self.pluginClose.Bind(wx.EVT_BUTTON, self.onCloseMouseClick) self.Bind(wx.EVT_LEAVE_WINDOW, self.onPanelMouseLeave) self.Bind(wx.EVT_ENTER_WINDOW, self.onPanelMouseOver) def onPanelMouseOver(self, event): self.overPanel = 1 self.overLabel = 0 self.SetBackgroundColour(self.colorOver) self.pluginName.SetForegroundColour(self.colorFont) self.Refresh() self.pluginClose.Show() def onPanelMouseLeave(self, event): if self.overLabel == 0: self.overPanel = 0 self.SetBackgroundColour(self.colorLeave) self.pluginName.SetForegroundColour(self.colorLeave) self.Refresh() self.pluginClose.Hide() def onLabelMouseOver(self, event): self.overPanel = 0 self.overLabel = 1 self.SetBackgroundColour(self.colorOver) self.pluginName.SetForegroundColour(self.colorFont) self.Refresh() self.pluginClose.Show() def onLabelMouseLeave(self, event): if self.overPanel == 0: self.overLabel = 0 self.SetBackgroundColour(self.colorLeave) self.pluginName.SetForegroundColour(self.colorLeave) self.Refresh() self.pluginClose.Hide() def OnClose(self, event): self.Close() app.Destroy() def onCloseMouseClick(self, event): self.Hide() def getName(self): return self.name whenever I get over the BitmapButton the next two events: self.Bind(wx.EVT_LEAVE_WINDOW, self.onPanelMouseLeave) self.Bind(wx.EVT_ENTER_WINDOW, self.onPanelMouseOver) are allways beeing called. What is wrong with it? How can only one event be called? Note: if I bind the leave and enter window events to the BitmapButton the two previous events are still called. Answer: Problem is you are hiding and showing bitmap on mouseover, so when you move mouseover bitmap, mouse goes off panel, onPanelMouseLeave is called and you hide bitmap, which means now mouse if over panel, onPanelMouseOver is called and in that event you again show bitmap and that means now mouse if over bitmap again and out of panel and hence you are stuck in a hide/show circle. Comment out self.pluginClose.Hide() in onPanelMouseLeave and you won't see multiple events. Try to come with a different approach e.g. check if mouse if over bitmap and hence do not hide it.
In a functional language, how to conditionally select elements to be used in zip- or zipWith-style function? Question: I am familiar with standard `zipWith` functions which operate on corresponding elements of two sequences, but in a functional language (or a language with some functional features), what is the most succinct way to _conditionally_ select the pairs of elements to be zipped, based on a third sequence? This curiosity arose while scratching out a few things in Excel. With numbers in A1:A10, B1:B10, C1:C10, D1, E1 and F1, I'm using a formula like this: {=AVERAGE(IF((D1<=(A1:A10))*((A1:A10)<=E1),B1:B10/C1:C10))} Each half of the multiplication in the IF statement will produce an array of Boolean values, which are then multiplied (AND'ed) together. Those Booleans control which of the ten quotients will ultimately be averaged, so it's as though ten separate IF statements were being evaluated. If, for example, only the second and third of the 10 values in A1:A10 satisfy the conditions (both >=D1 and <=E1), then the formula ends up evaluating thusly: AVERAGE(FALSE,B2/C2,B3/C3,FALSE,FALSE,FALSE,FALSE,FALSE,FALSE,FALSE) The AVERAGE function happens to ignore Boolean and text values, so we just get the average of the second and third quotients. Can this be done as succinctly with Haskell? Erlang? LINQ or F#? Python? etc.. NOTE that for this particular example, the formula given above isn't entirely correct--it was abbreviated to get the basic point across. When none of the ten elements in A1:A10 satisfies the conditions, then ten FALSE values will be passed to AVERAGE, which will incorrectly evaluate to 0. The formula should be written this way: {=AVERAGE(IF(NOT(OR((D1<=(A1:A10))*((A1:A10)<=E1))),NA(), IF((D1<=(A1:A10))*((A1:A10)<=E1),B1:B10/C1:C10)))} Where the `NA()` produces an error, indicating that the average is undefined. ## Update: Thanks for the answers. I realized that my first question was pretty trivial, in terms of applying a function on pairs of elements from the second and third lists when the corresponding element from the first list meets some particular criteria. I accepted Norman Ramsey's answer for that. However, where I went to next was wondering whether the function could be applied to a tuple representing corresponding elements from an arbitrary number of lists--hence my question to Lebertram about the limits of `zipWithN`. Apocalisp's info on applicative functors led me to info on python's unpacking of argument lists--applying a function to an arbitrary number of arguments. For the specific example I gave above, averaging the quotients of elements of lists (where `nums` is the list of lists), it looks like python can do it like this: from operator import div def avg(a): return sum(a,0.0)/len(a) avg([reduce(div,t[1:]) for t in zip(*nums) if d<=t[0] and t[0]<=e]) More generally, with a function `f` and a predicate `p` (along with `avg`) this becomes: avg([f(t[1:]) for t in zip(*nums) if p(t[0])]) Answer: What you're looking for is [Applicative Functors](http://www.soi.city.ac.uk/~ross/papers/Applicative.html). Specifically the "zippy" applicative from the linked paper. In Haskell notation, let's call your function `f`. Then with applicative programming, it would look as succinct as this: f d e as bs cs = if' <$> ((&&) <$> (d <=) <*> (e >=)) <$> as <*> ((/) <$> bs <*> cs) <*> (repeat 0) where if' x y z = if x then y else z (<*>) = zipWith ($) The result of `f` is a list. Simply take the average. To generify a little: f g p as bs cs = if' <$> p <$> as <*> (((Some .) . g) <$> bs <*> cs) <*> (repeat None) Here, p is a predicate, so you would call it with: average $ fromMaybe 0 <$> f (/) ((&&) <$> (d <=) <*> (e >=)) as bs cs ... given the same definition of `<*>` as above. Note: I haven't tested this code, so there might be missing parentheses and the like, but this gets the idea across.
How to write GUI in Python? Question: I would like to try to write a GUI application in Python. I found out that there are a lot of ways to do it (different toolkits). And, in this context, I have several basic (and I think simple) question? 1. Is it, in general, a good idea to write a GUI application in Python? 2. What is the standard (easiest and most stable) way to create a GUI applications in Python? 3. Does anybody can give me a link to a simple Hello World GUI application written in Python? Answer: 1. Depends on what application you are writing. I would use Python for a simple GUI, yes. 2. Use a proper toolkit (such as [PyQt](http://www.riverbankcomputing.co.uk/software/pyqt/intro) \- Python bindings for the popular Qt) 3. Sure Hello world in PyQt: import qt,sys a = qt.QApplication(sys.argv) w = qt.QPushButton("Hello World",None) a.setMainWidget(w) w.show() a.exec_loop()
Getting a machine's external IP address Question: Looking for a better way to get a machines current external IP #... Below works, but would rather not rely on an outside site to gather the information ... I am restricted to using standard Python 2.5.1 libraries bundled with Mac OS X 10.5.x import os import urllib2 def check_in(): fqn = os.uname()[1] ext_ip = urllib2.urlopen('http://whatismyip.org').read() print ("Asset: %s " % fqn, "Checking in from IP#: %s " % ext_ip) Answer: I wrote a module for that: [ipgetter](https://pypi.python.org/pypi/ipgetter). Is designed to fetch your external IP address from the internet. It is used mostly when behind a NAT. It picks your IP randomly from a serverlist to minimize request overhead on a single server. Actually with 44 server and test function to verify if the servers are returning the same IP. <https://github.com/phoemur/ipgetter> goes like this: >>> import ipgetter >>> IP = ipgetter.myip() >>> print(IP) 'xxx.xxx.xxx.xxx' >>> ipgetter.IPgetter().test() Number of servers: 44 IP's : 'xxx.xxx.xxx.xxx' = 44 ocurrencies