Commits

Phil Gyford committed a646801

Initial import

  • Participants

Comments (0)

Files changed (376)

+This is an unofficial set of files for James Bennett's 'Practical Django Projects' Second Edition, published by Apress. I have no connection with the author, the book or the publisher, but in the absence of any official example files I thought my finished set might be useful.
+
+I have tracked down fixes for most of the things that don't work from the book, and added templates where examples are missing. Most things seem to work fine for me, but I can't guarantee it will work for you.
+
+These files aren't designed to work as standalone applications -- they will probably need configuration and set-up, and assume you're following along with the book's tutorials and might just need a reference copy of the code.
+
+Here are some things that don't work / might not work / will need attention:
+
+### General
+
+* You'll need to do some configuration in cms/settings.py
+* No SQLite database is included -- the code should create one at cms/cms.db
+
+### Coltrane
+
+* In the weblog app, I'm not sure if Akismet works (it doesn't complain).
+* In the weblog, sending emails after a comment is posted might not work (no complaint, but email doesn't seem to arrive when sent from my laptop).
+* The bit that sends an email notification when a comment is posted needs a template at comments/comment_notification_email.txt so I've put that outside of the templates/cms/coltrane/ directory, inside templates/cms/.
+* Setting up the tagging is problematic. This code currently works fine, but you may need to manually add the 'tags' column to your tables. http://blog.sveri.de/index.php?/categories/2-Django
+
+I can't guarantee to ever update this code or supply help with problems (I hardly know what I'm doing myself), but you can post comments here: http://www.gyford.com/phil/writing/2010/01/14/django.php
+
+Phil Gyford
+http://www.gyford.com/
+
+# Version 0.2.0
+# 2009/06/18
+
+# Copyright Michael Foord 2005-2009
+# akismet.py
+# Python interface to the akismet API
+# E-mail fuzzyman@voidspace.org.uk
+
+# http://www.voidspace.org.uk/python/modules.shtml
+# http://akismet.com
+
+# Released subject to the BSD License
+# See http://www.voidspace.org.uk/python/license.shtml
+
+
+"""
+A python interface to the `Akismet <http://akismet.com>`_ API.
+This is a web service for blocking SPAM comments to blogs - or other online 
+services.
+
+You will need a Wordpress API key, from `wordpress.com <http://wordpress.com>`_.
+
+You should pass in the keyword argument 'agent' to the name of your program,
+when you create an Akismet instance. This sets the ``user-agent`` to a useful
+value.
+
+The default is : ::
+
+    Python Interface by Fuzzyman | akismet.py/0.2.0
+
+Whatever you pass in, will replace the *Python Interface by Fuzzyman* part.
+**0.2.0** will change with the version of this interface.
+
+Usage example::
+    
+    from akismet import Akismet
+    
+    api = Akismet(agent='Test Script')
+    # if apikey.txt is in place,
+    # the key will automatically be set
+    # or you can call api.setAPIKey()
+    #
+    if api.key is None:
+        print "No 'apikey.txt' file."
+    elif not api.verify_key():
+        print "The API key is invalid."
+    else:
+        # data should be a dictionary of values
+        # They can all be filled in with defaults
+        # from a CGI environment
+        if api.comment_check(comment, data):
+            print 'This comment is spam.'
+        else:
+            print 'This comment is ham.'
+"""
+
+
+import os, sys
+from urllib import urlencode
+
+import socket
+if hasattr(socket, 'setdefaulttimeout'):
+    # Set the default timeout on sockets to 5 seconds
+    socket.setdefaulttimeout(5)
+
+__version__ = '0.2.0'
+
+__all__ = (
+    '__version__',
+    'Akismet',
+    'AkismetError',
+    'APIKeyError',
+    )
+
+__author__ = 'Michael Foord <fuzzyman AT voidspace DOT org DOT uk>'
+
+__docformat__ = "restructuredtext en"
+
+user_agent = "%s | akismet.py/%s"
+DEFAULTAGENT = 'Python Interface by Fuzzyman/%s'
+
+isfile = os.path.isfile
+
+urllib2 = None
+try:
+    from google.appengine.api import urlfetch
+except ImportError:
+    import urllib2
+
+if urllib2 is None:
+    def _fetch_url(url, data, headers):
+        req = urlfetch.fetch(url=url, payload=data, method=urlfetch.POST, headers=headers)
+        if req.status_code == 200:
+            return req.content
+        raise Exception('Could not fetch Akismet URL: %s Response code: %s' % 
+                        (url, req.status_code))
+else:
+    def _fetch_url(url, data, headers):
+        req = urllib2.Request(url, data, headers)
+        h = urllib2.urlopen(req)
+        resp = h.read()
+        return resp
+
+
+class AkismetError(Exception):
+    """Base class for all akismet exceptions."""
+
+class APIKeyError(AkismetError):
+    """Invalid API key."""
+
+class Akismet(object):
+    """A class for working with the akismet API"""
+
+    baseurl = 'rest.akismet.com/1.1/'
+
+    def __init__(self, key=None, blog_url=None, agent=None):
+        """Automatically calls ``setAPIKey``."""
+        if agent is None:
+            agent = DEFAULTAGENT % __version__
+        self.user_agent = user_agent % (agent, __version__)
+        self.setAPIKey(key, blog_url)
+
+
+    def _getURL(self):
+        """
+        Fetch the url to make requests to.
+        
+        This comprises of api key plus the baseurl.
+        """
+        return 'http://%s.%s' % (self.key, self.baseurl)
+    
+    
+    def _safeRequest(self, url, data, headers):
+        try:
+            resp = _fetch_url(url, data, headers)
+        except Exception, e:
+            raise AkismetError(str(e))
+        return resp
+
+
+    def setAPIKey(self, key=None, blog_url=None):
+        """
+        Set the wordpress API key for all transactions.
+        
+        If you don't specify an explicit API ``key`` and ``blog_url`` it will
+        attempt to load them from a file called ``apikey.txt`` in the current
+        directory.
+        
+        This method is *usually* called automatically when you create a new
+        ``Akismet`` instance.
+        """
+        if key is None and isfile('apikey.txt'):
+            the_file = [l.strip() for l in open('apikey.txt').readlines()
+                if l.strip() and not l.strip().startswith('#')]
+            try:
+                self.key = the_file[0]
+                self.blog_url = the_file[1]
+            except IndexError:
+                raise APIKeyError("Your 'apikey.txt' is invalid.")
+        else:
+            self.key = key
+            self.blog_url = blog_url
+
+
+    def verify_key(self):
+        """
+        This equates to the ``verify-key`` call against the akismet API.
+        
+        It returns ``True`` if the key is valid.
+        
+        The docs state that you *ought* to call this at the start of the
+        transaction.
+        
+        It raises ``APIKeyError`` if you have not yet set an API key.
+        
+        If the connection to akismet fails, it allows the normal ``HTTPError``
+        or ``URLError`` to be raised.
+        (*akismet.py* uses `urllib2 <http://docs.python.org/lib/module-urllib2.html>`_)
+        """
+        if self.key is None:
+            raise APIKeyError("Your have not set an API key.")
+        data = { 'key': self.key, 'blog': self.blog_url }
+        # this function *doesn't* use the key as part of the URL
+        url = 'http://%sverify-key' % self.baseurl
+        # we *don't* trap the error here
+        # so if akismet is down it will raise an HTTPError or URLError
+        headers = {'User-Agent' : self.user_agent}
+        resp = self._safeRequest(url, urlencode(data), headers)
+        if resp.lower() == 'valid':
+            return True
+        else:
+            return False
+
+    def _build_data(self, comment, data):
+        """
+        This function builds the data structure required by ``comment_check``,
+        ``submit_spam``, and ``submit_ham``.
+        
+        It modifies the ``data`` dictionary you give it in place. (and so
+        doesn't return anything)
+        
+        It raises an ``AkismetError`` if the user IP or user-agent can't be
+        worked out.
+        """
+        data['comment_content'] = comment
+        if not 'user_ip' in data:
+            try:
+                val = os.environ['REMOTE_ADDR']
+            except KeyError:
+                raise AkismetError("No 'user_ip' supplied")
+            data['user_ip'] = val
+        if not 'user_agent' in data:
+            try:
+                val = os.environ['HTTP_USER_AGENT']
+            except KeyError:
+                raise AkismetError("No 'user_agent' supplied")
+            data['user_agent'] = val
+        #
+        data.setdefault('referrer', os.environ.get('HTTP_REFERER', 'unknown'))
+        data.setdefault('permalink', '')
+        data.setdefault('comment_type', 'comment')
+        data.setdefault('comment_author', '')
+        data.setdefault('comment_author_email', '')
+        data.setdefault('comment_author_url', '')
+        data.setdefault('SERVER_ADDR', os.environ.get('SERVER_ADDR', ''))
+        data.setdefault('SERVER_ADMIN', os.environ.get('SERVER_ADMIN', ''))
+        data.setdefault('SERVER_NAME', os.environ.get('SERVER_NAME', ''))
+        data.setdefault('SERVER_PORT', os.environ.get('SERVER_PORT', ''))
+        data.setdefault('SERVER_SIGNATURE', os.environ.get('SERVER_SIGNATURE',
+            ''))
+        data.setdefault('SERVER_SOFTWARE', os.environ.get('SERVER_SOFTWARE',
+            ''))
+        data.setdefault('HTTP_ACCEPT', os.environ.get('HTTP_ACCEPT', ''))
+        data.setdefault('blog', self.blog_url)
+
+
+    def comment_check(self, comment, data=None, build_data=True, DEBUG=False):
+        """
+        This is the function that checks comments.
+        
+        It returns ``True`` for spam and ``False`` for ham.
+        
+        If you set ``DEBUG=True`` then it will return the text of the response,
+        instead of the ``True`` or ``False`` object.
+        
+        It raises ``APIKeyError`` if you have not yet set an API key.
+        
+        If the connection to Akismet fails then the ``HTTPError`` or
+        ``URLError`` will be propogated.
+        
+        As a minimum it requires the body of the comment. This is the
+        ``comment`` argument.
+        
+        Akismet requires some other arguments, and allows some optional ones.
+        The more information you give it, the more likely it is to be able to
+        make an accurate diagnosise.
+        
+        You supply these values using a mapping object (dictionary) as the
+        ``data`` argument.
+        
+        If ``build_data`` is ``True`` (the default), then *akismet.py* will
+        attempt to fill in as much information as possible, using default
+        values where necessary. This is particularly useful for programs
+        running in a {acro;CGI} environment. A lot of useful information
+        can be supplied from evironment variables (``os.environ``). See below.
+        
+        You *only* need supply values for which you don't want defaults filled
+        in for. All values must be strings.
+        
+        There are a few required values. If they are not supplied, and
+        defaults can't be worked out, then an ``AkismetError`` is raised.
+        
+        If you set ``build_data=False`` and a required value is missing an
+        ``AkismetError`` will also be raised.
+        
+        The normal values (and defaults) are as follows : ::
+        
+            'user_ip':          os.environ['REMOTE_ADDR']       (*)
+            'user_agent':       os.environ['HTTP_USER_AGENT']   (*)
+            'referrer':         os.environ.get('HTTP_REFERER', 'unknown') [#]_
+            'permalink':        ''
+            'comment_type':     'comment' [#]_
+            'comment_author':   ''
+            'comment_author_email': ''
+            'comment_author_url': ''
+            'SERVER_ADDR':      os.environ.get('SERVER_ADDR', '')
+            'SERVER_ADMIN':     os.environ.get('SERVER_ADMIN', '')
+            'SERVER_NAME':      os.environ.get('SERVER_NAME', '')
+            'SERVER_PORT':      os.environ.get('SERVER_PORT', '')
+            'SERVER_SIGNATURE': os.environ.get('SERVER_SIGNATURE', '')
+            'SERVER_SOFTWARE':  os.environ.get('SERVER_SOFTWARE', '')
+            'HTTP_ACCEPT':      os.environ.get('HTTP_ACCEPT', '')
+        
+        (*) Required values
+        
+        You may supply as many additional 'HTTP_*' type values as you wish.
+        These should correspond to the http headers sent with the request.
+        
+        .. [#] Note the spelling "referrer". This is a required value by the
+            akismet api - however, referrer information is not always
+            supplied by the browser or server. In fact the HTTP protocol
+            forbids relying on referrer information for functionality in 
+            programs.
+        .. [#] The `API docs <http://akismet.com/development/api/>`_ state that this value
+            can be " *blank, comment, trackback, pingback, or a made up value*
+            *like 'registration'* ".
+        """
+        if self.key is None:
+            raise APIKeyError("Your have not set an API key.")
+        if data is None:
+            data = {}
+        if build_data:
+            self._build_data(comment, data)
+        if 'blog' not in data:
+            data['blog'] = self.blog_url
+        url = '%scomment-check' % self._getURL()
+        # we *don't* trap the error here
+        # so if akismet is down it will raise an HTTPError or URLError
+        headers = {'User-Agent' : self.user_agent}
+        resp = self._safeRequest(url, urlencode(data), headers)
+        if DEBUG:
+            return resp
+        resp = resp.lower()
+        if resp == 'true':
+            return True
+        elif resp == 'false':
+            return False
+        else:
+            # NOTE: Happens when you get a 'howdy wilbur' response !
+            raise AkismetError('missing required argument.')
+
+
+    def submit_spam(self, comment, data=None, build_data=True):
+        """
+        This function is used to tell akismet that a comment it marked as ham,
+        is really spam.
+        
+        It takes all the same arguments as ``comment_check``, except for
+        *DEBUG*.
+        """
+        if self.key is None:
+            raise APIKeyError("Your have not set an API key.")
+        if data is None:
+            data = {}
+        if build_data:
+            self._build_data(comment, data)
+        url = '%ssubmit-spam' % self._getURL()
+        # we *don't* trap the error here
+        # so if akismet is down it will raise an HTTPError or URLError
+        headers = {'User-Agent' : self.user_agent}
+        self._safeRequest(url, urlencode(data), headers)
+
+
+    def submit_ham(self, comment, data=None, build_data=True):
+        """
+        This function is used to tell akismet that a comment it marked as spam,
+        is really ham.
+        
+        It takes all the same arguments as ``comment_check``, except for
+        *DEBUG*.
+        """
+        if self.key is None:
+            raise APIKeyError("Your have not set an API key.")
+        if data is None:
+            data = {}
+        if build_data:
+            self._build_data(comment, data)
+        url = '%ssubmit-ham' % self._getURL()
+        # we *don't* trap the error here
+        # so if akismet is down it will raise an HTTPError or URLError
+        headers = {'User-Agent' : self.user_agent}
+        self._safeRequest(url, urlencode(data), headers)

akismet.pyc

Binary file added.

cab/__init__.py

Empty file added.

cab/__init__.pyc

Binary file added.
+from django.contrib import admin
+from cab.models import Snippet, Language
+
+class LanguageAdmin(admin.ModelAdmin):
+    prepopulated_fields = { 'slug': ['name'] }
+
+admin.site.register(Language, LanguageAdmin)
+
+
+class SnippetAdmin(admin.ModelAdmin):
+    pass
+    
+admin.site.register(Snippet, SnippetAdmin)
+
+

cab/admin.pyc

Binary file added.

cab/css/pygments.css

+.hll { background-color: #ffffcc }
+.c { color: #606060; font-style: italic } /* Comment */
+.err { color: #F00000; background-color: #F0A0A0 } /* Error */
+.k { color: #208090; font-weight: bold } /* Keyword */
+.o { color: #303030 } /* Operator */
+.cm { color: #606060; font-style: italic } /* Comment.Multiline */
+.cp { color: #507090 } /* Comment.Preproc */
+.c1 { color: #606060; font-style: italic } /* Comment.Single */
+.cs { color: #c00000; font-weight: bold; font-style: italic } /* Comment.Special */
+.gd { color: #A00000 } /* Generic.Deleted */
+.ge { font-style: italic } /* Generic.Emph */
+.gr { color: #FF0000 } /* Generic.Error */
+.gh { color: #000080; font-weight: bold } /* Generic.Heading */
+.gi { color: #00A000 } /* Generic.Inserted */
+.go { color: #808080 } /* Generic.Output */
+.gp { color: #c65d09; font-weight: bold } /* Generic.Prompt */
+.gs { font-weight: bold } /* Generic.Strong */
+.gu { color: #800080; font-weight: bold } /* Generic.Subheading */
+.gt { color: #0040D0 } /* Generic.Traceback */
+.kc { color: #208090; font-weight: bold } /* Keyword.Constant */
+.kd { color: #208090; font-weight: bold } /* Keyword.Declaration */
+.kn { color: #208090; font-weight: bold } /* Keyword.Namespace */
+.kp { color: #0080f0; font-weight: bold } /* Keyword.Pseudo */
+.kr { color: #208090; font-weight: bold } /* Keyword.Reserved */
+.kt { color: #6060f0; font-weight: bold } /* Keyword.Type */
+.m { color: #6000E0; font-weight: bold } /* Literal.Number */
+.s { background-color: #e0e0ff } /* Literal.String */
+.na { color: #000070 } /* Name.Attribute */
+.nb { color: #007020 } /* Name.Builtin */
+.nc { color: #e090e0; font-weight: bold } /* Name.Class */
+.no { color: #50e0d0; font-weight: bold } /* Name.Constant */
+.nd { color: #505050; font-weight: bold } /* Name.Decorator */
+.ni { color: #800000 } /* Name.Entity */
+.ne { color: #F00000; font-weight: bold } /* Name.Exception */
+.nf { color: #50e0d0; font-weight: bold } /* Name.Function */
+.nl { color: #907000; font-weight: bold } /* Name.Label */
+.nn { color: #0e84b5; font-weight: bold } /* Name.Namespace */
+.nt { color: #007000 } /* Name.Tag */
+.nv { color: #003060 } /* Name.Variable */
+.ow { color: #000000; font-weight: bold } /* Operator.Word */
+.w { color: #bbbbbb } /* Text.Whitespace */
+.mf { color: #6000E0; font-weight: bold } /* Literal.Number.Float */
+.mh { color: #005080; font-weight: bold } /* Literal.Number.Hex */
+.mi { color: #6060f0; font-weight: bold } /* Literal.Number.Integer */
+.mo { color: #4000E0; font-weight: bold } /* Literal.Number.Oct */
+.sb { background-color: #e0e0ff } /* Literal.String.Backtick */
+.sc { color: #8080F0 } /* Literal.String.Char */
+.sd { color: #D04020 } /* Literal.String.Doc */
+.s2 { background-color: #e0e0ff } /* Literal.String.Double */
+.se { color: #606060; font-weight: bold; background-color: #e0e0ff } /* Literal.String.Escape */
+.sh { background-color: #e0e0ff } /* Literal.String.Heredoc */
+.si { background-color: #e0e0e0 } /* Literal.String.Interpol */
+.sx { color: #f08080; background-color: #e0e0ff } /* Literal.String.Other */
+.sr { color: #000000; background-color: #e0e0ff } /* Literal.String.Regex */
+.s1 { background-color: #e0e0ff } /* Literal.String.Single */
+.ss { color: #f0c080 } /* Literal.String.Symbol */
+.bp { color: #007020 } /* Name.Builtin.Pseudo */
+.vc { color: #c0c0f0 } /* Name.Variable.Class */
+.vg { color: #f08040 } /* Name.Variable.Global */
+.vi { color: #a0a0f0 } /* Name.Variable.Instance */
+.il { color: #6060f0; font-weight: bold } /* Literal.Number.Integer.Long */
+# Not needed.
+
+# from django import forms
+# from cab.models import Snippet, Language
+# 
+# class AddSnippetForm(forms.Form):
+#     def __init__(self, author, *args, **kwargs):
+#         super(AddSnippetForm, self).__init__(*args, **kwargs)
+#         self.author = author
+# 
+#     title = forms.CharField(max_length=255)
+#     description = forms.CharField(widget=forms.Textarea())
+#     code = forms.CharField(widget=forms.Textarea())
+#     tags = forms.CharField(max_length=255)
+#     language = forms.ModelChoiceField(queryset=Language.objects.all())
+#     
+#     def save(self):
+#         return Snippet.objects.create(title=self.cleaned_data['title'],
+#                           description=self.cleaned_data['description'],
+#                           code=self.cleaned_data['code'],
+#                           tags=self.cleaned_data['tags'],
+#                           author=self.author,
+#                           language=self.cleaned_data['language'])
+from django.db import models
+from django.contrib.auth.models import User
+from django.db.models import Count, Sum
+
+class SnippetManager(models.Manager):
+    def top_authors(self):
+        return User.objects.annotate(score=Count('snippet')).order_by('-score')
+
+    def most_bookmarked(self):
+        return self.annotate(score=Count('bookmark')).order_by('-score')
+
+    def top_rated(self):
+        return self.annotate(score=Sum('rating')).order_by('score')
+        
+       
+class LanguageManager(models.Manager):
+    def top_languages(self):
+        return self.annotate(score=Count('snippet')).order_by('-score')
+

cab/managers.pyc

Binary file added.
+from cab import managers
+from django.contrib.auth.models import User
+from django.db import models
+from django.db.models import Sum
+from markdown import markdown
+from pygments import formatters, highlight, lexers
+from tagging.fields import TagField
+import datetime
+import tagging
+
+
+class Language(models.Model):
+    name = models.CharField(max_length=100)
+    slug = models.SlugField(unique=True)
+    language_code = models.CharField(max_length=50)
+    mime_type = models.CharField(max_length=100)
+    objects = managers.LanguageManager()
+    
+    class Meta:
+        ordering = ['name']
+    
+    def __unicode__(self):
+        return self.name
+
+    @models.permalink
+    def get_absolute_url(self):
+        return ('cab_language_detail', (), { 'slug': self.slug })
+
+    def get_lexer(self):
+        return lexers.get_lexer_by_name(self.language_code)
+
+
+class Snippet(models.Model):
+    title = models.CharField(max_length=255)
+    language = models.ForeignKey(Language)
+    author = models.ForeignKey(User)
+    description = models.TextField()
+    description_html = models.TextField(editable=False)
+    code = models.TextField()
+    highlighted_code = models.TextField(editable=False)
+    pub_date = models.DateTimeField(editable=False)
+    updated_date = models.DateTimeField(editable=False)
+    objects = managers.SnippetManager()
+    tags = TagField()
+ 
+    class Meta:
+        ordering = ['-pub_date']
+    
+    def __unicode__(self):
+        return self.title
+
+    def save(self, force_insert=False, force_update=False):
+        if not self.id:
+            self.pub_date = datetime.datetime.now()
+        self.updated_date = datetime.datetime.now()
+        self.description_html = markdown(self.description)
+        self.highlighted_code = self.highlight()
+        super(Snippet, self).save(force_insert, force_update)
+
+    @models.permalink
+    def get_absolute_url(self):
+        return ('cab_snippet_detail', (), { 'object_id': self.id })
+    
+    def highlight(self):
+        return highlight(self.code,
+                         self.language.get_lexer(),
+                         formatters.HtmlFormatter(linenos=True))
+
+# See http://blog.sveri.de/index.php?/categories/2-Django
+tagging.register(Snippet, tag_descriptor_attr='etags')
+
+
+class Bookmark(models.Model):
+    snippet = models.ForeignKey(Snippet)
+    user = models.ForeignKey(User, related_name='cab_bookmarks')
+    date = models.DateTimeField(editable=False)
+    
+    class Meta:
+        ordering = ['-date']
+    
+    def __unicode__(self):
+        return "%s bookmarked by %s" % (self.snippet, self.user)
+
+    # See http://blog.haydon.id.au/2008/09/10-finishing-code-sharing-application.html
+    def save(self, **kwargs):
+        if not self.id:
+            self.date = datetime.datetime.now()
+        super(Bookmark, self).save(**kwargs)
+
+
+class Rating(models.Model):
+    RATING_UP = 1
+    RATING_DOWN = -1
+    RATING_CHOICES = ((RATING_UP, 'useful'),
+                      (RATING_DOWN, 'not useful'))
+    snippet = models.ForeignKey(Snippet)
+    user = models.ForeignKey(User, related_name='cab_rating')
+    rating = models.IntegerField(choices=RATING_CHOICES)
+    date = models.DateTimeField()
+    
+    def __unicode__(self):
+        return "%s rating %s (%s)" % (self.user, self.snippet, self.get_rating_display())
+    
+    def save(self):
+        if not self.id:
+            self.date = datetime.datetime.now()
+        super(Rating, self).save()
+    
+    def get_score(self):
+        return self.rating_set.aggregate(Sum('rating'))
+        

cab/models.pyc

Binary file added.

cab/templatetags/__init__.py

Empty file added.

cab/templatetags/__init__.pyc

Binary file added.

cab/templatetags/snippets.py

+from django import template
+from cab.models import Bookmark, Rating
+
+def do_if_bookmarked(parser, token):
+    bits = token.contents.split()
+    if len(bits) != 3:
+        raise template.TemplateSyntaxError("%s tag takes two arguments" % bits[0])
+    nodelist_true = parser.parse(('else', 'endif_bookmarked'))
+    token = parser.next_token()
+    if token.contents == 'else':
+        nodelist_false = parser.parse(('endif_bookmarked',))
+        parser.delete_first_token()
+    else:
+        nodelist_false = template.NodeList()
+    return IfBookmarkedNode(bits[1], bits[2], nodelist_true, nodelist_false)
+
+class IfBookmarkedNode(template.Node):
+    def __init__(self, user, snippet, nodelist_true, nodelist_false):
+        self.nodelist_true = nodelist_true
+        self.nodelist_false = nodelist_false
+        self.user = template.Variable(user)
+        self.snippet = template.Variable(snippet)
+    
+    def render(self, context):
+        try:
+            user = self.user.resolve(context)
+            snippet = self.snippet.resolve(context)
+        except template.VariableDoesNotExist:
+            return ''
+        if Bookmark.objects.filter(user__pk=user.id, snippet__pk=snippet.id):
+            return self.nodelist_true.render(context)
+        else:
+            return self.nodelist_false.render(context)
+
+register = template.Library()
+register.tag('if_bookmarked', do_if_bookmarked)
+
+
+def do_if_rated(parser, token):
+    bits = token.contents.split()
+    if len(bits) != 3:
+        raise template.TemplateSyntaxError("%s tag takes two arguments" % bits[0])
+    nodelist_true = parser.parse(('else', 'endif_rated'))
+    token = parser.next_token()
+    if token.contents == 'else':
+        nodelist_false = parser.parse(('endif_rated',))
+        parser.delete_first_token()
+    else:
+        nodelist_false = template.NodeList()
+    return IfRatedNode(bits[1], bits[2], nodelist_true, nodelist_false)
+
+class IfRatedNode(template.Node):
+    def __init__(self, user, snippet, nodelist_true, nodelist_false):
+        self.nodelist_true = nodelist_true
+        self.nodelist_false = nodelist_false
+        self.user = template.Variable(user)
+        self.snippet = template.Variable(snippet)
+    
+    def render(self, context):
+        try:
+            user = self.user.resolve(context)
+            snippet = self.snippet.resolve(context)
+        except template.VariableDoesNotExist:
+            return ''
+        if Rating.objects.filter(user__pk=user.id, snippet__pk=snippet.id):
+            return self.nodelist_true.render(context)
+        else:
+            return self.nodelist_false.render(context)
+register.tag('if_rated', do_if_rated)
+
+
+def do_get_rating(parser, token):
+    bits = token.contents.split()
+    if len(bits) != 5:
+        raise template.TemplateSyntaxError("%s tag takes four arguments" % bits[0])
+    if bits[3] != 'as':
+        raise template.TemplateSyntaxError("Third argument to %s must be 'as'" % bits[0])
+    return GetRatingNode(bits[1], bits[2], bits[4])
+    
+class GetRatingNode(template.Node):
+    def __init__(self, user, snippet, varname):
+        self.user = template.Variable(user)
+        self.snippet = template.Variable(snippet)
+        self.varname = varname
+    
+    def render(self, context):
+        try:
+            user = self.user.resolve(context)
+            snippet = self.snippet.resolve(context)
+        except template.VariableDoesNotExist:
+            return ''
+        rating = Rating.objects.get(user__pk=user.id, snippet__pk=snippet.id)
+        context[self.varname] = rating
+        return ''
+register.tag('get_rating', do_get_rating)

cab/templatetags/snippets.pyc

Binary file added.
+"""
+This file demonstrates two different styles of tests (one doctest and one
+unittest). These will both pass when you run "manage.py test".
+
+Replace these with more appropriate tests for your application.
+"""
+
+from django.test import TestCase
+
+class SimpleTest(TestCase):
+    def test_basic_addition(self):
+        """
+        Tests that 1 + 1 always equals 2.
+        """
+        self.failUnlessEqual(1 + 1, 2)
+
+__test__ = {"doctest": """
+Another way to test that 1 + 1 is equal to 2.
+
+>>> 1 + 1 == 2
+True
+"""}
+

cab/urls/__init__.py

Empty file added.

cab/urls/__init__.pyc

Binary file added.

cab/urls/bookmarks.py

+from django.conf.urls.defaults import *
+from cab.views import bookmarks
+
+urlpatterns = patterns('',
+    url(r'^add/(?P<snippet_id>\d+)/$',
+        bookmarks.add_bookmark,
+        name='cab_bookmark_add'),
+
+    url(r'^delete/(?P<snippet_id>\d+)/$',
+        bookmarks.delete_bookmark,
+        name='cab_bookmark_delete'),
+    
+    url(r'^$', bookmarks.user_bookmarks, name='cab_user_bookmarks'),
+)

cab/urls/bookmarks.pyc

Binary file added.
+from django.conf.urls.defaults import *
+from cab.views.home import home
+
+urlpatterns = patterns('',
+    url(r'^$', home, name='cab_home'),
+)

cab/urls/home.pyc

Binary file added.

cab/urls/languages.py

+from django.conf.urls.defaults import *
+from django.views.generic.list_detail import object_list
+from cab.models import Language
+from cab.views.languages import language_detail
+
+language_info = { 'queryset': Language.objects.all(),
+                  'paginate_by': 20 }
+
+urlpatterns = patterns('',
+    url(r'^$',
+        object_list,
+        language_info,
+        name='cab_language_list'),
+    url(r'^(?P<slug>[-\w]+)/$',
+        language_detail,
+        name='cab_language_detail'),
+)

cab/urls/languages.pyc

Binary file added.

cab/urls/popular.py

+from django.conf.urls.defaults import *
+from cab.views import popular
+
+urlpatterns = patterns('',
+    url(r'^authors/$',
+        popular.top_authors,
+        name='cab_top_authors'),
+        
+    url(r'^languages/$',
+        popular.top_languages,
+        name='cab_top_languages'),
+    
+    url(r'^bookmarks/$', popular.most_bookmarked, name='cab_most_bookmarked'),
+    
+    url(r'^ratings/$', popular.top_rated, name='cab_top_rated'),
+    
+)

cab/urls/popular.pyc

Binary file added.

cab/urls/ratings.py

+from django.conf.urls.defaults import *
+from cab.views.ratings import rate
+
+urlpatterns = patterns('',
+    url(r'^(?P<snippet_id>\d+)$', rate, name='cab_snippet_rate'),
+)

cab/urls/ratings.pyc

Binary file added.

cab/urls/snippets.py

+from django.conf.urls.defaults import *
+from django.views.generic.list_detail import object_list, object_detail
+from cab.models import Snippet
+from cab.views.snippets import add_snippet, edit_snippet
+
+snippet_info = { 'queryset': Snippet.objects.all() }
+
+urlpatterns = patterns('',
+        url(r'^$', 
+            object_list, 
+            dict(snippet_info, paginate_by=20),
+            name='cab_snippet_list'),
+            
+        url(r'^(?P<object_id>\d+)/$',
+            object_detail, 
+            snippet_info, 
+            name='cab_snippet_detail'),
+        
+        url(r'^add/$', add_snippet, name='cab_snippet_add'),
+        url(r'^edit/(?P<snippet_id>\d+)/$', edit_snippet, name='cab_snippet_edit'),
+)

cab/urls/snippets.pyc

Binary file added.
+from django.conf.urls.defaults import *
+from cab.models import Snippet
+from tagging.models import Tag
+
+
+urlpatterns = patterns('',
+    (r'^(?P<tag>[-\w]+)/$', 'tagging.views.tagged_object_list', { 
+        'queryset_or_model': Snippet.objects.all(), 
+        'template_name': 'cab/snippets_by_tag.html'
+    }, 'cab_snippet_archive_tag'),
+)

cab/urls/tags.pyc

Binary file added.

cab/views/__init__.py

Empty file added.

cab/views/__init__.pyc

Binary file added.

cab/views/bookmarks.py

+from django.http import HttpResponseRedirect
+from django.shortcuts import get_object_or_404, render_to_response
+from django.contrib.auth.decorators import login_required
+from cab.models import Bookmark, Snippet
+from django.views.generic.list_detail import object_list
+from django.template import RequestContext
+
+def add_bookmark(request, snippet_id):
+    snippet = get_object_or_404(Snippet, pk=snippet_id)
+    try:
+        Bookmark.objects.get(user__pk=request.user.id, snippet__pk=snippet_id)
+    except Bookmark.DoesNotExist:
+        bookmark = Bookmark.objects.create(user=request.user, snippet=snippet)
+    return HttpResponseRedirect(snippet.get_absolute_url())
+add_bookmark = login_required(add_bookmark)
+
+def delete_bookmark(request, snippet_id):
+    if request.method == 'POST':
+        snippet = get_object_or_404(Snippet, pk=snippet_id)
+        Bookmark.objects.filter(user__pk=request.user.id, snippet__pk=snippet.id).delete()
+        return HttpResponseRedirect(snippet.get_absolute_url())
+    else:
+        return render_to_response('cab/confirm_bookmark_delete.html', 
+                                    { 'snippet': snippet },
+                                    context_instance=RequestContext(request))
+delete_bookmark = login_required(delete_bookmark)
+
+def user_bookmarks(request):
+    return object_list(request,
+                        queryset=Bookmark.objects.filter(user__pk=request.user.id),
+                        template_name='cab/user_bookmarks.html',
+                        paginate_by=20)

cab/views/bookmarks.pyc

Binary file added.

cab/views/home.py

+from django.shortcuts import render_to_response
+
+def home(request):
+    return render_to_response('cab/home.html')

cab/views/home.pyc

Binary file added.

cab/views/languages.py

+from django.shortcuts import get_object_or_404
+from django.views.generic.list_detail import object_list
+from cab.models import Language
+
+def language_detail(request, slug):
+    language = get_object_or_404(Language, slug=slug)
+    return object_list(request,
+                        queryset=language.snippet_set.all(),
+                        paginate_by=20,
+                        template_name='cab/language_detail.html',
+                        extra_context={ 'language': language })
+

cab/views/languages.pyc

Binary file added.

cab/views/popular.py

+from cab.models import Language, Snippet
+from django.views.generic.list_detail import object_list
+
+def top_authors(request):
+    return object_list(request, queryset=Snippet.objects.top_authors(),
+                        template_name='cab/top_authors.html',
+                        paginate_by=20)
+
+def top_languages(request):
+    return object_list(request, queryset=Language.objects.top_languages(),
+                        template_name='cab/top_languages.html',
+                        paginate_by=20)
+
+def most_bookmarked(request):
+    return object_list(request, queryset=Snippet.objects.most_bookmarked(),
+                        template_name='cab/most_bookmarked.html',
+                        paginate_by=20)
+
+def top_rated(request):
+    return object_list(request, queryset=Snippet.objects.top_rated(),
+                        template_name='cab/top_rated.html',
+                        paginate_by=20)

cab/views/popular.pyc

Binary file added.

cab/views/ratings.py

+from django.http import HttpResponseRedirect
+from django.shortcuts import get_object_or_404
+from django.contrib.auth.decorators import login_required
+from cab.models import Rating, Snippet
+
+def rate(request, snippet_id):
+    snippet = get_object_or_404(Snippet, pk=snippet_id)
+    if 'rating' not in request.GET or request.GET['rating'] not in ('1', '-1'):
+        return HttpResponseRedirect(snippet.get_absolute_url())
+    try:
+        rating = Rating.objects.get(user__pk=request.user.id, snippet__pk=snippet.id)
+    except Rating.DoesNotExist:
+        rating = Rating(user=request.user, snippet=snippet)
+    rating.rating = int(request.GET['rating'])
+    rating.save()
+    return HttpResponseRedirect(snippet.get_absolute_url())
+rate = login_required(rate)

cab/views/ratings.pyc

Binary file added.

cab/views/snippets.py

+from django.http import HttpResponseRedirect, HttpResponseForbidden
+from django.forms import ModelForm
+from django.shortcuts import render_to_response
+from django.contrib.auth.decorators import login_required
+from cab.models import Snippet
+from django.shortcuts import get_object_or_404
+from django.template import RequestContext
+
+class SnippetForm(ModelForm):
+    class Meta:
+        model = Snippet
+        exclude = ['author']
+    
+def add_snippet(request):
+    if request.method == 'POST':
+        form = SnippetForm(data=request.POST)
+        if form.is_valid():
+            new_snippet = form.save(commit=False)
+            new_snippet.author = request.user
+            new_snippet.save()
+            return HttpResponseRedirect(new_snippet.get_absolute_url())
+    else:
+        form = SnippetForm()
+    return render_to_response('cab/snippet_form.html', 
+                                { 'form': form, 'add': True },
+                                context_instance=RequestContext(request))
+add_snippet = login_required(add_snippet)
+
+def edit_snippet(request, snippet_id):
+    snippet = get_object_or_404(Snippet, pk=snippet_id)
+    if request.user.id != snippet.author.id:
+        return HttpResponseForbidden()
+    if request.method == 'POST':
+        form = SnippetForm(instance=snippet, data=request.POST)
+        if form.is_valid():
+            snippet = form.save()
+            return HttpResponseRedirect(snippet.get_absolute_url())
+    else:
+        form = SnippetForm(instance=snippet)
+    return render_to_response('cab/snippet_form.html',
+                                { 'form': form, 'add': False },
+                                context_instance=RequestContext(request))
+edit_snippet = login_required(edit_snippet)
+        

cab/views/snippets.pyc

Binary file added.

cms/.DS_Store

Binary file added.

cms/__init__.py

Empty file added.

cms/__init__.pyc

Binary file added.

cms/js/.DS_Store

Binary file added.

cms/js/tiny_mce/langs/en.js

+tinyMCE.addI18n({en:{
+common:{
+edit_confirm:"Do you want to use the WYSIWYG mode for this textarea?",
+apply:"Apply",
+insert:"Insert",
+update:"Update",
+cancel:"Cancel",
+close:"Close",
+browse:"Browse",
+class_name:"Class",
+not_set:"-- Not set --",
+clipboard_msg:"Copy/Cut/Paste is not available in Mozilla and Firefox.\nDo you want more information about this issue?",
+clipboard_no_support:"Currently not supported by your browser, use keyboard shortcuts instead.",
+popup_blocked:"Sorry, but we have noticed that your popup-blocker has disabled a window that provides application functionality. You will need to disable popup blocking on this site in order to fully utilize this tool.",
+invalid_data:"Error: Invalid values entered, these are marked in red.",
+more_colors:"More colors"
+},
+contextmenu:{
+align:"Alignment",
+left:"Left",
+center:"Center",
+right:"Right",
+full:"Full"
+},
+insertdatetime:{
+date_fmt:"%Y-%m-%d",
+time_fmt:"%H:%M:%S",
+insertdate_desc:"Insert date",
+inserttime_desc:"Insert time",
+months_long:"January,February,March,April,May,June,July,August,September,October,November,December",
+months_short:"Jan,Feb,Mar,Apr,May,Jun,Jul,Aug,Sep,Oct,Nov,Dec",
+day_long:"Sunday,Monday,Tuesday,Wednesday,Thursday,Friday,Saturday,Sunday",
+day_short:"Sun,Mon,Tue,Wed,Thu,Fri,Sat,Sun"
+},
+print:{
+print_desc:"Print"
+},
+preview:{
+preview_desc:"Preview"
+},
+directionality:{
+ltr_desc:"Direction left to right",
+rtl_desc:"Direction right to left"
+},
+layer:{
+insertlayer_desc:"Insert new layer",
+forward_desc:"Move forward",
+backward_desc:"Move backward",
+absolute_desc:"Toggle absolute positioning",
+content:"New layer..."
+},
+save:{
+save_desc:"Save",
+cancel_desc:"Cancel all changes"
+},
+nonbreaking:{
+nonbreaking_desc:"Insert non-breaking space character"
+},
+iespell:{
+iespell_desc:"Run spell checking",
+download:"ieSpell not detected. Do you want to install it now?"
+},
+advhr:{
+advhr_desc:"Horizontal rule"
+},
+emotions:{
+emotions_desc:"Emotions"
+},
+searchreplace:{
+search_desc:"Find",
+replace_desc:"Find/Replace"
+},
+advimage:{
+image_desc:"Insert/edit image"
+},
+advlink:{
+link_desc:"Insert/edit link"
+},
+xhtmlxtras:{
+cite_desc:"Citation",
+abbr_desc:"Abbreviation",
+acronym_desc:"Acronym",
+del_desc:"Deletion",
+ins_desc:"Insertion",
+attribs_desc:"Insert/Edit Attributes"
+},
+style:{
+desc:"Edit CSS Style"
+},
+paste:{
+paste_text_desc:"Paste as Plain Text",
+paste_word_desc:"Paste from Word",
+selectall_desc:"Select All"
+},
+paste_dlg:{
+text_title:"Use CTRL+V on your keyboard to paste the text into the window.",
+text_linebreaks:"Keep linebreaks",
+word_title:"Use CTRL+V on your keyboard to paste the text into the window."
+},
+table:{
+desc:"Inserts a new table",
+row_before_desc:"Insert row before",
+row_after_desc:"Insert row after",
+delete_row_desc:"Delete row",
+col_before_desc:"Insert column before",
+col_after_desc:"Insert column after",
+delete_col_desc:"Remove column",
+split_cells_desc:"Split merged table cells",
+merge_cells_desc:"Merge table cells",
+row_desc:"Table row properties",
+cell_desc:"Table cell properties",
+props_desc:"Table properties",
+paste_row_before_desc:"Paste table row before",
+paste_row_after_desc:"Paste table row after",
+cut_row_desc:"Cut table row",
+copy_row_desc:"Copy table row",
+del:"Delete table",
+row:"Row",
+col:"Column",
+cell:"Cell"
+},
+autosave:{
+unload_msg:"The changes you made will be lost if you navigate away from this page."
+},
+fullscreen:{
+desc:"Toggle fullscreen mode"
+},
+media:{
+desc:"Insert / edit embedded media",
+edit:"Edit embedded media"
+},
+fullpage:{
+desc:"Document properties"
+},
+template:{
+desc:"Insert predefined template content"
+},
+visualchars:{
+desc:"Visual control characters on/off."
+},
+spellchecker:{
+desc:"Toggle spellchecker",
+menu:"Spellchecker settings",
+ignore_word:"Ignore word",
+ignore_words:"Ignore all",
+langs:"Languages",
+wait:"Please wait...",
+sug:"Suggestions",
+no_sug:"No suggestions",
+no_mpell:"No misspellings found."
+},
+pagebreak:{
+desc:"Insert page break."
+}}});

cms/js/tiny_mce/license.txt

+		  GNU LESSER GENERAL PUBLIC LICENSE
+		       Version 2.1, February 1999
+
+ Copyright (C) 1991, 1999 Free Software Foundation, Inc.
+ 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301  USA
+ Everyone is permitted to copy and distribute verbatim copies
+ of this license document, but changing it is not allowed.
+
+[This is the first released version of the Lesser GPL.  It also counts
+ as the successor of the GNU Library Public License, version 2, hence
+ the version number 2.1.]
+
+			    Preamble
+
+  The licenses for most software are designed to take away your
+freedom to share and change it.  By contrast, the GNU General Public
+Licenses are intended to guarantee your freedom to share and change
+free software--to make sure the software is free for all its users.
+
+  This license, the Lesser General Public License, applies to some
+specially designated software packages--typically libraries--of the
+Free Software Foundation and other authors who decide to use it.  You
+can use it too, but we suggest you first think carefully about whether
+this license or the ordinary General Public License is the better
+strategy to use in any particular case, based on the explanations below.
+
+  When we speak of free software, we are referring to freedom of use,
+not price.  Our General Public Licenses are designed to make sure that
+you have the freedom to distribute copies of free software (and charge
+for this service if you wish); that you receive source code or can get
+it if you want it; that you can change the software and use pieces of
+it in new free programs; and that you are informed that you can do
+these things.
+
+  To protect your rights, we need to make restrictions that forbid
+distributors to deny you these rights or to ask you to surrender these
+rights.  These restrictions translate to certain responsibilities for
+you if you distribute copies of the library or if you modify it.
+
+  For example, if you distribute copies of the library, whether gratis
+or for a fee, you must give the recipients all the rights that we gave
+you.  You must make sure that they, too, receive or can get the source
+code.  If you link other code with the library, you must provide
+complete object files to the recipients, so that they can relink them
+with the library after making changes to the library and recompiling
+it.  And you must show them these terms so they know their rights.
+
+  We protect your rights with a two-step method: (1) we copyright the
+library, and (2) we offer you this license, which gives you legal
+permission to copy, distribute and/or modify the library.
+
+  To protect each distributor, we want to make it very clear that
+there is no warranty for the free library.  Also, if the library is
+modified by someone else and passed on, the recipients should know
+that what they have is not the original version, so that the original
+author's reputation will not be affected by problems that might be
+introduced by others.
+
+  Finally, software patents pose a constant threat to the existence of
+any free program.  We wish to make sure that a company cannot
+effectively restrict the users of a free program by obtaining a
+restrictive license from a patent holder.  Therefore, we insist that
+any patent license obtained for a version of the library must be
+consistent with the full freedom of use specified in this license.
+
+  Most GNU software, including some libraries, is covered by the
+ordinary GNU General Public License.  This license, the GNU Lesser
+General Public License, applies to certain designated libraries, and
+is quite different from the ordinary General Public License.  We use
+this license for certain libraries in order to permit linking those
+libraries into non-free programs.
+
+  When a program is linked with a library, whether statically or using
+a shared library, the combination of the two is legally speaking a
+combined work, a derivative of the original library.  The ordinary
+General Public License therefore permits such linking only if the
+entire combination fits its criteria of freedom.  The Lesser General
+Public License permits more lax criteria for linking other code with
+the library.
+
+  We call this license the "Lesser" General Public License because it
+does Less to protect the user's freedom than the ordinary General
+Public License.  It also provides other free software developers Less
+of an advantage over competing non-free programs.  These disadvantages
+are the reason we use the ordinary General Public License for many
+libraries.  However, the Lesser license provides advantages in certain
+special circumstances.
+
+  For example, on rare occasions, there may be a special need to
+encourage the widest possible use of a certain library, so that it becomes
+a de-facto standard.  To achieve this, non-free programs must be
+allowed to use the library.  A more frequent case is that a free
+library does the same job as widely used non-free libraries.  In this
+case, there is little to gain by limiting the free library to free
+software only, so we use the Lesser General Public License.
+
+  In other cases, permission to use a particular library in non-free
+programs enables a greater number of people to use a large body of
+free software.  For example, permission to use the GNU C Library in
+non-free programs enables many more people to use the whole GNU
+operating system, as well as its variant, the GNU/Linux operating
+system.
+
+  Although the Lesser General Public License is Less protective of the
+users' freedom, it does ensure that the user of a program that is
+linked with the Library has the freedom and the wherewithal to run
+that program using a modified version of the Library.
+
+  The precise terms and conditions for copying, distribution and
+modification follow.  Pay close attention to the difference between a
+"work based on the library" and a "work that uses the library".  The
+former contains code derived from the library, whereas the latter must
+be combined with the library in order to run.
+
+		  GNU LESSER GENERAL PUBLIC LICENSE
+   TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION
+
+  0. This License Agreement applies to any software library or other
+program which contains a notice placed by the copyright holder or
+other authorized party saying it may be distributed under the terms of
+this Lesser General Public License (also called "this License").
+Each licensee is addressed as "you".
+
+  A "library" means a collection of software functions and/or data
+prepared so as to be conveniently linked with application programs
+(which use some of those functions and data) to form executables.
+
+  The "Library", below, refers to any such software library or work
+which has been distributed under these terms.  A "work based on the
+Library" means either the Library or any derivative work under
+copyright law: that is to say, a work containing the Library or a
+portion of it, either verbatim or with modifications and/or translated
+straightforwardly into another language.  (Hereinafter, translation is
+included without limitation in the term "modification".)
+
+  "Source code" for a work means the preferred form of the work for
+making modifications to it.  For a library, complete source code means
+all the source code for all modules it contains, plus any associated
+interface definition files, plus the scripts used to control compilation
+and installation of the library.
+
+  Activities other than copying, distribution and modification are not
+covered by this License; they are outside its scope.  The act of
+running a program using the Library is not restricted, and output from
+such a program is covered only if its contents constitute a work based
+on the Library (independent of the use of the Library in a tool for
+writing it).  Whether that is true depends on what the Library does
+and what the program that uses the Library does.
+  
+  1. You may copy and distribute verbatim copies of the Library's
+complete source code as you receive it, in any medium, provided that
+you conspicuously and appropriately publish on each copy an
+appropriate copyright notice and disclaimer of warranty; keep intact
+all the notices that refer to this License and to the absence of any
+warranty; and distribute a copy of this License along with the
+Library.
+
+  You may charge a fee for the physical act of transferring a copy,
+and you may at your option offer warranty protection in exchange for a
+fee.
+
+  2. You may modify your copy or copies of the Library or any portion
+of it, thus forming a work based on the Library, and copy and
+distribute such modifications or work under the terms of Section 1
+above, provided that you also meet all of these conditions:
+
+    a) The modified work must itself be a software library.
+
+    b) You must cause the files modified to carry prominent notices
+    stating that you changed the files and the date of any change.
+
+    c) You must cause the whole of the work to be licensed at no
+    charge to all third parties under the terms of this License.
+
+    d) If a facility in the modified Library refers to a function or a
+    table of data to be supplied by an application program that uses
+    the facility, other than as an argument passed when the facility
+    is invoked, then you must make a good faith effort to ensure that,
+    in the event an application does not supply such function or
+    table, the facility still operates, and performs whatever part of
+    its purpose remains meaningful.
+
+    (For example, a function in a library to compute square roots has
+    a purpose that is entirely well-defined independent of the
+    application.  Therefore, Subsection 2d requires that any
+    application-supplied function or table used by this function must
+    be optional: if the application does not supply it, the square
+    root function must still compute square roots.)
+
+These requirements apply to the modified work as a whole.  If
+identifiable sections of that work are not derived from the Library,
+and can be reasonably considered independent and separate works in
+themselves, then this License, and its terms, do not apply to those
+sections when you distribute them as separate works.  But when you
+distribute the same sections as part of a whole which is a work based
+on the Library, the distribution of the whole must be on the terms of
+this License, whose permissions for other licensees extend to the
+entire whole, and thus to each and every part regardless of who wrote
+it.
+
+Thus, it is not the intent of this section to claim rights or contest
+your rights to work written entirely by you; rather, the intent is to
+exercise the right to control the distribution of derivative or
+collective works based on the Library.
+
+In addition, mere aggregation of another work not based on the Library
+with the Library (or with a work based on the Library) on a volume of
+a storage or distribution medium does not bring the other work under
+the scope of this License.
+
+  3. You may opt to apply the terms of the ordinary GNU General Public
+License instead of this License to a given copy of the Library.  To do
+this, you must alter all the notices that refer to this License, so
+that they refer to the ordinary GNU General Public License, version 2,
+instead of to this License.  (If a newer version than version 2 of the
+ordinary GNU General Public License has appeared, then you can specify
+that version instead if you wish.)  Do not make any other change in
+these notices.
+
+  Once this change is made in a given copy, it is irreversible for
+that copy, so the ordinary GNU General Public License applies to all
+subsequent copies and derivative works made from that copy.
+
+  This option is useful when you wish to copy part of the code of
+the Library into a program that is not a library.
+
+  4. You may copy and distribute the Library (or a portion or
+derivative of it, under Section 2) in object code or executable form
+under the terms of Sections 1 and 2 above provided that you accompany
+it with the complete corresponding machine-readable source code, which
+must be distributed under the terms of Sections 1 and 2 above on a
+medium customarily used for software interchange.
+
+  If distribution of object code is made by offering access to copy
+from a designated place, then offering equivalent access to copy the
+source code from the same place satisfies the requirement to
+distribute the source code, even though third parties are not
+compelled to copy the source along with the object code.
+
+  5. A program that contains no derivative of any portion of the
+Library, but is designed to work with the Library by being compiled or
+linked with it, is called a "work that uses the Library".  Such a
+work, in isolation, is not a derivative work of the Library, and
+therefore falls outside the scope of this License.
+
+  However, linking a "work that uses the Library" with the Library
+creates an executable that is a derivative of the Library (because it
+contains portions of the Library), rather than a "work that uses the
+library".  The executable is therefore covered by this License.
+Section 6 states terms for distribution of such executables.
+
+  When a "work that uses the Library" uses material from a header file
+that is part of the Library, the object code for the work may be a
+derivative work of the Library even though the source code is not.
+Whether this is true is especially significant if the work can be
+linked without the Library, or if the work is itself a library.  The
+threshold for this to be true is not precisely defined by law.
+
+  If such an object file uses only numerical parameters, data
+structure layouts and accessors, and small macros and small inline
+functions (ten lines or less in length), then the use of the object
+file is unrestricted, regardless of whether it is legally a derivative
+work.  (Executables containing this object code plus portions of the
+Library will still fall under Section 6.)
+
+  Otherwise, if the work is a derivative of the Library, you may
+distribute the object code for the work under the terms of Section 6.
+Any executables containing that work also fall under Section 6,
+whether or not they are linked directly with the Library itself.
+
+  6. As an exception to the Sections above, you may also combine or
+link a "work that uses the Library" with the Library to produce a
+work containing portions of the Library, and distribute that work
+under terms of your choice, provided that the terms permit
+modification of the work for the customer's own use and reverse
+engineering for debugging such modifications.
+
+  You must give prominent notice with each copy of the work that the
+Library is used in it and that the Library and its use are covered by
+this License.  You must supply a copy of this License.  If the work
+during execution displays copyright notices, you must include the
+copyright notice for the Library among them, as well as a reference
+directing the user to the copy of this License.  Also, you must do one
+of these things:
+
+    a) Accompany the work with the complete corresponding
+    machine-readable source code for the Library including whatever
+    changes were used in the work (which must be distributed under
+    Sections 1 and 2 above); and, if the work is an executable linked
+    with the Library, with the complete machine-readable "work that
+    uses the Library", as object code and/or source code, so that the
+    user can modify the Library and then relink to produce a modified
+    executable containing the modified Library.  (It is understood
+    that the user who changes the contents of definitions files in the
+    Library will not necessarily be able to recompile the application
+    to use the modified definitions.)
+
+    b) Use a suitable shared library mechanism for linking with the
+    Library.  A suitable mechanism is one that (1) uses at run time a
+    copy of the library already present on the user's computer system,