Never been to DZone Snippets 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

About this user

David R. MacIver http://unenterprise.blogspot.com

« Newer Snippets
Older Snippets »
Showing 11-20 of 21 total

Chickenfoot shortcut script

Here's a little script to get Chickenfoot to add some keyboard shortcuts to firefox.

Add this to run as a trigger on window open and you'll be able to acquire focus on the current chickenfoot editor window by pressing 'alt-C' and to regain focus on the main tab (which is something I've often wanted to be able to do) with 'alt-D'

// attach keyboard shortcut (Alt-C)
chromeWindow.addEventListener("keypress",
   function(event) {
     if (event.altKey && event.charCode == 'c'.charCodeAt(0)) {
       event.preventDefault();
       var sidebar = Chickenfoot.getSidebarWindow(chromeWindow);
       if (sidebar) {
          sidebar.getSelectedBuffer().focus();
       }
     }
    },
    true);


// attach keyboard shortcut (Alt-D)
chromeWindow.addEventListener("keypress",
   function(event) {
     if (event.altKey && event.charCode == 'd'.charCodeAt(0)) {
       event.preventDefault();
	   tab.focus();
       }
    },
    false);



2 + 2 = 5

Here is some very exciting Java code for printing 5.

import java.security.*;
import java.lang.reflect.*;
import java.util.*;

public class Test
{
    public static void main(String[] args) throws Exception
    {   
        AccessController.doPrivileged( new PrivilegedAction<Object>(){ public Object run(){try {
        Field field = Class.forName("java.lang.Integer$IntegerCache").getDeclaredFields()[0];
        field.setAccessible(true);

        Integer[] cache = (Integer[])field.get(null);
            
        cache[130] = 3;  
            
        Integer foo = 2;
 
        System.out.println(foo + 2); 
            
        return null;} catch(Exception e) { throw new RuntimeException(e); } } }); 
    }


}

JSON Parser in Haskell

I've been having trouble writing parsers recently, and I've been meaning to get to grips with Haskell at some point, so I figured I'd write a simple JSON parser using Haskell's Parsec library. Here's the code for it:

Update: I've modified this to use Data.Map instead of a list of key value pairs for the record / object implementation. I've also removed the 'identifier' feature as it isn't really part of JSON proper. Also, I've noticed that this seems to have acquired some sort of presence on google. This isn't really very good code - it's more a demonstration of parsec than it is an actually useful parser. (I mean, it works fine, and it's probably sufficient for trivial uses, but I wouldn't e.g. guarantee it to be bug free). I strongly recommend using this one instead.

import Text.ParserCombinators.Parsec
import System
import qualified Data.Map as Map

-- Main method. Currently not very interesting - just a test piece of code which accepts
-- a file and prints out a representation of the parsed type (or an error message if it is
-- invalid.
mainParser = do {
    val <- valueParser
    ; skipMany space
    ; eof
    ; return val }

main :: IO ()
main = do {
    args <- getArgs 
  ; val <- parseFromFile mainParser $ args !! 0 
  ; print(val) } 

-- Matches string literals. 
literalString :: Parser JSON 
literalString = do {
        char '"'
      ;  val <-  many1 letter
      ;  char '"'
      ; return $ LiteralString val}


-- Data type representing a JSON AST. Roughly corresponds to a Javascript object.
data JSON = ListValue [JSON] 
          | LiteralString String
          | LiteralInt Integer
          | LiteralBoolean Bool
          | RecordValue (Map.Map String JSON)
            deriving Show         


-- Combined parser.
valueParser :: Parser JSON
valueParser =       
        literalString
    <|> literalInt
    <|> literalBoolean
    <|> recordParser
    <|> listParser 

-- Matches literal integers.
literalInt :: Parser JSON
literalInt = do {
    ; val <- many1 digit
    ; return $ LiteralInt (read val)
        }

-- Matches boolean literals
literalBoolean :: Parser JSON
literalBoolean =
                do{ 
                  string "true"
                ; return $ LiteralBoolean True}
            <|> do{
                  string "false"
                ; return $ LiteralBoolean False}

-- Code for parsing lists.
-- Matches comma separated lists enclosed in [ ]
listParser :: Parser JSON 
listParser = do{ 
                char '['
              ; words <- sepBy1 valueParser listSeparator
              ; char ']'
              ; return $ ListValue words
              }

-- Matches ',' with any amount of space on either side.
listSeparator :: Parser ()
listSeparator = do{ 
      skipMany space 
    ; char ','
    ; skipMany space
}

-- Code for parsing records.
-- Matches { word : JSON; word : JSON; word : value; ... }
recordParser :: Parser JSON 
recordParser = do{
      char '{'
    ; defs <- endBy definitionParser definitionSeparator
    ; char '}'
    ; return $ RecordValue $ Map.fromList defs 
}

-- Matches things of the form word : JSON
definitionParser :: Parser (String, JSON)
definitionParser = do{
      skipMany space
    ; key <- many1 letter 
    ; skipMany space
    ; char ':'
    ; skipMany space
    ; val <- valueParser
    ; return (key, val)
}

-- Matches ';' with any amount of space on either side.
definitionSeparator :: Parser ()
definitionSeparator = do {
      skipMany space
    ; char ';'
    ; skipMany space
    ; return () 
}


Simple stack machine interpreter written in Scala

I wanted to implement a simple stack machine, and I wanted some practice with Scala. The two seemed to combine well.

I'll write up a description of the instruction set when I can be bothered, but it's hopefully pretty self explanatory.

package StackMachine;

import scala.collection.mutable._
import java.io.File;
import java.io.File._;
import java.io.BufferedReader;
import java.io.BufferedReader._ 
import java.io.InputStreamReader;
import java.io.InputStreamReader._;
import java.io.FileInputStream; 
import java.io.FileInputStream._;
import scala.collection.jcl.ArrayList;

class Memory(size : int) {
    private val internalMemory = new Array[int](size);
    
    override def toString : String = internalMemory.toString;    

    def load( location : int) = internalMemory(location % size);
    def store( location : int, value : int) { 
        internalMemory(location % size) = value; }
}

abstract class Instruction;

case class push (value : int) extends Instruction;
case class pop extends Instruction;
case class plus extends Instruction;
case class print extends Instruction;
case class break extends Instruction;
case class dup extends Instruction;
case class goto(instruction : int) extends Instruction;
case class noop extends Instruction;
case class ifCurrent(instruction : int) extends Instruction;
case class minus extends Instruction;
case class store(register : int) extends Instruction;
case class load(register : int) extends Instruction;
case class loadCurrent extends Instruction;
case class storeCurrent extends Instruction;
case class ifEmpty(instruction : int) extends Instruction;

object Instruction{
    def parse (value : String) = {
        if (value.startsWith("#")) noop()
        else {
        val split = splitString(value);
        val instruction = split._1.toLowerCase;
        val args = split._2;

        instruction match {
            case "pop"          => pop()
            case "plus"         => plus()
            case "print"        => print()
            case "push"         => push(args(0)) 
            case "break"        => break()
            case "dup"          => dup()
            case "goto"         => goto(args(0))
            case "ifstack"      => ifCurrent(args(0))
            case "store"        => store(args(0))
            case "load"         => load(args(0))
            case ""             => noop()
            case "minus"        => minus()
            case "ifempty"      => ifEmpty(args(0))
            case "loadcurrent"  => loadCurrent()
            case "storecurrent" => storeCurrent()
            case  _             => throw new Exception("Couldn't parse " + value)}}}

    private def splitString (value : String) = {
        val strings = value.split("\\s");
        
        Tuple2[String, List[int]](strings(0), 
            for {
                val i <- List.range(1, strings.length);
                strings(i) != ""}
            yield Integer.parseInt(strings(i)))
    }
}

class Machine(memorySize : int, states : Array[Instruction]) {
    val stack = new Stack[int]();
    val memory = new Memory(memorySize);
    var position = 0;
    
    private def advance { position = position + 1; }
    private def goto (instruction : int) { position = instruction - 1};    

    private def execute (instruction : Instruction) = 
        instruction match {
            // Stack manipulation
            case push(value)            => { stack += value; 
                                             advance; }
            case pop()                  => { stack.pop; 
                                             advance; }
            case dup()                  => { stack += stack.top; 
                                             advance; }
            
            // Arithmetic
            case plus()                 => { stack += (stack.pop + stack.pop); 
                                             advance; }
            
            case minus()                => { val second = stack.pop;
                                             val first = stack.pop;
                                             stack.push(if (second > first) 0 else (first - second));
                                             advance; }
            // Control flow
            // Our instructions are labelled from 1. Why? Laziness - vim does it that way.
            case goto(instruction)      => goto(instruction);
            case noop()                 => { advance; }
            
            case ifCurrent(instruction)   => { if (stack.pop == 0) goto(instruction); 
                                             else advance; }
            case ifEmpty(instruction)   => { if (stack.isEmpty) goto(instruction);
                                             else advance; }

            // Memory manipulation
            case load(register)         => { stack.push(memory.load(register));      
                                             advance; }                                   
            case store(register)        => { memory.store(register, stack.pop); 
                                             advance; }                                         
            case loadCurrent()          => { stack.push(memory.load(stack.pop)); 
                                             advance;}
            case storeCurrent()         => { val value = stack.pop;
                                             val register = stack.pop;
                                             memory.store(register, value);
                                             advance;}
            
            // IO instructions
            case print()                => { Console.println(stack.top); 
                                             advance; }
        };

    def run(){
        while (position < states.length){
            execute(states(position));
        }
    } 

    def execute (instructions : Iterable[Instruction]) : Unit = { 
        for (val instruction <- instructions)
        yield execute(instruction : Instruction);
        ();}
}

object Main{
    def main (args : Array[String]){
        if (args.length > 0){
            val file = new File(args(0));
            val reader = new BufferedReader(new InputStreamReader(new FileInputStream(file)));    

            var line = reader.readLine();
            
            val instructions = new ArrayList[Instruction]();

            while (line != null) {
                val instruction = Instruction.parse(line);
                instructions.add(instruction); 
                 
                
                line = reader.readLine();
                }

            val machine = new Machine(32, instructions.toArray);
            
            for (val i <- List.range(1, args.length))
            yield { machine.stack.push(Integer.parseInt(args(i))); }
            
            machine.run();
            
            Console.print("\n\n");
            Console.println("Machine terminated with:");
            Console.println("     Memory: " + machine.memory);
            Console.println("     Stack: " + machine.stack);
            Console.print("\n\n");
        }
        else Console.println("Please supply a file name");                
    }    
}

Extracting the values of all forms on the page

This is a simple piece of javascript intended to be run from Firebug or as a bookmarklet which extracts all the name : value pairs from forms on the page and pops up a new window listing them.

It's not very well written, and doesn't yet handle any non input form elements, but it will do for now. :-)

var displayWindow = window.open();

function showFormValues(form ) { 
    displayWindow.document.write('Form:');
    displayWindow.document.write(form.name);
    displayWindow.document.write('<br>');

    var formElements = form.getElementsByTagName('input');

    for (var i = 0; i < formElements.length; i++){
        var element = formElements[i];
        
        displayWindow.document.write(element.name + ' :  ' + element.value + ' <br>');}} 

Array.forEach(document.forms, showFormValues);


Simple locking primitives for Nice

A simple sketch of a library for how you could implement some good locking primitives on top of Nice. For an object myLock implementing the Lockable interface you can use it as follows:

locking(myLock)
{
// code
}

This will do whatever is neccessary (as specified by the implementation of the interface) to lock and then unlock the object.

Lockables can be combined with the & operator. myFirstLock & mySecondLock will acquire both locks 'simultaneously' - it will try them in some order. If it doesn't acquire all the locks it will unlock those it has acquired and wait until it can acquire the one it failed to acquire, with some random waits in there to avoid live lock.

Unfortunately Java's locking libraries don't appear to be all that great, so this is of limited use at the moment. :-) It's more a demonstration of a point and might be portable to C#.

package locking;

import java.util.concurrent.locks.*;
import java.util.concurrent.*;
import java.util.*;

interface Lockable { }

class NiceLock implements Lock, Lockable {
    private final Lock lock;

    lock()                            = lock.lock(); 
    lockInterruptibly()               = lock.lockInterruptibly();
    newCondition()                    = lock.newCondition();
    tryLock()                         = lock.tryLock();
    tryLock(long time, TimeUnit unit) = lock.tryLock(time, unit);
    tryLock(long time, null)          = lock.tryLock(time, TimeUnit.MILLISECONDS);
    unlock()                          = lock.unlock();}

class SynchronisedLock implements Lockable{
    Object object;
}

override void locking(SynchronisedLock lock, () -> void action) { 
    synchronized(lock.object) { action(); }}

/** This is wrong. I can't figure out how to make it work properly at the minute. */
override void tryLocking(SynchronisedLock lock, () -> void action) = locking(lock, action);

void locking(Lockable lock, () -> void action);
void tryLocking(Lockable lock, () -> void action);

class LockNotAvailableException extends Exception { Lockable lock; } 

override void locking(NiceLock lock, () -> void action){
    try {
        lock.lock.lock();
        action();}

    finally{ lock.lock.unlock(); }}

override void tryLocking (NiceLock lock, () -> void action){
    try {
        if (!lock.tryLock()) throw new LockNotAvailableException(lock : lock);
        else action();}
    finally{
        lock.unlock();}}


void tryLocking(List<Lockable> locks, () -> void action){
    if (locks.size() == 0) action();
    else{
        tryLocking(locks[0]){
            tryLocking(locks.slice(from : 1), action);}}}

class JoinedLock implements Lockable{
    private Lockable[] locks;
    private Random random = new Random();}

override void locking (JoinedLock lock, () -> void action){
    boolean failed = false;

    do{ 
        try{
            locking (lock.locks[0]){
            tryLocking(lock.locks.slice(from : 1), action);
            failed = false;}}
        catch (LockNotAvailableException e){ 
            lock.locks = concat([e.lock], lock.locks.filter(Lockable l => (l != e.lock)));
            failed = true;
            /* Sleep for a random amount of time to prevent live locking. */
            Thread.sleep(lock.random.nextInt(100));}} 
    while (failed);}


override void tryLocking (JoinedLock lock, () -> void action) = tryLocking (lock.locks, action);

Lockable `&` (Lockable first, Lockable second)                = new JoinedLock (locks : [first, second]);
override Lockable `&` (JoinedLock first, Lockable second)     = new JoinedLock (locks : concat(first.locks, [second]));
override Lockable `&` (Lockable first, JoinedLock second)     = new JoinedLock (locks : concat([first], second.locks));
override Lockable `&` (JoinedLock first, JoinedLock second)   = new JoinedLock (locks : concat(first.locks, second.locks));

Reading a webpage in Java

A trivial piece of example code demonstrating how to get a BufferedReader from a Url as a String and do something with it. This code simply prints the contents of the website at the first argument to stdout.

import java.io.*;
import java.net.URL;

public class WebsiteReader
{
	public static BufferedReader read(String url) throws Exception{
		return new BufferedReader(
			new InputStreamReader(
				new URL(url).openStream()));}

	public static void main (String[] args) throws Exception{
		BufferedReader reader = read(args[0]);
		String line = reader.readLine();

		while (line != null) {
			System.out.println(line);
			line = reader.readLine(); }}
}

Webcrawler

The core classes from my webcrawler implementation.

Again, not really working code as there are a bunch of dependencies missing. This is really for demonstration purposes.

public class WebCrawler<T extends WebPage> implements Iterable<T>
{    
    private final HashSet<T> visitedPages = new HashSet<T>();
    private final LinkedList<Object> workQueue = new LinkedList<Object>();
    private final PageProcessor<T> processor;
            
    // Map of URLs to pages.
    private final Map<String, WebPage> pages = new HashMap<String, WebPage>();     
    
    private final Predicate<Object> unvisited = new Predicate<Object>() { 
        public boolean satisfies(Object page){
            return !WebCrawler.this.visitedPages.contains(page);}};    

            
    public WebCrawler(PageProcessor<T> processor, String... urls){
        this.processor = processor;
        
        for (String url : urls){
            this.workQueue.add(processor.page(url));}}
    
    /* Iterator which iterates over all WebPages that haven't yet been visited.
     * It is thoroughly lazy and a web page will never be visited until it turns
     * up in this iterator.*/
    public final Iterator<T> pageIterator = (Iterator<T>)
        new FlatteningIterator(
            new ListeningIterator<Object>(
                    new FilterIterator<Object>(
                        unvisited, 
                        new PoppingIterator<Object>(this.workQueue))){
                @Override public void onNext(Object next){
                    if (next instanceof WebPage){
                        WebCrawler.this.visitedPages.add((T)next);
                        WebCrawler.this.workQueue.add(
                            new FilterIterator(unvisited, WebCrawler.this.processor.linkedPages((WebPage)next)));}}});
                    
    public Iterator<T> iterator(){ return IteratorUtils.link(this.visitedPages.iterator(), this.pageIterator); }                        
}

/**
 * Abstract class representing a mechanism for processing urls into pages. Contains 
 * utility methods and a cacheing strategy.
 *
 * @author david
 */
public abstract class PageProcessor<T extends WebPage> implements Transformer<String, T>
{
    private final PageCache<T> cache;
    private final IteratorTransformer<String, T> iteratorTransformer = new IteratorTransformer<String, T>(this);
    private Predicate<String> domain;
    
    public PageProcessor(Predicate<String> domain, PageCache<T> cache){
        this.domain = domain;
        this.cache = cache;}
    
    public PageProcessor(String domainPrefix, PageCache<T> cache){
        this(StringUtils.startsWith(domainPrefix), cache);}
    
    /**
     * Take the Url and return a WebPage corresponding to it.
     */
    protected abstract T process(String url);
        
    public T transform(String url){ return this.page(url); }
    
    /**
     * If the page has previously been processed, retrieve it from the internal cache.
     * Else process it and put it in the eternal cache.
     */
    public T page(String url){
        T page = cache.getCachedPage(url);
        
        if (page == null){
                page = this.process(url);
                cache.cachePage(page);}
        
        return page;}
    
    /**
     * Returns an iterator over all pages linked to by this page.
     */
    public Iterator<T> linkedPages(WebPage page){
        return iteratorTransformer.transform(new FilterIterator(domain, page.getLinkUrls()));}
}

/**
 * A very simple PageProcessor<WebPage> implementation based on the HTMLParser library
 * which uses a MapBackedPageCache.
 *
 * @author david
 */
public class HtmlParserPageProcessor extends PageProcessor<WebPage>
{       
    private static NodeFilter ALLOWED_TAGS = new NodeFilter(){
        public boolean accept(Node node){ 
            return (node instanceof LinkTag) || (node instanceof TitleTag);}};
    
    public HtmlParserPageProcessor(Predicate<String> domain){
        super(domain,  new MapBackedPageCache<WebPage>());}
            
    public HtmlParserPageProcessor(String domain){
        super(domain,  new MapBackedPageCache<WebPage>());}
                   
    /**
     * Fetches the resource represented by the URL, parses the HTML and extracts
     * the title element and all the links and uses them to build a WebPage object.
     */
    public WebPage process(String url){
        try{
            Parser parser = new Parser(url);
            NodeIterator iterator = parser.parse(ALLOWED_TAGS).elements();
        
            String title = "";
            List<String> links = new ArrayList<String>();
        
            while (iterator.hasMoreNodes()){
                Node node = iterator.nextNode();
                
                if (node instanceof TitleTag) title = ((TitleTag)node).getTitle();
                else if (node instanceof LinkTag) links.add(((LinkTag)node).extractLink());}
            return new WebPage(url, title, links);}               
        catch (Exception e){ throw new RuntimeException(e); }}
}

Recursively listing all files below a directory

// description of your code here
Simple iterator to iterate over all non-directory files the lie below a given directory. Demonstrates a use case for the FlatteningIterator snippet.


package playground.library.files;

import java.io.File;
import java.io.FileFilter;
import java.util.Arrays;
import java.util.Iterator;
import playground.library.functional.iterator.FlatteningIterator;

/**
 * Iterates over all non-directory files contained in some subdirectory of the 
 * current one.
 *
 * @author david
 */
public class RecursiveFileListIterator implements Iterator<File>
{
    private final FlatteningIterator flatteningIterator;
    
    public void remove() { } 
    
    pub