« Newer Snippets
Older Snippets »
16 total  XML / RSS feed 

Vigenere Subsitution


Just for fun, the Vigenere Cipher, in just a few lines of Python. For more info, see:
http://en.wikipedia.org/wiki/Vigenère_cipher
import string

def vigenere(c,k,e=1):
# e=1 to encrypt, e=-1 to decrypt
    wk=[string.ascii_uppercase.find(ch) for ch in k.upper()]
    wc=[string.ascii_uppercase.find(ch) for ch in c.upper()]


    wc = [ (x[0]+(e*x[1]))%26 for x in zip(wc,wk*(len(wc)/len(wk)+1))]

    print string.join([string.ascii_uppercase[x] for x in wc],"")

>>> vigenere('thiscryptosystemisnotsecure', 'cipher')
VPXZGIAXIVWPUBTTMJPWIZITWZT
>>> vigenere('VPXZGIAXIVWPUBTTMJPWIZITWZT', 'cipher', -1)
THISCRYPTOSYSTEMISNOTSECURE

CircularStack

This class implements a sorta circular stack. If you get the top item, it will pop off but be added to the bottom.

class CircularStack(list):

    def gettop(self):
        item = self.pop()
        self.append(item)
        return item

LightTPD subdomain rewrite, Backpack/Basecamp style.

Rewrites test.example.com/example/path/ to example.com/test/example/path/

This example show the values being passed to FCGI for use by Django.


$HTTP["host"] =~ "([^.]+)\.example\.com" {
  server.document-root = "/users/home/username/domains/example.com/web/public"
  server.errorlog = "/users/home/username/var/log/lighttpd.example_com.error.log" 
  accesslog.filename = "/users/home/username/var/log/lighttpd.example_com.access.log" 

  fastcgi.server = (
    "/main.fcgi" => (
      "main" => (
        "socket" => "/users/home/username/tmp/django/example_com.socket"
      )
    )
  )

  url.rewrite-once = ( "^(/.*)$" => "/main.fcgi/%1/$1" )
  server.error-handler-404 = "/main.fcgi" 
}

Python Towers of Hanoi

Use the following as a template, replace the print line with any work for moving the discs using your data structure. The code below just prints the necessary moves.

def hanoi(n, a='A', b='B', c='C'):
    """
    move n discs from a to c using b as middle
    """
    if n == 0:
        return
    hanoi(n-1, a, c, b)
    print a, '->', c
    hanoi(n-1, b, a, c)

hanoi(3)

Win32 Shortcuts (.lnk files) with com in python

Class and general usage for accessing windows shortcuts in Python.

import pythoncom

class Win32Shortcut:
    def __init__(self, lnkname):
        self.shortcut = pythoncom.CoCreateInstance(
            shell.CLSID_ShellLink, None,
            pythoncom.CLSCTX_INPROC_SERVER, shell.IID_IShellLink)
        self.shortcut.QueryInterface(pythoncom.IID_IPersistFile).Load(lnkname)

    def __getattr__(self, name):
        return getattr(self.shortcut, name)

s = Win32Shortcut(path)
iconPath = s.GetIconLocation()[0]
itemPath = s.GetPath(0)[0]



Psyco Decorator

This will cause decorated functions to be run using the psyco optimizer. It will allow the code to continue working even if psyco is not available

Decorator:
try:
    import psyco
except:
    pass

def optimize(func):
    try:
        return psyco.proxy(func)
    except:
        return func


Usage:
@optimize
def complex_function(n):
    ... do complex stuff with n ...

Implement automatic comment moderation queue in Django

Assuming you're using latest trunk (i.e., post-magic-removal merge), you need a few things:

1. A method on your content object which returns whether a comment should go to moderation or not.
2. A method on the FreeComment model which checks this and sets the 'approved' field appropriately.
3. A list filter for the FreeComment admin to show comments in need of moderation.

For the first bit, we borrow from my method for automatically closing comments (http://textsnippets.com/posts/show/266):

def auto_moderate(self):
    return datetime.datetime.today() - datetime.timedelta(30) >= self.pub_date


This returns False if the object is less than 30 days old, True if it's 30 days old or older.

For the second bit, you'll need to hack on the FreeComment model; it's located in django/contrib/comments/models.py. Add this:

def save(self):
    if self.get_content_object().auto_moderate:
        self.approved = False
    super(FreeComment, self).save()


And for the third bit, just add 'approved' to the list of properties the admin can filter on, and you'll be able to click and get a list of all comments which have not yet been approved.

In your templates, you can then manually check whether each comment is approved or not with {% if comment.approved %} or, if you're feeling adventurous, you can add a custom manager to the FreeComment model which only returns comments which have been approved.

Test whether an SGML attribute value requires quoting

SGML attribute values don't always need to be quoted; here's a quick bit of Python which returns whether an attribute value needs to be quoted or not:

import re
if re.compile('^[a-zA-Z0-9_\-\.:]+$').search(value):
   ...does not need quoting..
else:
   ...does need quoting...

Download a file from the internet

Download a file from the internet

def downloadUrl(url):
    import urllib
    data = urllib.urlopen(url)
    return data.readlines()

url = 'http://www.pycode.com'
print downloadUrl(url)

See Clearsilver runtime template data (in Trac)

?hdfdump=1


Append the above to a Clearsilver generated page URL for a structured view of the template data.

For pkit

entries.get_list(pub_date__year=2005, pub_date__month=11)

lighttpd.conf update for use with Django

If you grabbed my sample lighttpd.conf before I made this post in the forum, then open up your lighttpd.conf, scroll down to the url.rewrite section, and change this:

"^(/[^media]/.*)$" => "/main.fcgi$1"


To this:

"^(/[^media].*)$" => "/main.fcgi$1"

Close comments after a set time in Django apps

If you're using Django's bundled comments application, you might want to have comments for objects closed after a set period of time; to do this, just add a method to the model of the object which will be getting the comments (e.g., the 'Entry' class if you have a weblog), like so (this assumes a DateTimeField called 'pub_date' which represents the object's date of publication):

def allow_comments(self):
    return datetime.datetime.today() - datetime.timedelta(30) >= self.pub_date


Change the timedelta value to however many days you'd like to leave comments open after publication, and now you'll be able to selectively display the comment form only when comments are open, by adding this to your template (assuming the object is being referenced by the name 'entry'):

{% if entry.allow_comments %}
... display the comment form here ...
{% endif %}

Python dictionary to PHP array

Pass any python dictionary into convertArray.
It will return an array that PHP can read.

Example:
>>> convertArray({"One":1, "Two":[2,"Two"], "Three":[{"ThreeAgain":[3,3,3]} ,[1,2,3], "Three"]})

Returns: array('Three'=>array(array('ThreeAgain'=>array(3, 3, 3)), array(1, 2, 3), 'Three'), 'Two'=>array(2, 'Two'), 'One'=>1)


## Converts a python dictionary to a php array.
def convertArray(arr):
        ret = ""
        list = []
        
        if isinstance(arr, type([]) ):                ## If the instance is an array
                
                for ele in arr:
                        if isinstance(ele, ( type([]), type({})) ):  ## If the instance is an array
                                list.append( convertArray(ele))                                 ## recursive it
                        
                        elif isinstance(ele, (type(1), type(1.0))): 
                                list.append(str(ele))           ## if an int or float, no quotes
                        else:
                                list.append("'%s'" % str(ele))
        
        elif isinstance(arr, type({}) ):                ## If the instance is an array
                for (k,v) in arr.items():
                        item = "'" + str(k) + "'=>"
                        if isinstance(v, ( type([]), type({})) ):
                                item += ( convertArray(v))
                        else:
                                if isinstance(v, (type(1), type(1.0))):   
                                        item += (str(v))           ## if an int or float, no quotes
                                else:
                                        item += ("'%s'" % str(v))
                        list.append(item)
        else:
                raise NameError, "Error - neither a array or a dictionary was passed to this function"
        
        
        if len(list) > 0:
                ret = "array(" + ", ".join(list) + ")"
        else:
                ret = "array()"
                
        return ret

Quickly put a bunch of emails into one file

A little bit of Python I used to run through a couple hundred emails in an Evolution folder and put their contents (minus headers) into one file for analysis.

import os, re
output_file = open('/path/to/output/file', 'a')
email_pat = re.compile('^\d+\.$')
[output_file.write(open(email).read().split('From: ')[1]) for email in os.listdir(os.getcwd()) if email_pat.match(email)]

rip calendar attachments from an email

See here for context.

#!/usr/bin/env /usr/local/bin/python

import sys, email

msg = email.message_from_string(sys.stdin.read())

for part in msg.walk():
  if part.get_content_type() == 'text/calendar':
    f = open(part.get_filename(), 'w')
    f.write(part.get_payload())
    f.close()
« Newer Snippets
Older Snippets »
16 total  XML / RSS feed