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

« Newer Snippets
Older Snippets »
Showing 1-5 of 5 total  RSS 

JSP: Printing Java stacktraces in JSP pages

// This snippet shows how to view java stack traces for exceptions occurring inside jsp files.


try{
  //some code that throws an exception
}
catch(Exception e){
  // Cannot print using standard out. Cast JSP writer into a print writer.
  e.printStackTrace( new java.io.PrintWriter(out))
}

A solution for the "Stack 'em Up" problem

A solution for the "Stack 'em Up" problem.

Problem description:
http://icpcres.ecs.baylor.edu/onlinejudge/external/102/10205.html

Author: Joana Matos Fonseca da Trindade
Date: 2008.04.05
/* 
 * Solution for "Stack 'em Up" problem.
 * UVa ID: 10205
 */
#include <iostream>

#define NVALUES 13
#define NSUITS 4
#define NCARDS 52
#define NSHUFFLES 100
#define WSIZE 9

using namespace std;

char values[NVALUES][WSIZE] = {"2", "3", "4", "5", "6", "7", "8", "9", "10", "Jack", "Queen", "King", "Ace"};
char suits[NSUITS][WSIZE] = {"Clubs", "Diamonds", "Hearts", "Spades"};
int shuffles[NSHUFFLES][NCARDS];
int deck[NCARDS];

/* read all dealer shuffles */
void read_shuffles(int n_shuff) {
	for(int i=0; i<n_shuff; i++) {
		for (int j=0; j<NCARDS; j++) {
			cin >> shuffles[i][j];
		}
	}
}

/* shuffle the deck with one of the known shuffles */
void shuffle_deck(int s_id) {
	int tmpdeck[NCARDS];
	for (int i=0; i<NCARDS; i++) {
		tmpdeck[i] = deck[shuffles[s_id][i] - 1];
	}
	for (int i=0; i<NCARDS;i++) {
		deck[i] = tmpdeck[i];
	}
}

/* main */
int main (int argc, const char *argv[]) {
	int nc; /* number of cases */
	int ns;	/* number of shuffles */
	int s; /* current shuffle */
		
	cin >> nc;
		
	for (int i=0; i<nc; i++) {	
		cin >> ns;
			
		/* initialize deck */
		for (int p=0; p<NCARDS; p++) {
			deck[p] = p;
		}
		
		/* read list of known shuffles */
		read_shuffles(ns);
		
		/* shuffle deck */
		for (int j=0; j<ns; j++) {
			cin >> s;
			shuffle_deck(s - 1);
		}

		/* print deck */
		for (int k=0; k<NCARDS; k++) {
			cout << values[deck[k] % NVALUES] << " of " << suits[deck[k] / NVALUES] << endl;
		}
		if (i < (nc - 1)) {
			cout << endl;
		}
	}
	
}


Get a String version of a stacktrace

// Get a String version of a stacktrace

    Throwable t = new Throwable();  // test code

    final Writer result = new StringWriter();
    final PrintWriter printWriter = new PrintWriter(result);
    t.printStackTrace(printWriter);
    result.toString();

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");                
    }    
}

Simple Stack //Pascal Class

A simple pointer stack...

unit Stack;

interface

uses
  SysUtils, Classes;

type
  TStack = class
  private
    FList: PPointerList;
    FCapacity, FCount: Cardinal;
    procedure Grow;
  public
    destructor Destroy; override;
    procedure Push( const Data: Pointer );
    function Pop: Pointer;
  end;

implementation

{ TStack }

destructor TStack.Destroy;
begin
  FreeMem( FList );
  inherited;
end;

procedure TStack.Grow;
begin
  if FCapacity > 64 then
    Inc( FCapacity, FCapacity div 4 )
  else
    if FCapacity > 8 then
      Inc( FCapacity, 16 )
    else
      Inc( FCapacity, 4 );
  ReallocMem( FList, FCapacity * SizeOf( Pointer ) );
end;

function TStack.Pop: Pointer;
begin
  if FCount > 0 then
  begin
    Dec( FCount );
    Result := FList^[FCount];
  end
  else
    Result := nil;
end;

procedure TStack.Push(const Data: Pointer);
begin
  if FCapacity = FCount then
    Grow;
  FList^[FCount] := Data;
  Inc( FCount );
end;

end.

« Newer Snippets
Older Snippets »
Showing 1-5 of 5 total  RSS