The document describes the main classes of a simple text-based adventure game called "World of Zuul". It includes classes for commands, command words, rooms, a game class to run the game, and a parser class to interpret user input. The game has different rooms connected by exits where the player can use commands like "go" and "quit" to navigate between rooms or end the game.
Big Data Day LA 2015 - Mongoose v/s Waterline: Battle of the ORM by Tim Fulme...Data Con LA
Mongo is swiftly becoming the default, general purpose database du jour. In green field Node.JS systems, Mongo is almost the default persistence mechanism. At the same time, going completely schema-less raises it's own issues.
Enter the NoSQL ORM solution. By encoding schema information in easily changeable JavaScript definitions, Node.JS systems can get the benefits of both worlds. High velocity change throughput, with just enough guardrails to keep things on the tracks.
Mongoose has traditionally been the go-to ORM package, providing lightweight schema definitions on top of Mongo. Waterline has recently come out of the Sails.JS project with some interesting innovations. In this presentation we compare and contrast the two packages through a few typical ORM use cases.
Making Java more dynamic: runtime code generation for the JVMRafael Winterhalter
While Java’s strict type system is a great help for avoiding programming errors, it also takes away some of the flexibility that developers appreciate when using dynamic languages. By using runtime code generation, it is possible to bring some of this flexibility back to the Java virtual machine. For this reason, runtime code generation is widely used by many state-of-the-art Java frameworks for implementing POJO-centric APIs but it also opens the door to assembling more modular applications. This presentation offers an introduction to the complex of runtime code generation and its use on the Java platform. Furthermore, it discusses the up- and downsides of several code generation libraries such as ASM, Javassist, cglib and Byte Buddy.
Presentation derived from the "What's new in Python 2.6" document on http://www.python.org/ including much reformatting for presenting and presenter notes.
Please download the Keynote original - that way the presentation notes aren't burned into the slides.
Big Data Day LA 2015 - Mongoose v/s Waterline: Battle of the ORM by Tim Fulme...Data Con LA
Mongo is swiftly becoming the default, general purpose database du jour. In green field Node.JS systems, Mongo is almost the default persistence mechanism. At the same time, going completely schema-less raises it's own issues.
Enter the NoSQL ORM solution. By encoding schema information in easily changeable JavaScript definitions, Node.JS systems can get the benefits of both worlds. High velocity change throughput, with just enough guardrails to keep things on the tracks.
Mongoose has traditionally been the go-to ORM package, providing lightweight schema definitions on top of Mongo. Waterline has recently come out of the Sails.JS project with some interesting innovations. In this presentation we compare and contrast the two packages through a few typical ORM use cases.
Making Java more dynamic: runtime code generation for the JVMRafael Winterhalter
While Java’s strict type system is a great help for avoiding programming errors, it also takes away some of the flexibility that developers appreciate when using dynamic languages. By using runtime code generation, it is possible to bring some of this flexibility back to the Java virtual machine. For this reason, runtime code generation is widely used by many state-of-the-art Java frameworks for implementing POJO-centric APIs but it also opens the door to assembling more modular applications. This presentation offers an introduction to the complex of runtime code generation and its use on the Java platform. Furthermore, it discusses the up- and downsides of several code generation libraries such as ASM, Javassist, cglib and Byte Buddy.
Presentation derived from the "What's new in Python 2.6" document on http://www.python.org/ including much reformatting for presenting and presenter notes.
Please download the Keynote original - that way the presentation notes aren't burned into the slides.
An overview how to realize code generation of languages on the JVM that implement other class layouts than the Java programming languages. As an example, the inline-mock-maker for Mockito is discussed which supports languages like Kotlin that make any property final by default.
These are my slides from a mini Clojure tutorial presented at the "7 Languages in 7 Months" meetup group. The first part of the presentation faithfully presents material from Bruce Tate book, and the second part covers the more advanced topics of state management and macros
Brief introduction to testing talk prepared to creates a starting point at TAPTAP Networks & SONATA Usa Corp. The companies where I work as Q&A Team member.
Some testing - Everything you should know about testing to go with @pedro_g_s...Sergio Arroyo
I usually attend to several talks about testing. Everyone tells us how good, how important and valuable could be having a good test suite. But almost anybody tells us how hard is achieving this goal. With this talk, I wanted to provide an overview for people who is starting with software testing. Even for those who never tried it.
But this is not only an introduction. Though I start talking about the basics and principles and concepts, I also try to talk about my experience. What worked, where I failed and how I tried to solve the problems I found.
CS117-S18-AlharbiMohammed-master/.gitignore
*.class
*.ctxt
*.*~
doc
/.project
default.log
defaultlog.txt
CS117-S18-AlharbiMohammed-master/Command.javaCS117-S18-AlharbiMohammed-master/Command.javaimport java.util.ArrayList;
/**
* This class is part of the "Campus of Kings" application. "Campus of Kings" is a
* very simple, text based adventure game.
*
* This class holds information about a command that was issued by the user. A
* command currently consists of two strings: a command word and a second word
* (for example, if the command was "take map", then the two strings obviously
* are "take" and "map").
*
* The way this is used is: Commands are already checked for being valid command
* words. If the user entered an invalid command (a word that is not known) then
* the command word is <null>.
*
* If the command had only one word, then the second word is <null>.
*
* @author Maria Jump
* @version 2015.02.01
*/
publicclassCommand{
/** The command word for this command. */
privateString commandWord;
/** The rest of the line with all the spaces removed. */
privateArrayList<String> restOfLine;
/**
* Create a command object. First is supplied. The second word is assumed
* to be null.
*
* @param firstWord
* The first word of the command. Null if the command was not
* recognized.
*/
publicCommand(String firstWord){
commandWord = firstWord;
restOfLine =newArrayList<String>();
}
/**
* Create a command object. First and second word must be supplied, but
* either one (or both) can be null.
*
* @param firstWord
* The first word of the command. Null if the command was not
* recognized.
* @param rest
* The rest of the command.
*/
publicCommand(String firstWord,ArrayList<String> rest){
commandWord = firstWord;
restOfLine = rest;
}
/**
* Return the command word (the first word) of this command. If the command
* was not understood, the result is null.
*
* @return The command word.
*/
publicString getCommandWord(){
return commandWord;
}
/**
* Returns if this command was not understood.
*
* @return true if this command was not understood.
*/
publicboolean isUnknown(){
return(commandWord ==null);
}
/**
* Returns if this command has a second word.
*
* @return true if the command has a second word.
*/
publicboolean hasSecondWord(){
return restOfLine !=null;
}
/**
* Returns if this command has more words.
*
* @param index The index of the word needed.
* @return true if the command has a word at given index.
*/
publicboolean hasWord(int index){
return index >=0&& index < restOfLine.size();
}
/**
* Returns the word at the requested index in the command.
*
* @param index
* The index of word in the command that is being requested.
*
* @ret.
MIS 4310-01 Final Take Home Exam (100 points) DUE Thursd.docxraju957290
MIS 4310-01 Final Take Home Exam (100 points)
DUE: Thursday, December 14th, 2017 by 11:59 PM
Use the code provided on Blackboard as your template. Fill in your own code where
prompted. When finished, upload to Blackboard a file called “treasure_hunt.java”. Change
the block comment to include your own name. This is an individual assignment! Code that
you write that you cannot explain will result in an automatic zero.
Create a Java application that simulates a treasure hunt with a 2D array. Your output
should match the output below with similar input. Do NOT alter the code provided. Fill
in code in the SEVEN (7) locations under each comment // YOUR CODE HERE.
Sample Output:
import java.util.Random;
import java.util.Scanner;
/*
* First Last
* MIS 4310 Fall 2017
* FINAL TAKE HOME EXAM
*/
public class treasure_hunt {
public static void main(String[] args) {
boolean found = false; // is true if the treasure is found
int dug = 0; // holds the number of times user digs
Random gen = new Random(9);
Scanner scan = new Scanner(System.in);
int locationRow; // stores the row where the treasure is
int locationCol; // stores the column where the treasure is
/*
* Generates a String array that looks like
* undug grass when printed to represent the backyard.
*/
String[][] backyard = new String[5][5];
for (int row = 0; row < backyard.length; row++) {
for (int col = 0; col < backyard[row].length; col++) {
backyard[row][col] = "^";
System.out.print(backyard[row][col] + " ");
} // end inner loop
System.out.println();
} // end outer loop
/*
* Generate a random number for both the row and column
* location of the treasure. Store the results in
* locationRow and locationCol, respectively.
* The random numbers should be within the array dimensions.
*/
//**************************
// YOUR CODE HERE (1 OF 7)
//**************************
/*
* A while loop that runs as long as the treasure
* is not found.
*/
while (found == false) {
/*
* Declare two integer variables, guessRow and guessCol
* and set them both to -1.
* Increment the variable dug to represent a dig.
*/
//**************************
// YOUR CODE HERE (2 OF 7)
//**************************
/*
* Ask the user which row they want to dig.
* Use a while loop to validate the input.
* Run the while loop as long as the guessRow
* value is outside the bounds of the array.
*/
//**************************
// YOUR CODE HERE (3 OF 7)
//**************************
/*
* Ask the user which column they want to dig.
* Use a while loop to validate the input.
* Run the while loop as long as the guessCol
* value is outside the bounds of the array.
*/
...
An overview how to realize code generation of languages on the JVM that implement other class layouts than the Java programming languages. As an example, the inline-mock-maker for Mockito is discussed which supports languages like Kotlin that make any property final by default.
These are my slides from a mini Clojure tutorial presented at the "7 Languages in 7 Months" meetup group. The first part of the presentation faithfully presents material from Bruce Tate book, and the second part covers the more advanced topics of state management and macros
Brief introduction to testing talk prepared to creates a starting point at TAPTAP Networks & SONATA Usa Corp. The companies where I work as Q&A Team member.
Some testing - Everything you should know about testing to go with @pedro_g_s...Sergio Arroyo
I usually attend to several talks about testing. Everyone tells us how good, how important and valuable could be having a good test suite. But almost anybody tells us how hard is achieving this goal. With this talk, I wanted to provide an overview for people who is starting with software testing. Even for those who never tried it.
But this is not only an introduction. Though I start talking about the basics and principles and concepts, I also try to talk about my experience. What worked, where I failed and how I tried to solve the problems I found.
CS117-S18-AlharbiMohammed-master/.gitignore
*.class
*.ctxt
*.*~
doc
/.project
default.log
defaultlog.txt
CS117-S18-AlharbiMohammed-master/Command.javaCS117-S18-AlharbiMohammed-master/Command.javaimport java.util.ArrayList;
/**
* This class is part of the "Campus of Kings" application. "Campus of Kings" is a
* very simple, text based adventure game.
*
* This class holds information about a command that was issued by the user. A
* command currently consists of two strings: a command word and a second word
* (for example, if the command was "take map", then the two strings obviously
* are "take" and "map").
*
* The way this is used is: Commands are already checked for being valid command
* words. If the user entered an invalid command (a word that is not known) then
* the command word is <null>.
*
* If the command had only one word, then the second word is <null>.
*
* @author Maria Jump
* @version 2015.02.01
*/
publicclassCommand{
/** The command word for this command. */
privateString commandWord;
/** The rest of the line with all the spaces removed. */
privateArrayList<String> restOfLine;
/**
* Create a command object. First is supplied. The second word is assumed
* to be null.
*
* @param firstWord
* The first word of the command. Null if the command was not
* recognized.
*/
publicCommand(String firstWord){
commandWord = firstWord;
restOfLine =newArrayList<String>();
}
/**
* Create a command object. First and second word must be supplied, but
* either one (or both) can be null.
*
* @param firstWord
* The first word of the command. Null if the command was not
* recognized.
* @param rest
* The rest of the command.
*/
publicCommand(String firstWord,ArrayList<String> rest){
commandWord = firstWord;
restOfLine = rest;
}
/**
* Return the command word (the first word) of this command. If the command
* was not understood, the result is null.
*
* @return The command word.
*/
publicString getCommandWord(){
return commandWord;
}
/**
* Returns if this command was not understood.
*
* @return true if this command was not understood.
*/
publicboolean isUnknown(){
return(commandWord ==null);
}
/**
* Returns if this command has a second word.
*
* @return true if the command has a second word.
*/
publicboolean hasSecondWord(){
return restOfLine !=null;
}
/**
* Returns if this command has more words.
*
* @param index The index of the word needed.
* @return true if the command has a word at given index.
*/
publicboolean hasWord(int index){
return index >=0&& index < restOfLine.size();
}
/**
* Returns the word at the requested index in the command.
*
* @param index
* The index of word in the command that is being requested.
*
* @ret.
MIS 4310-01 Final Take Home Exam (100 points) DUE Thursd.docxraju957290
MIS 4310-01 Final Take Home Exam (100 points)
DUE: Thursday, December 14th, 2017 by 11:59 PM
Use the code provided on Blackboard as your template. Fill in your own code where
prompted. When finished, upload to Blackboard a file called “treasure_hunt.java”. Change
the block comment to include your own name. This is an individual assignment! Code that
you write that you cannot explain will result in an automatic zero.
Create a Java application that simulates a treasure hunt with a 2D array. Your output
should match the output below with similar input. Do NOT alter the code provided. Fill
in code in the SEVEN (7) locations under each comment // YOUR CODE HERE.
Sample Output:
import java.util.Random;
import java.util.Scanner;
/*
* First Last
* MIS 4310 Fall 2017
* FINAL TAKE HOME EXAM
*/
public class treasure_hunt {
public static void main(String[] args) {
boolean found = false; // is true if the treasure is found
int dug = 0; // holds the number of times user digs
Random gen = new Random(9);
Scanner scan = new Scanner(System.in);
int locationRow; // stores the row where the treasure is
int locationCol; // stores the column where the treasure is
/*
* Generates a String array that looks like
* undug grass when printed to represent the backyard.
*/
String[][] backyard = new String[5][5];
for (int row = 0; row < backyard.length; row++) {
for (int col = 0; col < backyard[row].length; col++) {
backyard[row][col] = "^";
System.out.print(backyard[row][col] + " ");
} // end inner loop
System.out.println();
} // end outer loop
/*
* Generate a random number for both the row and column
* location of the treasure. Store the results in
* locationRow and locationCol, respectively.
* The random numbers should be within the array dimensions.
*/
//**************************
// YOUR CODE HERE (1 OF 7)
//**************************
/*
* A while loop that runs as long as the treasure
* is not found.
*/
while (found == false) {
/*
* Declare two integer variables, guessRow and guessCol
* and set them both to -1.
* Increment the variable dug to represent a dig.
*/
//**************************
// YOUR CODE HERE (2 OF 7)
//**************************
/*
* Ask the user which row they want to dig.
* Use a while loop to validate the input.
* Run the while loop as long as the guessRow
* value is outside the bounds of the array.
*/
//**************************
// YOUR CODE HERE (3 OF 7)
//**************************
/*
* Ask the user which column they want to dig.
* Use a while loop to validate the input.
* Run the while loop as long as the guessCol
* value is outside the bounds of the array.
*/
...
Modified Code Game.javaimport java.util.;public class Game.pdfgalagirishp
Modified Code: Game.java:
import java.util.*;
public class Game
{
private Parser parser;
private Room currentRoom;
private Stack route;
/**
* Create the game and initialize its internal map.
*/
public Game()
{
createRooms();
parser = new Parser();
route=new Stack();
}
/**
* Create all the rooms and link their exits together.
*/
private void createRooms()
{
Room outside, theatre, pub, lab, office, basement;
// create the rooms
outside = new Room(\"outside the main entrance of the university\");
theatre = new Room(\"in a lecture theatre\");
pub = new Room(\"in the campus pub\");
lab = new Room(\"in a computing lab\");
office = new Room(\"in the computing admin office\");
basement = new Room(\"in the basement\");
// initialise room exits
outside.setExit(\"east\", theatre);
outside.setExit(\"south\", lab);
outside.setExit(\"west\", pub);
theatre.setExit(\"west\", outside);
pub.setExit(\"east\", outside);
lab.setExit(\"north\", outside);
lab.setExit(\"east\", office);
lab.setExit(\"down\", basement);
basement.setExit(\"up\", lab);
office.setExit(\"west\", lab);
currentRoom = outside; // start game outside
}
/**
* Main play routine. Loops until end of play.
*/
public void play()
{
printWelcome();
// Enter the main command loop. Here we repeatedly read commands and
// execute them until the game is over.
boolean finished = false;
while (! finished)
{
Command command = parser.getCommand();
finished = processCommand(command);
}
System.out.println(\"Thank you for playing. Good bye.\");
}
/**
* Print out the opening message for the player.
*/
private void printWelcome()
{
System.out.println();
System.out.println(\"Welcome to the World of Zuul!\");
System.out.println(\"World of Zuul is a new, incredibly boring adventure game.\");
System.out.println(\"Type \'help\' if you need help.\");
System.out.println();
System.out.println(currentRoom.getLongDescription());
}
/**
* Given a command, process (that is: execute) the command.
* If this command ends the game, true is returned, otherwise false is
* returned.
*/
private boolean processCommand(Command command)
{
boolean wantToQuit = false;
if(command.isUnknown())
{
System.out.println(\"I don\'t know what you mean...\");
return false;
}
String commandWord = command.getCommandWord();
if (commandWord.equals(\"help\")){
printHelp();
}
else if (commandWord.equals(\"go\")) {
goRoom(command);
}
else if (commandWord.equals(\"back\")) {
goBack();
}
else if (commandWord.equals(\"quit\")) {
wantToQuit = quit(command);
}
return wantToQuit;
}
// implementations of user commands:
/**
* Print out some help information.
* Here we print some stupid, cryptic message and a list of the
* command words.
*/
private void printHelp()
{
System.out.println(\"You are lost. You are alone. You wander\");
System.out.println(\"around at the university.\");
System.out.println();
System.out.println(\"Your command words are:\");
parser.showCommands();
}
/**
* Try to go to one direction. If there is an exit, enter the new
* room, otherwise prin.
Please read the comment ins codeExpressionTree.java-------------.pdfshanki7
Please read the comment ins code
ExpressionTree.java
----------------------------------
/**
* This is the class for Expression Tree.
* Used to create Expression Tree and Evaluate it
*/
/**
* Following logic is used to construct a Tree
* Here we use stack for Preparing Tree
* Loop through given Expression String
* If Character is Operand , Create node and push to stack
* If Character is Operator then
* 1)Create Node for Operator
* 2)Pop 2 nodes from Stack and Made
* OpretorNode--> left == first node pop
* OpretorNode--> right == second node pop
* At the end of creation of Expression Tree, Stack have only one node , which is root of
Expression tree
*/
/** Class ExpressionTree **/
class ExpressionTree
{
/** class TreeNode
* Stored Character ==> Digit(0..9) or a Operator +,-,*,/
* Left Node and Right Node
*
* **/
class TreeNode
{
char data;
TreeNode left, right;
/** constructor **/
public TreeNode(char data)
{
this.data = data;
this.left = null;
this.right = null;
}
}
/** class StackNode **/
class StackNode
{
TreeNode treeNode;
StackNode next;
/** constructor **/
public StackNode(TreeNode treeNode)
{
this.treeNode = treeNode;
next = null;
}
}
private static StackNode top;
/** constructor
* Constructor takes input string like \"+-+7*935*82*625\"
* Input should be in Prefix notation
* **/
public ExpressionTree(String expression)
{
top = null;
//Call Method for prepare expression tree
buildTree(expression);
}
/** function to clear tree **/
public void clear()
{
top = null;
}
/** function to push a node **/
private void push(TreeNode ptr)
{
if (top == null)
top = new StackNode(ptr);
else
{
StackNode nptr = new StackNode(ptr);
nptr.next = top;
top = nptr;
}
}
/** function to pop a node
* When it find operator pop 2 elements from Stack
*
* **/
private TreeNode pop()
{
if (top == null)
throw new RuntimeException(\"Underflow\");
else
{
TreeNode ptr = top.treeNode;
top = top.next;
return ptr;
}
}
/** function to get top node **/
private TreeNode peek()
{
return top.treeNode;
}
/** function to insert character **/
private void insert(char val)
{
try
{
//If Operand , Create node and push to Stack
if (isDigit(val))
{
TreeNode nptr = new TreeNode(val);
push(nptr);
}
//If Operator , Create node and popup 2 elements and make them its right and left
else if (isOperator(val))
{
TreeNode nptr = new TreeNode(val);
nptr.left = pop();
nptr.right = pop();
push(nptr);
}
}
catch (Exception e)
{
System.out.println(\"Invalid Expression\");
}
}
/** function to check if digit **/
private boolean isDigit(char ch)
{
return ch >= \'0\' && ch <= \'9\';
}
/** function to check if operator **/
private boolean isOperator(char ch)
{
return ch == \'+\' || ch == \'-\' || ch == \'*\' || ch == \'/\';
}
/** function to convert character to digit **/
private int toDigit(char ch)
{
return ch - \'0\';
}
/** function to build tree from input */
public void buildTree(String eqn)
{
for (int i = eqn.length() - 1; i >= 0; i--)
insert(eqn.charAt(i));
}
/** function to evaluate tree */
public dou.
I need help completing this C++ code with these requirements.instr.pdfeyeonsecuritysystems
I need help completing this C++ code with these requirements.
instructions: IN C++ LANGUAGE PLEASE
Update the comments for each prototype by filling in the pre and post conditions.
Remember that pre conditions indicate what conditions must be met BEFORE the user calls the
function. The function will not work properly unless the pre conditions are met.
Post conditions indicate what will be the result of the function call. In other words, what
conditions will exist after the function is called.
See class notes from Thursday on pre and post conditions for some examples and further
explanation.
Code begins here:
#include //for NULL
class List
{
private:
struct Node
{
int data;
Node* next;
Node(int data): data(data), next(NULL){}
};
typedef struct Node* Nodeptr;
Nodeptr first;
Nodeptr last;
int size;
public:
/**Constructors and Destructors*/
List();
//Default constructor; initializes and empty list
//Postcondition:
~List();
//Destructor. Frees memory allocated to the list
//Postcondition:
/**Accessors*/
int getFirst();
//Returns the first element in the list
//Precondition:
int getLast();
//Returns the last element in the list
//Precondition:
bool isEmpty();
//Determines whether a list is empty.
int getSize();
//Returns the size of the list
/**Manipulation Procedures*/
void removeLast();
//Removes the value of the last element in the list
//Precondition:
//Postcondition:
void removeFirst();
//Removes the value of the first element in the list
//Precondition:
//Postcondition:
void insertLast(int data);
//Inserts a new element at the end of the list
//If the list is empty, the new element becomes both first and last
//Postcondition:
void insertFirst(int data);
//Inserts a new element at the start of the list
//If the list is empty, the new element becomes both first and last
//Postcondition:
/**Additional List Operations*/
void printList();
//Prints to the console the value of each element in the list sequentially
//and separated by a blank space
//Prints nothing if the list is empty
};
Solution
PROGRAM CODE:
#include
#include //for NULL
using namespace std;
class List
{
private:
struct Node
{
int data;
Node* next;
Node(int data): data(data), next(NULL){}
};
typedef struct Node* Nodeptr;
Nodeptr first;
Nodeptr last;
int size;
public:
/**Constructors and Destructors*/
List()
{
first = (Node*) malloc(sizeof(Node));
last = (Node*) malloc(sizeof(Node));
size = 0;
}
//Default constructor; initializes and empty list
//Postcondition:
~List()
{
delete first;
delete last;
}
//Destructor. Frees memory allocated to the list
//Postcondition:
/**Accessors*/
int getFirst()
{
return first->data;
}
//Returns the first element in the list
//Precondition:
int getLast()
{
return last->data;
}
//Returns the last element in the list
//Precondition:
bool isEmpty()
{
if(first == NULL)
return true;
else return false;
}
//Determines whether a list is empty.
int getSize()
{
return size;
}
//Returns the size of the list
/**Manipulation Procedures*/
void removeLast()
{
last = .
Frequency .java Word frequency counter package frequ.pdfarshiartpalace
Frequency .java
/**
* Word frequency counter
*/
package frequency;
import java.util.Iterator;
/**
*
* @author UMD CS
*/
public class Frequency implements Iterable{
private Node first;
private int N;
Frequency(){
N = 0;
first = null;
}
@Override
public Iterator iterator() {
return new ListIterator();
}
/**
*
* List iterator
*
*/
private class ListIterator implements Iterator{
private Node current;
private int index ;
ListIterator(){
current = first;
index = 0;
}
@Override
public boolean hasNext() {
return current != null;
}
public String next() {
if(!hasNext()){
return null;
}
String word = current.key;
int count = current.count;
String r = \"(\"+word + \",\" + Integer.toString(count)+\")\";
current = current.next;
return r;
}
@Override
public void remove() {
}
}
/**
*
* Node class
*
*/
private class Node {
private String key;
private int count;
private Node next;
Node(String item){
key = item;
count = 1;
next = null;
}
@Override
public String toString(){
return \"(\"+key +\",\"+count+\")\";
}
}
/*
* Inserts a word into the linked list. If the word exists, increment the
* count by q.
*/
public void insert(String word){
if(word.equals(\"\")){
return;
}
//TODO
/*
* implement here
*/
}
/**
*
* @param str input string
* This method splits a string into words and pass the words to insert method
*
*/
public void insertWords(String str){
String delims = \"[ .,?!\'\\\"()}{;/<>&=#-:\\\\ _]+\";
String[] words = str.split(delims);
for(String s: words){
s = s.toLowerCase();
insert(s);
}
}
/**
* prints the word frequency list
*/
public void print(){
Node c = first;
while(c != null){
System.out.print(\"(\"+c.key + \",\" + c.count+\")\");
c = c.next;
}
System.out.print(\"\ \");
}
}
--------------------------------------------------------------------------------------------------------------------
------------------------------------------------------
WordFrequency.java
package frequency;
import utils.In;
import utils.Stopwatch;
/**
*
* @author UMD CS
*/
public class WordFrequency {
/**
* @param input source
* @param
* This method receives input resource and return the word frequency string
* DO NOT CHANGE THIS METHOD.
*/
public static String freq(String inputSource, int maxLines){
In in;
// Frequency class can only count the frequency of strings. DO NOT CHANGE THIS.
Frequency freq = new Frequency();
int MAX = 100;
String inputSourceName = inputSource;
try {
in = new In(inputSourceName);
while (!in.isEmpty()) {
String s = in.readLine();
//System.out.println(s);
freq.insertWords(s);
}
}
catch (Exception e) {
e.printStackTrace();
}
StringBuilder strFrequency = new StringBuilder();
int cnt = 0;
for(String s: freq){
strFrequency.append(s);
strFrequency.append(\",\");
cnt++;
if(cnt >= maxLines){break;}
}
return strFrequency.toString();
}
/**
*
*/
public static void main(String[] args) {
In in;
Frequency freq = new Frequency();
int MAX = 100;
// String inputSourceName =
\"http://www.cs.umd.edu/class/summer2015/cmsc132/projects/P3_WordFrequency/test1.html\";
String .
Kotlin Bytecode Generation and Runtime Performanceintelliyole
In this talk, we'll dive into the details of how various language features supported by Kotlin are translated to Java bytecode. We'll use the JMH microbenchmarking tool to study the relative performance of various constructs and to understand how we can ensure top performance of the Kotlin code that we write.
Functional Programming You Already KnowKevlin Henney
Presented at NDC 2013 in Oslo (13th June 2013)
Video available on Vimeo: https://vimeo.com/68327245
From JVM to .NET languages, from minor coding idioms to system-level architectures, functional programming is enjoying a long overdue surge in interest. Functional programming is certainly not a new idea and, although not apparently as mainstream as object-oriented and procedural programming, many of its concepts are also more familiar than many programmers believe.
This talk examines functional and declarative programming styles from the point of view of coding patterns, little languages and programming techniques already familiar to many programmers.
Writing code that writes code - Nguyen LuongVu Huy
“The Pragmatic Programmer” admonished us all to “write code that writes code”: use code generators to increase productivity and avoid duplication. The language communities have clearly caught on, as more and more frameworks generate code at compile time: Project Lombok, Google Auto, and more.
This session reviews these approaches including examples of how and why we’d want to do this.
We will see newest Java language tools, write our own AST tranform and look at some amazing libraries based on these techniques.
Bio: Nguyen Luong is a senior java technical lead at Ekino Vietnam. He likes to research new technologies and solve security challenges.
“The Pragmatic Programmer” admonished us all to “write code that writes code”: use code generators to increase productivity and avoid duplication. The language communities have clearly caught on, as more and more frameworks generate code at compile time: Project Lombok, Google Auto, and more.
This session reviews these approaches including examples of how and why we’d want to do this.
We will see newest Java language tools, write our own AST tranform and look at some amazing libraries based on these techniques.
Bio: Nguyen Luong is a senior java technical lead at Ekino Vietnam. He likes to research new technologies and solve security challenges.
package singlylinkedlist; public class Node { public String valu.pdfamazing2001
package singlylinkedlist;
public class Node {
public String value;
public Node next;
public Node(String value) {
this.value = value;
}
@Override
public String toString() {
return value;
}
}
SingleyLinkedList.java :
package singlylinkedlist;
import java.io.*;
import java.util.*;
/**
* Defines the interface for a singly-linked list.
*
*/
public interface SinglyLinkedList {
/**
* @return Reference to the first node. If the list is empty, this method
* returns null.
*/
public Node getFirst();
/**
* @return Reference to the last node . If the list is empty, this method
* returns null.
*/
public Node getLast();
/**
* @return Number of nodes in the list
*/
public int size();
/**
* @return true if the list has no nodes; false otherwise
*/
public boolean isEmpty();
/**
* Removes all nodes in the list.
*/
public void clear();
/**
* Inserts a new node with the given value after cursor.
*
* @param cursor
* The node to insert after. Set this to null to insert value as
the
* new first Node.
* @param value
* The value to insert
* @return a reference to the newly inserted Node
*/
public Node insert(Node cursor, String value);
/**
* Inserts a new node with the given value at the "end" of the list.
*
* @param value
* @return a reference to the newly inserted Node
*/
public Node append(String value);
/**
* Removes the node after the specified Node (cursor) from the list.
*
* @param cursor
* A reference to the Node to remove.
*/
public void removeAfter(Node cursor);
/**
* Returns a reference to the first Node containing the key, starting from
the
* given Node.
*
* @param start
* @param key
* @return a reference to the first Node containing the key
*/
public Node find(Node start, String key);
/**
* Prints the values of all the items in a list
*/
public void printWholeList();
}
SinglyLinkedTester.java:
package sbccunittest;
import static java.lang.Math.*;
import static java.lang.System.*;
import static org.apache.commons.lang3.StringUtils.*;
import static org.junit.Assert.*;
import static sbcc.Core.*;
import java.io.*;
import java.lang.reflect.*;
import java.nio.file.*;
import java.util.*;
import java.util.stream.*;
import org.apache.commons.lang3.*;
import org.junit.*;
import org.w3c.dom.ranges.*;
import sbcc.*;
import singlylinkedlist.*;
/**
* 09/16/2021
*
* @author sstrenn
*
*/
public class SinglyLinkedListTester {
public static String newline = System.getProperty("line.separator");
public static int totalScore = 0;
public static int extraCredit = 0;
public static boolean isZeroScore = false;
public static String scorePreamble = "";
@BeforeClass
public static void beforeTesting() {
totalScore = 0;
extraCredit = 0;
}
@AfterClass
public static void afterTesting() {
if (isZeroScore) {
totalScore = 0;
extraCredit = 0;
}
println(scorePreamble + "Estimated score (w/o late penalties, etc.) is:
" + totalScore + " out of 25.");
// If the project follows the naming convention, save the results in a
folder on
// the desktop. (Alex Kohanim)
try {
String directory =
substri.
please navigate to cs112 webpage and go to assignments -- Trees. Th.pdfaioils
please navigate to cs112 webpage and go to assignments --> Trees. This will give you the
directions for the assignment. Please do the last 2 methods in huffman.java called encode() and
decode()
Code is provided below:
HuffmanCoding.java
package huffman;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.util.ArrayList;
import java.util.Collections;
/**
* This class contains methods which, when used together, perform the
* entire Huffman Coding encoding and decoding process
*
* @author Ishaan Ivaturi
* @author Prince Rawal
*/
public class HuffmanCoding {
private String fileName;
private ArrayList sortedCharFreqList;
private TreeNode huffmanRoot;
private String[] encodings;
/**
* Constructor used by the driver, sets filename
* DO NOT EDIT
* @param f The file we want to encode
*/
public HuffmanCoding(String f) {
fileName = f;
}
/**
* Reads from filename character by character, and sets sortedCharFreqList
* to a new ArrayList of CharFreq objects with frequency > 0, sorted by frequency
*/
public void makeSortedList() {
StdIn.setFile(fileName);
/* Your code goes here */
}
/**
* Uses sortedCharFreqList to build a huffman coding tree, and stores its root
* in huffmanRoot
*/
public void makeTree() {
/* Your code goes here */
}
/**
* Uses huffmanRoot to create a string array of size 128, where each
* index in the array contains that ASCII character's bitstring encoding. Characters not
* present in the huffman coding tree should have their spots in the array left null.
* Set encodings to this array.
*/
public void makeEncodings() {
/* Your code goes here */
}
/**
* Using encodings and filename, this method makes use of the writeBitString method
* to write the final encoding of 1's and 0's to the encoded file.
*
* @param encodedFile The file name into which the text file is to be encoded
*/
public void encode(String encodedFile) {
StdIn.setFile(fileName);
/* Your code goes here */
}
/**
* Writes a given string of 1's and 0's to the given file byte by byte
* and NOT as characters of 1 and 0 which take up 8 bits each
* DO NOT EDIT
*
* @param filename The file to write to (doesn't need to exist yet)
* @param bitString The string of 1's and 0's to write to the file in bits
*/
public static void writeBitString(String filename, String bitString) {
byte[] bytes = new byte[bitString.length() / 8 + 1];
int bytesIndex = 0, byteIndex = 0, currentByte = 0;
// Pad the string with initial zeroes and then a one in order to bring
// its length to a multiple of 8. When reading, the 1 signifies the
// end of padding.
int padding = 8 - (bitString.length() % 8);
String pad = "";
for (int i = 0; i < padding-1; i++) pad = pad + "0";
pad = pad + "1";
bitString = pad + bitString;
// For every bit, add it to the right spot in the corresponding byte,
// and store bytes in the array when finished
for (char c : bitString.toCharArray()) {
if (c != '1' && c != '0') {
System.out.println("Invalid characters in bitstring");
return;
}
if (c .
Similar to Chapter06 designing class-zuul bad (20)
Designing for Privacy in Amazon Web ServicesKrzysztofKkol1
Data privacy is one of the most critical issues that businesses face. This presentation shares insights on the principles and best practices for ensuring the resilience and security of your workload.
Drawing on a real-life project from the HR industry, the various challenges will be demonstrated: data protection, self-healing, business continuity, security, and transparency of data processing. This systematized approach allowed to create a secure AWS cloud infrastructure that not only met strict compliance rules but also exceeded the client's expectations.
Climate Science Flows: Enabling Petabyte-Scale Climate Analysis with the Eart...Globus
The Earth System Grid Federation (ESGF) is a global network of data servers that archives and distributes the planet’s largest collection of Earth system model output for thousands of climate and environmental scientists worldwide. Many of these petabyte-scale data archives are located in proximity to large high-performance computing (HPC) or cloud computing resources, but the primary workflow for data users consists of transferring data, and applying computations on a different system. As a part of the ESGF 2.0 US project (funded by the United States Department of Energy Office of Science), we developed pre-defined data workflows, which can be run on-demand, capable of applying many data reduction and data analysis to the large ESGF data archives, transferring only the resultant analysis (ex. visualizations, smaller data files). In this talk, we will showcase a few of these workflows, highlighting how Globus Flows can be used for petabyte-scale climate analysis.
First Steps with Globus Compute Multi-User EndpointsGlobus
In this presentation we will share our experiences around getting started with the Globus Compute multi-user endpoint. Working with the Pharmacology group at the University of Auckland, we have previously written an application using Globus Compute that can offload computationally expensive steps in the researcher's workflows, which they wish to manage from their familiar Windows environments, onto the NeSI (New Zealand eScience Infrastructure) cluster. Some of the challenges we have encountered were that each researcher had to set up and manage their own single-user globus compute endpoint and that the workloads had varying resource requirements (CPUs, memory and wall time) between different runs. We hope that the multi-user endpoint will help to address these challenges and share an update on our progress here.
In 2015, I used to write extensions for Joomla, WordPress, phpBB3, etc and I ...Juraj Vysvader
In 2015, I used to write extensions for Joomla, WordPress, phpBB3, etc and I didn't get rich from it but it did have 63K downloads (powered possible tens of thousands of websites).
In software engineering, the right architecture is essential for robust, scalable platforms. Wix has undergone a pivotal shift from event sourcing to a CRUD-based model for its microservices. This talk will chart the course of this pivotal journey.
Event sourcing, which records state changes as immutable events, provided robust auditing and "time travel" debugging for Wix Stores' microservices. Despite its benefits, the complexity it introduced in state management slowed development. Wix responded by adopting a simpler, unified CRUD model. This talk will explore the challenges of event sourcing and the advantages of Wix's new "CRUD on steroids" approach, which streamlines API integration and domain event management while preserving data integrity and system resilience.
Participants will gain valuable insights into Wix's strategies for ensuring atomicity in database updates and event production, as well as caching, materialization, and performance optimization techniques within a distributed system.
Join us to discover how Wix has mastered the art of balancing simplicity and extensibility, and learn how the re-adoption of the modest CRUD has turbocharged their development velocity, resilience, and scalability in a high-growth environment.
Advanced Flow Concepts Every Developer Should KnowPeter Caitens
Tim Combridge from Sensible Giraffe and Salesforce Ben presents some important tips that all developers should know when dealing with Flows in Salesforce.
How Recreation Management Software Can Streamline Your Operations.pptxwottaspaceseo
Recreation management software streamlines operations by automating key tasks such as scheduling, registration, and payment processing, reducing manual workload and errors. It provides centralized management of facilities, classes, and events, ensuring efficient resource allocation and facility usage. The software offers user-friendly online portals for easy access to bookings and program information, enhancing customer experience. Real-time reporting and data analytics deliver insights into attendance and preferences, aiding in strategic decision-making. Additionally, effective communication tools keep participants and staff informed with timely updates. Overall, recreation management software enhances efficiency, improves service delivery, and boosts customer satisfaction.
Providing Globus Services to Users of JASMIN for Environmental Data AnalysisGlobus
JASMIN is the UK’s high-performance data analysis platform for environmental science, operated by STFC on behalf of the UK Natural Environment Research Council (NERC). In addition to its role in hosting the CEDA Archive (NERC’s long-term repository for climate, atmospheric science & Earth observation data in the UK), JASMIN provides a collaborative platform to a community of around 2,000 scientists in the UK and beyond, providing nearly 400 environmental science projects with working space, compute resources and tools to facilitate their work. High-performance data transfer into and out of JASMIN has always been a key feature, with many scientists bringing model outputs from supercomputers elsewhere in the UK, to analyse against observational or other model data in the CEDA Archive. A growing number of JASMIN users are now realising the benefits of using the Globus service to provide reliable and efficient data movement and other tasks in this and other contexts. Further use cases involve long-distance (intercontinental) transfers to and from JASMIN, and collecting results from a mobile atmospheric radar system, pushing data to JASMIN via a lightweight Globus deployment. We provide details of how Globus fits into our current infrastructure, our experience of the recent migration to GCSv5.4, and of our interest in developing use of the wider ecosystem of Globus services for the benefit of our user community.
Gamify Your Mind; The Secret Sauce to Delivering Success, Continuously Improv...Shahin Sheidaei
Games are powerful teaching tools, fostering hands-on engagement and fun. But they require careful consideration to succeed. Join me to explore factors in running and selecting games, ensuring they serve as effective teaching tools. Learn to maintain focus on learning objectives while playing, and how to measure the ROI of gaming in education. Discover strategies for pitching gaming to leadership. This session offers insights, tips, and examples for coaches, team leads, and enterprise leaders seeking to teach from simple to complex concepts.
Paketo Buildpacks : la meilleure façon de construire des images OCI? DevopsDa...Anthony Dahanne
Les Buildpacks existent depuis plus de 10 ans ! D’abord, ils étaient utilisés pour détecter et construire une application avant de la déployer sur certains PaaS. Ensuite, nous avons pu créer des images Docker (OCI) avec leur dernière génération, les Cloud Native Buildpacks (CNCF en incubation). Sont-ils une bonne alternative au Dockerfile ? Que sont les buildpacks Paketo ? Quelles communautés les soutiennent et comment ?
Venez le découvrir lors de cette session ignite
top nidhi software solution freedownloadvrstrong314
This presentation emphasizes the importance of data security and legal compliance for Nidhi companies in India. It highlights how online Nidhi software solutions, like Vector Nidhi Software, offer advanced features tailored to these needs. Key aspects include encryption, access controls, and audit trails to ensure data security. The software complies with regulatory guidelines from the MCA and RBI and adheres to Nidhi Rules, 2014. With customizable, user-friendly interfaces and real-time features, these Nidhi software solutions enhance efficiency, support growth, and provide exceptional member services. The presentation concludes with contact information for further inquiries.
Multiple Your Crypto Portfolio with the Innovative Features of Advanced Crypt...Hivelance Technology
Cryptocurrency trading bots are computer programs designed to automate buying, selling, and managing cryptocurrency transactions. These bots utilize advanced algorithms and machine learning techniques to analyze market data, identify trading opportunities, and execute trades on behalf of their users. By automating the decision-making process, crypto trading bots can react to market changes faster than human traders
Hivelance, a leading provider of cryptocurrency trading bot development services, stands out as the premier choice for crypto traders and developers. Hivelance boasts a team of seasoned cryptocurrency experts and software engineers who deeply understand the crypto market and the latest trends in automated trading, Hivelance leverages the latest technologies and tools in the industry, including advanced AI and machine learning algorithms, to create highly efficient and adaptable crypto trading bots
Globus Connect Server Deep Dive - GlobusWorld 2024Globus
We explore the Globus Connect Server (GCS) architecture and experiment with advanced configuration options and use cases. This content is targeted at system administrators who are familiar with GCS and currently operate—or are planning to operate—broader deployments at their institution.
Your Digital Assistant.
Making complex approach simple. Straightforward process saves time. No more waiting to connect with people that matter to you. Safety first is not a cliché - Securely protect information in cloud storage to prevent any third party from accessing data.
Would you rather make your visitors feel burdened by making them wait? Or choose VizMan for a stress-free experience? VizMan is an automated visitor management system that works for any industries not limited to factories, societies, government institutes, and warehouses. A new age contactless way of logging information of visitors, employees, packages, and vehicles. VizMan is a digital logbook so it deters unnecessary use of paper or space since there is no requirement of bundles of registers that is left to collect dust in a corner of a room. Visitor’s essential details, helps in scheduling meetings for visitors and employees, and assists in supervising the attendance of the employees. With VizMan, visitors don’t need to wait for hours in long queues. VizMan handles visitors with the value they deserve because we know time is important to you.
Feasible Features
One Subscription, Four Modules – Admin, Employee, Receptionist, and Gatekeeper ensures confidentiality and prevents data from being manipulated
User Friendly – can be easily used on Android, iOS, and Web Interface
Multiple Accessibility – Log in through any device from any place at any time
One app for all industries – a Visitor Management System that works for any organisation.
Stress-free Sign-up
Visitor is registered and checked-in by the Receptionist
Host gets a notification, where they opt to Approve the meeting
Host notifies the Receptionist of the end of the meeting
Visitor is checked-out by the Receptionist
Host enters notes and remarks of the meeting
Customizable Components
Scheduling Meetings – Host can invite visitors for meetings and also approve, reject and reschedule meetings
Single/Bulk invites – Invitations can be sent individually to a visitor or collectively to many visitors
VIP Visitors – Additional security of data for VIP visitors to avoid misuse of information
Courier Management – Keeps a check on deliveries like commodities being delivered in and out of establishments
Alerts & Notifications – Get notified on SMS, email, and application
Parking Management – Manage availability of parking space
Individual log-in – Every user has their own log-in id
Visitor/Meeting Analytics – Evaluate notes and remarks of the meeting stored in the system
Visitor Management System is a secure and user friendly database manager that records, filters, tracks the visitors to your organization.
"Secure Your Premises with VizMan (VMS) – Get It Now"
Into the Box Keynote Day 2: Unveiling amazing updates and announcements for modern CFML developers! Get ready for exciting releases and updates on Ortus tools and products. Stay tuned for cutting-edge innovations designed to boost your productivity.
Innovating Inference - Remote Triggering of Large Language Models on HPC Clus...Globus
Large Language Models (LLMs) are currently the center of attention in the tech world, particularly for their potential to advance research. In this presentation, we'll explore a straightforward and effective method for quickly initiating inference runs on supercomputers using the vLLM tool with Globus Compute, specifically on the Polaris system at ALCF. We'll begin by briefly discussing the popularity and applications of LLMs in various fields. Following this, we will introduce the vLLM tool, and explain how it integrates with Globus Compute to efficiently manage LLM operations on Polaris. Attendees will learn the practical aspects of setting up and remotely triggering LLMs from local machines, focusing on ease of use and efficiency. This talk is ideal for researchers and practitioners looking to leverage the power of LLMs in their work, offering a clear guide to harnessing supercomputing resources for quick and effective LLM inference.
A Comprehensive Look at Generative AI in Retail App Testing.pdfkalichargn70th171
Traditional software testing methods are being challenged in retail, where customer expectations and technological advancements continually shape the landscape. Enter generative AI—a transformative subset of artificial intelligence technologies poised to revolutionize software testing.
Understanding Globus Data Transfers with NetSageGlobus
NetSage is an open privacy-aware network measurement, analysis, and visualization service designed to help end-users visualize and reason about large data transfers. NetSage traditionally has used a combination of passive measurements, including SNMP and flow data, as well as active measurements, mainly perfSONAR, to provide longitudinal network performance data visualization. It has been deployed by dozens of networks world wide, and is supported domestically by the Engagement and Performance Operations Center (EPOC), NSF #2328479. We have recently expanded the NetSage data sources to include logs for Globus data transfers, following the same privacy-preserving approach as for Flow data. Using the logs for the Texas Advanced Computing Center (TACC) as an example, this talk will walk through several different example use cases that NetSage can answer, including: Who is using Globus to share data with my institution, and what kind of performance are they able to achieve? How many transfers has Globus supported for us? Which sites are we sharing the most data with, and how is that changing over time? How is my site using Globus to move data internally, and what kind of performance do we see for those transfers? What percentage of data transfers at my institution used Globus, and how did the overall data transfer performance compare to the Globus users?
1. 1 / 7
zuul-bad
/**
* This class is the main class of the "World of Zuul"
application.
* "World of Zuul" is a very simple, text based
adventure game.
*
* This class holds information about a command that
was issued by the user.
* A command currently consists of two strings: a
command word and a second
* word (for example, if the command was "take map",
then the two strings
* obviously are "take" and "map").
*
* The way this is used is: Commands are already
checked for being valid
* command words. If the user entered an invalid
command (a word that is not
* known) then the command word is <null>.
*
* If the command had only one word, then the second
word is <null>.
*
* @author Michael Kolling and David J. Barnes
* @version 1.0 (February 2002)
*/
class Command
{
private String commandWord;
private String secondWord;
/**
* Create a command object. First and second word
must be supplied, but
* either one (or both) can be null. The command
word should be null to
* indicate that this was a command that is not
recognised by this game.
*/
public Command(String firstWord, String secondWord)
{
commandWord = firstWord;
this.secondWord = secondWord;
}
/**
* Return the command word (the first word) of this
command. If the
* command was not understood, the result is null.
*/
public String getCommandWord()
{
return commandWord;
}
/**
* Return the second word of this command. Returns
null if there was no
* second word.
*/
public String getSecondWord()
{
return secondWord;
}
/**
* Return true if this command was not understood.
*/
public boolean isUnknown()
{
return (commandWord == null);
}
/**
* Return true if the command has a second word.
*/
public boolean hasSecondWord()
{
return (secondWord != null);
}
}
2. 2 / 7
/*
* This class is the main class of the "World of Zuul"
application.
* "World of Zuul" is a very simple, text based
adventure game.
*
* This class holds an enumeration of all command words
known to the game.
* It is used to recognise commands as they are typed
in.
*
* @author Michael Kolling and David J. Barnes
* @version 1.0 (February 2002)
*/
class CommandWords
{
// a constant array that holds all valid command
words
private static final String validCommands[] = {
"go", "quit", "help", "look"
};
/**
* Constructor - initialise the command words.
*/
public CommandWords()
{
// nothing to do at the moment...
}
/**
* Check whether a given String is a valid command
word.
* Return true if it is, false if it isn't.
*/
public boolean isCommand(String aString)
{
for(int i = 0; i < validCommands.length; i++) {
if(validCommands[i].equals(aString))
return true;
}
// if we get here, the string was not found in
the commands
return false;
}
}
3. 3 / 7
/**
* This class is the main class of the "World of Zuul"
application.
* "World of Zuul" is a very simple, text based
adventure game. Users
* can walk around some scenery. That's all. It should
really be extended
* to make it more interesting!
*
* To play this game, create an instance of this class
and call the "play"
* method.
*
* This main class creates and initialises all the
others: it creates all
* rooms, creates the parser and starts the game. It
also evaluates and
* executes the commands that the parser returns.
*
* @author Michael Kolling and David J. Barnes
* @version 1.0 (February 2002)
*/
class Game
{
private Parser parser;
private Room currentRoom;
/**
* Create the game and initialise its internal map.
*/
public Game()
{
createRooms();
parser = new Parser();
}
/**
* Create all the rooms and link their exits
together.
*/
private void createRooms()
{
Room outside, theatre, pub, lab, office;
// create the rooms
outside = new Room("outside the main entrance
of the university");
theatre = new Room("in a lecture theatre");
pub = new Room("in the campus pub");
lab = new Room("in a computing lab");
office = new Room("in the computing admin
office");
// initialise room exits
outside.setExits(null, theatre, lab, pub);
theatre.setExits(null, null, null, outside);
pub.setExits(null, outside, null, null);
lab.setExits(outside, office, null, null);
office.setExits(null, null, null, lab);
currentRoom = outside; // start game outside
}
/**
* Main play routine. Loops until end of play.
*/
public void play()
{
printWelcome();
// Enter the main command loop. Here we
repeatedly read commands and
// execute them until the game is over.
boolean finished = false;
while (! finished) {
Command command = parser.getCommand();
finished = processCommand(command);
}
System.out.println("Thank you for playing.
Good bye.");
}
/**
* Print out the opening message for the player.
*/
private void printWelcome()
{
System.out.println();
4. 4 / 7
System.out.println("Welcome to Adventure!");
System.out.println("Adventure is a new,
incredibly boring adventure game.");
System.out.println("Type 'help' if you need
help.");
System.out.println();
System.out.println("You are " +
currentRoom.getDescription());
System.out.print("Exits: ");
if(currentRoom.northExit != null)
System.out.print("north ");
if(currentRoom.eastExit != null)
System.out.print("east ");
if(currentRoom.southExit != null)
System.out.print("south ");
if(currentRoom.westExit != null)
System.out.print("west ");
System.out.println();
}
/**
* Given a command, process (that is: execute) the
command.
* If this command ends the game, true is returned,
otherwise false is
* returned.
*/
private boolean processCommand(Command command)
{
boolean wantToQuit = false;
if(command.isUnknown()) {
System.out.println("I don't know what you
mean...");
return false;
}
String commandWord = command.getCommandWord();
if (commandWord.equals("help"))
printHelp();
else if (commandWord.equals("go"))
goRoom(command);
else if (commandWord.equals("quit"))
wantToQuit = quit(command);
return wantToQuit;
}
// implementations of user commands:
/**
* Print out some help information.
* Here we print some stupid, cryptic message and a
list of the
* command words.
*/
private void printHelp()
{
System.out.println("You are lost. You are
alone. You wander");
System.out.println("around at the
university.");
System.out.println();
System.out.println("Your command words are:");
System.out.println(" go quit help");
}
/**
* Try to go to one direction. If there is an exit,
enter
* the new room, otherwise print an error message.
*/
private void goRoom(Command command)
{
if(!command.hasSecondWord()) {
// if there is no second word, we don't
know where to go...
System.out.println("Go where?");
return;
}
String direction = command.getSecondWord();
// Try to leave current room.
Room nextRoom = null;
if(direction.equals("north"))
nextRoom = currentRoom.northExit;
if(direction.equals("east"))
nextRoom = currentRoom.eastExit;
if(direction.equals("south"))
5. 5 / 7
nextRoom = currentRoom.southExit;
if(direction.equals("west"))
nextRoom = currentRoom.westExit;
if (nextRoom == null)
System.out.println("There is no door!");
else {
currentRoom = nextRoom;
System.out.println("You are " +
currentRoom.getDescription());
System.out.print("Exits: ");
if(currentRoom.northExit != null)
System.out.print("north ");
if(currentRoom.eastExit != null)
System.out.print("east ");
if(currentRoom.southExit != null)
System.out.print("south ");
if(currentRoom.westExit != null)
System.out.print("west ");
System.out.println();
}
}
/**
* "Quit" was entered. Check the rest of the
command to see
* whether we really quit the game. Return true, if
this command
* quits the game, false otherwise.
*/
private boolean quit(Command command)
{
if(command.hasSecondWord()) {
System.out.println("Quit what?");
return false;
}
else
return true; // signal that we want to
quit
}
}
6. 6 / 7
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.util.StringTokenizer;
/*
* This class is the main class of the "World of Zuul"
application.
* "World of Zuul" is a very simple, text based
adventure game.
*
* This parser reads user input and tries to interpret
it as an "Adventure"
* command. Every time it is called it reads a line
from the terminal and
* tries to interpret the line as a two word command.
It returns the command
* as an object of class Command.
*
* The parser has a set of known command words. It
checks user input against
* the known commands, and if the input is not one of
the known commands, it
* returns a command object that is marked as an
unknown command.
*
* @author Michael Kolling and David J. Barnes
* @version 1.0 (February 2002)
*/
class Parser
{
private CommandWords commands; // holds all valid
command words
public Parser()
{
commands = new CommandWords();
}
public Command getCommand()
{
String inputLine = ""; // will hold the full
input line
String word1;
String word2;
System.out.print("> "); // print prompt
BufferedReader reader =
new BufferedReader(new
InputStreamReader(System.in));
try {
inputLine = reader.readLine();
}
catch(java.io.IOException exc) {
System.out.println ("There was an error
during reading: "
+ exc.getMessage());
}
StringTokenizer tokenizer = new
StringTokenizer(inputLine);
if(tokenizer.hasMoreTokens())
word1 = tokenizer.nextToken(); // get
first word
else
word1 = null;
if(tokenizer.hasMoreTokens())
word2 = tokenizer.nextToken(); // get
second word
else
word2 = null;
// note: we just ignore the rest of the input
line.
// Now check whether this word is known. If so,
create a command
// with it. If not, create a "null" command
(for unknown command).
if(commands.isCommand(word1))
return new Command(word1, word2);
else
return new Command(null, word2);
}
}
7. 7 / 7
/*
* Class Room - a room in an adventure game.
*
* This class is the main class of the "World of Zuul"
application.
* "World of Zuul" is a very simple, text based
adventure game.
*
* A "Room" represents one location in the scenery of
the game. It is
* connected to other rooms via exits. The exits are
labelled north,
* east, south, west. For each direction, the room
stores a reference
* to the neighboring room, or null if there is no exit
in that direction.
*
* @author Michael Kolling and David J. Barnes
* @version 1.0 (February 2002)
*/
class Room
{
public String description;
public Room northExit;
public Room southExit;
public Room eastExit;
public Room westExit;
/**
* Create a room described "description".
Initially, it has
* no exits. "description" is something like "a
kitchen" or
* "an open court yard".
*/
public Room(String description)
{
this.description = description;
}
/**
* Define the exits of this room. Every direction
either leads
* to another room or is null (no exit there).
*/
public void setExits(Room north, Room east, Room
south, Room west)
{
if(north != null)
northExit = north;
if(east != null)
eastExit = east;
if(south != null)
southExit = south;
if(west != null)
westExit = west;
}
/**
* Return the description of the room (the one that
was defined
* in the constructor).
*/
public String getDescription()
{
return description;
}
}