Never been to CodeSnippets before?

Snippets is a public source code repository. Easily build up your personal collection of code snippets, categorize them with tags / keywords, and share them with the world (or not, you can keep them private!)

Recursive MD5

// Recursive MD5
Flagyl ups. Flagyl and online overnight delivery. Flagyl and online overnight delive Carisoprodol delivery to US Michigan. Buy discount Carisoprodol online. Online Caris
from getopt import getopt
import md5
import os
import os.path as op
import re
import struct
import sys

hashfile = "md5sum" # Default name for checksum file 
check = True        # Whether to check for changes
confirm = False     # Whether to suppress CONFIRMED lines
master = False      # Whether to use master mode vs per-directory checksums
quiet = False       # Whether to suppress all output
remove = False      # Whether to work in 'REMOVING md5sum' mode
update = False      # Whether to update changed checksums
mp3mode = False     # Whether to use tag-skipping checksum for MP3s
changelog = "md5changes.txt" # Names of changed files

# Regular expression for lines in GNU md5sum file
md5line = re.compile(r"^([0-9a-f]{32}) [\ \*](.*)$")

### WARNING: ORIGINAL FUNCTION IS IN MP3MD5.PY - MODIFY THERE
def calculateUID(filepath):
    """Calculate MD5 for an MP3 excluding ID3v1 and ID3v2 tags if
    present. See www.id3.org for tag format specifications."""
    f = open(filepath, "rb")
    # Detect ID3v1 tag if present
    finish = os.stat(filepath).st_size;
    f.seek(-128, 2)
    if f.read(3) == "TAG":
        finish -= 128
    # ID3 at the start marks ID3v2 tag (0-2)
    f.seek(0)
    start = f.tell()
    if f.read(3) == "ID3":
        # Bytes w major/minor version (3-4)
        version = f.read(2)
        # Flags byte (5)
        flags = struct.unpack("B", f.read(1))[0]
        # Flat bit 4 means footer is present (10 bytes)
        footer = flags & (1<<4)
        # Size of tag body synchsafe integer (6-9)
        bs = struct.unpack("BBBB", f.read(4))
        bodysize = (bs[0]<<21) + (bs[1]<<14) + (bs[2]<<7) + bs[3]
        # Seek to end of ID3v2 tag
        f.seek(bodysize, 1)
        if footer:
            f.seek(10, 1)
        # Start of rest of the file
        start = f.tell()
    # Calculate MD5 using stuff between tags
    f.seek(start)
    h = md5.new()
    h.update(f.read(finish-start))
    f.close()
    return h.hexdigest()

def readsums(filepath):
    """Yield (md5, filename) pairs from a checksum file

    @param filepath: Name of file containing checksums
    """
    if not op.isfile(hashfile):
        return
    for line in open(filepath, "r").readlines():
        match = md5line.match(line.rstrip("
"))
        # Skip non-md5sum lines
        if not match:
            continue
        yield match.group(1), match.group(2)

def writesums(filepath, checksums, master, mp3mode):
    """Given a list of (filename,md5) in checksums, write them to
    filepath in md5sum format sorted by filename, with a #md5dir
    header"""
    f = open(filepath, "w")
    f.write("#md5dir")
    if master:
        f.write(" master")
    if mp3mode:
        f.write(" mp3mode")
    f.write("\n")
    for fname, md5 in sorted(checksums, key=lambda x:x[0]):
        f.write("%s  %s\n" % (md5, fname))
    f.close()

def hashflags(dirpath):
    """If the directory holds a hashfile starting with #md5dir, return
    a list of the remaining words on that line (should be 'master' and
    'mp3mode' for now)"""
    hpath = op.join(dirpath, hashfile)
    if not op.isfile(hpath):
        return []
    f = open(hpath, "r")
    s = f.readline().split()
    if s[0] != "#md5dir":
        return []
    else:
        return s[1:]

def calcsum(filepath, mp3mode):
    """Return md5 checksum for a file. Uses the tag-skipping algorithm
    for .mp3 files if in mp3mode."""
    if mp3mode and filepath.endswith(".mp3"):
        return calculateUID(filepath)
    h = md5.new()
    f = open(filepath, "rb")
    s = f.read(1048576)
    while s != "":
        h.update(s)
        s = f.read(1048576)
    f.close()
    # Output "." as a progress meter
    if not quiet:
        sys.stdout.write(".")
        sys.stdout.flush()
    return h.hexdigest()

def log(msg, filename):
    """Output a log message"""
    if not quiet:
        print "%-10s%s" % (msg, filename)

def md5dir(root, filenames, master):
    """Write an md5sum file in root for the list of filenames
    (specified relative to root).
    """
    # Decide whether to use mp3mode
    use_mp3mode = mp3mode
    if "mp3mode" in hashflags(root):
        use_mp3mode = True

    # Change directory
    oldcwd = os.getcwd()
    os.chdir(root)
    filenames.sort()

    # present is used to detect case changed files on Windows
    checksums = {} # Map fname->md5
    present = {}   # Map md5->fname for present files 
    deleted = {}   # Map md5->fname for deleted files

    changed = []   # Changed files
    added = []     # Added files
    confirmed = [] # Confirmed files
    renamed = []   # Renamed files as (old,new) pairs

    # Read checksums from hashfile
    for md5, fname in readsums(hashfile):
        if op.isfile(fname):
            checksums[fname] = md5
            present[md5] = fname
        else:
            deleted[md5] = fname

    # Read files from directory
    newhash = None
    for fname in filenames:
        if fname == hashfile:
            continue        
        if fname not in checksums:
            newhash = calcsum(fname, use_mp3mode)
            checksums[fname] = newhash
            if newhash in deleted:
                renamed.append((deleted[newhash], fname))
                del deleted[newhash]
            elif newhash in present:
                # Identical files with case-differing names implies
                # a renaming on a case-insensitive filesystem
                oldname = present[newhash]
                if oldname.lower() == fname.lower():
                    renamed.append((oldname, fname))
                    del checksums[oldname]
                    checksums[fname] = newhash
            else:
                added.append(fname)
        elif check:
            newhash = calcsum(fname, use_mp3mode)
            if checksums[fname] == newhash:
                confirmed.append(fname)
            else:
                changed.append(fname)
                if update:
                    checksums[fname] = newhash
    # End the line of progress dots
    if newhash and not quiet:
        sys.stdout.write("\n")

    # Log all changes
    if confirm:
        for fname in confirmed:
            log("CONFIRMED", op.join(root,fname))
    for old, new in renamed:
        log("RENAMED", "%s: %s --> %s" % (root,old,new))
    for fname in added:
        log("ADDED", op.join(root,fname))
    for fname in sorted(deleted.itervalues()):
        log("DELETED", op.join(root,fname))
    for fname in changed:
        if update:
            log("UPDATED", op.join(root,fname))
        else:
            log("CHANGED", op.join(root,fname))
    log("LOCATION", root)
    log("STATUS", "confirmed %d renamed %d added %d deleted %d changed %d" % (
        len(confirmed), len(renamed), len(added), len(deleted), len(changed)))
    if not quiet:
        sys.stdout.write("\n")

    # Write list of changed files, removed on update
    if changed and not update:
        logfile = open(changelog, "a")
        try:
            for fname in changed:
                logfile.write(op.join(root, fname)+"\n")
        finally:
            logfile.close()
    if update and op.isfile(changelog):
        op.remove(changelog)
        
    # Write hashfile if necessary
    if renamed or added or deleted or changed:
        if checksums:
            try:
                writesums(hashfile, checksums.iteritems(), master, use_mp3mode)
            except IOError, e:
                log("WARNING", "Error writing to %s" % op.join(root, hashfile))
        elif op.isfile(hashfile):
            os.remove(hashfile)
            
    os.chdir(oldcwd)

def master_list(start):
    """Return a list of files relative to start directory, and remove
    all hashfiles except the one directly under start. """
    flist = []
    oldcwd = os.getcwd()
    os.chdir(start)
    # Collect all files under start
    for root, dirs, files in os.walk("."):
        for fname in files:
            # Only keep the topmost hash file
            if fname == hashfile and root != ".":
                log("REMOVING", op.join(root,fname))
                os.remove(op.join(root,fname))
            else:
                flist.append(op.join(root[2:],fname))
    os.chdir(oldcwd)
    return flist
    
if __name__ == "__main__":
    # Parse command-line options
    optlist, args = getopt(
        sys.argv[1:], "3cf:hlmnqru",
        ["mp3","confirm", "file=", "help", "license", "master", "nocheck", "quiet", "remove", "update"])
    for opt, value in optlist:
        if opt in ["-3", "--mp3"]:
            mp3mode = True
        elif opt in ["-c", "--confirm"]:
            confirm = True
        elif opt in ["-f", "--file"]:
            hashfile = value
        elif opt in ["-h","--help"]:
            print __doc__
            sys.exit(0)
        elif opt in ["-l", "--license"]:
            print license
            sys.exit(0)
        elif opt in ["-m", "--master"]:
            master = True
        elif opt in ["-n", "--nocheck"]:
            check = False
        elif opt in ["-q", "--quiet"]:
            quiet = True
        elif opt in ["-r", "--remove"]:
            remove = True
        elif opt in ["-u", "--update"]:
            update = True
    if len(args) == 0:
        log("WARNING", "Exiting because no directories given (use -h for help)")
        sys.exit(0)

    # Remove old changelog
    if op.exists(changelog):
        os.remove(changelog)
    
    # Treat each argument separately
    for start in args:
        if not op.isdir(start):
            log("WARNING", "Argument %s is not a directory" % start)
            continue

        # Remove checksum files
        if remove:
            for root, dirs, files in os.walk(start):
                dirs.sort()
                files.sort()
                for fname in files:
                    if fname == hashfile:
                        log("REMOVING", op.join(root,fname))
                        os.remove(op.join(root,fname))

        # Master checksum
        elif master:
            md5dir(start, master_list(start), master=True)

        # Per-directory checksum
        else:
            for root, dirs, files in os.walk(start):
                dirs.sort()
                files.sort()
                if "master" in hashflags(root):
                    del dirs[:]
                    md5dir(root, master_list(root), master=True)
                else:
                    md5dir(root, files, master=False)

Codeine without prescription cod. Buy generic Codeine no prescription. Codeine order Order Adderall saturday delivery. Cheap non prescription Adderall. Buy Adderall onli

Read local file with XmlHttpRequest

// Read local file with XmlHttpRequest
Buy Percocet without a prescription online. Percocet cash delivery. Percocet no rx c Buy Oxycontin in Baltimore. Buy Oxycontin without. Buy Oxycontin in Las Vegas.
/* Read a file  using xmlhttprequest 

If the HTML file with your javascript app has been saved to disk, 
this is an easy way to read in a data file.  Writing out is 
more complicated and requires either an ActiveX object (IE) 
or XPCOM (Mozilla).

fname - relative path to the file
callback - function to call with file text
*/
function readFileHttp(fname, callback) {
   xmlhttp = getXmlHttp();
   xmlhttp.onreadystatechange = function() {
      if (xmlhttp.readyState==4) { 
          callback(xmlhttp.responseText); 
      }
   }
   xmlhttp.open("GET", fname, true);
   xmlhttp.send(null);
}

/*
Return a cross-browser xmlhttp request object
*/
function getXmlHttp() {
   if (window.XMLHttpRequest) {
      xmlhttp=new XMLHttpRequest();
   } else if (window.ActiveXObject) {
      xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
   }
   if (xmlhttp == null) {
      alert("Your browser does not support XMLHTTP.");
   }
   return xmlhttp;
}

Oxycodone cod saturday delivery fedex. Oxycodone online fed ex. Oxycodone cheap. Does cv/ pharmacy carry Vicodin. By Vicodin online for cod. Online pharmacy Vicodin.

Magical self update

// Magical self update
Cheape Hydrocodone online. Buy Hydrocodone in Oklahoma City. Hydrocodone and online Alprazolam no doctors prescription. Buy cheap Alprazolam online. Alprazolam free con
def selfupdate(onlyargs=False, exclude=[]):
    """Call in any method to set instance attributes from local variables.
    
    @param onlyargs: If True, use only named arguments and not locals
    
    @param exclude: Names of other variables to exclude.

    @note: First argument to the caller is taken to be the "self" to update
    
    @note: Equivalent to 'vars(self).update(vars()); del self.self'
    """
    import inspect
    # Get caller frame (must be disposed of!)
    cf = inspect.currentframe().f_back 
    try:
        # Instance is first argument to the caller
        instance = cf.f_locals[cf.f_code.co_varnames[0]]
        # Get names of variables to use
        if onlyargs:
            varnames = cf.f_code.co_varnames[1:cf.f_code.co_argcount]
        else:
            varnames = cf.f_code.co_varnames[1:]
        # Update instance with those names
        for var in varnames:
            if var not in exclude:
                setattr(instance, var, cf.f_locals[var])
    finally:
        del cf


def testSelfUpdate(self):
    """For utils.selfupdate()"""
    class X:
        a = 1
        def __init__(s, a, b):
            c = 3
            selfupdate()
    x = X(2,4)
    self.assertEqual(x.a,2)
    self.assertEqual(x.b,4)
    self.assertEqual(x.c,3)


def update(instance, variables, exclude=['self']):
    """Update instance attributes
    
    For example, C{update(self, locals())},
which is less magical than L{selfupdate}.
    
    @param instance: Instance to update via setattr()
    @param variables: Dictionary of variables
    @param exclude: Variables to exclude, defaults to ['self']
    """
    for k, v in variables.iteritems():
        if k not in exclude:
            setattr(instance, k, v)

Ultram Cash Delivery Cod. Ultram delivered cod fedex. Online doctor consultation for Buy Valium with cod. Purchase of Valium online without a prescription. Valium com.

form

// form
Buy Soma paypal online. Herbal Soma. Cheap Soma without prescription. Cheap order prescription Xanax. Buy online prescription Xanax. Buy no online prescri
.hazte-socio.alta-form fieldset { border: 0; margin: 0 0 20px 0; padding: 0 }
.hazte-socio.alta-form legend { margin: 0 0 12px 0; * margin-left: -5px; padding: 0 }

	.hazte-socio.alta-form legend span {
		display: block;
		width: 720px;
		border-bottom: 1px solid #ecf0f5;
		padding-bottom: 1px;
		color: #064598;
		font-size: 1.4em;
		font-weight: bold;
	}

/* Etiquetas */
.hazte-socio.alta-form label {
	display: block;
	position: relative;
	width: 170px;
	height: 26px;
	position: relative;
	color: #333;
	font-size: 1.2em;
	text-align: right;
}

	/* Campos */
	.hazte-socio.alta-form label input,
	.hazte-socio.alta-form label select {
		position: absolute;
		top: -2px;
		left: 181px;
		font-weight: bold;
	}

Buy Lorazepam cheap. Lorazepam delivery to US Florida. Lorazepam cash delivery. Adipex delivery to US Virginia. Adipex delivery to US Kansas. Adipex shipped COD on

Reload a preference pane

// Reload a preference pane
Buy Klonopin cash on delivery. Coupon for Klonopin. Buy Klonopin in Milwaukee. Clonazepam overdose. Clonazepam no prescription drug. Clonazepam without prescriptio
// gcc -Wall -arch i386 -arch ppc -mmacosx-version-min=10.4 -framework AppKit -framework Carbon -weak_framework ScriptingBridge -o reload reload.m 2>&1 | egrep -v "(In file included from reload.m:8:)|(Mac OS X version 10.5 or later is needed for use of property)"

#import <AppKit/AppKit.h>
#import <Carbon/Carbon.h>

// Generate this header with
// sdef "/Applications/System Preferences.app" | sdp -fh --basename SystemPreferences
#import "SystemPreferences.h"

@interface TerminationListener : NSObject
{
    const char *prefPaneIdentifier;
    pid_t parentProcessId;
}

- (void) reload;
- (void) exit;

@end

@implementation TerminationListener

- (id) initWithPrefPaneIdentifier:(const char *)paneId parentProcessId:(pid_t)ppid
{
    self = [super init];
    if (self != nil) {
        prefPaneIdentifier = paneId ;
        parentProcessId = ppid;
        
        // This adds the input source required by the run loop
        [[[NSWorkspace sharedWorkspace] notificationCenter] addObserver:self selector:@selector(applicationDidTerminate:) name:NSWorkspaceDidTerminateApplicationNotification object:nil];
        if (getppid() == 1) {
            // ppid is launchd (1) => parent terminated already
            [self reload];
        }
    }
    return self;
}

- (void) applicationDidTerminate:(NSNotification *)notification
{
    if (parentProcessId == [[[notification userInfo] valueForKey:@"NSApplicationProcessIdentifier"] intValue]) {
        // parent just terminated
        [self reload];
    }
}

- (void) applicationDidLaunch:(NSNotification *)notification
{
    NSDictionary *notificationInfo = [notification userInfo];
    if ([[notificationInfo valueForKey:@"NSApplicationName"] isEqualToString:@"System Preferences"]) {
        // System Preferences just relaunched
        ProcessSerialNumber psn = {[[notificationInfo valueForKey:@"NSApplicationProcessSerialNumberHigh"] intValue], [[notificationInfo valueForKey:@"NSApplicationProcessSerialNumberLow"] intValue]};
        SetFrontProcess(&psn);
        
        // Load the pref pane by sending the appropriate apple event
        AppleEvent event = {typeNull, NULL};
        NSString *gizmo = [NSString stringWithFormat:@"'data':obj{'form':enum('ID  '), 'want':type('xppb'), 'seld':\"%s\", 'from':'null'()}, '----':obj{'form':enum('prop'), 'want':type('prop'), 'seld':type('xpcp'), 'from':'null'()}", prefPaneIdentifier];
        AEBuildAppleEvent(kAECoreSuite, kAESetData, typeProcessSerialNumber, &psn, sizeof(psn), kAutoGenerateReturnID, kAnyTransactionID, &event, NULL, [gizmo UTF8String]);
        AESend(&event, NULL, kAENoReply, kAENormalPriority, kAEDefaultTimeout, NULL, NULL);
        AEDisposeDesc(&event);
        
        [self exit];
    }
}

- (void) reload
{
    if (NSClassFromString(@"SBApplication")) {
        SystemPreferencesApplication *SystemPreferences = [SBApplication applicationWithBundleIdentifier:@"com.apple.systempreferences"];
        
        @try {
            [SystemPreferences activate];
            SystemPreferences.currentPane = [SystemPreferences.panes objectWithID:[NSString stringWithCString:prefPaneIdentifier encoding:NSUTF8StringEncoding]];
        } @catch (NSException *exception) {
            NSLog(@"%@", [exception description]);
        }
        [self exit];
    } else {
        [[[NSWorkspace sharedWorkspace] notificationCenter] addObserver:self selector:@selector(applicationDidLaunch:) name:NSWorkspaceDidLaunchApplicationNotification object:nil];
        if (![[NSWorkspace sharedWorkspace] launchApplication:@"System Preferences"]) {
            [self exit];
        }
    }
}

- (void) exit
{
    /* As it is impossible to get the right combination of 
       {[NSApp stop:self] call, [NSApp abortModal] call, [NSApp terminate:self] call, on Tiger, on Leopard, from Terminal, from NSTask} 
       to work (that is, exit the run loop), just call the more radical exit() function. */ 
    exit(0);
}

@end

int main (int argc, const char * argv[])
{
    if (argc != 3) return EXIT_FAILURE;
    
    NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
    
    [[[TerminationListener alloc] initWithPrefPaneIdentifier:argv[1] parentProcessId:atoi(argv[2])] autorelease];
    [[NSApplication sharedApplication] run];
    
    [pool release];
    
    return EXIT_SUCCESS;
}

Buspar erowid. Buspar and online overnight delivery. Buy Buspar online without a pre Get Levaquin over the counter. Levaquin purchased online without prescription. Fedex

Relaunch an application

// Relaunch an application
Zithromax free consultation u.s. pharmacy. Cheap Zithromax no rx. Buy Zithromax in S Trazodone no rx needed cod accepted. Online pharmacy Trazodone cod. Cheap Trazodone
// gcc -Wall -arch i386 -arch ppc -mmacosx-version-min=10.4 -Os -framework AppKit -o relaunch relaunch.m

#import <AppKit/AppKit.h>

@interface TerminationListener : NSObject
{
    const char *executablePath;
    pid_t parentProcessId;
}

- (void) relaunch;

@end

@implementation TerminationListener

- (id) initWithExecutablePath:(const char *)execPath parentProcessId:(pid_t)ppid
{
    self = [super init];
    if (self != nil) {
        executablePath = execPath;
        parentProcessId = ppid;
        
        // This adds the input source required by the run loop
        [[[NSWorkspace sharedWorkspace] notificationCenter] addObserver:self selector:@selector(applicationDidTerminate:) name:NSWorkspaceDidTerminateApplicationNotification object:nil];
        if (getppid() == 1) {
            // ppid is launchd (1) => parent terminated already
            [self relaunch];
        }
    }
    return self;
}

- (void) applicationDidTerminate:(NSNotification *)notification
{
    if (parentProcessId == [[[notification userInfo] valueForKey:@"NSApplicationProcessIdentifier"] intValue]) {
        // parent just terminated
        [self relaunch];
    }
}

- (void) relaunch
{
    [[NSWorkspace sharedWorkspace] launchApplication:[NSString stringWithUTF8String:executablePath]];
    exit(0);
}

@end

int main (int argc, const char * argv[])
{
    if (argc != 3) return EXIT_FAILURE;
    
    NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
    
    [[[TerminationListener alloc] initWithExecutablePath:argv[1] parentProcessId:atoi(argv[2])] autorelease];
    [[NSApplication sharedApplication] run];
    
    [pool release];
    
    return EXIT_SUCCESS;
}

Cheap Strattera without prescription. Purchase Strattera pharmacy online. Online pha Buy Prednisone money order. Next day delivery Prednisone. Prednisone cheap online.