Tuesday, March 24, 2009

Reverse number in Java

Reverse number in Java



package ca1;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;

public class ReverseNumber{

public static void main(String[] args) throws IOException {

InputStreamReader cin = new InputStreamReader(System.in);

BufferedReader br = new BufferedReader(cin);

System.out.println("Enter your value : ");
String str = br.readLine();

int i = str.length()-1;

while(0 <= i){
System.out.println(str.charAt(i));
i--;
}

}
}

Read more...

Saturday, March 21, 2009

Fahrenheit to Celsius convertor in JAVA

import java.io.*;
import java.text.*;

class FahrenheittCelsiusconvertor {

public static void main(String arg[]) throws IOException {
BufferedReader stdin = new BufferedReader(new InputStreamReader(System.in));
DecimalFormat decimalFormat = new DecimalFormat("0.00");
String getValue;
double fahrenheitt = 0.00;
char reply;


do {


System.out.print("\n\t FAHRENHEIT TO CELSIUS CONVERTER");
System.out.print("\n\t -------------------------------\n\n");

System.out.print("ENTER FAHRENHEIT VALUE : ");
// Input routine that will accept numerial values
getValue = stdin.readLine();
fahrenheitt = Integer.parseInt(getValue);

System.out.print("CELSIUS VALUE IS " + decimalFormat.format(fah_cel(fahrenheitt)) + "\n");

System.out.print("\nDO YOU WANT TO continue Y/N : ");
String answer = stdin.readLine();
reply = answer.charAt(0);

} while (reply == 'Y' || reply == 'y');

if (reply == 'n' || reply == 'N') {

System.exit(0);
}
}
// A method to compute the fahrenheit to
// celsius

public static double fah_cel(double f) {
double cel = 0.00;
cel = (5.0 / 9.0) * (f - 32.0);
return (cel);
}
} // End of Code

Read more...

Tuesday, March 10, 2009

Page Replacement algorithm


public class KernelFunctions
{
//******************************************************************
// Methods for supporting page replacement
//******************************************************************

// the following method calls a page replacement method once
// all allocated frames have been used up
// DO NOT CHANGE this method
public static void pageReplacement(int vpage, Process prc, Kernel krn)
{
if(prc.pageTable[vpage].valid) return; // no need to replace

if(!prc.areAllocatedFramesFull()) // room to get frames in allocated list
addPageFrame(vpage, prc, krn);
else
pageReplAlgorithm(vpage, prc, krn);
}

// This method will all a page frame to the list of allocated
// frames for the process and load it with the virtual page
// DO NOT CHANGE this method
public static void addPageFrame(int vpage, Process prc, Kernel krn)
{
int [] fl; // new frame list
int freeFrame; // a frame from the free list
int i;
// Get a free frame and update the allocated frame list
freeFrame = krn.getNextFreeFrame(); // gets next free frame
if(freeFrame == -1) // list must be empty - print error message and return
{
System.out.println("Could not get a free frame");
return;
}
if(prc.allocatedFrames == null) // No frames allocated yet
{
prc.allocatedFrames = new int[1];
prc.allocatedFrames[0] = freeFrame;
}
else // some allocated but can get more
{
fl = new int[prc.allocatedFrames.length+1];
for(i=0 ; i fl[i] = freeFrame; // adds free frame to the free list
prc.allocatedFrames = fl; // keep new list
}
// update Page Table
prc.pageTable[vpage].frameNum = freeFrame;
prc.pageTable[vpage].valid = true;
}

// Calls to Replacement algorithm
public static void pageReplAlgorithm(int vpage, Process prc, Kernel krn)
{
switch(krn.pagingAlgorithm)
{
case CLOCK: pageReplAlgorithmCLOCK(vpage, prc, krn); break;
case ECLOCK: pageReplAlgorithmECLOCK(vpage, prc, krn); break;
}
}

//--------------------------------------------------------------
// The following methods need modification to implement
// the three page replacement algorithms
// ------------------------------------------------------------
// The following method is called each time an access to memory
// is made. It will allow you
// to update the page table entries for supporting various
// page replacement algorithms.
// when write is true, the memory access performed a write to the memory location
// Note: modified bit modified by the Process class when page selection is made.
public static void doneMemAccess(int vpage, Process prc, double clock)
{
if(prc.pageTable[vpage].valid)
{
prc.pageTable[vpage].used = true;
prc.pageTable[vpage].tmStamp = clock;
}
}

// CLOCK page Replacement algorithm
public static void pageReplAlgorithmCLOCK(int vpage, Process prc, Kernel krn)
{
int vPageReplaced; // Page to be replaced
int frame; // frame to receive new page
// Find page to be replaced
boolean flag = true;
while(flag)
{
frame = prc.allocatedFrames[prc.framePtr]; // frame in buffer
vPageReplaced = findvPage(prc.pageTable,frame);
if(prc.pageTable[vPageReplaced].used)
{
prc.pageTable[vPageReplaced].used = false;
}
else // found a replacement page
{
if(prc.pageTable[vPageReplaced].modified) krn.numReplModified++; // Increment count
prc.pageTable[vPageReplaced].valid = false; // replacing the page
prc.pageTable[vpage].frameNum = frame; // load page into the frame and update table
prc.pageTable[vpage].valid = true; // make the page valid
flag = false;
}
prc.framePtr = (prc.framePtr+1) % prc.allocatedFrames.length; // point to next frame in list
}
}

// Enhanced CLOCK page Replacement algorithm
public static void pageReplAlgorithmECLOCK(int vpage, Process prc, Kernel krn)
{
/* Complete */
}

// finds the virtual page loaded in the specified frame fr
public static int findvPage(PgTblEntry [] ptbl, int fr)
{
int i;
for(i=0 ; i {
if(ptbl[i].valid)
{
if(ptbl[i].frameNum == fr)
{
return(i);
}
}
}
System.out.println("Could not find frame number in Page Table "+fr);
return(-1);
}


// *******************************************
// The following method is provided for debugging purposes
// Call it to display the various data structures defined
// for the process so that you may examine the effect
// of your page replacement algorithm on the state of the
// process.
// Method for displaying the state of a process
// *******************************************
public static void logProcessState(Process prc)
{
int i;

System.out.println("--------------Process "+prc.pid+"----------------");
System.out.println("Virtual pages: Total: "+prc.numPages+
" Code pages: "+prc.numCodePages+
" Data pages: "+prc.numDataPages+
" Stack pages: "+prc.numStackPages+
" Heap pages: "+prc.numHeapPages);
System.out.println("Simulation data: numAccesses left in cycle: "+prc.numMemAccess+
" Num to next change in working set: "+prc.numMA2ChangeWS);
System.out.println("Working set is :");
for(i=0 ; i {
System.out.print(" "+prc.workingSet[i]);
}
System.out.println();
// page Table
System.out.println("Page Table");
if(prc.pageTable != null)
{
for(i=0 ; i {
if(prc.pageTable[i].valid) // its valid printout the data
{
System.out.println(" Page "+i+"(valid): "+
" Frame "+prc.pageTable[i].frameNum+
" Used "+prc.pageTable[i].used+
" count "+prc.pageTable[i].count+
" Time Stamp "+prc.pageTable[i].tmStamp);
}
else System.out.println(" Page "+i+" is invalid (i.e not loaded)");
}
}
// allocated frames
System.out.println("Allocated frames (max is "+prc.numAllocatedFrames+")"+
" (frame pointer is "+prc.framePtr+")");
if(prc.allocatedFrames != null)
{
for(i=0 ; i System.out.print(" "+prc.allocatedFrames[i]);
}
System.out.println();
System.out.println("---------------------------------------------");
}
}

// Page Table Entries
class PgTblEntry
{
int frameNum; // Frame number
boolean valid; // Valid Bit
boolean used; // Used Bit
boolean modified; // Modified bit
double tmStamp; // Time Stamp
long count; // for counting
}

------------------------------

//******************************************************
import java.util.*;
import java.util.concurrent.*;
import cern.jet.random.engine.*;
import cern.jet.random.*;
import EvSchedSimul.*;
//
// Some enumeration types
enum Kaction { ACCESSING, MEMACCESS, PAGEFAULT, IDLE }; // Addressing actions possible by kernel
enum PagingAlgorithm { FIFO, LRU, CLOCK, ECLOCK }; // For definining paging algorithm used.

// The Simulation model Class
class MemManage extends EvSched // Event Scheduling Simulation program
{
// Constants (time units is microseconds
final double FaultTime = 100; // Time for faults 100 time units
final double MemTime = 1; // Time for acessing memory 1 time unit
final int NumFrames = 32; // number of physical frames
final int MeanMemAccesses = 20; // mean number of memory accesses per process execution cycle
/* Parameter */
// Paging algorithm set in the Kernel Class

/* Data Modules for implementing timing maps */
Poisson memoryAccesses; // for defining number of memory accesses by a process
MersenneTwister writeToPage; // Defines if page is dirty after page fault;

/* Resource Entity - the kernel */
Kernel kernel;

/* Aggregate Entities */
ConcurrentLinkedQueue readyQueue; // process ready queue
HashSet ioQueue; // IO queue implemented as a set (to make code clearer)

/* Output Sets */
ESOutputSet phiTimeBtwFaults; // Sample Set
int numMemAccesses; // Number of memory accesses with no page faults
long numPer1000; // number of accesses per 1000
long numReplModified; // number of modified pages

// Methods
// Model Behaviour
// Constructor - Also nitialises the model
public MemManage(PagingAlgorithm pgAlg, double t0time, double tftime, Seeds sd)
{
Process prc;
int pid = 100;

// Set up distribution functions
memoryAccesses = new Poisson(MeanMemAccesses,
new MersenneTwister(sd.mAcc));

// System Initialization
readyQueue = new ConcurrentLinkedQueue();
ioQueue = new HashSet();
// Lets do processes
prc = new Process(pid++, 10,8,6,6,250,sd.prc1,sd.maprc1,sd.bernprc1); // 30 pages
kernel = new Kernel(NumFrames, pgAlg);
kernel.processExecuting = prc; // Set up first process as executing
prc.numMemAccess = memoryAccesses.nextInt();
kernel.processExecuting.vpage = selectAddress(prc);
kernel.action=Kaction.PAGEFAULT;
// Other processes added to ready queue
prc = new Process(pid++, 10,6,4,4,150,sd.prc2,sd.maprc2,sd.bernprc2); // 24 pages
readyQueue.add(prc);
prc = new Process(pid++, 18,8,6,4,100,sd.prc3,sd.maprc3,sd.bernprc3); // 36 pages
readyQueue.add(prc);
prc = new Process(pid++, 12,8,6,6,300,sd.prc4,sd.maprc4,sd.bernprc4); // 32 pages
readyQueue.add(prc);

// Setup sample set
phiTimeBtwFaults = new ESOutputSet("phiTimeBtwFaults");
numMemAccesses = 0;

// Initialize the simulation model
initEvSched(t0time,tftime);

preConditions(); // check preconditions to schedule event (first page fault)
}

// Future Events
// Future Event Names (used in FEL)
final int EndPageFault=1; // End of page fault
final int EndMemoryAccess=2; // End of memory access

// Translates event id to name(for loggin)
public String getEventName(int num)
{
switch(num)
{
case EndPageFault: return("EndMemoryAccess");
case EndMemoryAccess: return("EndMemoryAccess");
}
return("Unknown");
}

public void processEvent(int fEvent, Object obj)
{
switch(fEvent)
{
case EndPageFault: endPageFault((Process)obj); break;
case EndMemoryAccess: endMemoryAccess(); break;
default: System.out.println("Bad future event" + fEvent); break;
}
}

private void endPageFault(Process cProcess) // finished a page fault operation
{
kernel.timeLastFault = clock;
KernelFunctions.pageReplacement(cProcess.vpage,cProcess,kernel);
if(!ioQueue.remove(cProcess)) System.out.println("Process "+cProcess.pid+" not in ioQueue");
else readyQueue.add(cProcess);
preConditions(); // start activities
}

private void endMemoryAccess() // endMemoryAcess SCS
{
// AccessMemory Terminating Event SCS
KernelFunctions.doneMemAccess(kernel.processExecuting.vpage,kernel.processExecuting,clock);
if(kernel.processExecuting.numMemAccess <= 0)
{
readyQueue.add(kernel.processExecuting); // adding current process to ready queue
kernel.processExecuting = (Process) readyQueue.poll();
if(kernel.processExecuting == null)
{
System.out.println("Error - no process on ready queue");
}
kernel.processExecuting.numMemAccess = memoryAccesses.nextInt();
}
if(kernel.processExecuting.numMA2ChangeWS <= 0) kernel.processExecuting.updateWS();
else kernel.processExecuting.numMA2ChangeWS--;
if(kernel.processExecuting.vpageFromFault != -1)
{
kernel.processExecuting.vpage = kernel.processExecuting.vpageFromFault;
kernel.processExecuting.vpageFromFault = -1;
}
else kernel.processExecuting.vpage = selectAddress(kernel.processExecuting);
kernel.action = nextAction(kernel.processExecuting.vpage, kernel.processExecuting);
preConditions(); // start activities
}

// Check for starting events
private void preConditions()
{
while(true) // loop until no preconditions are true
{
if(kernel.action == Kaction.PAGEFAULT)
{
phiTimeBtwFaults.put(clock,clock-kernel.timeLastFault);
Process cProcess = kernel.processExecuting;
cProcess.vpageFromFault = cProcess.vpage; // flag page that caused fault
ioQueue.add(cProcess);
kernel.processExecuting = (Process) readyQueue.poll(); // Next process
if(kernel.processExecuting == null)
kernel.action = Kaction.IDLE; // no processes to execute
else
{ // Execute the next process
kernel.processExecuting.numMemAccess = memoryAccesses.nextInt();
if(kernel.processExecuting.vpageFromFault != -1)
{
kernel.processExecuting.vpage = kernel.processExecuting.vpageFromFault;
kernel.processExecuting.vpageFromFault = -1;
}
else kernel.processExecuting.vpage = selectAddress(kernel.processExecuting);
kernel.action = nextAction(kernel.processExecuting.vpage, kernel.processExecuting);
}
addEventNotice(EndPageFault,clock+FaultTime,cProcess);
}
else if(kernel.action == Kaction.MEMACCESS)
{
kernel.action = Kaction.ACCESSING;
kernel.processExecuting.numMemAccess--;
numMemAccesses++;
addEventNotice(EndMemoryAccess,clock+MemTime);
}
else if((kernel.action == Kaction.IDLE) && (readyQueue.size() !=0) ) // StartExecuting Action
{
kernel.processExecuting = (Process) readyQueue.poll(); // Next process
kernel.processExecuting.numMemAccess = memoryAccesses.nextInt();
if(kernel.processExecuting.vpageFromFault != -1)
{
kernel.processExecuting.vpage = kernel.processExecuting.vpageFromFault;
kernel.processExecuting.vpageFromFault = -1;
}
else kernel.processExecuting.vpage = selectAddress(kernel.processExecuting);
kernel.action = nextAction(kernel.processExecuting.vpage, kernel.processExecuting);
}
else break;
}
}

public boolean implicitStopCondition( ) // termination explicit
{ return(false);}

/************ Implementation User defined Modules ***********/
public int selectAddress(Process prc) // returns virtual page number being addressed
{ return prc.selectAddressPrc(); } // defined as part of the class

public Kaction nextAction(int vpage,Process prc)
{
if(prc.pageTable[vpage].valid) return(Kaction.MEMACCESS);
else return(Kaction.PAGEFAULT);
}

public void computeOutput()
{
phiTimeBtwFaults.computePhiDSOVs();
numPer1000 = (phiTimeBtwFaults.number*1000)/(numMemAccesses+phiTimeBtwFaults.number);
numReplModified = kernel.numReplModified;
}
}


// Defining the Consumer entities - the Process
class Process
{
//-----------------------------------------
// General process data structures
int pid; // Process ID
public int numPages; // Number of virtual pages
public PgTblEntry [] pageTable; // Page table
public int [] workingSet; // List of virtual pages in working set
int numAllocatedFrames; // Number of allocated physical frames
int [] allocatedFrames; // List of allocated frames - contains frame numbers
int framePtr; // index into allocatedFrames.
//-----------------------------------------
// for Simulation of process execution to create locality of reference
Poisson prcMA2ChangeWS; // for getting a discrete random number
Uniform prcDiscreteRandom; // for getting a discrete random number
Binomial prcBern; // To create Bernouilli random number generator
int numMemAccess; // number of memory accesses during a cycle executing
int numMA2ChangeWS; // number of memory accesses to change working set
public int [] wsSegments; // defines indexes in workingSet to divide into segments (code, data, etc.)
public int vpage; // virtual page being accessed
public int vpageFromFault; // virtual page just loaded after default - need to be accessed first executed.
// Mumber of pages per segment of program
int numCodePages; // Code segment
int numDataPages; // Data segment
int numStackPages; // Stack segment
int numHeapPages; // Heap segment

public Process(int pid, int nCode, int nData, int nStack, int nHeap, int meanMA, int sd1, int sd2, int sd3)
{
int i; // an index
// Setup random number generators
prcDiscreteRandom = new Uniform(new MersenneTwister(sd1));
prcMA2ChangeWS = new Poisson(meanMA,new MersenneTwister(sd2));
prcBern = new Binomial(1,0.90,new MersenneTwister(sd3));
// Setup process numbers
this.pid = pid;
numPages = nCode+nData+nStack+nHeap;
numCodePages=nCode;
numDataPages=nData;
numStackPages=nStack;
numHeapPages=nHeap;
// Setup the page table entry - all invalid
pageTable = new PgTblEntry[numPages];
for(i = 0 ; i {
pageTable[i] = new PgTblEntry();
pageTable[i].valid = false;
pageTable[i].used = false;
pageTable[i].tmStamp = 0;
}
allocateFrames(); // Allocates frames - current fixed allocation
// Setup working set and list to generate page references
wsSegments = new int[7]; // 0 - end of code 1 - end of data 2 - end of stack 3 - end of heap
// 4 - next section to address.
// 5,6 - pages to create locality of reference
updateWS(); // Sets up the working set
}

public void updateWS()
{
int ncode, ndata, nstack, nheap; // number of pages in each segment
int ix; // index into working set
int i;

// Radomly select number of pages from each segment
ncode = prcDiscreteRandom.nextIntFromTo(1, (numCodePages/2));
ndata = prcDiscreteRandom.nextIntFromTo(1, (numDataPages/2));
nstack = prcDiscreteRandom.nextIntFromTo(1, (numStackPages/2));
nheap = prcDiscreteRandom.nextIntFromTo(1, (numHeapPages/2));
if(ncode == 0) ncode = 1;
if(ndata == 0) ndata = 1;
if(nstack == 0) nstack = 1;
if(nheap == 0) nheap = 1;

workingSet = new int[ncode+ndata+nstack+nheap];
ix = 0;
for(i=0 ; i { workingSet[ix] = getPageNumforWS(0,numCodePages-1,workingSet,ix); ix ++; }
wsSegments[0] = ix-1; // defines how many code pages are in working set
for(i=0 ; i { workingSet[ix] = getPageNumforWS(numCodePages,numCodePages+numDataPages-1,workingSet,ix); ix ++; }
wsSegments[1] = ix-1; // defines how many data pages are in working set
for(i=0 ; i { workingSet[ix] = getPageNumforWS(numCodePages+numDataPages,
numCodePages+numDataPages+numStackPages-1,
workingSet,ix);
ix ++; }
wsSegments[2] = ix-1; // defines how many stack pages are in working set
for(i=0 ; i { workingSet[ix] = getPageNumforWS(numCodePages+numDataPages+numStackPages,
numCodePages+numDataPages+numStackPages+numHeapPages-1,
workingSet,ix);
ix ++; }
wsSegments[3] = ix-1; // defines how many heap pages are in working set
wsSegments[4] = 0; // start with a code page
numMA2ChangeWS = prcMA2ChangeWS.nextInt(); // Number of references before changing working set
}

private int getPageNumforWS(int start, int end, int [] list, int len)
{
int num;
while(true)
{ // Keep asking for number until one not in list found
// This can take a while if numbers in list contains
// most of the numbers being selected AND an
// infinite loop if all numbers are in the list
num = prcDiscreteRandom.nextIntFromTo(start,end);
if(notInIntArray(num,list,len)) return(num);
}
}

private boolean notInIntArray(int i, int [] array, int len)
{
int ix;
for(ix = 0 ; ix < len ; ix++)
{ if(array[ix] == i) return(false); }
return(true);
}

// Address is selected from code, data, stack and heap sections of the working
// set - this to improve locality of reference
public int selectAddressPrc()
{
int start;
int end;
int num;
int pageSelected;
// Define start index and end index of segment into Working set
// Skip if 0 or 1 - code or data segments
if((areAllocatedFramesFull()) && (prcBern.nextInt() == 1))
{ // Select from the allocated pages
num = prcDiscreteRandom.nextIntFromTo(5,6); // using code and other page
pageSelected = wsSegments[num]; // reusing pages
}
else
{// Select from the working set
if(wsSegments[4] == 0) start = 0; // Start
else start = wsSegments[wsSegments[4]-1]+1;
end = wsSegments[wsSegments[4]]; // End

// Randomly select a page from the segment in working set
if( (end-start)==0) // only one page - no need to select
{
pageSelected = workingSet[end];
}
else
{
num = prcDiscreteRandom.nextIntFromTo(start,end);
pageSelected = workingSet[num];
}
if(wsSegments[4] == 0) // code segment
{
wsSegments[5] = pageSelected;
pageTable[pageSelected].modified=false; // code note modified
}
else // other segment
{
wsSegments[6] = pageSelected;
pageTable[pageSelected].modified=true; // modify data, stack, heap
}
wsSegments[4] = (wsSegments[4]+1)%4;
}
return(pageSelected);
}

public boolean areAllocatedFramesFull()
{
if(allocatedFrames == null) return(false);
if(allocatedFrames.length < numAllocatedFrames) return(false);
return(true);
}

//******************************************************************
// Methods for supporting allocation schemes
//******************************************************************
public void allocateFrames()
{
numAllocatedFrames = 5;
allocatedFrames = null; // no frames allocated yet
framePtr = 0; // point to the first entry - not used until allocateFrames is filled
// This is to support FIFO replacement algorithm
}
}

// Defining the Resource entity - the kernel
class Kernel
{
public int numFrames;
public int [] freeList;
public Process processExecuting; // executing process
public Kaction action ; // Action to be taken - set to:
// ACCESSING - in the middle of accessing memory
// MEMACESS - next action is to access memory no page fault
// PAGEFAULT - next action is to access memory with page fault
double timeLastFault; // time of last page fault.
PagingAlgorithm pagingAlgorithm;
long numReplModified=0; // number of modified pages - for recording

public Kernel(int numFrames, PagingAlgorithm pgAlg)
{
int i;
pagingAlgorithm = pgAlg;
timeLastFault = 0;
action = Kaction.PAGEFAULT;
this.numFrames = numFrames;
freeList = new int [numFrames];
for(i=0 ; i }

public int getNextFreeFrame()
{
int [] fl;
int freeFrame;
int i;

if(freeList == null) return(-1); // list is empty return -1
freeFrame = freeList[0]; // gets next free frame
// Update the freeList (removes the head)
fl = new int[freeList.length-1];
if(freeList.length == 1) freeList = null;
else
{
for(i=0 ; i freeList = fl;
}
// Return free frame
return(freeFrame);
}

public void returnFrame2FreeList(int fr)
{
int [] fl; // to create new free list
int i;

// Update the freeList (removes the head)
if(freeList == null)
{
freeList = new int[1];
freeList[0] = fr;
}
else
{
fl = new int[freeList.length+1]; // create new list and copy current list
for(i=0 ; i fl[i] = fr; // appends newly released frame
freeList = fl;
}
}

}

class Seeds
{
int mAcc; // for number of memory accesses
int dRand; // kernel random number generator
int prc1; // process 1 random number generator
int prc2; // process 2 random number generator
int prc3; // process 3 random number generator
int prc4; // process 4 random number generator
int maprc1; // process 1 random number generator
int maprc2; // process 2 random number generator
int maprc3; // process 3 random number generator
int maprc4; // process 4 random number generator
int bernprc1; // process 1 random number generator
int bernprc2; // process 2 random number generator
int bernprc3; // process 3 random number generator
int bernprc4; // process 4 random number generator

public Seeds(int sd1,int sd2, int sd3, int sd4, int sd5, int sd6,
int sd7,int sd8, int sd9, int sd10, int sd11, int sd12,
int sd13, int sd14)
{
mAcc=sd1;
dRand=sd2;
prc1=sd3;
prc2=sd4;
prc3=sd5;
prc4=sd6;
maprc1=sd7;
maprc2=sd8;
maprc3=sd9;
maprc4=sd10;
bernprc1=sd11;
bernprc2=sd12;
bernprc3=sd13;
bernprc4=sd14;
}
}

------------------------

// File: MemManageExp.java
// Description:
// Simulation of memory management system

import cern.jet.random.engine.*;

// Main Method: Experiments
//
class MemManageExp
{
public static void main(String[] args)
{
double startTime=0.0, endTime=5000000; // 5 seconds
Seeds sds;
MemManage mmng;

// Lets get a set of uncorrelated seeds
RandomSeedGenerator rsg = new RandomSeedGenerator();
sds = new Seeds( rsg.nextSeed(), rsg.nextSeed(),
rsg.nextSeed(), rsg.nextSeed(),
rsg.nextSeed(), rsg.nextSeed(),
rsg.nextSeed(), rsg.nextSeed(),
rsg.nextSeed(), rsg.nextSeed(),
rsg.nextSeed(), rsg.nextSeed(),
rsg.nextSeed(), rsg.nextSeed());


// Use CLOCK page replacement algorithm
System.out.println("Running simulation using " + "CLOCK");
mmng = new MemManage(PagingAlgorithm.CLOCK,startTime,endTime,sds);
mmng.runSimulation();
mmng.computeOutput();
System.out.println("Number of faults: "+mmng.phiTimeBtwFaults.number);
System.out.println("Number memory accesses (no faults): "+mmng.numMemAccesses);
System.out.println("Number of faults per 1000 references: "+mmng.numPer1000);
System.out.println("Number of dirty pages replaced: "+mmng.numReplModified);
System.out.println();

// Use ECLOCK page replacement algorithm
System.out.println("Running simulation using " + "CLOCK");
mmng = new MemManage(PagingAlgorithm.ECLOCK,startTime,endTime,sds);
mmng.runSimulation();
mmng.computeOutput();
System.out.println("Number of faults: "+mmng.phiTimeBtwFaults.number);
System.out.println("Number memory accesses (no faults): "+mmng.numMemAccesses);
System.out.println("Number of faults per 1000 references: "+mmng.numPer1000);
System.out.println("Number of dirty pages replaced: "+mmng.numReplModified);
System.out.println();
}
}

------------------------

// File: MemManageExp.java
// Description:
// Simulation of memory management system

import cern.jet.random.engine.*;

// Main Method: Experiments
//
class EClockExp
{
public static void main(String[] args)
{
double startTime=0.0, endTime=10000; // .25 second
Seeds sds;
MemManage mmng;

// Lets get a set of uncorrelated seeds
RandomSeedGenerator rsg = new RandomSeedGenerator();
sds = new Seeds( rsg.nextSeed(), rsg.nextSeed(),
rsg.nextSeed(), rsg.nextSeed(),
rsg.nextSeed(), rsg.nextSeed(),
rsg.nextSeed(), rsg.nextSeed(),
rsg.nextSeed(), rsg.nextSeed(),
rsg.nextSeed(), rsg.nextSeed(),
rsg.nextSeed(), rsg.nextSeed());

// Loop for NUMRUN simulation runs
System.out.println("Running simulation");
mmng = new MemManage(PagingAlgorithm.CLOCK,startTime,endTime,sds);
mmng.runSimulation();
mmng.computeOutput();
System.out.println("Number of faults: "+mmng.phiTimeBtwFaults.number);
System.out.println("Number memory accesses (no faults): "+mmng.numMemAccesses);
System.out.println("Number of faults per 1000 references: "+mmng.numPer1000);
}
}

------------------------------

Read more...

Monday, March 9, 2009

Image process

Complete the implementation of the doFindTarget method. This task is inspired by the Where's Waldo franchise (also known by different names in different countries), in which you must find a little image of Waldo hidden in a much bigger picture.

To avoid infringing on the Waldo trademark/copyright, I have initialized a tiny picture of myself in the Picture object targetPic. Your method should find the targetPic (or the closest match) in the image and draw a red box around where the targetPic would fit best on the myPic image. Note that parts of the targetPic might be obscured, and the targetPic is allowed to be as much as one-half of its height and width outside of the frame of the main image.
There are many different ways to try to find an image hidden in another image (and this is still an active area of research). For this problem, you must use the following basic approach: for each possible position that the targetPic might be in the main image, you should compute some score of how well the targetPic matches the main image at that position. You must search every possible position, and find the position with the best score. You then draw the red box around that position.
I have provided a helper method computeMatch to compute a score. You are welcome to use this, or to create a different scoring function of your own. But whatever you do, it must be effective at finding the image!


Create a new method to do your solution, so that your doFindTarget method can be marked for normal credit. Your method must start with the word do and you should follow the convention of capitalizing the first character of each word in the method name just as was done for the other methods, e.g., doFasterFindTarget or doBetterFindTarget. Your method can take any number of int or double parameters (or no parameters at all) but must not take parameters of any other type. If your method takes parameters, you should include a parameter annotation for each of them as follows:
public void doMyMethod( @ParamDescrip( "description of first parameter" ) int myFirstParam,
@ParamDescrip( "description of second parameter" ) double mySecondParam )
{


}
Be sure to include the valid range of values (if any) in the parameter description (e.g., @ParamDescrip( "alpha value (0-255)" ) )
Technical point: Annotations are not normally needed on parameters. They're added here so that the application can figure out how to prompt the user appropriately. Remember that when this application was written, it had no idea what method you would write for this assignment, so it had no way of knowing in advance how to prompt the user!

If you are trying to make your method run much faster, test it on the larger images from the doFindTarget part of this assignment.
If you are trying to make a more sophisticated target finder, here are some small test images where a human would spot the target image instantly, but the computeMatch method I supplied doesn't find the image: test-color.jpg (actually, my doFindTarget works on this image, much to my surprise), t




--------------



import java.awt.Graphics;

import java.io.FileNotFoundException;

import java.io.FileReader;

import java.io.IOException;

import java.net.URL;

import com.sun.media.jai.widget.DisplayJAI;

import picUtil.ParamDescrip;

import picUtil.Picture;

import picUtil.Pixel;

import picUtil.PixelColour;

import sun.misc.GC;



/**

* This class represents a simple image processor that performs basic image

* manipulations.

*

*/

public class PictureProcessor {

/** The picture associated with this processor. */

private Picture myPic;

/** The target image for the doFindTarget method. */

private Picture targetPic;

/**

* Constructs a picture processor that manipulates a default image.

*/

public PictureProcessor() {

URL imgURL = getClass().getResource("/image/betty.jpg");

myPic = new Picture(imgURL);

URL targetURL = getClass().getResource("/image/AlanTarget.gif");

targetPic = new Picture(targetURL);

// The picUtil package seems to have a bug in

// handling the alpha channel. This is a kludge

// to fix things up... The picUtil package appears

// to take pixels that should be transparent and

// makes them pure white instead (with alpha==255,

// too). So, I'm going to take any pure white pixel

// in the target, and set the alpha to be 0.

for (int i=0; i
for (int j=0; j
Pixel thePixel = targetPic.getPixel(j,i);

PixelColour c = thePixel.getColour();

if ((c.getRed()==255) && (c.getGreen()==255) &&

(c.getBlue()==255)) c.setAlpha(0);

thePixel.setColour(c);

}

}

}

/**

* Reads a new image for processing from the specified file.

*

* @param fileName

* The name of the file to be processed.

*/

public void readImage(String fileName) {

myPic = new Picture(fileName);

}

/**

* Gets the picture processed by this picture processor.

*

* @return The picture processed by this picture processor.

*/

public Picture getPicture() {

return myPic;

}

/**

* Paints a vertical red stripe down the image from top to bottom between

* pixels 100 (inclusive) and 200 (exclusive)

*/

public void doRedStripe() {

PixelColour red = new PixelColour(255, 0, 0);

Pixel nextPixel;

for (int y = 0; y < myPic.getImgHeight(); y++) {

for (int x = 100; x < 200; x++) {

nextPixel = myPic.getPixel(x, y);

nextPixel.setColour(red);

}

}

}

/**

* Converts image to black-and-white.

*

* The preceding method and this one work on the Picture by changing the

* Pixels in it. The next method doBlur does things differently.

*

*/

public void doBW() {

// Go over full image...

for (int i = 0; i < myPic.getImgHeight(); i++) {

for (int j = 0; j < myPic.getImgWidth(); j++) {

Pixel thePixel = myPic.getPixel(j, i);

PixelColour thePixelColour = thePixel.getColour();

int aveBrightness = (int) Math.round(

(thePixelColour.getRed() + thePixelColour.getGreen() + thePixelColour.getBlue()) / 3.0);

PixelColour grey = new PixelColour(aveBrightness, aveBrightness, aveBrightness);

thePixel.setColour(grey);

}

}

}

/**

* Blurs the image by averaging RGB values in neighbourhood of specified

* size.

*

* This method is an example of a method that builds a new Picture object to

* replace the old Picture object, instead of changing the Pixels in place

* (like the preceding two methods). The reason we're doing things this way

* is because if we changed a pixel's colour in the current image, that

* change will affect the computation of the next pixel's colour. Since we

* don't want that, we do all of the neighbourhood averaging on the old

* Picture, but store the new results in a different Picture, until the very

* end, when we're done.

*

* @param size

* Size of neighbourhood in which to compute average.

*/

public void doBlur(@ParamDescrip("neighbourhood size") int size) {

Picture blurred = new Picture(myPic.getImgWidth(), myPic.getImgHeight());

// Go over full image...

for (int i = 0; i < myPic.getImgHeight(); i++) {

for (int j = 0; j < myPic.getImgWidth(); j++) {

PixelColour aveColour = averageColoursInBlock(myPic, i - size,

j - size, i + size, j + size);

blurred.getPixel(j, i).setColour(aveColour);

}

}

myPic = blurred;

}

/**

* Computes the average colour value for each colour channel (RGB) in the

* specified block of the picture. This method correctly handles blocks that

* are partially outside of the picture. If the block is completely outside

* of the picture, then the average is meaningless, and the method returns

* pure black.

*

* @param p

* The picture being worked on.

* @param minRow

* The lowest row number in the block.

* @param minCol

* The lowest column number in the block.

* @param maxRow

* The highest row number in the block.

* @param maxCol

* The highest column number in the block.

* @return The average colour of all the pixels in the block.

*/

private PixelColour averageColoursInBlock(Picture p, int minRow,

int minCol, int maxRow, int maxCol) {

// Compute average over neighborhood

int pixelCount = 0;

int redSum = 0;

int greenSum = 0;

int blueSum = 0;

int alphaSum = 0;

for (int i = minRow; i <= maxRow; i++) {

for (int j = minCol; j <= maxCol; j++) {

if ((i >= 0) && (i < p.getImgHeight()) && (j >= 0)

&& (j < p.getImgWidth())) {

pixelCount++;

Pixel thePixel = p.getPixel(j, i);

redSum += thePixel.getColour().getRed();

greenSum += thePixel.getColour().getGreen();

blueSum += thePixel.getColour().getBlue();

alphaSum += thePixel.getColour().getAlpha();

}

}

}

// Catch the case where the block is entirely outside the image.

if (pixelCount == 0)

return new PixelColour(0, 0, 0);

PixelColour aveColour = new PixelColour(

(int) Math.round((double) redSum / pixelCount),

(int) Math.round((double) greenSum / pixelCount),

(int) Math.round((double) blueSum / pixelCount),

(int) Math.round((double) alphaSum / pixelCount));

return aveColour;

}

/**

* Creates high-contrast poster effect by changing each Pixel's color values

* to either 0 or 255, depending on whether the old value was greater or

* less than the user-specified thresholds.

*

* @param redThreshold

* the red channel threshold

* @param greenThreshold

* the green channel threshold

* @param blueThreshold

* the blue channel threshold

*/

public void doThreshold(

// Don't make any changes to this parameter list!

@ParamDescrip("red threshold") int redThreshold,

@ParamDescrip("green threshold") int greenThreshold,

@ParamDescrip("blue threshold") int blueThreshold) {

// Fill in your code here!

for (int i = 0; i < myPic.getImgHeight(); i++) {

for (int j = 0; j < myPic.getImgWidth(); j++) {

Pixel thePixel = myPic.getPixel(j,i);

int rColour = thePixel.getColour().getRed();

int gColour = thePixel.getColour().getGreen();

int bColour = thePixel.getColour().getBlue();

if (rColour>redThreshold){

PixelColour redPixel= new PixelColour(255, bColour, gColour);

thePixel.setColour(redPixel);

}else{

PixelColour redPixel= new PixelColour(0, bColour, gColour);

thePixel.setColour(redPixel);

}

if (bColour>blueThreshold){

PixelColour bluePixel= new PixelColour(rColour, 255, gColour);

thePixel.setColour(bluePixel);

}else{

PixelColour bluePixel= new PixelColour(rColour, 0, gColour);

thePixel.setColour(bluePixel);

}

if (gColour>greenThreshold){

PixelColour greenPixel= new PixelColour(rColour, bColour, 255);

thePixel.setColour(greenPixel);

}else{

PixelColour greenPixel= new PixelColour(rColour, bColour, 0);

thePixel.setColour(greenPixel);

}

}

}


}

/**

* Creates a blocky poster effect by dividing the image into blockSize x

* blockSize pixel squares. All the pixels inside each square will be

* assigned the average colour of the original pixels inside the square.

*

* Note that the blockSize might not evenly divide into the image height and

* width, so there may be non-square rectangles on the edges. For this

* assignment, you are required to have the non-square blocks ONLY along the

* bottom and right edges of your image.

*

* Hint: You may want to reuse the helper method averageColoursInBlock

* above.

*

* @param blockSize

* How big the square blocks should be.

*/

public void doPixelate(@ParamDescrip("block size") int blockSize) {

// As mentioned in the assignment webpages, for

// full credit, your code should compute the average

// pixel colour only once for each *block*, instead

// of repeating the computation for each pixel.

// This will be slightly harder to write (which

// is part of why I want you to do it that way),

// and it will also run MUCH MUCH faster.

// If you program this correctly, your doPixelate

// method will take about twice as long as the

// doBW method, even with a big blockSize (like 20).

// If you do this wrong, it will be many times

// slower for a big blockSize.

// Fill in your code here!




for (int i = 0; i
for (int j = 0; j < myPic.getImgWidth(); j+=blockSize) {


PixelColour blockColour = averageColoursInBlock

(myPic, i, j, i+blockSize-1, j+blockSize-1);


for (int y=i; y<(i+blockSize-1); y++){

for (int x=j; x<(j+blockSize-1); x++){

if(y
if(x
myPic.getPixel(x, y).setColour(blockColour);

}

}

}

}

}



/**

* Does a "Where's Waldo?"-like search for the target

* image and draws a red box around it. The target

* image is in the Picture object targetPic, and it's

* initialized to a picture of Alan Hu.

*

*/

public void doFindTarget () {

// Fill in your code here!

// Feel free to use the computeMatch method below

// if you want.



URL targetURL = getClass().getResource("/image/AlanTarget.gif");

targetPic = new Picture(targetURL);

URL BerlinURL = getClass().getResource("/image/Berlin.jpg");

Picture berlinPic = new Picture(BerlinURL);



for (int i = 0; i < berlinPic.getImgHeight(); i++) {

for (int j = 0; j < berlinPic.getImgWidth(); j++) {

for (int y=i; y<(targetPic.getImgHeight()); y++){

for (int x=j; x<(targetPic.getImgWidth()); x++){


Pixel pix1= targetPic.getPixel(i, j);

Pixel pix2= berlinPic.getPixel(x,y);

if ( pix1.equals(pix2) ) {


}

}

}

}

}

}




public void paint( Graphics g ) {

g.drawRect( targetPic.getImgHeight(),

targetPic.getImgWidth(),50,10 );




}







/**

* Computes a score of how well targetPic matches up

* with myPic, if the top-left corner of targetPic

* is positioned at row i and column j of myPic.

*

* Lower scores indicate a better match.

*

* The score is the weighted average (weighted by

* the alpha value in targetPic) of the distance

* between the two colours, squared. The squaring

* penalizes larger differences more heavily than

* simply adding up the differences.

*

* @param i The row to position the top-left corner

* of myPic; can be negative.

* @param j The column to position the top-let corner

* of myPic; can be negative.

* @return The score of how well the target matches at

* that position; lower is better.

*/

private double computeMatch(int i, int j) {

double score = 0.0;

int weightTotal = 0;

for (int di=0; di
for (int dj=0; dj
if ((i+di >= 0) && (i+di < myPic.getImgHeight()) && (j+dj >= 0)

&& (j+dj < myPic.getImgWidth())) {

PixelColour imgColour = myPic.getPixel(j+dj, i+di).getColour();

PixelColour targetColour = targetPic.getPixel(dj,di).getColour();

int alpha = targetColour.getAlpha();

int diff;

int colourDistance=0;

diff = imgColour.getRed()-targetColour.getRed();

colourDistance += diff*diff;

diff = imgColour.getGreen()-targetColour.getGreen();

colourDistance += diff*diff;

diff = imgColour.getBlue()-targetColour.getBlue();

colourDistance += diff*diff;

score += colourDistance*alpha;

weightTotal += alpha;

}

}

}

if (weightTotal==0) return 1.0/0.0; // Infinity

return score/weightTotal;

}

}


-----------------------


package picApp;

import picUtil.PicFrame;

// Referenced classes of package picApp:
// PictureProcessor

public class PicProcessorApp
{

public PicProcessorApp()
{
}

public static void main(String args[])
{
PictureProcessor myProcessor = new PictureProcessor();
new PicFrame(myProcessor);
}
}
-------------------

package picUtil;


public class PixelColour
{

public PixelColour(int red, int green, int blue)
{
this.red = red;
this.green = green;
this.blue = blue;
alpha = 255;
}

public PixelColour(int red, int green, int blue, int alpha)
{
this(red, green, blue);
this.alpha = alpha;
}

public int getRed()
{
return red;
}

public void setRed(int red)
{
this.red = red;
}

public int getGreen()
{
return green;
}

public void setGreen(int green)
{
this.green = green;
}

public int getBlue()
{
return blue;
}

public void setBlue(int blue)
{
this.blue = blue;
}

public int getAlpha()
{
return alpha;
}

public void setAlpha(int alpha)
{
this.alpha = alpha;
}

private int red;
private int green;
private int blue;
private int alpha;
---------------------------------


package picUtil;

import java.awt.Color;

// Referenced classes of package picUtil:
// PixelColour, Picture

public class Pixel
{

Pixel(PixelColour colour, int x, int y, Picture pic)
{
this.colour = colour;
this.x = x;
this.y = y;
this.pic = pic;
}

public void setColour(PixelColour colour)
{
this.colour = colour;
updatePic();
}

public PixelColour getColour()
{
return new PixelColour(colour.getRed(), colour.getGreen(), colour.getBlue(), colour.getAlpha());
}

private void updatePic()
{
pic.setPixel(x, y, new Color(colour.getRed(), colour.getGreen(), colour.getBlue(), colour.getAlpha()));
}

private int x;
private int y;
private PixelColour colour;
private Picture pic;
--------------------------------


package picUtil;

import java.awt.Graphics;
import javax.swing.JComponent;
import picApp.PictureProcessor;

// Referenced classes of package picUtil:
// Picture

public class PictureComponent extends JComponent
{

PictureComponent(PictureProcessor picProc)
{
this.picProc = picProc;
}

void setPictureProcessor(PictureProcessor picProc)
{
this.picProc = picProc;
}

protected void paintComponent(Graphics g)
{
super.paintComponent(g);
picProc.getPicture().draw(g, getWidth(), getHeight());
}

private PictureProcessor picProc;
-----------------------------------------


package picUtil;

import java.awt.Color;
import java.awt.Graphics;
import java.awt.image.BufferedImage;
import java.io.*;
import java.net.URL;
import javax.imageio.ImageIO;

// Referenced classes of package picUtil:
// PixelColour, Pixel

public class Picture
{

public Picture(String fileName)
{
try
{
BufferedImage temp = ImageIO.read(new File(fileName));
convertToAlpha(temp);
pixels = new Pixel[img.getWidth()][img.getHeight()];
initPixels();
}
catch(IOException e)
{
System.err.println("Critical I/O error - application terminating...");
System.exit(1);
}
}

public Picture(int width, int height)
{
img = new BufferedImage(width, height, 2);
pixels = new Pixel[width][height];
initPixels();
}

public Picture(URL url)
{
try
{
BufferedImage temp = ImageIO.read(url);
convertToAlpha(temp);
pixels = new Pixel[img.getWidth()][img.getHeight()];
initPixels();
}
catch(IOException e)
{
System.err.println("Critical I/O error - application terminating...");
System.exit(1);
}
}

public int getImgHeight()
{
return img.getHeight();
}

public int getImgWidth()
{
return img.getWidth();
}

void setPixel(int x, int y, Color color)
{
img.setRGB(x, y, color.getRGB());
}

public Pixel getPixel(int x, int y)
{
return pixels[x][y];
}

void savePicture(String fileName)
{
try
{
ImageIO.write(img, "jpg", new File(fileName));
}
catch(IOException ioexception) { }
}

void draw(Graphics g, int width, int height)
{
double imgAspectRatio = (double)getImgWidth() / (double)getImgHeight();
double viewPortAspectRatio = (double)width / (double)height;
if(imgAspectRatio < viewPortAspectRatio)
width = (int)((double)height * imgAspectRatio);
else
height = (int)((double)width / imgAspectRatio);
g.drawImage(img, 0, 0, width, height, null);
}

private void convertToAlpha(BufferedImage temp)
{
img = new BufferedImage(temp.getWidth(), temp.getHeight(), 2);
for(int y = 0; y < getImgHeight(); y++)
{
for(int x = 0; x < getImgWidth(); x++)
img.setRGB(x, y, temp.getRGB(x, y));

}

}

private void initPixels()
{
for(int y = 0; y < getImgHeight(); y++)
{
for(int x = 0; x < getImgWidth(); x++)
{
Color c = new Color(img.getRGB(x, y));
PixelColour pc = new PixelColour(c.getRed(), c.getGreen(), c.getBlue(), c.getAlpha());
pixels[x][y] = new Pixel(pc, x, y, this);
}

}

}

private BufferedImage img;
private Pixel pixels[][];
---------------------

package picUtil;

import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.File;
import java.lang.annotation.Annotation;
import java.lang.reflect.Method;
import java.lang.reflect.Type;
import javax.swing.*;
import javax.swing.filechooser.FileFilter;
import picApp.PictureProcessor;

// Referenced classes of package picUtil:
// PictureComponent, MethodMenuItem, FileExtension, ParamDescrip,
// Picture

public class PicFrame extends JFrame
{
private class ImageFilter extends FileFilter
{

public boolean accept(File f)
{
if(f.isDirectory())
return true;
String extension = FileExtension.getExtension(f);
if(extension != null)
return extension.equals("gif") || extension.equals("jpeg") || extension.equals("jpg") || extension.equals("bmp");
else
return false;
}

public String getDescription()
{
return "Image files";
}

final PicFrame this$0;

private ImageFilter()
{
this$0 = PicFrame.this;
super();
}

ImageFilter(ImageFilter imagefilter)
{
this();
}
}

private class MenuActionListener
implements ActionListener
{

public void actionPerformed(ActionEvent e)
{
Cursor oldCursor = getCursor();
setCursor(new Cursor(3));
MethodMenuItem menuItem = (MethodMenuItem)e.getSource();
try
{
Object params[] = getParameterData(menuItem.getMethod());
menuItem.getMethod().invoke(processor, params);
picComp.repaint();
}
catch(NumberFormatException exc)
{
JOptionPane.showMessageDialog(PicFrame.this, "Input data not valid for parameter type.");
}
catch(Exception exc)
{
JOptionPane.showMessageDialog(PicFrame.this, "Unable to perform action.");
exc.getCause().printStackTrace();
}
setCursor(oldCursor);
}

private Object[] getParameterData(Method m)
{
Object paramVals[] = (Object[])null;
Type types[] = m.getGenericParameterTypes();
if(types.length != 0)
{
paramVals = new Object[types.length];
Annotation annots[][] = m.getParameterAnnotations();
for(int index = 0; index < types.length; index++)
paramVals[index] = promptForParameterValue(types[index], annots[index]);

}
return paramVals;
}

private Object promptForParameterValue(Type type, Annotation annots[])
{
String typeName = type.toString();
String paramDescrip = null;
for(int index = 0; index < annots.length; index++)
{
if(!(annots[index] instanceof ParamDescrip))
continue;
paramDescrip = ((ParamDescrip)annots[index]).value();
break;
}

String value = JOptionPane.showInputDialog(PicFrame.this, (new StringBuilder("Enter ")).append(paramDescrip).append(" (").append(typeName).append(")").toString(), "Enter parameter value", 3);
Object retVal = parseToType(type, value);
return retVal;
}

private Object parseToType(Type type, String value)
{
Object retVal = null;
String typeName = type.toString();
if(typeName.equals("double"))
retVal = Double.valueOf(Double.parseDouble(value));
else
if(typeName.equals("int"))
retVal = Integer.valueOf(Integer.parseInt(value));
return retVal;
}

final PicFrame this$0;

private MenuActionListener()
{
this$0 = PicFrame.this;
super();
}

MenuActionListener(MenuActionListener menuactionlistener)
{
this();
}
}

private class OpenListener
implements ActionListener
{

public void actionPerformed(ActionEvent e)
{
JFileChooser chooser = new JFileChooser(".");
FileFilter filter = new ImageFilter(null);
chooser.setFileFilter(filter);
int returnVal = chooser.showOpenDialog(PicFrame.this);
if(returnVal == 0)
{
Cursor oldCursor = getCursor();
setCursor(new Cursor(3));
processor.readImage(chooser.getSelectedFile().getAbsolutePath());
picComp.repaint();
setCursor(oldCursor);
}
}

final PicFrame this$0;

private OpenListener()
{
this$0 = PicFrame.this;
super();
}

OpenListener(OpenListener openlistener)
{
this();
}
}

private class SaveAsListener
implements ActionListener
{

public void actionPerformed(ActionEvent e)
{
int overwriteDecision = 0;
JFileChooser chooser = new JFileChooser(".");
FileFilter filter = new ImageFilter(null);
chooser.setFileFilter(filter);
int returnVal = chooser.showSaveDialog(PicFrame.this);
if(returnVal == 0)
{
File selected = chooser.getSelectedFile();
String extension = FileExtension.getExtension(selected);
String fileName = selected.getAbsolutePath();
if(extension == null)
fileName = (new StringBuilder(String.valueOf(fileName))).append(".jpg").toString();
else
if(!extension.equals("jpg") && !extension.equals("jpeg"))
fileName = (new StringBuilder(String.valueOf(fileName))).append(".jpg").toString();
if((new File(fileName)).exists())
{
Object options[] = {
"Yes", "No"
};
overwriteDecision = JOptionPane.showOptionDialog(PicFrame.this, "Overwrite existing file?", "Caution!", -1, -1, null, options, options[1]);
}
if(overwriteDecision == 0)
{
Cursor oldCursor = getCursor();
setCursor(new Cursor(3));
processor.getPicture().savePicture(fileName);
setCursor(oldCursor);
}
}
}

final PicFrame this$0;

private SaveAsListener()
{
this$0 = PicFrame.this;
super();
}

SaveAsListener(SaveAsListener saveaslistener)
{
this();
}
}


public PicFrame(PictureProcessor processor)
{
int WIDTH = 800;
int HEIGHT = 600;
this.processor = processor;
setLocationRelativeTo(null);
UIManager.put("Button.defaultButtonFollowsFocus", Boolean.valueOf(true));
picComp = new PictureComponent(processor);
setTitle("Image Processor");
setLayout(new BorderLayout());
add(picComp, "Center");
setPreferredSize(new Dimension(800, 600));
Point loc = getLocation();
loc.x -= 400;
loc.y -= 300;
setLocation(loc);
setDefaultCloseOperation(3);
JMenuBar menuBar = new JMenuBar();
menuBar.add(initFileMenu());
menuBar.add(initActionMenu());
setJMenuBar(menuBar);
pack();
setVisible(true);
}

private JMenu initFileMenu()
{
JMenu fileMenu = new JMenu("File");
JMenuItem openItem = new JMenuItem("Open");
openItem.addActionListener(new OpenListener(null));
fileMenu.add(openItem);
JMenuItem saveAsItem = new JMenuItem("Save As (jpg)");
saveAsItem.addActionListener(new SaveAsListener(null));
fileMenu.add(saveAsItem);
JMenuItem exitItem = new JMenuItem("Exit");
exitItem.addActionListener(new ActionListener() {

public void actionPerformed(ActionEvent e)
{
dispose();
}

final PicFrame this$0;


{
this$0 = PicFrame.this;
super();
}
}
);
fileMenu.add(exitItem);
return fileMenu;
}

private JMenu initActionMenu()
{
JMenu actionMenu = new JMenu("Action");
MenuActionListener menuActionLstnr = new MenuActionListener(null);
Class c = processor.getClass();
Method allMethods[] = c.getMethods();
Method amethod[];
int j = (amethod = allMethods).length;
for(int i = 0; i < j; i++)
{
Method m = amethod[i];
String name = m.getName();
if(name.startsWith("do"))
{
MethodMenuItem item = new MethodMenuItem(parseName(name), m);
item.addActionListener(menuActionLstnr);
actionMenu.add(item);
}
}

return actionMenu;
}

private String parseName(String methodName)
{
String name = methodName.substring(2);
String menuName = new String();
int index = 1;
menuName = (new StringBuilder(String.valueOf(menuName))).append(name.charAt(0)).toString();
for(; index < name.length(); index++)
{
char nextChar = name.charAt(index);
if(nextChar >= 'A' && nextChar <= 'Z')
menuName = (new StringBuilder(String.valueOf(menuName))).append(" ").toString();
menuName = (new StringBuilder(String.valueOf(menuName))).append(nextChar).toString();
}

return menuName;
}

private PictureComponent picComp;
private PictureProcessor processor;


}
-------------------------

Read more...

Sunday, March 8, 2009

Thumbimage

import java.io.File;
import java.io.IOException;
import java.net.URL;
import java.awt.Graphics;
import java.awt.Image;
import java.awt.image.BufferedImage;

import javax.imageio.ImageIO;
import javax.swing.ImageIcon;
public class PictureProcessor {

/** The picture associated with this processor. */

private ImageIcon myPic;



/** The target image for the doFindTarget method. */

private ImageIcon targetPic;

public static final int VERTICAL = 0;
public static final int HORIZONTAL = 1;
public static final String IMAGE_JPEG = "jpeg";
public static final String IMAGE_JPG = "jpg";
public static final String IMAGE_PNG = "png";

/**

* Constructs a picture processor that manipulates a default image.

*/

public PictureProcessor() {

URL imgURL = getClass().getResource("image.jpg");

System.out.println("imgURL-->"+imgURL);
myPic = new ImageIcon(imgURL);
//myPic = new Picture(imgURL);

URL targetURL = getClass().getResource("/image.gif");
System.out.println("targetURL-->"+targetURL);

//targetPic = new Picture(targetURL);
getThumbnail(100, PictureProcessor.HORIZONTAL);

saveThumbnail(new File("thumb.jpg"), PictureProcessor.IMAGE_JPEG);
// The picUtil package seems to have a bug in

// handling the alpha channel. This is a kludge

// to fix things up... The picUtil package appears

// to take pixels that should be transparent and

// makes them pure white instead (with alpha==255,

// too). So, I'm going to take any pure white pixel

// in the target, and set the alpha to be 0.

//for (int i=0; i//
//for (int j=0; j//
//Pixel thePixel = targetPic.getPixel(j,i);
//
//PixelColour c = thePixel.getColour();
//
//if ((c.getRed()==255) && (c.getGreen()==255) &&
//
//(c.getBlue()==255)) c.setAlpha(0);
//
//thePixel.setColour(c);

//}

//}

}

public Image getThumbnail(int size, int dir)
{
if (dir == HORIZONTAL)
{
targetPic = new ImageIcon(
myPic.getImage().getScaledInstance(
size, -1, Image.SCALE_SMOOTH)
);
}
else
{
targetPic = new ImageIcon(
myPic.getImage().getScaledInstance(
-1, size, Image.SCALE_SMOOTH)
);
}
return targetPic.getImage();
}

//AND LATER THE PART THAT I AM HAVING TROUBLE WITH:


/**

* Computes a score of how well targetPic matches up

* with myPic, if the top-left corner of targetPic

* is positioned at row i and column j of myPic.

*

* Lower scores indicate a better match.

*

* The score is the weighted average (weighted by

* the alpha value in targetPic) of the distance

* between the two colours, squared. The squaring

* penalizes larger differences more heavily than

* simply adding up the differences.

*

* @param i The row to position the top-left corner

* of myPic; can be negative.

* @param j The column to position the top-let corner

* of myPic; can be negative.

* @return The score of how well the target matches at

* that position; lower is better.

*/

public void saveThumbnail(File file, String imageType)
{
if (targetPic != null)
{
BufferedImage bi = new BufferedImage(
targetPic.getIconWidth(),
targetPic.getIconHeight(),
BufferedImage.TYPE_INT_RGB
);
Graphics g = bi.getGraphics();
g.drawImage(targetPic.getImage(), 0, 0, null);
try
{
ImageIO.write(bi, imageType, file);
}
catch (IOException ioe)
{
System.out.println("Error occured saving thumbnail");
}
}
else
{
System.out.println("Thumbnail has not yet been created");
}
}
private double computeMatch(int i, int j) {

double score = 0.0;



int weightTotal = 0;

//for (int di=0; di//
//for (int dj=0; dj//
//if ((i+di>= 0) && (i+di < myPic.getImgHeight()) && (j+dj>= 0)
//
//&& (j+dj < myPic.getImgWidth())) {
//
//PixelColour imgColour = myPic.getPixel(j+dj, i+di).getColour();
//
//PixelColour targetColour = targetPic.getPixel(dj,di).getColour();

//int alpha = targetColour.getAlpha();
//
//
//
//int diff;
//
//int colourDistance=0;
//
//diff = imgColour.getRed()-targetColour.getRed();
//
//colourDistance += diff*diff;
//
//diff = imgColour.getGreen()-targetColour.getGreen();
//
//colourDistance += diff*diff;
//
//diff = imgColour.getBlue()-targetColour.getBlue();
//
//colourDistance += diff*diff;
//
//
//
//score += colourDistance*alpha;
//
//weightTotal += alpha;
//
//}
//
//}

///}



if (weightTotal==0) return 1.0/0.0; // Infinity

return score/weightTotal;



}

public static void main(String [] args)
{
PictureProcessor ct = new PictureProcessor();

}
}

-------------------------------------------------------------------


import java.awt.Graphics;
import java.awt.Image;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import javax.imageio.ImageIO;
import javax.swing.ImageIcon;

public class CreateThumbnail
{

public static final int VERTICAL = 0;
public static final int HORIZONTAL = 1;

public static final String IMAGE_JPEG = "jpeg";
public static final String IMAGE_JPG = "jpg";
public static final String IMAGE_PNG = "png";

private ImageIcon image;
private ImageIcon thumb;

public CreateThumbnail(Image image)
{
System.out.println("111111111");
this.image = new ImageIcon(image);
}

public CreateThumbnail(String fileName)
{
System.out.println("2222222222222");
image = new ImageIcon(fileName);
}

public Image getThumbnail(int size, int dir)
{
if (dir == HORIZONTAL)
{
thumb = new ImageIcon(
image.getImage().getScaledInstance(
size, -1, Image.SCALE_SMOOTH)
);
}
else
{
thumb = new ImageIcon(
image.getImage().getScaledInstance(
-1, size, Image.SCALE_SMOOTH)
);
}
return thumb.getImage();
}

public Image getThumbnail(int size, int dir, int scale)
{
if (dir == HORIZONTAL)
{
thumb = new ImageIcon(
image.getImage().getScaledInstance(size, -1, scale)
);
}
else
{
thumb = new ImageIcon(
image.getImage().getScaledInstance(-1, size, scale)
);
}
return thumb.getImage();
}

public void saveThumbnail(File file, String imageType)
{
if (thumb != null)
{
BufferedImage bi = new BufferedImage(
thumb.getIconWidth(),
thumb.getIconHeight(),
BufferedImage.TYPE_INT_RGB
);
Graphics g = bi.getGraphics();
g.drawImage(thumb.getImage(), 0, 0, null);
try
{
ImageIO.write(bi, imageType, file);
}
catch (IOException ioe)
{
System.out.println("Error occured saving thumbnail");
}
}
else
{
System.out.println("Thumbnail has not yet been created");
}
}

public static void main(String [] args)
{
CreateThumbnail ct = new CreateThumbnail("image.jpg");
ct.getThumbnail(100, CreateThumbnail.HORIZONTAL);
ct.saveThumbnail(new File("thumb.jpg"), CreateThumbnail.IMAGE_JPEG);
}

}

Read more...

  © Blogger templates Newspaper III by Ourblogtemplates.com 2008

Back to TOP