file_id
stringlengths 4
9
| content
stringlengths 146
15.9k
| repo
stringlengths 9
113
| path
stringlengths 6
76
| token_length
int64 34
3.46k
| original_comment
stringlengths 14
2.81k
| comment_type
stringclasses 2
values | detected_lang
stringclasses 1
value | excluded
bool 1
class | file-tokens-Qwen/Qwen2-7B
int64 30
3.35k
| comment-tokens-Qwen/Qwen2-7B
int64 3
624
| file-tokens-bigcode/starcoder2-7b
int64 34
3.46k
| comment-tokens-bigcode/starcoder2-7b
int64 3
696
| file-tokens-google/codegemma-7b
int64 36
3.76k
| comment-tokens-google/codegemma-7b
int64 3
684
| file-tokens-ibm-granite/granite-8b-code-base
int64 34
3.46k
| comment-tokens-ibm-granite/granite-8b-code-base
int64 3
696
| file-tokens-meta-llama/CodeLlama-7b-hf
int64 36
4.12k
| comment-tokens-meta-llama/CodeLlama-7b-hf
int64 3
749
| excluded-based-on-tokenizer-Qwen/Qwen2-7B
bool 2
classes | excluded-based-on-tokenizer-bigcode/starcoder2-7b
bool 2
classes | excluded-based-on-tokenizer-google/codegemma-7b
bool 2
classes | excluded-based-on-tokenizer-ibm-granite/granite-8b-code-base
bool 2
classes | excluded-based-on-tokenizer-meta-llama/CodeLlama-7b-hf
bool 2
classes | include-for-inference
bool 2
classes |
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
19761_24 | package Entities;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
/**
* This is the class used to define a Movie Object and it's methods.
* @author Koh Ming En
* @version 1.0
* @since 2022-11-02
*/
public class Movie {
/**
* Title of the Movie
*/
private String movieTitle;
/**
* Status of the Showing
*/
private String showingStatus;
/**
* Synopsis of the Movie
*/
private String synopsis;
/**
* Age Rating of Movie
*/
private AgeRating ageRating;
/**
* Director of Movie
*/
private String director;
/**
* List of Casts
*/
private String[] cast;
/**
* Duration of Movie
*/
private int duration;
/**
* Reviews Array
*/
private ArrayList<Review> reviews;
/**
* Overall Rating of Movie
*/
private float overallRating;
/**
* Total Sales of Movie
*/
private int totalSales;
/**
* Constructor of the Movie
* @param movieTitle name of movie
* @param showingStatus showing status of movie
* @param synopsis synopsis of movie
* @param ageRating age rating of movie
* @param director director of movie
* @param cast all casts of movie
* @param duration duration of movie
* @param reviews all reviews of movie
* @param overallRating overall rating of movie
* @param totalSales total bookings of movie
*/
public Movie(String movieTitle, String showingStatus, String synopsis, AgeRating ageRating, String director, String[] cast, int duration, ArrayList<Review> reviews, float overallRating, int totalSales) {
this.movieTitle = movieTitle;
this.showingStatus = showingStatus;
this.synopsis = synopsis;
this.ageRating = ageRating;
this.director = director;
this.cast = cast;
this.duration = duration;
this.reviews = reviews;
this.overallRating = overallRating;
this.totalSales = totalSales;
}
/**
* This is a getter function for retrieving Movie Title.
* @return Movie Title
*/
public String getMovieTitle() {
return this.movieTitle;
}
/**
* This is a setter function for setting Movie Title.
* @param movieTitle name of movie
*/
public void setMovieTitle(String movieTitle) {
this.movieTitle = movieTitle;
}
/**
* This is a getter function for retrieving Showing Status.
* @return Showing Status
*/
public String getShowingStatus() {
return this.showingStatus;
}
/**
* This is a setter function for setting Showing Status.
* @param showingStatus showing status of movie
*/
public void setShowingStatus(String showingStatus) {
this.showingStatus = showingStatus;
}
/**
* This is a getter function for retrieving Sypnosis.
* @return Synopsis
*/
public String getSynopsis() {
return this.synopsis;
}
/**
* This is a setter function for setting Sypnosis.
* @param synopsis synopsis of movie
*/
public void setSynopsis(String synopsis) {
this.synopsis = synopsis;
}
/**
* This is a getter function for retrieving Age Rating.
* @return Age Rating
*/
public AgeRating getAgeRating() {
return this.ageRating;
}
/**
* This is a setter function for setting Age Rating.
* @param ageRating age rating of movie
*/
public void setAgeRating(AgeRating ageRating) {
this.ageRating = ageRating;
}
/**
* This is a getter function for retrieving Director of the movie.
* @return Director of Movie
*/
public String getDirector() {
return this.director;
}
/**
* This is a setter function for setting director of movie.
* @param director director of movie
*/
public void setDirector(String director) {
this.director = director;
}
/**
* This is a getter function for retrieving all casts (string) of the movie.
* @param attributeDelimiter delimiter for joining casts
* @return Casts of the Movie
*/
public String getCast(String attributeDelimiter) {
return String.join(attributeDelimiter, cast);
}
/**
* This is a getter function for retrieving all the casts (object) of the movie.
* @return Arraylist of Casts
*/
public List<String> getAllCast() {
return Arrays.asList(cast);
}
/**
* This is a setter function for setting the casts.
* @param cast all cast members of movie
*/
public void setCast(List<String> cast) {
this.cast = cast.toArray(new String[0]);
}
/**
* This is a getter function for retrieving the duration of the movie.
* @return Duration of Movie
*/
public int getDuration() {
return this.duration;
}
/**
* This is a setter function for setting duration.
* @param duration length of movie
*/
public void setDuration(int duration) {
this.duration = duration;
}
/**
* This is a getter function for retrieving Reviews (string) of the movie.
* @param delimiter delimiter for joining to other movie details
* @param attributeDelimiter delimiter for joining reviews
* @return Reviews in a string format
*/
public String getReviews(String delimiter, String attributeDelimiter) {
String s = delimiter;
for (Review r : reviews) {
s += r.toString(attributeDelimiter) + delimiter;
}
return s.substring(0, s.length() - 3);
}
/**
* This is a getter function for retrieving Reviews (object) of the movie.
* @return Review in a Object format (array)
*/
public ArrayList<Review> getReviewArray() {
return this.reviews;
}
/**
* This function prints all the reviews in console.
*/
public void printReviews() {
for (Review r : reviews) {
r.printReview();
}
}
/**
* This function prints reviews of a individual based on phone number.
* @param phoneNumber phone number of person checking his review of this movie
*/
public void printReviews(int phoneNumber) {
for (Review r : reviews) {
if (r.getPhoneNumber() == phoneNumber) {
r.printReview();
return;
}
}
System.out.println("No reviews found for " + phoneNumber);
}
/**
* This function checks whether a user has reviews based on a phone number.
* @param phoneNumber phone number of person checking his review of this movie
* @return True/False
*/
public boolean hasReview(int phoneNumber) {
for (Review r : reviews) {
if (r.getPhoneNumber() == phoneNumber) {
return true;
}
}
return false;
}
/**
* This function checks whether this movie has reviews
* @return True/False
*/
public boolean hasReview() {
return reviews.size() > 0;
}
/**
* This is a setter function for setting Reviews.
* @param reviews all reviews of movie
*/
public void setReviews(ArrayList<Review> reviews) {
this.reviews = reviews;
}
/**
* This is a function for adding new reviews.
* @param review new review
*/
public void addReview(Review review) {
overallRating = (overallRating * reviews.size() + review.getRating()) / (reviews.size() + 1);
reviews.add(review);
}
/**
* This is a function for updating a review.
* @param review updated review
*/
public void updateReview(Review review) {
reviews.removeIf(r -> r.getPhoneNumber() == review.getPhoneNumber());
reviews.add(review);
overallRating = 0;
for (Review r : reviews) { overallRating += r.getRating(); }
overallRating /= reviews.size();
}
/**
* This is a getter function for retrieving the overall rating.
* @return Overall Rating
*/
public float getOverallRating() {
return this.overallRating;
}
/**
* This is a setter function for setting Overall Rating.
* @param overallRating new overall rating
*/
public void setOverallRating(float overallRating) {
this.overallRating = overallRating;
}
/**
* This is a getter function for retrieving Total Sales.
* @return Total Sales
*/
public int getTotalSales() {
return this.totalSales;
}
/**
* This is a function for adding a new sale to the movie.
*/
public void addOneSale() {
this.totalSales += 1;
}
/**
* This is a function for removing a sale from the movie.
*/
public void removeOneSale() {
this.totalSales -= 1;
}
/**
* This function converts the movie object to string and returns a string.
* @param delimiter delimiter for joining movie details
* @param attributeDelimiter delimiter for joining reviews
* @return String of Movie Object
*/
public String toString(String delimiter, String attributeDelimiter) {
String s = movieTitle + delimiter + showingStatus + delimiter + duration + delimiter + ageRating.toString() + delimiter + synopsis + delimiter + director + delimiter + getCast(attributeDelimiter);
if (overallRating >= 0) {
s += delimiter + overallRating;
s += getReviews(delimiter, attributeDelimiter);
}
return s;
}
/**
* This function prints the entire movie object onto console.
*/
public void print() {
System.out.println(""); // print empty line
System.out.println("---------------------------------------------------------");
System.out.println("Movie Title: " + movieTitle + " (" + showingStatus + ")");
System.out.println("---------------------------------------------------------");
System.out.println("Duration: " + duration + " mins");
System.out.println("Age Rating: " + ageRating.toString());
System.out.println("Synopsis: " + synopsis);
System.out.println("Director: " + director);
System.out.println("Cast: " + String.join(", ", cast));
System.out.println("Total Sales: " + totalSales);
if (overallRating >= 1) {
System.out.println("Overall Rating: " + overallRating);
} else {
System.out.println("Overall Rating: N/A");
}
System.out.println("---------------------------------------------------------");
System.out.println("");
}
/**
* This function is used to return the clone of a movie object.
*/
public Movie clone() {
return new Movie(movieTitle, showingStatus, synopsis, ageRating, director, cast, duration, reviews, overallRating, totalSales);
}
}
| MingEn82/MOBLIMA | Entities/Movie.java | 2,493 | /**
* This is a setter function for setting the casts.
* @param cast all cast members of movie
*/ | block_comment | en | false | 2,396 | 27 | 2,493 | 27 | 2,797 | 29 | 2,493 | 27 | 3,067 | 31 | false | false | false | false | false | true |
20325_3 | import java.util.ArrayList;
import java.util.List;
import java.util.*;
//We are Create a One Car Rental System Project Fully based on Concept Of oop's
class Car
{
// declare All Variables Are private To Achieve Encapsulation or Security of Data no Anyone can
//So that no person can change
private String carId;
private String model;
private String brand;
private double basePricePerDay;
private boolean isAvailable;
public Car(String carId,String model,String brand,double basePricePerDay)
{
this.carId=carId;
this.brand=brand;
this.model=model;
this.basePricePerDay=basePricePerDay;
this.isAvailable=isAvailable=true;
}
public String getCarId()
{
return carId;
}
public String getModel()
{
return model;
}
public String getBrand()
{
return brand;
}
//Suppose our car price is 1500 .customerDemand is 3 days car onrent
//This method is calculate the no of days's rent
public double calculatePrice(int rentalDays)
{
return basePricePerDay*rentalDays;
}
//car is Available for rent
public boolean isAvailable()
{
return isAvailable;
}
//carr is not Available for rent
public void rent()
{
isAvailable=false;
}
//Customer return the car and now car is Available for rent
public void returnCar()
{
isAvailable=true;
}
}
class Customer
{
//Name and id of Customer
private String name;
private String customerId;
public Customer(String name,String customerId)
{
this.name=name;
this.customerId=customerId;
}
public String getName()
{
return name;
}
public String getCustomerId()
{
return customerId;
}
}
//rental class
class Rental
{
private Car car;
private Customer customer;
private int days;
public Rental(Car car,Customer customer,int days)
{
this.car=car;
this.customer=customer;
this.days=days;
}
public Car getCar()
{
return car;
}
public Customer getCustomer()
{
return customer;
}
public int getDays()
{
return days;
}
}
class CarRentalSystem
{
//create a list to store car customers detail ,rental
private List<Car> cars;
private List<Customer> customers;
private List<Rental> rentals;
public CarRentalSystem()
{
cars=new ArrayList<>();
customers=new ArrayList<>();
rentals=new ArrayList<>();
}
//Adding new Cars or Customer for rent
public void addCar( Car car)
{
cars.add(car);
}
public void addCustomer( Customer customer)
{
customers.add(customer);
}
// Customer will come to take the car on rent, his details and for how many days will he take the car
public void rentCar(Car car,Customer customer,int days)
{
if(car.isAvailable())
{
//car rent ke liye de di gyi hai
car.rent();
//to hum add kr denge use arraylist me
rentals.add(new Rental(car,customer,days));
}
else
{
System.out.println("Car is not Available for rent");
}
}
//Customer return the car
public void returnCar(Car car)
{
car.returnCar();
Rental rentalToRemove=null;
for (Rental rental:rentals)
{
if(rental.getCar()==car)
{
rentalToRemove=rental;
break;
}
}
//Agr hme car mil gyi to hum rental ko remove kr denge
if(rentalToRemove!=null)
{
rentals.remove(rentalToRemove);
System.out.println("Car Returned SuccessFully");
}
else
{
System.out.println("Car Was not returned");
}
}
//Choice menu And select the car,return car,rent a car,Exit
public void menu()
{
Scanner sc=new Scanner(System.in);
while (true)//iske andr ki statement tab tk chlega jab tk hum exit nhi krte
{
System.out.println("===== Car Rental System =====");
System.out.println("1. Rent a Car");
System.out.println("2. Return a Car");
System.out.println("3. Exit");
System.out.println("Enter Your Choice:");
int choice=sc.nextInt();
sc.nextLine();//Consume new Line
//Customer ko kon si car chye wo Choose krega
if(choice==1)
{
System.out.println("\n== Rent a car ==");
System.out.println("Enter your name:");
String customerName=sc.nextLine();
System.out.println("\n Available Cars:");
for(Car car:cars)
{
if (car.isAvailable())
{
System.out.println(car.getCarId()+"-"+car.getBrand()+"-"+car.getModel());
}
}
System.out.println("\nEnter the Car ID You Want:");
String carId=sc.nextLine();
System.out.println("Enter The NUmber Of Days for Rental:");
int rentalDays=sc.nextInt();
sc.nextLine();//Consume space line
//Create a object of customer and +1 the size of customers size arraylist
//new Customer is Basically create a constructor
Customer newCustomer=new Customer("CUS"+(customers.size()+1),customerName);
addCustomer(newCustomer);
Car selectedCar=null;
for(Car car:cars)
{
if(car.getCarId().equals(carId) && car.isAvailable())
{
selectedCar=car;
break;
}
}
//Agr car null nahi hai uski koi value aa gyi hai to hum uska price calculte krenge no of days ke acc
if(selectedCar!=null)
{
double totalPrice=selectedCar.calculatePrice(rentalDays);
//Rental information of Customer
System.out.println("\n==== Rental Information ====\n");
System.out.println("Customer ID:"+newCustomer.getName());
System.out.println("Car:"+selectedCar.getBrand()+" "+selectedCar.getModel());
System.out.println("Rental days:"+rentalDays);
System.out.printf("Total Price: $%.2f%n", totalPrice);
System.out.println("\nConfirm Rental(Y/N):");
String confirm=sc.nextLine();
if(confirm.equalsIgnoreCase("Y"))
{
rentCar(selectedCar,newCustomer,rentalDays);
System.out.println("\nCar Rented Successfully");
}
else
{
System.out.println("\nRental Canceled");
}
}
else {
System.out.println("\nInvalid car selection or car not available for rent.");
}
}
else if(choice==2)
{
System.out.println("\n== Return a car==\n");
System.out.println("Enter the car ID you Want to Return:");
String carID=sc.nextLine();
Car carToReturn=null;
for(Car car:cars)
{
if(car.getCarId().equals(carID) && !car.isAvailable())
{
carToReturn=car;
break;
}
}
if (carToReturn != null) {
Customer customer = null;
for (Rental rental : rentals) {
if (rental.getCar() == carToReturn) {
customer = rental.getCustomer();
break;
}
}
if (customer != null) {
returnCar(carToReturn);
System.out.println("Car returned successfully by " + customer.getName());
} else {
System.out.println("Car was not rented or rental information is missing.");
}
}
else
{
System.out.println("Invalid car ID or car is not rented.");
}
}
// Select This Choice Exit to Car rental System
else if (choice==3)
{
break;
}
else
{
System.out.println("invalid choice Please Enter valid Option");
}
}
System.out.println("\nThanks for using Rental system");
}
}
//Main Class
public class Main {
public static void main(String[] args)
{
//Create a object of a CarRentalSystem Class
CarRentalSystem obj=new CarRentalSystem();
//Create a object of Cars
Car car1=new Car("C001","Toyota","cannery",60.0);
Car car2=new Car("C002","Honda","Accord",80.0);
Car car3=new Car("C003","mahindra","Thar",200.0);
//call All Cars By Object
obj.addCar(car1);
obj.addCar(car2);
obj.addCar(car3);
//Calling menu Method
obj.menu();
}
} | Anuragshukla786/Car-Rental-System | Main.java | 2,173 | //Suppose our car price is 1500 .customerDemand is 3 days car onrent | line_comment | en | false | 1,957 | 22 | 2,173 | 22 | 2,345 | 21 | 2,173 | 22 | 2,589 | 24 | false | false | false | false | false | true |
21899_5 | class Id {
String identifier;
void parse() {
Parser.expectedToken(Core.ID);
identifier = Parser.scanner.getID();
Parser.scanner.nextToken();
}
void print() {
System.out.print(identifier);
}
// Returns the string value of the Id
String getString() {
return identifier;
}
// Finds the stored value of the variable
Integer getValue() {
return Executor.getValue(identifier);
}
// Stores the passed value to the variable, used to handle regular assign
void storeValue(int value) {
Executor.storeValue(identifier, value);
}
// Called by assign to handle "class"-assign
void referenceCopy(Id copyFrom) {
Executor.referenceCopy(identifier, copyFrom.getString());
}
// Called by assign to handle "new"-assign
void heapAllocate() {
Executor.heapAllocate(identifier);
}
// Called when declaring an int variable
void executeIntAllocate() {
Executor.allocate(identifier, Core.INT);
}
// Called when declaring a class variable
void executeRefAllocate() {
Executor.allocate(identifier, Core.REF);
}
} | danielwu7777/CSE-3341-Project-4 | Id.java | 295 | // Called when declaring an int variable
| line_comment | en | false | 246 | 8 | 295 | 8 | 328 | 8 | 295 | 8 | 367 | 9 | false | false | false | false | false | true |
21994_2 | import java.io.BufferedReader;
import java.io.FileReader;
import java.util.ArrayList;
import java.io.IOException;
public class Main
{
public static int MAX_CHARGE = 240; // In minutes
public static int END_OF_DAY = 1439; // In minutes
public static String END_OF_LINE = "0 0";
public static void main(String[] args)
{
// Sets buffered reader to null because it allows us to exit the program in the catch
BufferedReader bf = null;
try
{
bf = new BufferedReader(new FileReader(args[0]));
}
catch(IOException e)
{
e.printStackTrace();
return;
}
catch(Exception e)
{
e.printStackTrace();
return;
}
// Reads the file in
ArrayList<String> lines = new ArrayList<String>();
String line = "";
try{
while((line = bf.readLine()) != null)
{
lines.add(line);
}
} catch(IOException e)
{
e.printStackTrace();
return;
}
// Goes to the bottom of the file where the bottom is "0 0"
int index = 0;
while(!lines.get(i).equals("0 0"))
{
String[] currentCase = line.split(" ");
int finalStation = Integer.parseInt(currentCase[0]) - 1;
int travelBlocks = Integer.parseInt(currentCase[1]);
int currentCharge = 240;
ArrayList<Path> paths = new ArrayList<Path>();
for(int i = 0; i < travelBlocks; i++) {
}
}
}
}
private class Path
{
public int start_time;
public int end_time;
public int travel_time;
public Path(String path) {
String[] pathArray = path.split(" ");
start_state = Integer.parseInt(pathArray[0]);
end_state = Integer.parseInt(pathArray[1]);
travel_time = Integer.parseInt(pathArray[2])
}
}
| fnk0/Electrocar | Main.java | 512 | // Sets buffered reader to null because it allows us to exit the program in the catch | line_comment | en | false | 414 | 17 | 512 | 17 | 551 | 17 | 512 | 17 | 601 | 19 | false | false | false | false | false | true |
22048_11 | import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.InputStreamReader;
import static java.lang.System.exit;
import java.util.regex.Pattern;
/**
*
* @author wangjs
*/
//This class is used to read each char and get the tokens
public class Lexer {
//Encoding format
private String encoding;
//File path
private String path;
//Directory path
private static String folderPath;
//File object
private File file;
//Variable used to store the line number
private int lineNumber;
//String variable used to store the text content stored in the source code file
private String textContent;
//Variable used to store the index used to record which characters have been accessed
private int index;
//Variable used to control whether the line number is needed to be increased
public static boolean newLineCheck = true;
//Constructor for initializing the lexer when parser needs to traverse the tokens from specific file
public Lexer(String fileName) {
encoding = "GBK";
path = folderPath + File.separator + fileName;
file = new File(path);
textContent = "";
lineNumber = 1;
index = 0;
}
//Constructor for initializing the lexer when file is read from the specific directory
public Lexer(String folderPath, String fileName) {
encoding = "GBK";
this.folderPath = folderPath;
path = folderPath + file.separator + fileName;
file = new File(path);
textContent = "";
lineNumber = 1;
index = 0;
}
//Read the source code from the file into the program
public void initLocalFile() {
try {
//String variable used to store the source codes
textContent = "";
//Check whether the file read is available
if (file.isFile() && file.exists()) {
InputStreamReader read = new InputStreamReader(
new FileInputStream(file), encoding);
BufferedReader bufferedReader = new BufferedReader(read);
String lineText = null;
while ((lineText = bufferedReader.readLine()) != null) {
textContent += (lineText + "\\n");
}
read.close();
} else {
System.out.println("Cannot find the file");
}
} catch (Exception e) {
System.out.println("Error: class not exists.");
e.printStackTrace();
}
}
//Method used to get the folder path
public String getFolderPath() {
return folderPath;
}
//Change the index used to record the number of characters which have been read already
public void setReadIndex(int value) {
index = value;
}
//Method used to return the current index for recording the number of characters which have been read already
public int getReadIndex() {
return index;
}
//Method used to return the source codes
public String getTextContent() {
return textContent;
}
//Method used to create the error information when the format of comments are not suitable
private void error(String errorInfor) {
System.out.printf("%s", errorInfor);
exit(0);
}
//Method used to operate the token exactly
private Token TokenOperation(String operationType) {
Token token = new Token();
String TokenName = "";
Pattern pattern = Pattern.compile("^[-\\+]?[\\d]+$");
while (index < textContent.length() - 2) {
if (textContent.charAt(index) == ' ') {
index++;
continue;
} else if (Character.isLowerCase(textContent.charAt(index))
|| Character.isUpperCase(textContent.charAt(index))
|| Character.isDigit(textContent.charAt(index))) {
TokenName += textContent.charAt(index);
index++;
if (index < textContent.length()
&& !Character.isLowerCase(textContent.charAt(index))
&& !Character.isUpperCase(textContent.charAt(index))
&& !Character.isDigit(textContent.charAt(index))) {
break;
}
} else {
TokenName += textContent.charAt(index);
TokenName = TokenName.trim();
index++;
if (token.Symbols.containsKey(TokenName)) {
if (TokenName.startsWith("/")) {
if (TokenName.equals("/")) {
if (Character.isLowerCase(textContent.charAt(index))
|| Character.isUpperCase(textContent.charAt(index))
|| Character.isDigit(textContent.charAt(index))
|| textContent.charAt(index) == ' ') {
break;
} else {
continue;
}
} else if (TokenName.equals("//") || TokenName.equals("/*")) {
if (TokenName.equals("/*")) {
if (textContent.indexOf("*/", index) == -1) {
error("Error: comment doesn't have the end symbol, line: " + lineNumber);
}
String comment = textContent.substring(index,
textContent.indexOf("*/", index));
String[] comment_s = comment.split("\\\\n");
lineNumber += comment_s.length - 1;
TokenName += comment + "*/";
index = textContent.indexOf("*/", index) + 2;
TokenName = "";
continue;
} else {
Token com_token = new Token();
String comment = textContent.substring(index,
textContent.indexOf("\\n", index));
TokenName += comment;
index = textContent.indexOf("\\n", index);
TokenName = "";
continue;
}
}
} else if (TokenName.startsWith("\"")) {
Token string_token = new Token();
int i = textContent.indexOf("\"", index);
if (i > 0) {
TokenName += textContent.substring(index, i + 1);
string_token.setToken(TokenName,
string_token.Type.String, lineNumber);
index = i + 1;
TokenName = "";
return string_token;
}
break;
} else {
break;
}
} else {
if (TokenName.startsWith("\\")) {
if (textContent.charAt(index) == 'n') {
if (newLineCheck && operationType.equals("get")) {
lineNumber++;
}
TokenName = "";
index++;
continue;
}
}
}
}
}
//Identify the type of the token and return the token
if (!TokenName.equals("")) {
TokenName = TokenName.trim();
while (true) {
if (token.Symbols.containsKey(TokenName)) {
token.setToken(TokenName, token.Type.Symbol, lineNumber);
break;
} else {
for (String keyword : token.Keywords) {
if (keyword.equals(TokenName)) {
token.setToken(TokenName, token.Type.Keyword, lineNumber);
}
}
if (token.Token != "") {
break;
}
}
if (pattern.matcher(TokenName).matches()) {
token.setToken(TokenName, token.Type.Constant, lineNumber);
break;
} else {
token.setToken(TokenName, token.Type.ID, lineNumber);
break;
}
}
}
return token;
}
//Get the next token from the source code and move the index
public Token GetNextToken() {
return TokenOperation("get");
}
//Peek the next token but not move the index
public Token PeekNextToken() {
int OldIndex = index;
Token token = TokenOperation("peek");
index = OldIndex;
return token;
}
}
| wangjs96/A-tutorial-compiler-written-in-Java | Lexer.java | 1,711 | //Constructor for initializing the lexer when file is read from the specific directory
| line_comment | en | false | 1,567 | 15 | 1,711 | 15 | 1,919 | 15 | 1,711 | 15 | 2,154 | 17 | false | false | false | false | false | true |
22527_9 | public class Set {
// Represent a set of nonnegative ints from 0 to maxElement-1
// for some initially specified maxElement.
// contains[k] is true if k is in the set, false if it isn't
private boolean[] contains;
// Initialize a set of ints from 0 to maxElement-1.
public Set (int maxElement) {
contains = new boolean[maxElement];
}
// precondition: 0 <= k < maxElement.
// postcondition: k is in this set.
public void insert (int k) {
contains[k] = true;
}
// precondition: 0 <= k < maxElement.
// postcondition: k is not in this set.
public void remove (int k) {
contains[k] = false;
}
// precondition: 0 <= k < maxElement
// Return true if k is in this set, false otherwise.
public boolean member (int k) {
if (contains[k]) {
return true;
}
return false;
}
// Return true if this set is empty, false otherwise.
public boolean isEmpty() {
for (int i = 0; i < contains.length; i++) {
if (contains[i] != false) {
return false;
}
}
return true;
}
}
| charleslee94/61BL | Set.java | 327 | // Return true if k is in this set, false otherwise. | line_comment | en | false | 292 | 13 | 327 | 13 | 353 | 13 | 327 | 13 | 369 | 13 | false | false | false | false | false | true |
22555_2 | /**
* From "Subtyping, Sublcassing, and Trouble with OOP"
* http://okmij.org/ftp/Computation/Subtyping
*/
/**
* <code>SetV</code> implements an immutable set.
*/
public class SetV extends BagV
{
/**
* Test whether an element is a member of this set
*/
public boolean memberOf(final Integer elem)
{
return count(elem) > 0;
}
/**
* Put an element into this set
* Overrides SetV::put
*/
@Override
public SetV put(final Integer elem)
{
if (!memberOf(elem))
{
return (SetV) super.put(elem);
}
else
{
return this;
}
}
/**
* Make a copy of this set
*/
public SetV clone()
{
return this;
}
}
| asicsdigital/jbag | SetV.java | 207 | /**
* Test whether an element is a member of this set
*/ | block_comment | en | false | 194 | 16 | 207 | 15 | 228 | 17 | 207 | 15 | 247 | 17 | false | false | false | false | false | true |
23147_2 | class RandomizedSet {
Map<Integer,Integer> map;
List<Integer> list;
Random rand;
/** Initialize your data structure here. */
public RandomizedSet() {
map = new HashMap<>();
list = new ArrayList<>();
rand = new Random();
}
/** Inserts a value to the set. Returns true if the set did not already contain the specified element. */
public boolean insert(int val) {
if(map.containsKey(val)) return false;
map.put(val,list.size());
list.add(val);
return true;
}
/** Removes a value from the set. Returns true if the set contained the specified element. */
public boolean remove(int val) {
if(!map.containsKey(val)) return false;
int i = map.get(val);
int d = list.get(list.size()-1);
list.set(i,d);
map.put(d,i);
map.remove(val);
list.remove(list.size()-1);
return true;
}
/** Get a random element from the set. */
public int getRandom() {
return list.get(rand.nextInt(list.size()));
}
}
/**
* Your RandomizedSet object will be instantiated and called as such:
* RandomizedSet obj = new RandomizedSet();
* boolean param_1 = obj.insert(val);
* boolean param_2 = obj.remove(val);
* int param_3 = obj.getRandom();
*/ | fztfztfztfzt/leetcode | 380.java | 341 | /** Removes a value from the set. Returns true if the set contained the specified element. */ | block_comment | en | false | 292 | 19 | 341 | 19 | 371 | 19 | 341 | 19 | 389 | 21 | false | false | false | false | false | true |
23176_2 | public class RandomizedCollection
{
Map<Integer, Set<Integer>> p;
Map<Integer, Integer> q;
/** Initialize your data structure here. */
RandomizedCollection()
{
p = new HashMap<>();
q = new HashMap<>();
}
/** Inserts a value to the collection. Returns true if the collection did not already
contain the specified element. */
public boolean insert(int val)
{
int n = q.size();
q.put(n + 1, val);
if(p.containsKey(val))
{
p.get(val).add(n + 1);
return false;
}
else
{
Set<Integer> t = new HashSet<>();
t.add(n + 1);
p.put(val, t);
return true;
}
}
/** Remove a value from the collection. Returns true if the colletion contained
the specified element. */
public boolean remove(int val)
{
if(p.containsKey(val))
{
Set<Integer> t = p.get(val);
int toRemove = t.iterator().next();
t.remove(toRemove);
if(t.size() == 0)
p.remove(val);
if(toRemove == q.size())
{
q.remove(toRemove);
return true;
}
int n = q.size();
int x = q.get(n);
Set<Integer> set = p.get(x);
set.remove(n);
set.add(toRemove);
q.remove(n);
q.put(toRemove, x);
return true;
}
else
return false;
}
/** Get a random element from the collection. */
public int getRandom()
{
if(q.size() == 0)
return -1;
return q.get(new Random().nextInt(q.size()) + 1);
}
} | CodeWithJava/SeventhRound | 381.java | 497 | /** Remove a value from the collection. Returns true if the colletion contained
the specified element. */ | block_comment | en | false | 385 | 22 | 497 | 21 | 499 | 23 | 497 | 21 | 591 | 24 | false | false | false | false | false | true |
24052_21 | /*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package policepartner;
import com.sun.org.apache.bcel.internal.generic.Select;
import java.awt.HeadlessException;
import static java.lang.ProcessBuilder.Redirect.from;
import java.sql.*;
import javax.swing.JOptionPane;
/**
*
* @author Gaurav Sachdeva
*/
public class officer extends javax.swing.JFrame {
/**
* Creates new form officer
*/
public officer() {
initComponents();
}
/**
* This method is called from within the constructor to initialize the form.
* WARNING: Do NOT modify this code. The content of this method is always
* regenerated by the Form Editor.
*/
@SuppressWarnings("unchecked")
// <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
private void initComponents() {
jPanel1 = new javax.swing.JPanel();
jLabel1 = new javax.swing.JLabel();
jLabel2 = new javax.swing.JLabel();
jLabel3 = new javax.swing.JLabel();
jLabel4 = new javax.swing.JLabel();
jTextField1 = new javax.swing.JTextField();
jComboBox1 = new javax.swing.JComboBox<>();
jLabel5 = new javax.swing.JLabel();
jPasswordField1 = new javax.swing.JPasswordField();
jButton1 = new javax.swing.JButton();
setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
jPanel1.setBackground(new java.awt.Color(153, 255, 204));
jPanel1.setBorder(javax.swing.BorderFactory.createTitledBorder(javax.swing.BorderFactory.createBevelBorder(javax.swing.border.BevelBorder.RAISED), "OFFICER'S LOGIN", javax.swing.border.TitledBorder.DEFAULT_JUSTIFICATION, javax.swing.border.TitledBorder.DEFAULT_POSITION, new java.awt.Font("Constantia", 1, 24))); // NOI18N
jLabel1.setBackground(new java.awt.Color(255, 255, 102));
jLabel1.setFont(new java.awt.Font("Times New Roman", 1, 14)); // NOI18N
jLabel1.setText("*Only for Police Officers");
jLabel2.setFont(new java.awt.Font("Times New Roman", 1, 18)); // NOI18N
jLabel2.setText("Name : ");
jLabel3.setFont(new java.awt.Font("Times New Roman", 1, 18)); // NOI18N
jLabel3.setText("Designation : ");
jLabel4.setFont(new java.awt.Font("Times New Roman", 1, 18)); // NOI18N
jLabel4.setText("Password : ");
jComboBox1.setFont(new java.awt.Font("Times New Roman", 1, 18)); // NOI18N
jComboBox1.setModel(new javax.swing.DefaultComboBoxModel<>(new String[] { "DGP", "ADGP", "DIGP", "SSP", "SP", "ASP", "DSP" }));
jLabel5.setFont(new java.awt.Font("Times New Roman", 1, 11)); // NOI18N
jLabel5.setText("*If any officer rank is not mentioned here he/she is not allowed to access the information ");
jButton1.setFont(new java.awt.Font("Times New Roman", 1, 18)); // NOI18N
jButton1.setForeground(new java.awt.Color(255, 0, 0));
jButton1.setText("LOGIN");
jButton1.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jButton1ActionPerformed(evt);
}
});
javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1);
jPanel1.setLayout(jPanel1Layout);
jPanel1Layout.setHorizontalGroup(
jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel1Layout.createSequentialGroup()
.addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel1Layout.createSequentialGroup()
.addGap(90, 90, 90)
.addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jLabel1)
.addGroup(jPanel1Layout.createSequentialGroup()
.addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
.addComponent(jLabel2)
.addComponent(jLabel3)
.addComponent(jLabel4))
.addGap(44, 44, 44)
.addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jTextField1, javax.swing.GroupLayout.PREFERRED_SIZE, 364, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGroup(jPanel1Layout.createSequentialGroup()
.addComponent(jComboBox1, javax.swing.GroupLayout.PREFERRED_SIZE, 172, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(jLabel5))
.addComponent(jPasswordField1, javax.swing.GroupLayout.PREFERRED_SIZE, 368, javax.swing.GroupLayout.PREFERRED_SIZE)))))
.addGroup(jPanel1Layout.createSequentialGroup()
.addGap(359, 359, 359)
.addComponent(jButton1)))
.addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
);
jPanel1Layout.setVerticalGroup(
jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel1Layout.createSequentialGroup()
.addGap(94, 94, 94)
.addComponent(jLabel1)
.addGap(66, 66, 66)
.addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
.addComponent(jLabel5)
.addGroup(jPanel1Layout.createSequentialGroup()
.addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jLabel2)
.addComponent(jTextField1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGap(43, 43, 43)
.addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jLabel3)
.addComponent(jComboBox1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))))
.addGap(47, 47, 47)
.addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
.addComponent(jLabel4, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(jPasswordField1))
.addGap(66, 66, 66)
.addComponent(jButton1)
.addContainerGap(72, Short.MAX_VALUE))
);
javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
getContentPane().setLayout(layout);
layout.setHorizontalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jPanel1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
);
layout.setVerticalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jPanel1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
);
pack();
}// </editor-fold>//GEN-END:initComponents
private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton1ActionPerformed
try{
Class.forName("oracle.jdbc.driver.OracleDriver");
Connection con=DriverManager.getConnection( "jdbc:oracle:thin:@localhost:1521:xe","sachdeva","1234");
String Name=jTextField1.getText();
String Designation=jComboBox1.getSelectedItem().toString();
String pass=jPasswordField1.getText();
PreparedStatement pst=con.prepareCall("Select * from officer where Name=?,Designation=?,Password=?");
ResultSet rs=pst.executeQuery();
if(rs.next())
{
JOptionPane.showMessageDialog(rootPane, " LOGIN Successful ");
new fetch().setVisible(true);
dispose();
}
else
{
JOptionPane.showMessageDialog(rootPane, " LOGIN Denied ");
}
}catch(ClassNotFoundException | SQLException | HeadlessException e)
{
JOptionPane.showMessageDialog(rootPane,e);
}
}//GEN-LAST:event_jButton1ActionPerformed
/**
* @param args the command line arguments
*/
public static void main(String args[]) {
/* Set the Nimbus look and feel */
//<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
/* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
* For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html
*/
try {
for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
if ("Nimbus".equals(info.getName())) {
javax.swing.UIManager.setLookAndFeel(info.getClassName());
break;
}
}
} catch (ClassNotFoundException ex) {
java.util.logging.Logger.getLogger(officer.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (InstantiationException ex) {
java.util.logging.Logger.getLogger(officer.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (IllegalAccessException ex) {
java.util.logging.Logger.getLogger(officer.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (javax.swing.UnsupportedLookAndFeelException ex) {
java.util.logging.Logger.getLogger(officer.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
}
//</editor-fold>
/* Create and display the form */
java.awt.EventQueue.invokeLater(new Runnable() {
public void run() {
new officer().setVisible(true);
}
});
}
// Variables declaration - do not modify//GEN-BEGIN:variables
private javax.swing.JButton jButton1;
private javax.swing.JComboBox<String> jComboBox1;
private javax.swing.JLabel jLabel1;
private javax.swing.JLabel jLabel2;
private javax.swing.JLabel jLabel3;
private javax.swing.JLabel jLabel4;
private javax.swing.JLabel jLabel5;
private javax.swing.JPanel jPanel1;
private javax.swing.JPasswordField jPasswordField1;
private javax.swing.JTextField jTextField1;
// End of variables declaration//GEN-END:variables
}
| grvsachdeva/Delhi-Police-Partner | officer.java | 2,657 | /* Create and display the form */ | block_comment | en | false | 2,099 | 7 | 2,657 | 7 | 2,793 | 7 | 2,657 | 7 | 3,362 | 7 | false | false | false | false | false | true |
24063_3 | /**
* 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)
**/
import java.util.ArrayList;
class Game
{
private Parser parser;
private Room currentRoom;
Room outside, theatre, pub, lab, office, onetwenty, library, cafeteria, parkinglot, gymnasium, field, lockerroom, portables, auditorium, studio, office2, home;
ArrayList<Item> inventory = new ArrayList<Item>();
/**
* 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()
{
// 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");
onetwenty = new Room("in the coolest place in the world");
library = new Room("in the Library. No one is here");
cafeteria = new Room("in the cafeteria");
parkinglot = new Room("in the parking lot");
gymnasium = new Room("in the gymnasium");
field = new Room("in the field");
lockerroom = new Room("in the locker room");
portables = new Room("in the portables");
auditorium = new Room("in the auditorium");
studio = new Room("in the art studio");
office2 = new Room("in the university main office");
home = new Room("on the way home");
// initialise room exits
outside.setExit("east", theatre);
outside.setExit("south", lab);
outside.setExit("west", pub);
outside.setExit("north", onetwenty);
theatre.setExit("west", outside);
theatre.setExit("south", studio);
theatre.setExit("north", auditorium);
theatre.setExit("east", gymnasium);
pub.setExit("east", outside);
pub.setExit("west", cafeteria);
lab.setExit("north", outside);
lab.setExit("south", office);
office.setExit("north", lab);
onetwenty.setExit("south", outside);
onetwenty.setExit("north", portables);
portables.setExit("south", onetwenty);
portables.setExit("east", field);
studio.setExit("north", theatre);
cafeteria.setExit("east", pub);
cafeteria.setExit("north", library);
library.setExit("south", cafeteria);
field.setExit("east",office2);
field.setExit("west", portables);
auditorium.setExit("south", theatre);
gymnasium.setExit("west", theatre);
gymnasium.setExit("north", lockerroom);
gymnasium.setExit("east", parkinglot);
parkinglot.setExit("west", gymnasium);
parkinglot.setExit("south", home);
lockerroom.setExit("south", gymnasium);
office2.setExit("west", field);
office.setExit("north", lab);
home.setExit("north", parkinglot);
currentRoom = outside; // start game outside
//All the items in their rooms
inventory.add(new Item("computer"));
onetwenty.setItem(new Item("robot"));
lab.setItem(new Item("keyboard"));
office.setItem(new Item("laptop"));
pub.setItem(new Item("bottle"));
cafeteria.setItem(new Item("pizza"));
library.setItem(new Item("book"));
field.setItem(new Item("ball"));
office2.setItem(new Item("phone"));
theatre.setItem(new Item("popcorn"));
studio.setItem(new Item("brush"));
auditorium.setItem(new Item("pamphlet"));
gymnasium.setItem(new Item("towel"));
lockerroom.setItem(new Item("lock"));
parkinglot.setItem(new Item("car"));
}
/**
* 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 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(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")) {
wantToQuit = goRoom(command);
}
else if (commandWord.equals("quit")) {
wantToQuit = quit(command);
}
else if (commandWord.equals("inventory")) {
printInventory();
}
else if (commandWord.equals("get")) {
getItem(command);
}
else if (commandWord.equals("drop")) {
dropItem(command);
}
return wantToQuit;
}
//get item command
private void getItem(Command command) {
if(!command.hasSecondWord()) {
// if there is no second word, we don't know what to pick up...
System.out.println("Get what?");
return;
}
String item = command.getSecondWord();
//Get an item
Item newItem = currentRoom.getItem(item);
if (newItem == null) {
System.out.println("That item is not here!");
}
else {
inventory.add(newItem);
currentRoom.removeItem(item);
System.out.println("Picked up: " + item);
}
}
//drop item command
private void dropItem(Command command) {
if(!command.hasSecondWord()) {
// if there is no second word, we don't know what to drop...
System.out.println("Drop what?");
return;
}
String item = command.getSecondWord();
//Drop an item
Item newItem = null;
int index = 0;
for (int i = 0; i < inventory.size(); i++) {
if (inventory.get(i).getDescription().equals(item)) {
newItem = inventory.get(i);
index = i;
}
}
if (newItem == null) {
System.out.println("That item is not in your inventory!");
}
else {
inventory.remove(index);
currentRoom.setItem(new Item(item));
System.out.println("Dropped: " + item);
}
}
//See whats in inventory
private void printInventory() {
String output = "";
for (int i = 0; i < inventory.size(); i++) {
output += inventory.get(i).getDescription() + " ";
}
System.out.println("You are carrying:");
System.out.println(output);
}
// 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("If you are lost and need help, here is map of the place");
System.out.println("https://docs.google.com/drawings/d/1oG1KxB3yH0X6Bhuim3RcQOgsVhaNhso-t_n2ayu-iT0/edit?usp=sharing");
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 print an error message.
*/
private boolean 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 false;
}
String direction = command.getSecondWord();
// Try to leave current room.
Room nextRoom = currentRoom.getExit(direction);
if (nextRoom == null)
System.out.println("There is no door!");
else {
currentRoom = nextRoom;
System.out.println(currentRoom.getLongDescription());
if (currentRoom == home && inventory.size() == 15) {//Win Condition
System.out.println("You win!");
return true;
}
}
return false;
}
/**
* "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
}
}
| znathan39/JavaProjects | Zuul/Game.java | 2,534 | // create the rooms | line_comment | en | false | 2,271 | 4 | 2,534 | 4 | 2,694 | 4 | 2,534 | 4 | 2,935 | 4 | false | false | false | false | false | true |
24259_5 | package selenium.practice;
import java.util.ArrayList;
import java.util.List;
import java.util.Set;
import java.util.concurrent.TimeUnit;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.interactions.Actions;
import org.openqa.selenium.support.ui.Select;
public class Nykaa {
//Launch Browser
/*
* public void launchBrowser() { public static ChromeDriver driver; }
*/
public static void main(String[] args) {
System.setProperty("webdriver.chrome.driver", "./Drivers/chromedriver.exe");
ChromeDriver driver = new ChromeDriver();
driver.manage().window().maximize();
driver.get("https://www.nykaa.com/");
driver.manage().timeouts().implicitlyWait(30, TimeUnit.SECONDS);
// mousehover on brands
WebElement brandMouseHover = driver.findElementByXPath("//li[@class='menu-dropdown-icon']");
Actions brand = new Actions(driver);
brand.moveToElement(brandMouseHover).perform();
//mousehover on Popular
WebElement popularMouseHover = driver.findElementByXPath("//a[text()='Popular']");
Actions popular = new Actions(driver);
popular.moveToElement(popularMouseHover).perform();
//Click Loreal paris
driver.findElementByXPath("//img[@src='https://adn-static2.nykaa.com/media/wysiwyg/2019/lorealparis.png']").click();
//Switch to new window
Set<String> winSet = driver.getWindowHandles();
List<String> winList = new ArrayList<String>(winSet);
driver.switchTo().window(winList.get(1));
//get Title
String pageTitle = driver.getTitle();
System.out.println(pageTitle);
driver.manage().timeouts().implicitlyWait(30, TimeUnit.SECONDS);
//sort by
driver.findElementByXPath("//i[@class='fa fa-angle-down']").click();
// Select Customer Top rated
driver.findElementByXPath("//span[text()='customer top rated']").click();
// click categories
driver.manage().timeouts().implicitlyWait(30, TimeUnit.SECONDS);
driver.findElementByXPath("//div[text()='Category']").click();
//click Shmapoo
driver.findElementByXPath("//label[@for='chk_Shampoo_undefined']//span[1]").click();
//check if the filter value has selected shampoo
if(driver.findElementByXPath("//li[text()='Shampoo']").isDisplayed())
{
System.out.println("The filtered product is shampoo");
}
// click Color protected
driver.findElementByXPath("//img[@src='https://images-static.nykaa.com/media/catalog/product/tr:w-276,h-276,cm-pad_resize/8/9/8901526102518_color_protect_shampoo_75ml_82.5ml__i1_1.png']").click();
// Switch to new window
Set<String> secondWindow = driver.getWindowHandles();
List<String> windowList = new ArrayList<String>(secondWindow);
driver.switchTo().window(windowList.get(2));
//Select Size as 175 ML
driver.findElementByXPath("//span[text()='175ml']").click();
//Print the MRP
String productMRP = driver.findElementByXPath("//span[text()='MRP:']").getText();
System.out.println("Product Price:" +productMRP);
//add to bag
driver.findElementByXPath("(//button[text()='ADD TO BAG'])[1]").click();
//click shopping bag
driver.findElementByClassName("BagItems").click();
//Print Grand Total
String grandTotal = driver.findElementByXPath("//div[text()='Grand Total:']").getText();
System.out.println("Grand Total:" +grandTotal);
//Click Proceed
driver.findElementByXPath("//span[text()='Proceed']").click();
//Click on Continue as guest
driver.findElementByXPath("//button[text()='CONTINUE AS GUEST']").click();
//Print Warning Message
String warnMessage = driver.findElementByXPath("//div[text()='Please expect delay in shipments because of the national lockdown']").getText();
System.out.println(warnMessage);
//Close Window
driver.quit();
}
}
| soundharya-b/MyLearningSpace | Nykaa.java | 1,110 | //mousehover on Popular | line_comment | en | false | 938 | 5 | 1,110 | 6 | 1,108 | 5 | 1,110 | 6 | 1,375 | 5 | false | false | false | false | false | true |
24344_3 | package org.example;
import java.util.Calendar;
public class Car extends Vehicle{
public Car( String brand,int modelYear) { //Creates a Car object with given brand and model year
super(brand, modelYear);
}
@Override
public void move() { // Displays a message indicating that the car is moving.
System.out.println("Car is moving");
}
public double fuelConsumption(int distance) {
// Calculates the fuel consumption of the car for the given distance
return distance * 0.15;
}
public int lossInValue() {
//Calculates the loss in value of the car.
int K = 1000; // it is a constant value for car.
return (Calendar.getInstance().get(Calendar.YEAR) - getModelYear()) * K;
}
}
| ahmetbekir22/OOP-with-java | Car.java | 189 | //Calculates the loss in value of the car.
| line_comment | en | false | 176 | 12 | 189 | 12 | 210 | 11 | 189 | 12 | 217 | 11 | false | false | false | false | false | true |
24494_26 | package application;
/*
* Software Design and Development: Complex Project Management App
* Developers: Joy Onyerikwu(Lead), Michael Tolitson and Cullen Vaughn
* November 2015, Clarkson Universiy
*/
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.FileWriter;
import java.io.IOException;
import java.io.PrintWriter;
import java.nio.channels.FileChannel;
import javafx.application.Application;
import javafx.application.Platform;
import javafx.stage.FileChooser;
import javafx.stage.Stage;
import javafx.scene.Parent;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.layout.GridPane;
import javafx.scene.layout.HBox;
import javafx.scene.layout.VBox;
import javafx.scene.image.Image;
import javafx.scene.image.ImageView;
public class Main extends Application {
Stage primaryStage = new Stage();
//directory to store gantt charts
private String gantt_dir = "gantt-charts/";
//directory to store excel files
private String excell_dir = "Files/";
private String file_path;
private String chart_name;
//this text file writes the data that matlab needs to read
//it writes the filename, directory and the name that the chart needs to be saved as
File data_file = new File("file_to_open.txt");
FileWriter writer = null;
FileChooser filechooser = new FileChooser();
@Override
public void start(Stage primaryStage) throws InterruptedException, IOException{
//make sure file directories exists
checkDirectories();
//set scene
primaryStage.setScene(new Scene(createDesign()));
primaryStage.setTitle("Complex Project Manager");;
primaryStage.show();
}
public static void main(String[] args) {
launch(args);
}
public Parent createDesign() throws IOException{
//grid pane for application
GridPane grid = new GridPane();
ImageView view = new ImageView();
grid.getStylesheets().add(getClass().getResource("application.css").toExternalForm());
VBox vbox = new VBox();
vbox.setPrefSize(600, 450);
vbox.getStylesheets().add(getClass().getResource("application.css").toExternalForm());
vbox.getStyleClass().add("hbox");
//hbox for buttons
HBox hbox = new HBox(40);
hbox.setPrefSize(30, 30);
Button upload_btn = new Button("Upload Excel File");
Button display_gantt = new Button("Display Existing Chart");
Button import_file = new Button("Add Excel File to Path");
Button close_app = new Button("Close Application");
hbox.getChildren().addAll(upload_btn, display_gantt, import_file, close_app);
//button upload an excel file to calculate
upload_btn.setOnAction(event ->{
try {
selectExcelFile();
runMatlab();
} catch (Exception e) {
e.printStackTrace();
}
//retrieve the recently saved by matlab
Image gantt = new Image(new File(gantt_dir+chart_name).toURI().toString(),600,450,false,false);
//set image to view
view.setImage(gantt);
});
//button to display an existing gantt chart already in the system
display_gantt.setOnAction(event ->{
filechooser.setInitialDirectory(new File(System.getProperty("user.home")));
File imagename = filechooser.showOpenDialog(new Stage());
System.out.println(imagename);
Image image = new Image((imagename).toURI().toString(),600,450,false,false);
//display image
view.setImage(image);
});
//button to import file from a different directory
import_file.setOnAction(event ->{
filechooser.setInitialDirectory(new File(System.getProperty("user.home")));
File original = filechooser.showOpenDialog(new Stage());
File copy = new File(excell_dir + original.getName());
try {
copy.createNewFile();
} catch (Exception e) {
// File could not be created
e.printStackTrace();
}
FileChannel source = null;
FileChannel dest = null;
FileInputStream istream;
FileOutputStream ostream;
try {
istream = new FileInputStream(original);
ostream = new FileOutputStream(copy);
source = istream.getChannel();
dest = ostream.getChannel();
dest.transferFrom(source, 0, source.size());
source.close();
dest.close();
istream.close();
ostream.close();
} catch (Exception e1) {
e1.printStackTrace();
}
});
//button to close application
close_app.setOnAction(event ->{
Platform.exit();
});
vbox.getChildren().add(view);
grid.add(vbox, 1, 0);
grid.add(hbox, 1, 1);
grid.setPrefSize(600, 480);
return grid;
}
//execute matlab code
public void runMatlab()throws IOException{
//set up command to call matlab
String command = "matlab -nodisplay -nosplash -nodesktop -r "
+ "-wait run('DominantConstraints.m')";
try{
//call matlab
Process process;
process = Runtime.getRuntime().exec(command);
process.waitFor();
//clear out contents of the text file once matlab has retrieved the information
new PrintWriter("file_to_open.txt").close();
}catch(Throwable t){
//process could not be started
}
}
//allows user to select the file they wish to make calculations with
public void selectExcelFile() throws IOException{
filechooser.setInitialDirectory(new File(System.getProperty("user.home")));
String file = filechooser.showOpenDialog(new Stage()).getName();
file_path = excell_dir + file;
chart_name = file + "_GanttChart.png";
try {
//if file that stores excell file names does not exists, create it
if(!data_file.exists()){
//this file holds saves information that matlab retrieves, it stores the
//excel file path, chart directory and the name to save the chart as
PrintWriter create = new PrintWriter(data_file,"UTF-8");
create.close();
}
//write excell file name to text file for matlab to retrieve
writer = new FileWriter(data_file,true);
BufferedWriter out = new BufferedWriter(writer);
out.write(file_path + "|" + gantt_dir + "|" + chart_name);
out.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
}
}
private void checkDirectories(){
//create new directories to store and organize needed files
File charts = new File(gantt_dir);
File data = new File(excell_dir);
if(!charts.isDirectory()){
charts.mkdir();
}
if(!data.isDirectory()){
data.mkdir();
}
}
}
| onyi-ada/project | Main.java | 1,844 | //write excell file name to text file for matlab to retrieve
| line_comment | en | false | 1,510 | 13 | 1,844 | 15 | 1,878 | 13 | 1,844 | 15 | 2,299 | 14 | false | false | false | false | false | true |
24979_0 | import java.io.File;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.Random;
import java.util.Scanner;
public class Deck {
ArrayList<Card> cards;
public Deck(String filename) {
// Create the deck by reading in the file.
cards = new ArrayList<Card>();
try {
Scanner scanner = new Scanner(new File(filename));
while (scanner.hasNextLine()) {
String action = scanner.nextLine();
Card newCard = new Card(action);
cards.add(newCard);
}
} catch (Exception e) {
System.out.println("Can't find comCard.txt!");
}
}
@Override
public String toString() {
return "Deck [cards=" + cards + "]";
}
private void shuffle() {
Collections.shuffle(cards);
}
public String drawChance() {
return ""; // TODO: Return the action of the card drawn
}
public String drawCommunity() {
Random random = new Random();
int randomNumber = random.nextInt(16);
return getCardAction(randomNumber); // TODO: Return the action of the card drawn
}
public String getCardAction(int index) {
if (index >= 0 && index < cards.size()) {
return cards.get(index).action;
} else {
return "Invalid index";
}
}
public int getNumberOfCards() {
return cards.size();
}
private class Card {
String action;
public Card(String action) {
this.action = action;
}
}
public static void main(String[] args) {
// Create a Deck object by providing the filename
Deck deck = new Deck("src/comCard.txt");
String action = deck.drawCommunity();
System.out.println(action);
}
}
| quaxlyqueen/cs2430-finalProject | src/Deck.java | 476 | // Create the deck by reading in the file. | line_comment | en | false | 377 | 10 | 476 | 10 | 474 | 10 | 476 | 10 | 564 | 10 | false | false | false | false | false | true |
25576_12 | package project4;
/***********************************************************************
DVD represents and stores the data for a currently rented out dvd.
@author David Whynot
@version 7/25/2018
***********************************************************************/
import java.io.Serializable;
import java.util.GregorianCalendar;
public class DVD implements Serializable {
private static final long serialVersionUID = 1L;
/** The date the DVD was rented **/
protected GregorianCalendar bought;
/** The date the DVD is due back **/
protected GregorianCalendar dueBack;
/** The name of the DVD **/
protected String title;
/** Name of the user that rented the DVD **/
protected String nameOfRenter;
/*******************************************************************
Default constructor creates a DVD with null/default field values.
*******************************************************************/
public DVD() {
this.bought = new GregorianCalendar();
this.dueBack = new GregorianCalendar();
this.title = null;
this.nameOfRenter = null;
bought.setLenient(false);
dueBack.setLenient(false);
}
/*******************************************************************
Constructor creates a dvd with the given date values, name, and
title.
@param bought the date the DVD rental was purchased
@param dueBack the date the DVD rental is due back
@param title the name of the DVD that was rented
@param name the name of the individual who rented the DVD
*******************************************************************/
public DVD(
GregorianCalendar bought,
GregorianCalendar dueBack,
String title,
String name
) {
this.bought = bought;
this.dueBack = dueBack;
this.title = title;
this.nameOfRenter = name;
bought.setLenient(false);
dueBack.setLenient(false);
}
/*******************************************************************
Gets the day the rental was purchased.
@return the day the rental was purchased.
*******************************************************************/
public GregorianCalendar getBought() {
return bought;
}
/*******************************************************************
Gets the day the rental is due back
@return the day the rental is due back
*******************************************************************/
public GregorianCalendar getDueBack() {
return dueBack;
}
/*******************************************************************
Gets the title of the DVD that was rented
@return the title of the DVD that was rented
*******************************************************************/
public String getTitle() {
return title;
}
/*******************************************************************
Gets the name individual who rented the DVD
@return the name of the renter
*******************************************************************/
public String getNameOfRenter() {
return nameOfRenter;
}
/*******************************************************************
Sets the date the rental was purchased
@param bought the date the rental was purchased
*******************************************************************/
public void setBought(GregorianCalendar bought) {
this.bought = bought;
}
/*******************************************************************
Sets the date the rental is due back on
@param dueBack the date the rental is due back on
*******************************************************************/
public void setDueBack(GregorianCalendar dueBack) {
this.dueBack = dueBack;
}
/*******************************************************************
Sets the title of the unit
@param title the title of the unit
*******************************************************************/
public void setTitle(String title) {
this.title = title;
}
/*******************************************************************
Sets the name of the individual who rented the unit
@param title the name of the individual who rented the unit
*******************************************************************/
public void setNameOfRenter(String nameOfRenter) {
this.nameOfRenter = nameOfRenter;
}
/*******************************************************************
Computes the cost of the rental if returned on the given date.
@param date the date of the return of this item
@return the fee for the rental
*******************************************************************/
public double getCost(GregorianCalendar date) {
// "date" is the date the dvd is being returned on
// cost is 1.20 if on time, 3.20 if late
if(this.dueBack.compareTo(date) < 0) { // dvd is late
return 3.20;
} else {
return 2.0;
}
}
}
| davidmwhynot/CIS163_Project_4 | src/project4/DVD.java | 955 | /*******************************************************************
Sets the date the rental is due back on
@param dueBack the date the rental is due back on
*******************************************************************/ | block_comment | en | false | 860 | 31 | 955 | 30 | 1,061 | 38 | 955 | 30 | 1,189 | 43 | false | false | false | false | false | true |
25631_1 | //Write a java program using interface for the shipping database. It should contain 3 classes and 3 member functions.
import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;
// Interface for the shipping database
interface ShippingInterface {
void addPackage(Package pkg);
void removePackage(int packageId);
void displayPackages();
}
// ShippingDatabase class implementing the ShippingInterface
class ShippingDatabase implements ShippingInterface {
private List<Package> packages;
public ShippingDatabase() {
packages = new ArrayList<>();
}
@Override
public void addPackage(Package pkg) {
packages.add(pkg);
System.out.println("Package added successfully.");
}
@Override
public void removePackage(int packageId) {
for (int i = 0; i < packages.size(); i++) {
Package pkg = packages.get(i);
if (pkg.getPackageId() == packageId) {
packages.remove(i);
System.out.println("Package removed successfully.");
return;
}
}
System.out.println("Package with ID " + packageId + " not found.");
}
@Override
public void displayPackages() {
if (packages.isEmpty()) {
System.out.println("No packages in the database.");
return;
}
System.out.println("Packages in the database:");
for (Package pkg : packages) {
System.out.println(pkg.toString());
}
}
}
// Package class representing a package
class Package {
private int packageId;
private String packageName;
public Package(int packageId, String packageName) {
this.packageId = packageId;
this.packageName = packageName;
}
public int getPackageId() {
return packageId;
}
@Override
public String toString() {
return "Package ID: " + packageId + ", Name: " + packageName;
}
}
// Shipper class to demonstrate the usage of the ShippingDatabase
// class Shipper {
class ShippingDB {
public static void main(String[] args) {
ShippingDatabase database = new ShippingDatabase();
Scanner scanner = new Scanner(System.in);
int choice;
do {
System.out.println("Shipping Database Menu:");
System.out.println("1. Add Package");
System.out.println("2. Remove Package");
System.out.println("3. Display Packages");
System.out.println("4. Exit");
System.out.print("Enter your choice: ");
choice = scanner.nextInt();
switch (choice) {
case 1:
System.out.print("Enter package ID: ");
int packageId = scanner.nextInt();
scanner.nextLine(); // Consume the newline character
System.out.print("Enter package name: ");
String packageName = scanner.nextLine();
Package pkg = new Package(packageId, packageName);
database.addPackage(pkg);
break;
case 2:
System.out.print("Enter package ID to remove: ");
int removePackageId = scanner.nextInt();
database.removePackage(removePackageId);
break;
case 3:
database.displayPackages();
break;
case 4:
System.out.println("Exiting...");
break;
default:
System.out.println("Invalid choice. Please try again.");
break;
}
System.out.println();
} while (choice != 4);
scanner.close();
}
}
| YsbAli/Java-Assignments | ShippingDB.java | 800 | // Interface for the shipping database
| line_comment | en | false | 698 | 7 | 800 | 7 | 910 | 7 | 800 | 7 | 995 | 8 | false | false | false | false | false | true |
25828_2 | import greenfoot.*; // (World, Actor, GreenfootImage, and Greenfoot)
import java.awt.Font;
import java.util.*;
/**
* Counter that displays a number.
*
* @author Michael Kolling
* @version 1.0.1
*/
public class Score extends Observer
{
public static int value = 0;
public static int target = 0;
public static String text;
public static int stringLength;
private ConcreteSubject subject;
public Score()
{
this("");
}
public Score(String prefix)
{
value = 0;
target = 0;
text = prefix;
stringLength = (text.length() + 2) * 16;
setImage(new GreenfootImage(stringLength, 24));
GreenfootImage image = getImage();
Font font = image.getFont();
image.setFont(font.deriveFont(24.0F)); // use larger font
updateImage();
}
public void act()
{
}
public int getValue()
{
return value;
}
/**
* Make the image
*/
public void updateImage()
{
GreenfootImage image = getImage();
image.clear();
image.drawString(text + target, 1, 18);
}
public void update(){
ArrayList<ConcreteSubject> listOfSubs = (ArrayList<ConcreteSubject>)(((MyWorld)getWorld()).getObjects(ConcreteSubject.class));
if(listOfSubs.size()>0){
subject = listOfSubs.get(0);
}
if(text.equalsIgnoreCase("Score: ")){
if (subject != null)
target = subject.getScore();
}
if(value > target)
{
value = 0;
// updateImage();
}
updateImage();
}
}
| gargsurbhi2015/2D-Greenfoot-Game--Subway-Surf- | Score.java | 418 | // use larger font | line_comment | en | false | 393 | 4 | 418 | 4 | 476 | 4 | 418 | 4 | 510 | 4 | false | false | false | false | false | true |
25894_2 | /* CVS $Id: $ */
import com.hp.hpl.jena.rdf.model.*;
/**
* Vocabulary definitions from http://rdfs.org/ns/void#
* @author Auto-generated by schemagen on 19 Sep 2012 13:35
*/
public class Void {
/** <p>The RDF model that holds the vocabulary terms</p> */
private static Model m_model = ModelFactory.createDefaultModel();
/** <p>The namespace of the vocabulary as a string</p> */
public static final String NS = "http://rdfs.org/ns/void#";
/** <p>The namespace of the vocabulary as a string</p>
* @see #NS */
public static String getURI() {return NS;}
/** <p>The namespace of the vocabulary as a resource</p> */
public static final Resource NAMESPACE = m_model.createResource( NS );
/** <p>The rdfs:Class that is the rdf:type of all entities in a class-based partition.</p> */
public static final Property class_ = m_model.createProperty( "http://rdfs.org/ns/void#class" );
/** <p>A subset of a void:Dataset that contains only the entities of a certain rdfs:Class.</p> */
public static final Property classPartition = m_model.createProperty( "http://rdfs.org/ns/void#classPartition" );
/** <p>The total number of distinct classes in a void:Dataset. In other words, the
* number of distinct resources occuring as objects of rdf:type triples in the
* dataset.</p>
*/
public static final Property classes = m_model.createProperty( "http://rdfs.org/ns/void#classes" );
/** <p>An RDF dump, partial or complete, of a void:Dataset.</p> */
public static final Property dataDump = m_model.createProperty( "http://rdfs.org/ns/void#dataDump" );
/** <p>The total number of distinct objects in a void:Dataset. In other words, the
* number of distinct resources that occur in the object position of triples
* in the dataset. Literals are included in this count.</p>
*/
public static final Property distinctObjects = m_model.createProperty( "http://rdfs.org/ns/void#distinctObjects" );
/** <p>The total number of distinct subjects in a void:Dataset. In other words, the
* number of distinct resources that occur in the subject position of triples
* in the dataset.</p>
*/
public static final Property distinctSubjects = m_model.createProperty( "http://rdfs.org/ns/void#distinctSubjects" );
/** <p>The total number of documents, for datasets that are published as a set of
* individual documents, such as RDF/XML documents or RDFa-annotated web pages.
* Non-RDF documents, such as web pages in HTML or images, are usually not included
* in this count. This property is intended for datasets where the total number
* of triples or entities is hard to determine. void:triples or void:entities
* should be preferred where practical.</p>
*/
public static final Property documents = m_model.createProperty( "http://rdfs.org/ns/void#documents" );
/** <p>The total number of entities that are described in a void:Dataset.</p> */
public static final Property entities = m_model.createProperty( "http://rdfs.org/ns/void#entities" );
public static final Property exampleResource = m_model.createProperty( "http://rdfs.org/ns/void#exampleResource" );
public static final Property feature = m_model.createProperty( "http://rdfs.org/ns/void#feature" );
/** <p>Points to the void:Dataset that a document is a part of.</p> */
public static final Property inDataset = m_model.createProperty( "http://rdfs.org/ns/void#inDataset" );
public static final Property linkPredicate = m_model.createProperty( "http://rdfs.org/ns/void#linkPredicate" );
/** <p>The dataset describing the objects of the triples contained in the Linkset.</p> */
public static final Property objectsTarget = m_model.createProperty( "http://rdfs.org/ns/void#objectsTarget" );
/** <p>An OpenSearch description document for a free-text search service over a void:Dataset.</p> */
public static final Property openSearchDescription = m_model.createProperty( "http://rdfs.org/ns/void#openSearchDescription" );
/** <p>The total number of distinct properties in a void:Dataset. In other words,
* the number of distinct resources that occur in the predicate position of triples
* in the dataset.</p>
*/
public static final Property properties = m_model.createProperty( "http://rdfs.org/ns/void#properties" );
/** <p>The rdf:Property that is the predicate of all triples in a property-based
* partition.</p>
*/
public static final Property property = m_model.createProperty( "http://rdfs.org/ns/void#property" );
/** <p>A subset of a void:Dataset that contains only the triples of a certain rdf:Property.</p> */
public static final Property propertyPartition = m_model.createProperty( "http://rdfs.org/ns/void#propertyPartition" );
/** <p>A top concept or entry point for a void:Dataset that is structured in a tree-like
* fashion. All resources in a dataset can be reached by following links from
* its root resources in a small number of steps.</p>
*/
public static final Property rootResource = m_model.createProperty( "http://rdfs.org/ns/void#rootResource" );
public static final Property sparqlEndpoint = m_model.createProperty( "http://rdfs.org/ns/void#sparqlEndpoint" );
/** <p>The dataset describing the subjects of triples contained in the Linkset.</p> */
public static final Property subjectsTarget = m_model.createProperty( "http://rdfs.org/ns/void#subjectsTarget" );
public static final Property subset = m_model.createProperty( "http://rdfs.org/ns/void#subset" );
/** <p>One of the two datasets linked by the Linkset.</p> */
public static final Property target = m_model.createProperty( "http://rdfs.org/ns/void#target" );
/** <p>The total number of triples contained in a void:Dataset.</p> */
public static final Property triples = m_model.createProperty( "http://rdfs.org/ns/void#triples" );
/** <p>Defines a simple URI look-up protocol for accessing a dataset.</p> */
public static final Property uriLookupEndpoint = m_model.createProperty( "http://rdfs.org/ns/void#uriLookupEndpoint" );
/** <p>Defines a regular expression pattern matching URIs in the dataset.</p> */
public static final Property uriRegexPattern = m_model.createProperty( "http://rdfs.org/ns/void#uriRegexPattern" );
/** <p>A URI that is a common string prefix of all the entity URIs in a void:Dataset.</p> */
public static final Property uriSpace = m_model.createProperty( "http://rdfs.org/ns/void#uriSpace" );
/** <p>A vocabulary that is used in the dataset.</p> */
public static final Property vocabulary = m_model.createProperty( "http://rdfs.org/ns/void#vocabulary" );
/** <p>A set of RDF triples that are published, maintained or aggregated by a single
* provider.</p>
*/
public static final Resource Dataset = m_model.createResource( "http://rdfs.org/ns/void#Dataset" );
/** <p>A web resource whose foaf:primaryTopic or foaf:topics include void:Datasets.</p> */
public static final Resource DatasetDescription = m_model.createResource( "http://rdfs.org/ns/void#DatasetDescription" );
/** <p>A collection of RDF links between two void:Datasets.</p> */
public static final Resource Linkset = m_model.createResource( "http://rdfs.org/ns/void#Linkset" );
/** <p>A technical feature of a void:Dataset, such as a supported RDF serialization
* format.</p>
*/
public static final Resource TechnicalFeature = m_model.createResource( "http://rdfs.org/ns/void#TechnicalFeature" );
}
| ariutta/wp2lod | ontologies/Void.java | 2,027 | /** <p>The RDF model that holds the vocabulary terms</p> */ | block_comment | en | false | 1,891 | 15 | 2,027 | 16 | 2,197 | 16 | 2,027 | 16 | 2,310 | 20 | false | false | false | false | false | true |
25999_19 | package com.github.javafaker;
import static java.nio.charset.StandardCharsets.UTF_8;
import java.util.ArrayList;
/**
* Faker class for generating Session Initiation Protocol (SIP) related data.
*
* @author TomerFi
*/
public final class Sip {
private final Faker faker;
private final ArrayList<Integer> portPool;
protected Sip(final Faker faker) {
this.faker = faker;
int port = 40000;
portPool = new ArrayList<Integer>();
while (port <= 50000) {
portPool.add(port);
port = port + 2;
}
}
/**
* The various SIP methods are listed in https://en.wikipedia.org/wiki/Session_Initiation_Protocol.
*
* @return a SIP method String, e.g. {@code INVITE}.
*/
public String method() {
return faker.resolve("sip.methods");
}
/**
* Content types are based on https://tools.ietf.org/html/rfc5621 and
* https://tools.ietf.org/html/rfc3261.
*
* @return a SIP content-type declaration String, e.g. {@code application/sdp}
*/
public String contentType() {
return faker.resolve("sip.content.types");
}
/**
* Get a 4 digit random port for SIP messaging.
*
* @return a SIP messaging port int, e.g. 5060.
*/
public int messagingPort() {
return faker.random().nextInt(1000, 9999);
}
/**
* Get a 5 digit positive even port for rtp udp communication.
*
* @return an RTP UDP 5 digit port int, e.g. 40002.
*/
public int rtpPort() {
return portPool.get(faker.random().nextInt(0, portPool.size()));
}
/**
* Proviosional code, the various response codes are listed in
* https://en.wikipedia.org/wiki/List_of_SIP_response_codes.
*
* @return a 3 digit SIP provisioan response code between 100 and 199 int, e.g. {@code 180}.
*/
public int provisionalResponseCode() {
return Integer.parseInt(faker.resolve("sip.response.codes.provisional"));
}
/**
* Success code, the various response codes are listed in
* https://en.wikipedia.org/wiki/List_of_SIP_response_codes.
*
* @return a 3 digit SIP success response code between 200 and 299 int, e.g. {@code 200}.
*/
public int successResponseCode() {
return Integer.parseInt(faker.resolve("sip.response.codes.success"));
}
/**
* Redirection code, the various response codes are listed in
* https://en.wikipedia.org/wiki/List_of_SIP_response_codes.
*
* @return a 3 digit SIP redirection response code between 300 and 399 int, e.g. {@code 301}.
*/
public int redirectResponseCode() {
return Integer.parseInt(faker.resolve("sip.response.codes.redirection"));
}
/**
* Client error code, the various response codes are listed in
* https://en.wikipedia.org/wiki/List_of_SIP_response_codes.
*
* @return a 3 digit SIP client error response code between 400 and 499 int, e.g. {@code 486}.
*/
public int clientErrorResponseCode() {
return Integer.parseInt(faker.resolve("sip.response.codes.clientError"));
}
/**
* Server error code, the various response codes are listed in
* https://en.wikipedia.org/wiki/List_of_SIP_response_codes.
*
* @return a 3 digit SIP server error response code between 500 and 599 int, e.g. {@code 503}.
*/
public int serverErrorResponseCode() {
return Integer.parseInt(faker.resolve("sip.response.codes.serverError"));
}
/**
* Global error code, the various response codes are listed in
* https://en.wikipedia.org/wiki/List_of_SIP_response_codes.
*
* @return a 3 digit SIP global error response code between 600 and 699 int, e.g. {@code 608}.
*/
public int globalErrorResponseCode() {
return Integer.parseInt(faker.resolve("sip.response.codes.globalError"));
}
/**
* Proviosional phrase, the various response phrases are listed in
* https://en.wikipedia.org/wiki/List_of_SIP_response_codes.
*
* @return a SIP provisional response phrase String, e.g. {@code Ringing}.
*/
public String provisionalResponsePhrase() {
return faker.resolve("sip.response.phrases.provisional");
}
/**
* Success phrase, the various response phrases are listed in
* https://en.wikipedia.org/wiki/List_of_SIP_response_codes.
*
* @return a SIP success response phrase String, e.g. {@code OK}.
*/
public String successResponsePhrase() {
return faker.resolve("sip.response.phrases.success");
}
/**
* Redirection phrase, the various response phrases are listed in
* https://en.wikipedia.org/wiki/List_of_SIP_response_codes.
*
* @return a SIP redirection response phrase String, e.g. {@code Moved Permanently}.
*/
public String redirectResponsePhrase() {
return faker.resolve("sip.response.phrases.redirection");
}
/**
* Client error phrase, the various response phrases are listed in
* https://en.wikipedia.org/wiki/List_of_SIP_response_codes.
*
* @return a SIP client error response phrase String, e.g. {@code Busy Here}.
*/
public String clientErrorResponsePhrase() {
return faker.resolve("sip.response.phrases.clientError");
}
/**
* Server error phrase, the various response phrases are listed in
* https://en.wikipedia.org/wiki/List_of_SIP_response_codes.
*
* @return a SIP server erro response phrase String, e.g. {@code Service Unavailable}.
*/
public String serverErrorResponsePhrase() {
return faker.resolve("sip.response.phrases.serverError");
}
/**
* Server error phrase, the various response phrases are listed in
* https://en.wikipedia.org/wiki/List_of_SIP_response_codes.
*
* @return a SIP global error response phrase String, e.g. {@code Rejected}.
*/
public String globalErrorResponsePhrase() {
return faker.resolve("sip.response.phrases.globalError");
}
/**
* Body example of SDP type can be found in https://tools.ietf.org/html/rfc5621.
*
* @return a fake SDP type SIP body String.
*/
public String bodyString() {
return "v=0\n" +
"o=" + faker.name().firstName() + " " + faker.internet().uuid() + " IN IP4 " + faker.internet().domainName() + "\n" +
"s=-\n" +
"c=IN IP4 " + faker.internet().ipV4Address() + "\n" +
"t=0 0\n" +
"m=audio " + rtpPort() + " RTP/AVP 0\n" +
"a=rtpmap:0 PCMU/8000";
}
/**
* Body example of SDP type can be found in https://tools.ietf.org/html/rfc5621.
*
* @return a fake SDP type SIP body byte array.
*/
public byte[] bodyBytes() {
return bodyString().getBytes(UTF_8);
}
/**
* Return a valid name address to use with {@code to/from} headers.
*
* @return a valid name address String, e.g. {@code <sip:[email protected]:5060>}.
*/
public String nameAddress() {
return "<sip:" + faker.name().firstName() + "@" + faker.internet().ipV4Address() + ":" + messagingPort() + ">";
}
}
| rohankumardubey/faker | Sip.java | 2,007 | /**
* Return a valid name address to use with {@code to/from} headers.
*
* @return a valid name address String, e.g. {@code <sip:[email protected]:5060>}.
*/ | block_comment | en | false | 1,795 | 58 | 2,007 | 60 | 2,196 | 64 | 2,007 | 60 | 2,444 | 69 | false | false | false | false | false | true |
26089_2 | import java.io.*;
import javax.crypto.*;
import javax.crypto.spec.*;
/**
* XYZprinting.com has changed its *.3W format, and now
* uses AES encrypted ZIP instead of simple base64-encoded ZIP.
*
* This code decrypts this new *.3W file and converts it back
* to *.ZIP file.
*
* @see http://voltivo.com/forum/davinci-software/6-ways-to-print-with-3rd-party-slicer?start=20
*/
public class DecryptXYZ3W {
public static void main(String[] args) throws Exception {
if (args.length != 2) {
System.err.println("Usage: DecryptXYZ3W infile.3w outfile.zip");
System.exit(1);
}
String infile = args[0];
String outfile = args[1];
int len;
byte[] buf = new byte[8192];
// read infile as bytedata
FileInputStream fis = new FileInputStream(infile);
ByteArrayOutputStream bos = new ByteArrayOutputStream();
while ((len = fis.read(buf)) > 0) {
bos.write(buf, 0, len);
}
byte[] data = bos.toByteArray();
fis.close();
bos.close();
// this is the secret key
String key = "@xyzprinting.com";
byte[] kbb = key.getBytes("UTF-8");
// initialize AES cipher engine
byte[] iv = new byte[16];
SecretKeySpec spec = new SecretKeySpec(kbb, "AES");
Cipher aes = Cipher.getInstance("AES/CBC/PKCS5Padding");
aes.init(Cipher.DECRYPT_MODE, spec, new IvParameterSpec(iv));
// decrypt each block and save result (ZIP data)
FileOutputStream fos = new FileOutputStream(args[1]);
for (int i = 0x2000; i < data.length; i += 0x2010) {
byte[] dec = aes.doFinal(data, i,
Math.min(data.length - i, 0x2010));
fos.write(dec);
}
fos.close();
}
}
| tai/decrypt-xyz3w | DecryptXYZ3W.java | 516 | // this is the secret key
| line_comment | en | false | 448 | 7 | 516 | 7 | 563 | 7 | 516 | 7 | 627 | 7 | false | false | false | false | false | true |
27688_0 |
/**
* This method holds the fields and methods for the Card class.
* An instance of this class is used to represent a traditional
* Card from a 52-card deck. The parameterized constructor can
* be used to pass in any value for the three fields that the
* user wishes.
*
* @author Matthew O'Neill
* @version 4/18/2019
*/
public class Card
{
//value represents relative value of card, usually between 1 and 13
private int value;
private String suit;
private String face;
/**
* This no-args constructor sets the fields in the Card class to the
* default values of 0 and None.
*/
public Card()
{
this.value = 0;
this.suit = "None";
this.face = "None";
}
/**
* This parameterized constructor sets the values of Card objects to
* the values passed into the method.
* @param int inValue - an int between 1 and 13 representing the value
* of a card, with 2 being the least ad Ace being the highest
* @param String inSuit - the suit of the card
* @param String inFace - the face value of the card, between 2 and Ace
*/
public Card(int inValue, String inSuit, String inFace)
{
this.value = inValue;
this.suit = inSuit;
this.face = inFace;
}
/**
* This copy constructor makes a hard copy of the Card reference passed
* into the method.
* @param Card other - the refenence to a Card object to be copied
*/
public Card(Card other)
{
this.value = other.value;
this.suit = other.suit;
this.face = other.face;
}
/**
* This get method returns the value of the value field.
* @return int this.Value - the value field
*/
public int getValue()
{
return this.value;
}
/**
* This get method returns the value of the suit field.
* @return String this.suit - the suit field
*/
public String getSuit()
{
return this.suit;
}
/**
* This get method returns the calue of the face field.
* @return String this.face -the face field
*/
public String getFace()
{
return this.face;
}
/**
* This method returns a String representation of the card object.
* @return String - String representation of the card object in the
* form of "face of suit"
*/
public String toString()
{
return face + " of " + suit;
}
/**
* This method compares two Card objects based on their value field,
* and returns 1 it this is greater, -1 if the one being passed in
* is greater, and 0 if they are equal
* @param Card other - reference to Card object being compared
* @return int - result of comparison based on value field
*/
public int compareTo(Card other)
{
//compares only on the basis of the value field
if(this.value > other.value){
return 1;
}
else if(other.value > this.value){
return -1;
}
else{
return 0;
}
}
/**
* This method compares the face and suit fields of two Card objects,
* and returns true if both are equal and false if they are different.
* @param Card other - reference to Card object being compared
* @return boolean - result of the comparison
*/
public boolean equals(Card other)
{
//compares on the basis of both face and suit
if(this.face.equals(other.face) && this.suit.equals(other.suit)){
return true;
}
else{
return false;
}
}
}
| mjoneill88/Java_War_Card_Game | Card.java | 885 | /**
* This method holds the fields and methods for the Card class.
* An instance of this class is used to represent a traditional
* Card from a 52-card deck. The parameterized constructor can
* be used to pass in any value for the three fields that the
* user wishes.
*
* @author Matthew O'Neill
* @version 4/18/2019
*/ | block_comment | en | false | 870 | 87 | 885 | 95 | 1,003 | 93 | 885 | 95 | 1,020 | 95 | false | false | false | false | false | true |
28525_11 |
public class Room {
private String description;
private boolean north;
private boolean south;
private boolean east;
private boolean west;
private boolean isDark;
private Lamp theLamp;
private Key theKey;
private Chest theChest;
/**
* Returns the text description of this room
*/
public String getDescription() {
return description;
}
/**
* Returns true if the player can go north from this room
*/
public boolean canGoNorth() {
return north;
}
/**
* Returns true if the player can go south from this room
*/
public boolean canGoSouth() {
return south;
}
/**
* Returns true if the player can go east from this room
*/
public boolean canGoEast() {
return east;
}
/**
* Returns true if the player can go west from this room
*/
public boolean canGoWest() {
return west;
}
/**
* Returns the lamp object in this room.
* If no lamp is present, returns null
*/
public Lamp getLamp() {
return theLamp;
}
/**
* Sets the lamp variable in this room to null
*/
public void clearLamp() {
theLamp = null;
}
/**
* Returns the key object in this room.
* If no key is present, returns null
*/
public Key getKey() {
return theKey;
}
/**
* Sets the key variable in this room to null
*/
public void clearKey() {
theKey = null;
}
/**
* Returns the chest object in this room.
* If no chest is present, returns null
*/
public Chest getChest() {
return theChest;
}
/**
* Returns true if there is no light in this room,
* veeeeeeeery dangerous!
*/
public boolean isDark() {
return isDark;
}
/**
* Hey wassup dawg? I'ma constructor. I make the objects round these parts,
* sometimes without even trying, knowwhatimssayin?
* Yall don't haveta worry 'bout me for this'ere game, but look me up in
* Chapter 6 sometime. Kay?
*
*/
public Room(String description, boolean north, boolean south, boolean east,
boolean west, boolean isDark, Lamp theLamp, Key theKey,
Chest theChest) {
super();
this.description = description;
this.north = north;
this.south = south;
this.east = east;
this.west = west;
this.isDark = isDark;
this.theLamp = theLamp;
this.theKey = theKey;
this.theChest = theChest;
}
}
| emilyockerman/Adventure | Room.java | 702 | /**
* Hey wassup dawg? I'ma constructor. I make the objects round these parts,
* sometimes without even trying, knowwhatimssayin?
* Yall don't haveta worry 'bout me for this'ere game, but look me up in
* Chapter 6 sometime. Kay?
*
*/ | block_comment | en | false | 620 | 79 | 702 | 81 | 736 | 83 | 702 | 81 | 811 | 88 | false | false | false | false | false | true |
29813_2 | package com.jvulopas.cash_tracker;
import java.util.Optional;
/**
* A flow is an increase or decrease of quantity of some security in some account.
* It's one component of a transaction, which consists of multiple simultaneous flows.
* @author jvulopas
*
*/
public class Flow {
private BNYMAccount account;
private String security;
private HoldingStatus status;
private double amount;
private Transaction transaction; // transaction housing this flow
private Optional<Boolean> settled;
private boolean settledAfterSweep;
public Flow(BNYMAccount account, String security, HoldingStatus status, double amount, Transaction transaction) {
this.account = account;
this.security = security;
this.status = status;
this.amount = amount;
this.transaction = transaction;
this.settled = Optional.empty();
this.settledAfterSweep = false;
}
public Optional<Boolean> hasSettled() {
if (settled.isEmpty()) return Optional.empty();
return Optional.of(settled.get());
}
/**
* @return the account
*/
public BNYMAccount getAccount() {
return account;
}
/**
* @return the security
*/
public String getSecurity() {
return security;
}
/**
* @return the status
*/
public HoldingStatus getStatus() {
return status;
}
/**
* @return the amount
*/
public double getAmount() {
return amount;
}
public void setAmount(double aValue) {
this.amount = aValue;
}
/**
* @return the transaction
*/
public Transaction getTransaction() {
return transaction;
}
/**
* Allocate this flow to a series (linked through actionID at transaction level)
* The crucial rounding moment takes place here.
* @param portion
* @return
*/
public Flow makeAllocation(double portion) {
Flow outp = new Flow(account, security, status, Math.round(portion * amount * 100.0)/100.0, transaction);
if (settled.isPresent()) {
if (settled.get().booleanValue()) {
outp.declareSettled(settledAfterSweep);
} else {
outp.declareFailing();
}
}
return outp;
}
public Flow makeAllocationManualAmountOverride(double manualAmount) {
Flow outp = new Flow(account, security, status, Math.round(manualAmount * 100.0)/100.0, transaction);
if (settled.isPresent()) {
if (settled.get().booleanValue()) {
outp.declareSettled(settledAfterSweep);
} else {
outp.declareFailing();
}
}
return outp;
}
public void declareFailing() {
settled = Optional.of(false);
}
public void declareSettled(boolean afterSweep) {
settled = Optional.of(true);
settledAfterSweep = afterSweep;
}
public boolean settledAfterSweep() {
return settledAfterSweep;
}
}
| tonylucid/LucidMA | cash_tracker/src/main/java/com/jvulopas/cash_tracker/Flow.java | 796 | /**
* @return the account
*/ | block_comment | en | false | 683 | 10 | 796 | 9 | 802 | 11 | 796 | 9 | 950 | 11 | false | false | false | false | false | true |
29966_5 | import java.lang.StringBuilder;
class Tour {
public static final boolean DEBUG = false;
/**
* A vector holding node indices.
*/
private int[] nodes;
/**
* A vector keeping track of in which position a given node
* occurs, where both are indices starting at zero.
*/
private int[] positions;
/**
* An integer that knows where to insert next.
* This equals current number of inserted nodes.
*/
private int currNumAddedNodes;
/**
* Constructs a new tour with the specified capacity.
* @param capacity The capacity of this tour
*/
Tour(int capacity) {
nodes = new int[capacity];
positions = new int[capacity];
currNumAddedNodes = 0;
}
/**
* Adds a node index to this tour.
*
* @param nodeIndex The node index to add
*/
void addNode(int nodeIndex) {
nodes[currNumAddedNodes] = nodeIndex;
positions[nodeIndex] = currNumAddedNodes;
currNumAddedNodes++;
return;
}
/**
* Sets the node index at the specified position index to the
* given node index. Does not care about nodes disappearing.
*
* @param posIndex position index
* @param nodeIndex node index
*/
private void setNode(int posIndex, int nodeIndex) {
nodes[posIndex] = nodeIndex;
positions[nodeIndex] = posIndex;
}
/**
* Moves the given node index in this tour to the specified
* position.
*
* @param x The node index to insert
* @param a The node index after which x should be placed
* @param a The node index before which x should be placed
*/
boolean moveBetween(int x, int a, int b) {
if (x == a || x == b || a == b) {
return false;
}
int posX = getPos(x);
int posA = getPos(a);
int posB = getPos(b);
if (DEBUG) {
System.err.print(String.format("moveBetween(x=%d, a=%d, b=%d)", x, a, b));
System.err.println(String.format(" = moveBetween(posX=%d, posA=%d, posB=%d)", posX, posA, posB));
}
if (posX < posA) {
for (int i = posX; i < posA; i++) {
setNode(i, getNode(i+1));
}
setNode(posA, x);
if (DEBUG) nodesPosInvariant();
} else { // posX > posA
for (int i = posX; i > posB; i--) {
setNode(i, getNode(i-1));
}
setNode(posB, x);
if (DEBUG) nodesPosInvariant();
}
return true;
}
/**
* Returns the node index at the specified position index of the
* tour, both starting with zero.
*
* @param posIndex The position index (0: first node)
* @return -1 if index out of bounds, otherwise the node index
*/
int getNode(int posIndex) {
if (posIndex == currNumAddedNodes)
return nodes[0];
return nodes[posIndex];
}
/**
* Returns the node index of the node that has the position index
* right after the one specified.
*
* @param posIndex the position index after which to get the next node from,
* if posIndex is equal to the size of the tour it equalizes with it being 0
* @return the node index if
*/
int getNextNode(int posIndex) {
if (posIndex+1 == currNumAddedNodes)
return nodes[0];
return nodes[(posIndex+1)];
}
int getPrevNode(int posIndex) {
if (posIndex == 0)
return nodes[currNumAddedNodes-1];
else
return nodes[posIndex];
}
/**
* Returns the node (index) that immediately follows the specified
* node (index) in this tour.
*
* @param node the node (index) before the wanted node index
* @return the node (index) following the specified node (index)
*/
int getNodeAfter(int node) {
int nodePos = getPos(node);
return getNextNode(nodePos);
}
/**
* Returns the position (order in this tour) index, starting with
* zero of the specified node index.
*
* @param nodeIndex the node index for the returned position index
* @return the position index, or -1 if not found
*/
int getPos(int nodeIndex) {
return positions[nodeIndex];
}
/**
* Swap places on two node indices in the tour
* @param a One of the node indices to change place
* @param b The other node index to change place
* TODO: review this after changing to correct variable names.
* I fear that the code might be borken, because of mixing
* of node indices and position indices.
*/
void swap (int a, int b) {
if (a == b)
return;
int tmpNode = nodes[a];
nodes[a] = nodes[b];
nodes[b] = tmpNode;
positions[nodes[a]] = a;
positions[nodes[b]] = b;
}
/**
* Returns the total length of this tour.
*
* @param tsp the TSP instance with distance method
* @return total length
*/
float length(TSP tsp) {
float sum = 0;
for (int i = 1; i < nodes.length; i++) {
sum += tsp.distance(nodes[i-1], nodes[i]);
}
sum += tsp.distance(nodes[0], nodes[nodes.length-1]);
return sum;
}
/**
* Returns the current number of nodes in this tour.
*
* @return current number of nodes
*/
int numNodes() {
return currNumAddedNodes;
}
/**
* Returns string representation of this tour, ending each node
* index with a newline, including the last one.
*/
public String toString() {
StringBuilder sb = new StringBuilder();
for (int node : nodes) {
sb.append(node + "\n");
}
return sb.toString();
}
/**
* Print this tour to the specified stream.
*
* @param out The output stream
*/
void print(Kattio out) {
for (int i = 0; i < currNumAddedNodes; i++) {
out.println(nodes[i]);
}
return;
}
/**
* Tests the invariant that nodes vector and positions vector
* should always be in sync.
*/
private void nodesPosInvariant() {
for (int node = 0; node < currNumAddedNodes; node++) {
String fail = String.format("node=%d == nodes[positions[node=%d]=%d]=%d", node, node, positions[node], nodes[positions[node]]);
assert node == nodes[positions[node]] : fail;
}
}
}
| ecksun/TSP-avalg-proj1 | Tour.java | 1,633 | /**
* Sets the node index at the specified position index to the
* given node index. Does not care about nodes disappearing.
*
* @param posIndex position index
* @param nodeIndex node index
*/ | block_comment | en | false | 1,584 | 50 | 1,633 | 49 | 1,824 | 53 | 1,633 | 49 | 1,914 | 55 | false | false | false | false | false | true |
30319_2 | import java.util.ArrayList;
/*
* Homework 3
* Ami Kano, ak7ra
* Sources:
*/
public class Album {
/*
* name is a String type variable that contains the name of the album
*/
private String name;
/*
* photos is an ArrayList of objects of type photograph
*/
private ArrayList<Photograph> photos;
/*
* the constructor makes a new album with inputs name and photos
*/
public Album(String name) {
this.name = name;
this.photos = new ArrayList<Photograph>();
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public ArrayList<Photograph> getPhotos() {
return photos;
}
/*
* addPhoto adds a photograph to an album
*
* @param p : object of type Photograph
* @return boolean : true if photograph was successfully added to the album, false if not
*/
public boolean addPhoto(Photograph p) {
if ((p != null) && (!(photos.contains(p)))) {
photos.add(p);
return true;
} else {
return false;
}
}
/*
* hasPhoto checks whether the album has a particular photo or not
*
* @param p : object of type Photograph
* @return boolean : true if album has p, if not false
*/
public boolean hasPhoto(Photograph p) {
if (photos.contains(p)) {
return true;
} else {
return false;
}
}
/*
* removePhoto removes a particular photo from the album
*
* @param p : object of type Photograph
* @return boolean : true if p was successfully removed from album, if not false
*/
public boolean removePhoto(Photograph p) {
if (photos.contains(p)) {
photos.remove(p);
return true;
} else {
return false;
}
}
/*
* numPhotographs gives the number of photographs that are in the album
*
* @return int : number of photographs that are in the album
*/
public int numPhotographs() {
return photos.size();
}
/*
* equals checks whether an object is the same thing as the album, based on its name
*
* @param o : an object
* @return boolean : true if the object refers to the album, if not false
*/
public boolean equals(Object o) {
if ((o instanceof Album) && (o != null)) {
Album otherAlbum = (Album) o;
if (this.name == otherAlbum.getName()) {
return true;
} else {
return false;
}
} else {
return false;
}
}
/*
* toString returns the name and content of the album in String form
*
* @return String : name and content of album
*/
public String toString() {
return "Album name:" + name + ", photos:" + photos;
}
@Override
public int hashCode() {
return this.name.hashCode();
}
}
| ak7ra/PhotoLibrary | Album.java | 769 | /*
* photos is an ArrayList of objects of type photograph
*/ | block_comment | en | false | 699 | 15 | 769 | 15 | 811 | 16 | 769 | 15 | 917 | 16 | false | false | false | false | false | true |
30379_0 |
import java.awt.*;
import javax.swing.*;
/**
* The Photo class extends JPanel and represents an image panel
* that can display an image on it.
*/
public class Photo extends JPanel {
private Image bimage;// The image to be displayed
/**
* Constructs a new Photo object with the given image file path.
* @param image The file path of the image to be displayed.
*/
public Photo(String image) {
bimage = new javax.swing.ImageIcon("../Convo app/images/"+image).getImage();
}
@Override
public void paintComponent(Graphics g) {
super.paintComponent(g);
Graphics2D g2 = (Graphics2D) g;
g2.drawImage(bimage, 0, 0,700,400, null);
}
/**
* Loads a new image and repaints the panel with it.
* @param i The new Image object to be displayed.
*/
public void loadImage(Image i) {
bimage = i;
repaint();
}
}
| SujalThakur1/Convo-App | Photo.java | 244 | /**
* The Photo class extends JPanel and represents an image panel
* that can display an image on it.
*/ | block_comment | en | false | 221 | 23 | 244 | 25 | 261 | 25 | 244 | 25 | 286 | 27 | false | false | false | false | false | true |
32036_9 | /*******************************************************************************
* Copyright (c) 2001-2013 Mathew A. Nelson and Robocode contributors
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://robocode.sourceforge.net/license/epl-v10.html
*******************************************************************************/
package sample;
import robocode.HitRobotEvent;
import robocode.Robot;
import robocode.ScannedRobotEvent;
import java.awt.*;
/**
* RamFire - a sample robot by Mathew Nelson.
* <p/>
* Drives at robots trying to ram them.
* Fires when it hits them.
*
* @author Mathew A. Nelson (original)
* @author Flemming N. Larsen (contributor)
*/
public class RamFire extends Robot {
int turnDirection = 1; // Clockwise or counterclockwise
/**
* run: Spin around looking for a target
*/
public void run() {
// Set colors
setBodyColor(Color.lightGray);
setGunColor(Color.gray);
setRadarColor(Color.darkGray);
while (true) {
turnRight(5 * turnDirection);
}
}
/**
* onScannedRobot: We have a target. Go get it.
*/
public void onScannedRobot(ScannedRobotEvent e) {
if (e.getBearing() >= 0) {
turnDirection = 1;
} else {
turnDirection = -1;
}
turnRight(e.getBearing());
ahead(e.getDistance() + 5);
scan(); // Might want to move ahead again!
}
/**
* onHitRobot: Turn to face robot, fire hard, and ram him again!
*/
public void onHitRobot(HitRobotEvent e) {
if (e.getBearing() >= 0) {
turnDirection = 1;
} else {
turnDirection = -1;
}
turnRight(e.getBearing());
// Determine a shot that won't kill the robot...
// We want to ram him instead for bonus points
if (e.getEnergy() > 16) {
fire(3);
} else if (e.getEnergy() > 10) {
fire(2);
} else if (e.getEnergy() > 4) {
fire(1);
} else if (e.getEnergy() > 2) {
fire(.5);
} else if (e.getEnergy() > .4) {
fire(.1);
}
ahead(40); // Ram him again!
}
}
| joukestoel/jtech-nerding-out-1 | robocode_app/robots/sample/RamFire.java | 690 | // We want to ram him instead for bonus points
| line_comment | en | false | 595 | 11 | 690 | 11 | 702 | 11 | 690 | 11 | 831 | 11 | false | false | false | false | false | true |
32143_0 | import java.util.Arrays;
class Solution {
int mod = 1000000007;
int[][][] memo = new int[101][101][101];
int find(int pos, int count, int profit, int n, int minProfit, int[] group, int[] profits) {
if (pos == group.length) {
// If profit exceeds the minimum required; it's a profitable scheme.
return profit >= minProfit ? 1 : 0;
}
if (memo[pos][count][profit] != -1) {
// Repeated subproblem, return the stored answer.
return memo[pos][count][profit];
}
// Ways to get a profitable scheme without this crime.
int totalWays = find(pos + 1, count, profit, n, minProfit, group, profits);
if (count + group[pos] <= n) {
// Adding ways to get profitable schemes, including this crime.
totalWays += find(pos + 1, count + group[pos], Math.min(minProfit, profit + profits[pos]), n, minProfit,
group, profits);
}
return memo[pos][count][profit] = totalWays % mod;
}
public int profitableSchemes(int n, int minProfit, int[] group, int[] profit) {
// Initializing all states as -1.
for (int i = 0; i <= group.length; i++) {
for (int j = 0; j <= n; j++) {
Arrays.fill(memo[i][j], -1);
}
}
return find(0, 0, 0, n, minProfit, group, profit);
}
}
| kalongn/LeetCode_Solution | 879.java | 405 | // If profit exceeds the minimum required; it's a profitable scheme. | line_comment | en | false | 372 | 14 | 405 | 15 | 419 | 15 | 405 | 15 | 461 | 17 | false | false | false | false | false | true |
32652_8 | /*************************************************************************************************
* Future interface
*
* Copyright 2020 Google LLC
* Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file
* except in compliance with the License. You may obtain a copy of the License at
* https://www.apache.org/licenses/LICENSE-2.0
* Unless required by applicable law or agreed to in writing, software distributed under the
* License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND,
* either express or implied. See the License for the specific language governing permissions
* and limitations under the License.
*************************************************************************************************/
package tkrzw;
/**
* Future containing a status object and extra data.
* @note Future objects are made by methods of AsyncDBM. Every future object should be destroyed by the "destruct" method or the "get" method to free resources.
*/
public class Future<T> {
/**
* Default forbidden constructor.
*/
private Future() {}
/**
* Destructs the object and releases resources.
*/
public native void destruct();
/**
* Awaits the operation to be done.
* @param timeout The waiting time in seconds. If it is negative, no timeout is set.
* @return True if the operation has done. False if timeout occurs.
*/
public native boolean await(double timeout);
/**
* Awaits the operation to be done and gets the result status.
* @return The result status and extra data if any. The existence and the type of extra data
* depends on the operation which makes the future. For DBM#Get, a tuple of the status and
* the retrieved value is returned. For DBM#Set and DBM#Remove, the status object itself is
* returned.
* @note The internal resource is released by this method. "aait" and "get" cannot be called after calling this method.
*/
public native T get();
/**
* Gets a string representation of the database.
*/
public native String toString();
/** The pointer to the native object */
private long ptr_ = 0;
/** Wheether the extra value is string data. */
private boolean is_str_ = false;
}
// END OF FILE
| estraier/tkrzw-java | Future.java | 513 | /** Wheether the extra value is string data. */ | block_comment | en | false | 495 | 11 | 513 | 12 | 551 | 11 | 513 | 12 | 590 | 11 | false | false | false | false | false | true |
32881_0 | /* Portion of Project Moses involving http get requests.
* Issues: Need to create switch for tags.
* Programmed by: Andrew Preuss && Andrew Miller
*/
import java.io.BufferedReader;
import java.io.DataOutputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
public class HTTPGet{
// Pulls down the twenty most recent text posts from a particular blog,
// Using wordCounter variable can return less than twenty posts.
// @return result a single massive string containing the text from all posts.
// @param urlName the name of the blog to be pulled down.
public static String getPostsByBlog(String urlName)throws Exception{
// Uses the urlName to get the tumblr blog from which posts will be extracted from.
String url = "http://api.tumblr.com/v2/blog/"+urlName+"/posts/text?api_key=FmuYeCbdQesF76ah7RJDMHcYUvrzKV85gWTV0HwtD7JRChh71F";
URL obj = new URL(url);
HttpURLConnection connection = (HttpURLConnection) obj.openConnection();
connection.setRequestMethod("GET");
//Reads in the JSON objects as a single unformatted string.
BufferedReader in = new BufferedReader(
new InputStreamReader(connection.getInputStream()));
String reader = in.readLine();
in.close(); //Closes the connection.
// wordCounter is used to limit how many posts/words we want to pull down.
// It counts each character in the posts including spaces and punctuation.
int wordCounter=0;
String result, finalResult="";
// This while loop formats the JSON string into a regular plaintext string.
while(wordCounter<900){
if(reader.contains("\"body\":")){
result = reader.substring(reader.indexOf("\"body\":"),reader.length());
reader = reader.substring(reader.indexOf("\"body\":")+6,reader.length());
result = result.substring(result.indexOf("\\u003E")+6 , result.indexOf("}"));
result = result.substring(0 , result.indexOf("\\u003C"));
result = result.replace("’","'");
result = result.replace("&","&");
}
else{
break;
}
wordCounter += result.length();
finalResult = finalResult + result + "\n";
}
return finalResult;
}
// This method pulls down posts by their tags as opposed to all the posts from one blog
// @param tag is the tag of all the posts that will be pulled.
// @return result a single massive string containing the text from all posts.
public static String getPostsByTag(String tag)throws Exception{
// Uses the urlName to get the tumblr blog from which posts will be extracted from.
String url = "http://api.tumblr.com/v2/tagged?tag="+tag+"&api_key=FmuYeCbdQesF76ah7RJDMHcYUvrzKV85gWTV0HwtD7JRChh71F";
URL obj = new URL(url);
HttpURLConnection connection = (HttpURLConnection) obj.openConnection();
connection.setRequestMethod("GET");
//Reads in the JSON objects as a single unformatted string.
BufferedReader in = new BufferedReader(
new InputStreamReader(connection.getInputStream()));
String reader = in.readLine();
in.close(); //Closes the connection.
// wordCounter is used to limit how many posts/words we want to pull down.
// It counts each character in the posts including spaces and punctuation.
int wordCounter=0;
String result="", finalResult="";
// This while loop formats the JSON string into a regular plaintext string.
while(wordCounter<400){
if(reader.contains("\"body\":") || reader.contains("\"caption\":")){
if(reader.contains("\"body\":")){
result = reader.substring(reader.indexOf("\"body\":") , reader.length());
reader = reader.substring(reader.indexOf("\"body\":")+6 , reader.length());
result = result.substring(result.indexOf("\\u003E")+6 , result.indexOf("}"));
result = result.substring(0 , result.indexOf("\\u003C"));
result = result.replace("’","'");
}
if(reader.contains("\"caption\":")){
result = reader.substring(reader.indexOf("\"caption\":") , reader.length());
reader = reader.substring(reader.indexOf("\"caption\":")+9 , reader.length());
result = result.replace("\\u003C" , "<");
result = result.replace("\\u003E" , ">");
result = result.replace("’" , "'");
result =result.replace("u0022" , "\"");
//result = result.substring(result.indexOf("\\u003Cp\\u003E")+13 , result.indexOf("\\u003C\\/p\\u003E"));
result = result.substring(result.indexOf("<p>")+3 , result.indexOf("<\\/p>"));
}
}
else{
break;
}
wordCounter += result.length();
finalResult = finalResult + result + "\n";
}
return finalResult;
}
}
| takadas1/ProjectMoses | HTTPGet.java | 1,319 | /* Portion of Project Moses involving http get requests.
* Issues: Need to create switch for tags.
* Programmed by: Andrew Preuss && Andrew Miller
*/ | block_comment | en | false | 1,125 | 34 | 1,319 | 39 | 1,305 | 35 | 1,319 | 39 | 1,566 | 38 | false | false | false | false | false | true |
33572_2 | /* File: Images.java - April 2011 */
package sudoku;
import java.awt.Image;
import java.awt.Toolkit;
import java.net.URL;
import java.util.ArrayList;
import java.util.HashMap;
import javax.swing.ImageIcon;
/**
* Utility class that loads and stores all the images that are used in the app.
*
* @author Rudi Theunissen
*/
public class Images {
/** An array that contains all the number images - white, mini, green, red.*/
public Image[] numberImages;
/** Maps a filename to an image. */
public HashMap<String, Image> imageMap;
/** Maps a number type (white, mini, green red) to an array index value. */
public HashMap<String, Integer> numberImageMap;
/**
* Default Constructor - sets an instance up for image loading.
*
* @param loadGameImages whether or not to load the number images.
*/
public Images(boolean loadGameImages) {
if (loadGameImages) {
loadNumberPictures();
}
loadImages();
}
/**
* Loads all the non-number images into maps and arrays.
*/
private void loadImages() {
String[] names = new String[]{"sudoku-grid", "selector", "instructions",
"button-summary", "help-exceeded", "game-finished", "invalid-solve"};
ArrayList<Image> images = new ArrayList<Image>();
imageMap = new HashMap<String, Image>();
for (int i = 0; i < names.length; i++) {
Image current = getResourceImage(names[i]);
do {
images.add(current);
} while (current == null);
imageMap.put(names[i], images.get(i));
}
}
/**
* Loads the number images into maps and arrays.
*/
private void loadNumberPictures() {
numberImageMap = new HashMap<String, Integer>();
numberImageMap.put("white", 0);
numberImageMap.put("mini", 9);
numberImageMap.put("green", 18);
numberImageMap.put("red", 27);
// loads all the number images into the array.
numberImages = new Image[36];
for (int i = 1; i < 10; i++) {
numberImages[i - 1] = getResourceImage(i + "");
numberImages[i + 8] = getResourceImage(i + "-mini");
numberImages[i + 17] = getResourceImage(i + "-green");
numberImages[i + 26] = getResourceImage(i + "-red");
}
}
/**
* Loads and returns an {@link ImageIcon} resource.
*
* Reduces code clutter when loading image icon resources.
*
* @param fileName The path of the image resource.
* @return ImageIcon for a JButton's constructor parameter.
*/
public ImageIcon getImageIcon(String fileName) {
String imageDirectory = Sudoku.IMAGE_DIRECTORY;
URL imgURL = getClass().getResource(imageDirectory + fileName + ".gif");
Image image = Toolkit.getDefaultToolkit().getImage(imgURL);
ImageIcon imageIcon = new ImageIcon(image);
return imageIcon;
}
/**
* Loads and returns an {@link Image} resource.
*
* Reduces code clutter when loading an image resource from a file.
*
* @param fileName name of the image resource.
* @return Image as resource.
*/
private Image getResourceImage(String fileName) {
String imageDirectory = Sudoku.IMAGE_DIRECTORY;
URL imgURL = getClass().getResource(imageDirectory + fileName + ".gif");
Image image = Toolkit.getDefaultToolkit().getImage(imgURL);
return image;
}
/**
* Loads and returns a number {@link Image} resource.
*
* Reduces code clutter when loading a number image resource from a class.
*
* @param type specifies what type of number image - white, mini, green, red.
* @param numberImage The position (from 0 - 80) in the game array.
* @return Image as resource.
*/
public Image getNumberImage(String type, int numberImage) {
return numberImages[numberImage + numberImageMap.get(type) - 1];
}
/**
* Reduces code clutter when loading an image resource from a class.
*
* @param type specifies which image is being requested.
* @return Image as resource.
*/
public Image getImage(String type) {
return imageMap.get(type);
}
/**
* Returns the array that contains all the number images.
* @return the array that contains all the number images.
*/
public Image[] getNumberImagesArray() {
return numberImages;
}
}
| rtheunissen/sudoku | src/Images.java | 1,101 | /** An array that contains all the number images - white, mini, green, red.*/ | block_comment | en | false | 999 | 19 | 1,101 | 18 | 1,180 | 18 | 1,101 | 18 | 1,272 | 19 | false | false | false | false | false | true |
34107_2 | /**
* SimGuide.java
*
* Created on 10-Mar-2005
* City University
* BSc Computing with Distributed Systems
* Project title: Simulating Animal Learning
* Project supervisor: Dr. Eduardo Alonso
* @author Dionysios Skordoulis
*
* Modified in October-2009
* The Centre for Computational and Animal Learning Research
* @supervisor Dr. Esther Mondragon
* email: [email protected]
* @author Rocio Garcia Duran
*
* Modified in July-2011
* The Centre for Computational and Animal Learning Research
* @supervisor Dr. Esther Mondragon
* email: [email protected]
* @author Dr. Alberto Fernandez
* email: [email protected]
*
*/
package simulator;
import java.awt.Dimension;
import java.io.IOException;
import javax.swing.JEditorPane;
import javax.swing.JFrame;
import javax.swing.JOptionPane;
import javax.swing.JScrollPane;
/**
* SimGuide presents a new frame with a JEditorPane inside it. The last can be
* used to present a rich-text document such as html pages. This advantage will
* help the application to produce a html page with a anchor navigated system.
* This page will be the user guide, manual of this animal learning simulator.
*/
public class SimGuide extends JFrame {
private JScrollPane scrollPane;
private JEditorPane htmlPane;
/**
* SimGuide's main Constructor Method.
*
* @param title
* the frame's title.
* @throws Exception
* if the html file can not be found it throws an exception.
*/
public SimGuide(String title) throws Exception {
super(title);
try {
String file = "/Extras/guide.html";
java.net.URL fileURL = this.getClass().getResource(file);
if (fileURL != null) {
htmlPane = new JEditorPane(fileURL);
htmlPane.setContentType("text/html");
htmlPane.setEditable(false);
scrollPane = new JScrollPane(htmlPane);
scrollPane.setPreferredSize(new Dimension(850, 500));
getContentPane().add(scrollPane);
this.getContentPane().add(scrollPane);
this.pack();
this.setResizable(false);
this.setLocation(50, 50);
} else {
System.err.println("Couldn't find file");
}
} catch (IOException e) {
JOptionPane.showMessageDialog(null, e.getMessage());
}
}
}
| cal-r/sscctd | src/simulator/SimGuide.java | 647 | /**
* SimGuide's main Constructor Method.
*
* @param title
* the frame's title.
* @throws Exception
* if the html file can not be found it throws an exception.
*/ | block_comment | en | false | 534 | 51 | 647 | 48 | 626 | 58 | 647 | 48 | 758 | 61 | false | false | false | false | false | true |
34495_8 | import java.util.HashSet;
import java.util.Scanner;
public class TTT {
static HashSet<Integer> userset=new HashSet<Integer>();
static HashSet<Integer> cpuset=new HashSet<Integer>();
public static void main(String[] args) {
/*make 2d array for the board*/
char [][]g_board=
{
{' ','|',' ','|',' '},
{'-','|','-','|','-'},
{' ','|',' ','|',' '},
{'-','|','-','|','-'},
{' ','|',' ','|',' '},
};
print_board(g_board);
Scanner sc= new Scanner(System.in);
while(true)
{
/*for user input*/
System.out.print("Enter position 1 to 9: ");
int upos = sc.nextInt();
while(userset.contains(upos)|| cpuset.contains(upos))
{
System.out.println();
System.out.print("RETRY-Enter position 1 to 9: ");
upos = sc.nextInt();
}
pholder(g_board,upos,"You");
// print_board(g_board);
String res = chkwinner();
if(res.length()>0)
{
System.out.println(res);
break;
}
/*for cpu input*/
// System.out.print("Enter position 1 to 9: ");
int cpos = random();
while(userset.contains(cpos)|| cpuset.contains(cpos))
{
cpos = random();
}
pholder(g_board,cpos,"CPU");
print_board(g_board);
res = chkwinner();
if(res.length()>0)
{
System.out.println(res);
break;
}
}
}
/*method for generating random cpu input*/
static int random()
{
int max=9;
int min=1;
int range =max-min+1;
int cpuin = (int)(Math.random()*range)+min;
return cpuin;
}
/*check winnner method*/
static String chkwinner()
{
HashSet<Integer> r1 = new HashSet<Integer>();
r1.add(1);r1.add(2);r1.add(3);
HashSet<Integer> r2 = new HashSet<Integer>();
r2.add(4);r2.add(5);r2.add(6);
HashSet<Integer> r3 = new HashSet<Integer>();
r3.add(7);r3.add(8);r3.add(9);
HashSet<Integer> c1 = new HashSet<Integer>();
c1.add(1);c1.add(4);c1.add(7);
HashSet<Integer> c2 = new HashSet<Integer>();
c2.add(2);c2.add(5);c2.add(8);
HashSet<Integer> c3 = new HashSet<Integer>();
c3.add(3);c3.add(6);c3.add(9);
HashSet<Integer> d1 = new HashSet<Integer>();
d1.add(1);d1.add(5);d1.add(9);
HashSet<Integer> d2 = new HashSet<Integer>();
d2.add(3);d2.add(5);d2.add(7);
/*hashset of the above hashsets*/
HashSet<HashSet> h1=new HashSet<HashSet>();
h1.add(r1);h1.add(r2);h1.add(r3);
h1.add(c1);h1.add(c2);h1.add(c3);
h1.add(d1);h1.add(d2);
for(HashSet c:h1)
{
if(userset.containsAll(c))
{
return "YOU WON";
}
else if (cpuset.containsAll(c)) {
return "YOU LOST";
}
}
if (userset.size()+ cpuset.size()==9)
{
return "DRAW";
}
return "";
}
/*method to print board*/
static void print_board(char[][]g_board)
{
for (int r=0;r< g_board.length;r++)
{
for (int c=0;c< g_board[r].length;c++)
{
System.out.print(g_board[r][c]);
}
System.out.println();
}
}
/*method for position selected by user*/
static void pholder(char[][]g_board,int pos,String user)
{
char syb='X';
if(user.equals("You"))
{
syb='X';
userset.add(pos);
}
else if (user.equals("CPU"))
{
syb='O';
cpuset.add(pos);
}
switch(pos)
{
case 1:
{
g_board[0][0]=syb;
}break;
case 2:
{
g_board[0][2]=syb;
}break;
case 3:
{
g_board[0][4]=syb;
}break;
case 4:
{
g_board[2][0]=syb;
}break;
case 5:
{
g_board[2][2]=syb;
}break;
case 6:
{
g_board[2][4]=syb;
}break;
case 7:
{
g_board[4][0]=syb;
}break;
case 8:
{
g_board[4][2]=syb;
}break;
case 9:
{
g_board[4][4]=syb;
}break;
default:
{
System.out.println("Invalid Choice");
}
}
}
} | Saahil3/TicTacToe-Java-Game | TTT.java | 1,380 | /*method to print board*/ | block_comment | en | false | 1,203 | 6 | 1,380 | 6 | 1,533 | 6 | 1,380 | 6 | 1,647 | 6 | false | false | false | false | false | true |
35123_6 | import info.gridworld.actor.Actor;
import info.gridworld.grid.Location;
import info.gridworld.grid.Grid;
public class Ant extends Actor implements Comparable<Ant>
{
private static final int PATH_LENGTH = 32;
private static final double MUTATION_RATE = 0.05;
private String path;
private AntColony colony;
public Ant(AntColony c)
{
colony = c;
path = randomPath();
}
// define an ordering such that the Ant whose path get it closest
// to the food is greatest
public int compareTo(Ant other)
{
return other.distanceFromFood() - distanceFromFood();
}
// the number of steps it will take us to get to food from the end
// of our path. imagine that we can smell it or something
public int distanceFromFood()
{
Grid g = colony.getGrid();
// this casting thing is ugly but i don't see a way around it
// unless we put getDistanceToFood in this class which seems
// wrong. TBD: move the method here anyway.
if(!(g instanceof GeneticGrid)) return Integer.MAX_VALUE;
GeneticGrid gr = (GeneticGrid)g;
Location end = followPathFrom(colony.getLocation());
if(end == null) return Integer.MAX_VALUE;
if(!gr.isValid(end)) return Integer.MAX_VALUE;
return gr.getDistanceToFood(end);
}
public void setPath(String newPath)
{
path = newPath;
}
public String getPathWithMutations()
{
String mutatedPath = "";
if(path.length() < PATH_LENGTH && Math.random() < MUTATION_RATE)
path += (int)(Math.random()*4);
for(int i=0; i<path.length(); i++)
{
String c = path.substring(i,i+1);
if(Math.random() < MUTATION_RATE)
{
mutatedPath += (int)(Math.random()*4);
// a rare mutation causes shorter paths
if(Math.random() < MUTATION_RATE) break;
}
else
{
mutatedPath += c;
}
}
return mutatedPath;
}
public String randomPath()
{
String randPath = "";
for(int i=0; i<PATH_LENGTH; i++)
{
int r = (int)(Math.random()*4);
randPath += r;
}
return randPath;
}
public Location followPathFrom(Location start)
{
Grid gr = colony.getGrid();
Location end = new Location(start.getRow(), start.getCol());
for(int i=0; i<path.length(); i++)
{
int p = Integer.parseInt(path.substring(i,i+1));
end = end.getAdjacentLocation(p * 90);
if(!gr.isValid(end))
{
System.out.println("invalid path because " + end);
return null;
}
}
return end;
}
public String toString()
{
return "ANT (path "+path+")";
}
} | benchun/GeneticWorld | Ant.java | 768 | // wrong. TBD: move the method here anyway. | line_comment | en | false | 637 | 11 | 768 | 12 | 817 | 11 | 768 | 12 | 885 | 12 | false | false | false | false | false | true |
35339_0 | class TrieNode {
int count; //how many words are on this subtree
Map<Character, TrieNode> children;
boolean isWord;
public TrieNode() {
children = new HashMap<>();
isWord = false;
}
}
public class Trie {
TrieNode root;
public Trie() {
root = new TrieNode();
}
public void insert(String word) {
TrieNode curr = this.root;
for (int i = 0; i < word.length(); i++) {
char c = word.charAt(i);
if (!curr.children.containsKey(c)) {
curr.children.put(c, new TrieNode());
}
curr = curr.children.get(c);
}
curr.isWord = true;
}
public boolean search(String word) {
TrieNode curr = root;
for (int i = 0; i < word.length(); i++) {
char c = word.charAt(i);
if (!curr.children.containsKey(c)) {
return false;
}
curr = curr.children.get(c);
}
return curr.isWord;
}
public boolean startsWith(String prefix) {
TrieNode curr = root;
for (int i = 0; i < prefix.length(); i++) {
char c = prefix.charAt(i);
if (!curr.children.containsKey(c)) {
return false;
}
curr = curr.children.get(c);
}
return true;
}
public boolean delete(String word) {
if (!search(word)) {
return false;
}
TrieNode curr = root;
for (int i = 0; i < word.length(); i++) {
char c = word.charAt(i);
TrieNode next = curr.children.get(c);
next.count--;
if (next.count == 0) {
curr.children.remove(word.charAt(i)); //remove leaf, 到中间就知道只剩一个了
return true;
}
curr = curr.children.get(c);
}
curr.isWord = false; //remove 中间,中间的下面还有另外一个单词
return true;
}
private TrieNode searchNode(String prefix) {
TrieNode curr = root;
for (int i = 0; i < prefix.length(); i++) {
char c = prefix.charAt(i);
if (!curr.children.containsKey(c)) {
return null;
}
curr = curr.children.get(c);
}
return curr;
}
public List<String> findAllWordsWithPrefix(String prefix) {
List<String> results = new ArrayList<>();
TrieNode matchNode = searchNode(prefix);
if (prefix == null || prefix.length() == 0 || matchNode == null) {
return results;
}
findAllWordsUnderNode(matchNode, new StringBuilder(prefix), results);
return results;
}
private void findAllWordsUnderNode(TrieNode curr, StringBuilder sb, List<String> results) {
if (curr.isWord) {
results.add(new String(sb));
}
for (char c : curr.children.keySet()) {
sb.append(c);
findAllWordsUnderNode(curr.children.get(c), sb, results);
sb.remove(sb.length() - 1);
}
}
}
| Mol1122/leetcode | Trie.java | 793 | //how many words are on this subtree | line_comment | en | false | 673 | 8 | 793 | 8 | 861 | 8 | 793 | 8 | 931 | 9 | false | false | false | false | false | true |
35341_1 | import java.util.*;
import dacheng.utils.*;
class TrieNode {
public TrieNode children[] = new TrieNode[26];
public boolean isEndOfWord;
public TrieNode() {
isEndOfWord = false;
for (int i = 0; i < 26; ++i) {
children[i] = null;
}
}
};
class Trie {
/** Initialize your data structure here. */
public TrieNode root;
public Trie() {
root = new TrieNode();
}
/** Inserts a word into the trie. */
public void insert(String word) {
TrieNode node = root;
for (char c : word.toCharArray()) {
int index = c - 'a';
if (node.children[index] == null) {
node.children[index] = new TrieNode();
}
node = node.children[index];
}
node.isEndOfWord = true;
}
/** Returns if the word is in the trie. */
public boolean search(String word) {
TrieNode node = root;
for (char c : word.toCharArray()) {
int index = c - 'a';
if (node.children[index] == null)
return false;
node = node.children[index];
}
return node.isEndOfWord;
}
/** Returns if there is any word in the trie that starts with the given prefix. */
public boolean startsWith(String prefix) {
TrieNode node = root;
for (char c : prefix.toCharArray()) {
int index = c - 'a';
if (node.children[index] == null)
return false;
node = node.children[index];
}
return true;
}
}
| GaryZhous/A-collection-of-interesting-stuff | Trie.java | 404 | /** Inserts a word into the trie. */ | block_comment | en | false | 368 | 9 | 404 | 10 | 446 | 9 | 404 | 10 | 475 | 12 | false | false | false | false | false | true |
35468_3 | /**
*
* The User class holds the attributes of a User object. This class is used
* throughout the rest of the project.
*
*
* @author Niharika Raj, Saahil Mathur, Sam Balakhanei, Abhi Tandon
* @version December 8, 2023
*/
public class User {
private String username;
private String password;
private boolean userType; // true = student, false = tutor
// Used during sign up
public User(String username, String password, boolean userType) {
this.username = username;
this.password = password;
this.userType = userType;
}
// Used during login
public User(String username, String password) {
this.username = username;
this.password = password;
}
// Used while finding a user to chat with
public User(String username, boolean userType) {
this.username = username;
this.userType = userType;
}
public String getUsername() {
return this.username;
}
public String getPassword() {
return this.password;
}
public void setUserType(boolean userType) {
this.userType = userType;
}
public boolean getUserType() {
return this.userType;
}
} | SamBalakhanei/CS180P4 | User.java | 295 | // Used during login | line_comment | en | false | 263 | 4 | 295 | 4 | 305 | 4 | 295 | 4 | 336 | 5 | false | false | false | false | false | true |
36574_24 | import java.util.ArrayList;
/**
* Driver to test various methods of the DNA class
*
* You don't need to but you may update this class.
*
* @author Seth Kelley
* @author Aastha Gandhi
*/
public class Driver {
public static void main(String[] args) {
String setup[] = { "Setup Constructor", "New STRs File" }; // List of setup methods
String methods[] = { "Create Unknown Profile", "Calculate Databases STRs", "Calculate Unknown Profile STRs",
"Display Database Profiles", "Display Unknown Profile",
"Find Matching Profile", "Find Possible Parents", "Quit" }; // List of methods to test
String options[] = { "Test new STRs file", "Test new method on same files",
"Quit" }; // List of options to choose from
int repeatChoice = 1; // Controls the options to change file, retest methods or quit
DNA studentDNASimulation = null; // The DNA Object the students will test methods on
Profile studentUnknownProfile = null; // The unknown profile to run tests on
// Enter loop to setup
// Listed as a label here to break out of loop if needed
outer: do {
StdOut.println("\nPlease setup the constructor, than you may change to new files at a later time.\n");
// Displays setup choices
for (int i = 0; i < setup.length; i++) {
System.err.printf("%d. %s\n", i + 1, setup[i]);
}
// Prompts user for choice from setup menu
StdOut.print("\nEnter a number: ");
int choice1 = StdIn.readInt();
StdIn.readLine();
StdOut.println();
// Switch statement for the pick appropriate choice the user entered
switch (choice1) {
case 1:
studentDNASimulation = setupDNASimulation(); // Setup constructor
break;
case 2:
newReadAllSTRs(studentDNASimulation); // Reads new allSTRs file | must have constructor setup first
break;
default:
StdOut.println("Not a valid method to test!");
}
// Check for if contructor is null or not
if (studentDNASimulation != null) {
// Loops to tests methods if construcor isn't null
do {
StdOut.println("\nWhat method would you like to test?\n");
StdIn.resync();
// Lists the possible methods to test
for (int i = 0; i < methods.length; i++) {
System.err.printf("%d. %s\n", i + 1, methods[i]);
}
// Prompt user for which method to test
StdOut.print("\nEnter a number: ");
int choice2 = StdIn.readInt();
StdIn.readLine();
StdOut.println();
// Switch the choice to test desired method
switch (choice2) {
case 1:
// Create unknown profile
studentUnknownProfile = testCreateUnknownProfile(studentDNASimulation);
break;
case 2:
// Creates STRs for all database profiles
testCalculateDatabaseSTRs(studentDNASimulation);
break;
case 3:
// Creates STRs for unknown profile
testCalculateUnknownProfileSTRs(studentDNASimulation, studentUnknownProfile);
break;
case 4:
// Displays the database profiles
displayDatabaseProfiles(studentDNASimulation);
break;
case 5:
// Displays the unknown profile
displayUnknownProfile(studentUnknownProfile);
break;
case 6:
// Tests matching profile
testFindMatchingProfile(studentDNASimulation, studentUnknownProfile);
break;
case 7:
// Tests possible parents
testFindPossibleParents(studentDNASimulation, studentUnknownProfile);
break;
case 8:
break outer; // Exits program
default:
StdOut.println("Not a valid method to test!");
}
StdIn.resync();
// Displays options to user
StdOut.println("\nWhat would you like to do now?\n");
for (int i = 0; i < options.length; i++) {
System.err.printf("%d. %s\n", i + 1, options[i]);
}
// Promts user for choice
StdOut.print("\nEnter a number: ");
repeatChoice = StdIn.readInt();
StdIn.readLine();
StdOut.println();
// Loops or exits depending on last choice
} while (repeatChoice == 2);
}
} while (repeatChoice == 1);
}
/**
* Initialization of the DNA Object for the student to do methods on
*
* @return The DNA object
*/
private static DNA setupDNASimulation() {
StdOut.print("Enter the database file name: ");
String database = StdIn.readLine();
StdOut.print("Enter the STRs file name: ");
String allSTRs = StdIn.readLine();
DNA myDNASimulation = new DNA(database, allSTRs);
return myDNASimulation;
}
/**
* Checks to see is the DNA instance variable has been initialized
*
* @param studentDNASimulation DNA Object to check initialization on
* @return True if not initialized, false otherwise
*/
private static boolean constructorNullCheck(DNA studentDNASimulation) {
if (studentDNASimulation == null) {
StdOut.println("Constructor not initialized yet!");
return true;
}
return false;
}
/**
* Checks to see if unknown profile has been initialized
*
* @param studentUnknownProfile Unknown Profile to check initialization on
* @return True if not initialized, false otherwise
*/
private static boolean unknownProfileNullCheck(Profile studentUnknownProfile) {
if (studentUnknownProfile == null) {
StdOut.println("Unknown Profile not initialized yet!");
return true;
}
return false;
}
/**
* If a new allSTRs file is desired to be tested this method will prompt for a
* new file
*
* @param studentDNASimulation DNA Object to check initialization on
*/
private static void newReadAllSTRs(DNA studentDNASimulation) {
// Must be initialized first
if (constructorNullCheck(studentDNASimulation))
return;
StdOut.print("Enter the new STRs file name: ");
String allSTRs = StdIn.readLine();
studentDNASimulation.readAllSTRsOfInterest(allSTRs);
}
/**
* Creates the unknown profile
*
* @param studentDNASimulation DNA Object to create the profile
* @return The unknown profile
*/
private static Profile testCreateUnknownProfile(DNA studentDNASimulation) {
StdOut.print("Enter the file name of the Unknown Profile DNA: ");
String unknownDNA = StdIn.readLine();
Profile myUnknownProfile = studentDNASimulation.createUnknownProfile(unknownDNA);
StdOut.println("Creating Unknown Profile...");
StdOut.println(
"Unknown Profile created successfully.\nSelect \"Calculate Unknown Profile STRs\" to find add STRs to the Unknown Profile");
return myUnknownProfile;
}
/**
* Calculates the STRs for all the profiles in the database
*
* @param studentDNASimulation DNA Object to call the method to calculate
* database STRs and get allSTRs
*/
private static void testCalculateDatabaseSTRs(DNA studentDNASimulation) {
studentDNASimulation.createDatabaseSTRs();
StdOut.println("Sending profiles to the lab to determine their STRs...");
StdOut.println(
"Database STRs for each Profile have been calculated.\nSelect \"Display Database Profiles\" to see the profiles.");
}
/**
* Calculates the STRs of the unknown profile
*
* @param studentDNASimulation DNA Object to call the methods to calculate the
* STRs
* @param studentUnknownProfile Unknown profile to to be used for creation of
* their STRs
*/
private static void testCalculateUnknownProfileSTRs(DNA studentDNASimulation, Profile studentUnknownProfile) {
// Must be initialized first
if (unknownProfileNullCheck(studentUnknownProfile))
return;
studentDNASimulation.createProfileSTRs(studentUnknownProfile,
studentDNASimulation.getSTRsOfInterest());
StdOut.println("Sending Unknown Profile to the lab to determine their STRs...");
StdOut.println(
"Unknown Profile STRs have been calculated.\nSelect \"Display Unknown Profile\" to see the Unknown Profile");
}
/**
* Displays the Database Profiles in full
*
* @param studentDNASimulation DNA Object to get the database of profiles to
* display
*/
private static void displayDatabaseProfiles(DNA studentDNASimulation) {
StdOut.println("All Profiles in the database:");
for (int i = 0; i < studentDNASimulation.getDatabase().length; i++) {
StdOut.println(studentDNASimulation.getDatabase()[i]);
}
}
/**
* Displays the unknown profile to display
*
* @param studentUnknownProfile The profile to be displaayed
*/
private static void displayUnknownProfile(Profile studentUnknownProfile) {
if (unknownProfileNullCheck(studentUnknownProfile))
return;
StdOut.println("Unknown persons profile:");
StdOut.println(studentUnknownProfile);
}
/**
* Method to test for matching profile of the unknown profile
*
* @param studentDNASimulation DNA Object to call find matching profile method
* and gets the database to use
* @param studentUnknownProfile The unknown profile to pass in their C1 STRs
*/
private static void testFindMatchingProfile(DNA studentDNASimulation, Profile studentUnknownProfile) {
if (unknownProfileNullCheck(studentUnknownProfile))
return;
ArrayList<Profile> matches = studentDNASimulation.findMatchingProfiles(studentUnknownProfile.getS1_STRs());
StdOut.println("Matching Profile(s) found:");
// For each loop to print all possible matches
for (Profile p : matches)
StdOut.println(p);
}
/**
* Method to test for finding possible parents
*
* @param studentDNASimulation DNA Object to call finding parents method and
* getting the database to use
* @param studentUnknownProfile Unknown profile to pass in the STRs for S1 and
* S2
*/
private static void testFindPossibleParents(DNA studentDNASimulation, Profile studentUnknownProfile) {
if (unknownProfileNullCheck(studentUnknownProfile))
return;
ArrayList<Profile> parentsList = studentDNASimulation.findPossibleParents(
studentUnknownProfile.getS1_STRs(),
studentUnknownProfile.getS2_STRs());
StdOut.println("Possible parents found:");
for (int i = 0; i < parentsList.size(); i += 2) {
StdOut.println("\n" + parentsList.get(i).getName() + ", " + parentsList.get(i + 1).getName());
}
}
}
| mtahoor/DNA | Driver.java | 2,500 | // Tests matching profile | line_comment | en | false | 2,411 | 4 | 2,500 | 4 | 2,741 | 4 | 2,500 | 4 | 3,015 | 5 | false | false | false | false | false | true |
36953_2 | import android.support.annotation.NonNull;
import java.util.ArrayList;
import java.util.List;
/**
* Created by rahulchowdhury on 12/2/16.
* <p>
* Pacman - Parallel API Call Manager
* <p>
* This utility class allows you to manage API calls that happen
* in parallel and receive a combined or reduced callback when
* all the specified calls have been performed
* <p>
* Just setup Pacman with the required API calls and update as
* and when the calls are made
* <p>
* Made with love by Rahul Chowdhury
*/
public class Pacman {
private static final List<CallGroup> mRequestedCallGroups = new ArrayList<>();
private static final List<CallGroup> mCompletedCallGroups = new ArrayList<>();
private static OnCallsCompleteListener mOnCallsCompleteListener;
/**
* Check whether all specified API calls are completed
*/
private static void checkForApiCallsCompletion() {
boolean allCallsComplete = true;
for (CallGroup callGroup : mRequestedCallGroups) {
if (!mCompletedCallGroups.contains(callGroup)) {
allCallsComplete = false;
break;
} else {
int indexOfSelectedCallGroup = mCompletedCallGroups.indexOf(callGroup);
CallGroup selectedGroup = mCompletedCallGroups.get(indexOfSelectedCallGroup);
if (selectedGroup.getCalls() < callGroup.getCalls()) {
allCallsComplete = false;
break;
}
}
}
//If all calls are made then fire a callback to the listener
if (allCallsComplete) {
mOnCallsCompleteListener.onCallsCompleted();
}
}
/**
* Required to initialize Pacman with the API call groups details
* and a callback listener to be notified when all calls have been
* completed
*
* @param callGroups An ArrayList of CallGroup objects with details for the call groups
* @param onCallsCompleteListener A callback listener to get notified when all calls are finished
*/
public static void initialize(@NonNull List<CallGroup> callGroups,
@NonNull OnCallsCompleteListener onCallsCompleteListener) {
mRequestedCallGroups.clear();
mCompletedCallGroups.clear();
mRequestedCallGroups.addAll(callGroups);
mOnCallsCompleteListener = onCallsCompleteListener;
}
/**
* Post an API call update to a specific call group
*
* @param groupId ID for the Call Group
*/
public static void postCallGroupUpdate(long groupId) {
CallGroup callGroupToUpdate = new CallGroup(groupId, 0);
if (!mRequestedCallGroups.contains(callGroupToUpdate)) {
return;
}
if (mCompletedCallGroups.contains(callGroupToUpdate)) {
int indexOfSpecifiedCallGroup = mCompletedCallGroups.indexOf(callGroupToUpdate);
CallGroup specifiedCallGroup = mCompletedCallGroups.get(indexOfSpecifiedCallGroup);
int callsMade = specifiedCallGroup.getCalls() + 1;
specifiedCallGroup.setCalls(callsMade);
mCompletedCallGroups.remove(indexOfSpecifiedCallGroup);
mCompletedCallGroups.add(specifiedCallGroup);
} else {
mCompletedCallGroups.add(new CallGroup(groupId, 1));
}
checkForApiCallsCompletion();
}
/**
* Post an API call update to a specific call group and also
* increase the no of calls to expect for that group
*
* @param groupId ID for the specific call group
* @param callsToAdd No of calls to add to that group
*/
public static void postCallGroupUpdate(long groupId, int callsToAdd) {
CallGroup callGroupToUpdate = new CallGroup(groupId, 0);
if (mRequestedCallGroups.contains(callGroupToUpdate)) {
int indexOfSpecifiedCallGroup = mRequestedCallGroups.indexOf(callGroupToUpdate);
CallGroup specifiedCallGroup = mRequestedCallGroups.get(indexOfSpecifiedCallGroup);
int callsToMake = specifiedCallGroup.getCalls() + callsToAdd;
specifiedCallGroup.setCalls(callsToMake);
mRequestedCallGroups.remove(indexOfSpecifiedCallGroup);
mRequestedCallGroups.add(specifiedCallGroup);
}
postCallGroupUpdate(groupId);
}
public interface OnCallsCompleteListener {
void onCallsCompleted();
}
}
| rahulchowdhury/Pacman | Pacman.java | 968 | //If all calls are made then fire a callback to the listener | line_comment | en | false | 912 | 13 | 968 | 13 | 1,031 | 13 | 968 | 13 | 1,144 | 13 | false | false | false | false | false | true |
37655_0 | import java.util.Locale;
import java.util.Scanner;
public class Email{
private String firstName;
private String lastName;
private String password;
private String department;
private String email;
private int mailboxCapacity = 500;
private int defaultPasswordLength = 10;
private String alternateEmail;
private String companySuffix = ".company.com";
// Constructor to receive the first name and last name
public Email(String firstName, String lastName){
this.firstName = firstName;
this.lastName = lastName;
System.out.println("Email created: " + this.firstName + " " + this.lastName);
//Call a method asking for th department - return the department
this.department = setDepartment();
System.out.println("Department: " + this.department);
//Call a method that returns a random password
this.password = randomPassword(defaultPasswordLength);
System.out.println("Your password is: " + this.password);
//Combine elements to generate email
email = firstName.toLowerCase() + "." + lastName.toUpperCase() + "@" + department + companySuffix;
}
//Ask for the department
private String setDepartment(){
System.out.println("1 for Sales\n2 for Development\n3 for Accounting\n0 for none\nEnter the department code");
Scanner in = new Scanner(System.in);
int choice = in.nextInt();
if (choice == 1){return "sales";}
else if (choice == 2) { return "dev";}
else if (choice == 3) {return "acct";}
else {return "";}
}
//Generate a random password
private String randomPassword(int length){
String passwordSet = "ABCDEFGHIJKLMOPQRSTUVWXYZ0123456789!@#$%";
char[]password = new char[length];
for (int i = 0; i<length; i++){
int rand = (int)(Math.random() * passwordSet.length());
password[i] = passwordSet.charAt(rand);
}
return new String(password);
}
//Set the mailbox capacity
public void setMailboxCapacity(int capacity){
this.mailboxCapacity = capacity;
}
//Set the alternate email
public void setAlternateEmail(String altEmail){
this.alternateEmail = altEmail;
}
//Change the password
public void changePassword(String password){
this.password = password;
}
public int getMailboxCapacity() { return mailboxCapacity;}
public String getAlternateEmail() { return alternateEmail; }
public String getPassword(){return password;}
//Display the worker's information
public String showInfo(){
return "DISPLAY NAME: " + firstName + " " + lastName +
"\nCOMPANY EMAIL: " + email +
"\nMAILBOX CAPACITY: " + mailboxCapacity + "mb";
}
} | Jed0203/EmailApp | Email.java | 648 | // Constructor to receive the first name and last name
| line_comment | en | false | 605 | 11 | 648 | 11 | 738 | 11 | 648 | 11 | 837 | 12 | false | false | false | false | false | true |
38597_6 | /*
* This code was written for an assignment for concept demonstration purposes:
* caution required
*
* The MIT License
*
* Copyright 2014 Victor de Lima Soares.
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
import crypto.ciphers.Cipher;
import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.security.NoSuchAlgorithmException;
/**
* Assignment 1 - CSS 527 A - Fall 2014 UWB
*
* <p>
* High level modeling for DES encryption algorithm in CBC mode.
* </p>
*
* @author Victor de Lima Soares
* @version 1.0
*/
public class DES {
/**
* Cipher to be used for encryption/decryption operations.
*/
private static final Cipher des = new crypto.ciphers.block.feistel.des.DES();
/**
* Main function to execute the commands passed by command line.
*
* @since 1.0
* @param args Arguments for execution. Options:
* <ul>
* <li>genkey password outputFile </li>
* <li>encrypt inputFile keyFile outputFile </li>
* <li>decrypt inputFile keyFile outputFile </li>
* </ul>
* @throws IOException
* <ul>
* <li>If it fails to open, reads or write in any of the files passed as argument.</li>
* </ul>
* @throws FileNotFoundException
* <ul>
* <li>If it fails to find any of the files passed as argument.</li>
* </ul>
* @throws NoSuchAlgorithmException
* <ul>
* <li>If it fails to find the UTF-8 encoding algorithm to encode the password string.</li>
* </ul>
*/
public static void main(String[] args) throws IOException, FileNotFoundException, NoSuchAlgorithmException {
switch (args[0]) {
case "genkey":
writePassword(args[1], args[2]);
break;
case "encrypt":
encrypt(args[1], args[2], args[3]);
break;
case "decrypt":
decrypt(args[1], args[2], args[3]);
break;
default:
System.err.println("Command not reconized. Options are:");
System.err.println("genkey password outputFile");
System.err.println("encrypt inputFile keyFile outputFile");
System.err.println("decrypt inputFile keyFile outputFile");
}
}
/**
* Writes a binary file containing a MD5 hash for the password string
* encoded as utf-8.
*
* @since 1.0
* @param password Password String.
* @param fileName Output file name.
* @throws FileNotFoundException
* @throws IOException
* @throws NoSuchAlgorithmException
*/
private static void writePassword(String password, String fileName) throws FileNotFoundException, IOException, NoSuchAlgorithmException {
try (OutputStream file = new BufferedOutputStream(new FileOutputStream(fileName))) {
file.write(((crypto.ciphers.block.feistel.des.DES) des).genkey(password.getBytes("UTF-8")));
}
}
/**
* Reads the password to be used on encryption and decryption.
*
* @since 1.0
* @param passwordFile Password file name.
* @return The key read.
*
* @throws FileNotFoundException
* @throws IOException
*/
private static byte[] readKey(String passwordFile) throws FileNotFoundException, IOException {
try (InputStream file = new BufferedInputStream(new FileInputStream(passwordFile))) {
byte buffer[] = new byte[8];
file.read(buffer);
return buffer;
}
}
/**
* Encrypts a file, recording the resulting data in the specified file.
*
* @since 1.0
* @param inputFileName Name of the file to be read.
* @param passwordFile Name for the file that contains the key for
* encryption.
* @param outputFileName Name of the output file.
* @throws IOException
*/
private static void encrypt(String inputFileName, String passwordFile, String outputFileName) throws IOException {
try (InputStream input = new BufferedInputStream(new FileInputStream(inputFileName));
OutputStream output = new BufferedOutputStream(new FileOutputStream(outputFileName))) {
des.encrypt(input, readKey(passwordFile), output);
}
}
/**
* Decrypts a file, recording the resulting data in the specified file.
*
* @since 1.0
* @param inputFileName Name of the file to be read.
* @param passwordFile Name for the file that contains the key for
* decryption.
* @param outputFileName Name of the output file.
* @throws IOException
*/
private static void decrypt(String inputFileName, String passwordFile, String outputFileName) throws IOException {
try (InputStream input = new BufferedInputStream(new FileInputStream(inputFileName));
OutputStream output = new BufferedOutputStream(new FileOutputStream(outputFileName))) {
des.decrypt(input, readKey(passwordFile), output);
}
}
}
| victorlima02/Crypto | src/DES.java | 1,407 | /**
* Encrypts a file, recording the resulting data in the specified file.
*
* @since 1.0
* @param inputFileName Name of the file to be read.
* @param passwordFile Name for the file that contains the key for
* encryption.
* @param outputFileName Name of the output file.
* @throws IOException
*/ | block_comment | en | false | 1,306 | 82 | 1,407 | 79 | 1,533 | 89 | 1,407 | 79 | 1,730 | 90 | false | false | false | false | false | true |
39582_25 | import java.net.URL;
import java.sql.Date;
import java.text.SimpleDateFormat;
import javafx.geometry.Pos;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.image.Image;
import javafx.scene.image.ImageView;
import javafx.scene.layout.Background;
import javafx.scene.layout.BackgroundImage;
import javafx.scene.layout.BackgroundPosition;
import javafx.scene.layout.BackgroundRepeat;
import javafx.scene.layout.BackgroundSize;
import javafx.scene.layout.VBox;
import javafx.scene.text.Font;
import javafx.scene.text.Text;
/**
*
* @author Alyza Diaz Rodriguez
*
*/
public class Player {
private String teamName;
private String name;
private int number;
private String flag;
private String position;
private String height;
private int weight;
private int experience;
private Date dob;
private int age;
private Image photo;
private ImageView view;
private ImageView copy;
private Image country;
private ImageView viewCountry;
private Button button;
private Button back;
private VBox vbox;
private Scene scene;
private BackgroundImage background;
private ClassLoader cl;
/**
* Initializes a new player with the following variables:
* @param a - team name
* @param b - name
* @param c - jersey number
* @param d - country/flag
* @param f - position
* @param g - height
* @param h - weight
* @param i - years of experience
* @param j - birthday
* @param k - age
*/
public Player(String a, String b, int c, String d, String f, String g, int h, int i, Date j, int k) {
teamName = a;
name = b;
number = c;
flag = d;
position = f;
height = g;
weight = h;
experience = i;
dob = j;
age = k;
button = new Button();
back = new Button("Back");
vbox = new VBox(10);
vbox.setAlignment(Pos.CENTER);
scene = new Scene(vbox, 900, 900);
setCountry(flag);
viewCountry = new ImageView(country);
cl = this.getClass().getClassLoader();
}
/**
* Will change the name of the player's team to a.
* @param a - team name
*/
public void setTeam(String a) {
teamName = a;
}
/**
* Returns the player's name
* @return
*/
public String getTeam() {
return teamName;
}
/**
* Change the player's name to b
* @param b - name
*/
public void setName(String b) {
name = b;
}
/**
* Returns the player's name
* @return
*/
public String getName() {
return name;
}
/**
* Sets the player's jersey number
* @param c - number
*/
public void setNumber(int c) {
number = c;
}
/**
* Returns the player's jersey number
* @return
*/
public int getNumber() {
return number;
}
/**
* Sets the player's country of origin
* @param d - flag
*/
public void setFlag(String d) {
flag = d;
}
/**
* Gets the player's country of origin
* @return
*/
public String getFlag() {
return flag;
}
/**
* Sets the player's game position
* @param f - position
*/
public void setPos(String f) {
position = f;
}
/**
* Returns the player's game position
* @return
*/
public String getPos() {
return position;
}
/**
* Sets player's height
* @param g - height
*/
public void setHeight(String g) {
height = g;
}
/**
* Gets players height
* @return
*/
public String getHeight() {
return height;
}
/**
* Sets the player's weight
* @param h - weight
*/
public void setWeight(int h) {
weight = h;
}
/**
* Gets the player's weight
* @return
*/
public int getWeight() {
return weight;
}
/**
* Sets the player's number of years of experience
* @param i - experience
*/
public void setExp(int i) {
experience = i;
}
/**
* Gets the player's number of years of experience
* @return
*/
public int getExp() {
return experience;
}
/**
* Sets the player's birthday
* @param j - dob
*/
public void setDOB(Date j) {
dob = j;
}
/**
* Gets the player's birthday
* @return
*/
public Date getDOB() {
return dob;
}
/**
* Sets the player's age
* @param k - age
*/
public void setAge(int k) {
age = k;
}
/**
* Gets the player's age
* @return
*/
public int getAge() {
return age;
}
/**
* Prints out all of a player's information
*/
public void print() {
System.out.printf("%s, %s #%d, %s, %s, height: %s, %d lbs, %d years of exp., ",
teamName, name, number, flag, position, height, weight, experience);
System.out.printf("%1$tA, %1$tB %1$tY,", dob);
System.out.printf(" %d years old\n", age);
}
/**
* Creates and sets the player's photo
*/
public void createPhoto(URL url) {
photo = new Image(url.toString());
view = new ImageView(photo);
view.setFitWidth(100);
view.setFitHeight(100);
//a copy of the player's headshot
copy = new ImageView(photo);
copy.setFitWidth(250);
copy.setFitHeight(250);
}
/**
* Gets the player's photo
* @return
*/
public ImageView getPhoto() {
return view;
}
/**
* Matches the player with their country flag image
* @param f - country abbreviation
*/
private void setCountry(String f) {
cl = this.getClass().getClassLoader();
switch(f) {
case "CAN":
country = new Image(cl.getResource("flags/can.png").toString());
break;
case "CZE":
country = new Image(cl.getResource("flags/cze.png").toString());
break;
case "FIN":
country = new Image(cl.getResource("flags/fin.png").toString());
break;
case "SVK":
country = new Image(cl.getResource("flags/svk.png").toString());
break;
case "SWE":
country = new Image(cl.getResource("flags/swe.png").toString());
break;
case "USA":
country = new Image(cl.getResource("flags/usa.png").toString());
}
}
/**
* Displays the player's country flag
* @return
*/
public ImageView getCountryFlag() {
return viewCountry;
}
/**
* Sets the player's button
* @param b
*/
public void setButton(Button b) {
button = b;
}
/**
* Returns the player's button
* @return
*/
public Button getButton() {
return button;
}
/**
* Returns the player's back button
* @return
*/
public Button getBack() {
return back;
}
/**
* Returns the player's VBox
* @return
*/
public VBox getBox() {
return vbox;
}
/*
* Returns the background image
*/
public BackgroundImage getBackground() {
return background;
}
/**
* Sets up the player's background with their action shot
*/
private void createBackG() {
String team = "";
switch(teamName) {
case "Bruins":
team = "bruins background.png";
break;
case "Blackhawks":
team = "hawks background.png";
break;
}
background = new BackgroundImage(new Image(cl.getResource("misc/"+team).toString(), 900, 900, false, true),
BackgroundRepeat.NO_REPEAT, BackgroundRepeat.NO_REPEAT, BackgroundPosition.CENTER,
BackgroundSize.DEFAULT);
vbox.setBackground(new Background(background));
}
/**
* Sets up the player's information page
*/
public void setup() {
Font bankFont = Font.loadFont(cl.getResource("misc/F25_Bank_Printer.otf").toString(), 15);
Font brushFont = Font.loadFont(cl.getResource("misc/brush.otf").toString(), 50);
Text tn = new Text(teamName);
tn.setFont(bankFont);
Text n = new Text(name);
n.setFont(brushFont);
Text j = new Text("#"+Integer.toString(number));
j.setFont(bankFont);
Text f = new Text("Country of Origin: "+flag);
f.setFont(bankFont);
Text p = new Text("Position: "+position);
p.setFont(bankFont);
Text h = new Text("Height: "+height);
h.setFont(bankFont);
Text e = new Text("Years of experience: "+Integer.toString(experience));
e.setFont(bankFont);
SimpleDateFormat form = new SimpleDateFormat("MM/dd/yyyy");
Text b = new Text("Birthday: "+form.format(dob));
b.setFont(bankFont);
Text a = new Text("Age: "+Integer.toString(age));
a.setFont(bankFont);
createBackG();
vbox.getChildren().addAll(viewCountry, copy, tn, n, j, f, p, h, e, b, a, back);
}
/**
* Returns the player's scene
* @return
*/
public Scene getScene() {
return scene;
}
}
| alyzadiaz/nhl | Player.java | 2,614 | /**
* Gets the player's photo
* @return
*/ | block_comment | en | false | 2,259 | 16 | 2,614 | 14 | 2,930 | 20 | 2,614 | 14 | 3,283 | 22 | false | false | false | false | false | true |
40274_4 | public class Leader implements NodeState {
private Node node;
private Watch watch;
public Leader(Node node) {
this.node = node;
}
@Override
public void work() {
sendAppendRequests();
this.watch = new Watch(74,75,this);
this.watch.start();
}
@Override
public void reactVoteRequest(VoteRequest message) {
//leader don't care about vote request
}
@Override
public void reactVoteReply(VoteReply message) {
//leader don't care about vote reply
}
@Override
public void reactAppendRequest(AppendRequest message) {
// see if there are leaders
if( message.getTerm() > this.node.getTerm()){
this.node.setState("Follower");
}
}
@Override
public void reactAppendReply(AppendReply message) {
if ( message.getTo().equals(this.node.getServiceAddress()) && message.getTerm()==this.node.getTerm()){
//different commit leader and follower
//try to sync replica
if(this.node.getCurrentCommitIndex() > message.getCommitIndex()){
Change c;
c = this.node.getChange(message.getCommitIndex()+1);
sendDirectedAppendRequest(message.getTo(),c,message.getCommitIndex()+1);
}
}
}
@Override
public void call() {
//call happens but state is different
if(!this.getState().equals(this.node.getCurrentState())) {
return;
}
work();
}
@Override
public String getState() {
return "Leader";
}
private void sendAppendRequests(){
Change c =checkForNewChanges();
Message m = MessageConstructor.constructApeendRequest(this.node,c);
this.node.sendUDPMessage(m);
}
private Change checkForNewChanges(){
Change c;
c = this.node.getChange(this.node.getPreviousCommitIndex()+1);
if(c!=null) {
this.node.setPreviousCommitIndex(this.node.getPreviousCommitIndex() + 1);
}
return c;
}
private void sendDirectedAppendRequest(Address to, Change change, int commit_index){
Message m = MessageConstructor.constructDirectApeendRequest(this.node,to,change,commit_index);
this.node.sendUDPMessage(m);
}
}
| LuckeLucky/Distributed-Systems | Leader.java | 547 | //try to sync replica | line_comment | en | false | 492 | 5 | 547 | 5 | 608 | 5 | 547 | 5 | 673 | 6 | false | false | false | false | false | true |
40461_2 | import java.text.DateFormat;
import java.time.Duration;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Collections;
import java.util.Comparator;
import java.util.GregorianCalendar;
/**
* Stores basic movie information.
*/
public class Movie implements Comparable<Movie> {
private final String title;
private final double rating;
private final Calendar released;
private final Duration length;
/**
* Initializes a new movie object.
*
* @param title the title of the movie
* @param released the release date of the movie
* @param length the length of the movie
* @param rating the IMDB rating of the movie
*/
public Movie(String title, Calendar released, Duration length, double rating) {
this.title = title;
this.released = released;
this.length = length;
this.rating = rating;
}
/**
* Returns the movie title
* @return movie title
*/
public String title() {
return this.title;
}
/**
* Returns the movie rating from IMDB.
* @return IMDB rating
*/
public double rating() {
return this.rating;
}
/**
* Returns the year this movie was released.
* @return year released
*/
public int year() {
return this.released.get(Calendar.YEAR);
}
/**
* Returns the length in minutes.
* @return length in minutes
*/
public long minutes() {
return this.length.toMinutes();
}
@Override
public String toString() {
DateFormat dateFormat = DateFormat.getDateInstance(DateFormat.SHORT);
String stringFormat = "\"%s\", released %s, %d minutes long, %2.1f rating";
Object[] args = {
this.title,
dateFormat.format(this.released.getTime()),
this.minutes(),
this.rating
};
return String.format(stringFormat, args);
}
/**
* Compares two {@link Movie} objects first by their title ignoring case in
* ascending order, and if the titles are equal, then by their release date in
* descending order.
*
* @see String#compareToIgnoreCase(String)
* @see String#CASE_INSENSITIVE_ORDER
* @see Comparator#comparing(java.util.function.Function)
* @see Comparator#thenComparing(Comparator)
* @see Movie#title
* @see Movie#released
*/
@Override
public int compareTo(Movie other) {
// TODO Implement this however you want.
return 0;
}
// TODO Implement by creating a private static nested class and creating an instance.
/**
* A {@link Comparator} that orders {@link Movie} objects by their title in
* case insensitive ascending order.
*
* @see String#compareToIgnoreCase(String)
* @see String#CASE_INSENSITIVE_ORDER
* @see Movie#title
*/
public static final Comparator<Movie> TITLE_CASE_INSENSITIVE_ORDER = null;
// TODO Implement by creating an anonymous inner class.
/**
* A {@link Comparator} that orders {@link Movie} objects by their length in
* ascending order.
*
* @see Duration#compareTo(Duration)
* @see Movie#length
*/
public static final Comparator<Movie> LENGTH_ORDER = null;
// TODO Implement using a lambda expression.
/**
* A {@link Comparator} that orders {@link Movie} objects by their release date
* in descending order.
*
* @see Calendar#compareTo(Calendar)
* @see Movie#released
*/
public static final Comparator<Movie> RELEASE_ORDER = null;
// TODO Implement using Comparator.comparingDouble and a method reference.
/**
* A {@link Comparator} that orders {@link Movie} objects by their rating in
* ascending order.
*
* @see Comparator#comparingDouble(java.util.function.ToDoubleFunction)
* @see Movie#rating
*/
public static final Comparator<Movie> RATING_ORDER = null;
/**
* Creates and outputs a movie instance.
*
* @param args unused
*/
public static void main(String[] args) {
// TODO You may modify this however you want.
Movie m1 = new Movie(
"The Lord of the Rings: The Fellowship of the Ring",
new GregorianCalendar(2001, Calendar.DECEMBER, 19),
Duration.ofHours(2).plusMinutes(58),
8.8);
Movie m2 = new Movie(
"The Lord of the Rings: The Two Towers",
new GregorianCalendar(2002, Calendar.DECEMBER, 18),
Duration.ofHours(2).plusMinutes(59),
8.7);
Movie m3 = new Movie(
"The Lord of the Rings: The Return of the King",
new GregorianCalendar(2003, Calendar.DECEMBER, 17),
Duration.ofHours(3).plusMinutes(21),
8.9);
ArrayList<Movie> movies = new ArrayList<>();
Collections.addAll(movies, m2, m1, m3);
Collections.sort(movies);
movies.forEach(System.out::println);
System.out.println();
}
}
| usf-cs212-fall2018/template-moviesorter | src/Movie.java | 1,283 | /**
* Returns the movie title
* @return movie title
*/ | block_comment | en | false | 1,123 | 17 | 1,283 | 15 | 1,311 | 18 | 1,283 | 15 | 1,526 | 18 | false | false | false | false | false | true |
40652_2 | import java.io.File;
import java.io.IOException;
import java.util.*;
public class IMDBGraph {
protected static class IMDBNode implements Node {
final private String _name;
final private Collection<IMDBNode> _neighbors;
/**
* Constructor
* @param name the name of the node
*/
public IMDBNode(String name) {
_name = name;
_neighbors = new ArrayList<>();
}
/**
* Adds n as a neighbor to the current node
* @param n the node
*/
protected void addNeighbor(IMDBNode n) {
_neighbors.add(n);
}
/**
* Returns the name of the node
* @return the name of the node
*/
@Override
public String getName() {
return _name;
}
/**
* Returns the collection of all the neighbors of the node
* @return the collection of all the neighbors of the node
*/
@Override
public Collection<IMDBNode> getNeighbors() {
return _neighbors;
}
/**
* Overrides original equals only to compare names of the node
* @param o an object to compare to the called object
*/
@Override
public boolean equals(Object o) {
return (((Node) o).getName().equals(_name));
}
}
final protected static class ActorNode extends IMDBNode {
/**
* Constructor
* @param name the name of the actor
*/
public ActorNode(String name) {
super(name);
}
}
final protected static class MovieNode extends IMDBNode {
/**
* Constructor
* @param name the name of the movie
*/
public MovieNode(String name) {
super(name);
}
}
final protected Map<String, ActorNode> actors;
final protected Map<String, MovieNode> movies;
/**
* Constructor
* @param actorsFilename the filename of the actors
* @param actressesFilename the filename of the actresses
* @throws IOException if the file is not found
*/
public IMDBGraph(String actorsFilename, String actressesFilename) throws IOException {
final Scanner actorsScanner = new Scanner(new File(actorsFilename), "ISO-8859-1");
final Scanner actressesScanner = new Scanner(new File(actressesFilename), "ISO-8859-1");
actors = new LinkedHashMap<>();
movies = new LinkedHashMap<>();
parseData(actorsScanner);
parseData(actressesScanner);
}
/**
* Parses through the given files from the scanner to construct a graph
* @param scanner the scanner object used for the IMDB files
*/
private void parseData(Scanner scanner) {
final String tab = "\t"; // 4 spaces
Boolean copyrightInfoDone = false;
String name;
ActorNode newActor = null;
MovieNode newMovie;
while (scanner.hasNextLine()) {
String line = scanner.nextLine();
// Skip copyright info
if (!copyrightInfoDone) {
if (line.equals("---- ------")) {
copyrightInfoDone = true;
}
continue;
}
// Skip bottom of file
if (line.equals("-----------------------------------------------------------------------------")) {
return;
}
// If new actor on this line
if (line.indexOf(tab) != 0 && !line.isEmpty()) {
name = line.substring(0, line.indexOf(tab));
// check to see if the actor has only starred in TV shows
checkIfActorHasMovies(newActor);
newActor = new ActorNode(name);
// add new actor
actors.put(newActor.getName(), newActor);
// check if the first movie is a TV show
if (checkTVShow(line)) {
continue;
}
final String firstMovie = getMovieAtLine(line);
newMovie = new MovieNode(firstMovie);
actors.get(newActor.getName()).addNeighbor(newMovie);
addMovies(newMovie, newActor);
} else {
// check if the first movie is a TV show
if (checkTVShow(line)) {
continue;
}
// if there is another movie, add it to the list, and add the neighbor
if (!line.isEmpty()) {
final String movie = getMovieAtLine(line);
newMovie = new MovieNode(movie);
addMovies(newMovie, newActor);
actors.get(newActor.getName()).addNeighbor(newMovie);
}
}
}
checkIfActorHasMovies(newActor);
}
/**
* Extracts the movie title from the given line
* @param line The line of the data file
* @return the movie title
*/
private static String getMovieAtLine(String line) {
if (line.contains("(V)")) {
return line.substring(line.lastIndexOf("\t") + 1, line.lastIndexOf(")") - 4);
} else {
return line.substring(line.lastIndexOf("\t") + 1, line.lastIndexOf(")") + 1);
}
}
/**
* If an actor does not have any movies (excluding TV movies),
* he/she is not included in the graph
* @param a the actor node
*/
private void checkIfActorHasMovies(ActorNode a) {
if (a == null) {
return;
}
if (a.getNeighbors().isEmpty()) {
actors.remove(a.getName());
}
}
/**
* Adds specified movie to the specified actor
* @param movieNode the movie node
* @param actorNode the actor node
*/
private void addMovies(MovieNode movieNode, ActorNode actorNode) {
// if the movie is already in the list
if (movies.containsKey(movieNode.getName())) {
movies.get(movieNode.getName()).addNeighbor(actorNode);
} else {
movieNode.addNeighbor(actorNode);
movies.put(movieNode.getName(), movieNode);
}
}
/**
* Checks if the given line contains a TV show and not a movie
* @param line the line of the data file
* @return a boolean
*/
private static boolean checkTVShow(String line) {
return (line.contains("(TV)") || line.contains("\""));
}
}
| varksvader/CS210X_Project3_IMDB | IMDBGraph.java | 1,525 | /**
* Returns the name of the node
* @return the name of the node
*/ | block_comment | en | false | 1,378 | 22 | 1,525 | 20 | 1,555 | 23 | 1,525 | 20 | 1,948 | 26 | false | false | false | false | false | true |
41314_0 | import java.util.HashSet;
import java.util.Set;
class Card {
private String symbol;
public Card(String symbol) {
this.symbol = symbol;
}
public String getSymbol() {
return symbol;
}
// Override equals and hashCode for proper HashSet functionality
@Override
public boolean equals(Object obj) {
if (this == obj) return true;
if (obj == null || getClass() != obj.getClass()) return false;
Card card = (Card) obj;
return symbol.equals(card.symbol);
}
@Override
public int hashCode() {
return symbol.hashCode();
}
}
public class Exp5 {
public static void main(String[] args) {
Set<Card> uniqueSymbolsSet = new HashSet<>();
// Adding cards to the set
uniqueSymbolsSet.add(new Card("Heart"));
uniqueSymbolsSet.add(new Card("Diamond"));
uniqueSymbolsSet.add(new Card("Spade"));
uniqueSymbolsSet.add(new Card("Club"));
Card duplicateCard = new Card("Heart");
if (uniqueSymbolsSet.add(duplicateCard)) {
System.out.println(duplicateCard.getSymbol() + " added successfully.");
} else {
System.out.println(duplicateCard.getSymbol() + " is a duplicate and won't be added.");
}
// Displaying unique symbols
System.out.println("Unique Symbols in the set:");
for (Card card : uniqueSymbolsSet) {
System.out.println(card.getSymbol());
}
}
} | Gautam1497/Java-sem-6 | Exp5.java | 351 | // Override equals and hashCode for proper HashSet functionality | line_comment | en | false | 312 | 9 | 351 | 9 | 386 | 9 | 351 | 9 | 422 | 12 | false | false | false | false | false | true |
41380_13 | /*
* 2024 - Jave II: 210
* Author: Talon Dunbar
* Student ID: 2131651
* Date: 05-12-2024
*/
public class Deck {
// Deck Fields
private CardPile cards;
// Deck Constructor
public Deck() {
this.cards = new CardPile();
initializeDeck(initializeCardTypes());
}
// Deck toString()
public String toString() {
int deckLength = this.cards.length();
String builder = "";
for (int i = 0; i < deckLength; i += 3) {
builder += this.cards.getCardAt(i) + ", " + this.cards.getCardAt(i + 1) + ", " + this.cards.getCardAt(i + 2)
+ "\n";
}
builder += "\u001b[0m";
return builder;
}
// Deck Custom Methods
/*
* shuffleDeck Method:
* This methods allows us to shuffle the Deck
* using a method defined in the CardPIle class.
*/
public void shuffleDeck() {
this.cards.shuffle();
}
/*
* drawTopCard Method:
* This method takes no input parameters and returns a card.
* It returns the to top Card of the Deck using a method defined in CardPile.
*/
public Card drawTopCard() {
return this.cards.drawTopCard();
}
/*
* initalizeCardTypes Method:
* This method takes no input parameters and returns a CardType[].
* The array holds each CardType in that game so that we can use it
* to initalize the deck with the CardType amountInDeck field.
*/
private CardType[] initializeCardTypes() {
CardType[] cardTypes = new CardType[] {
CardType.THREE_POTATO_CHIPS, // 8 Triple Potato Chips
CardType.TWO_POTATO_CHIPS, // 12 Dual Potato Chips
CardType.ONE_POTATO_CHIP, // 6 Single Potato Chips
CardType.CHICKEN_SANDWICH, // 5 Chicken Sandwiches
CardType.PORK_SANDWICH, // 10 Pork Sandwiches
CardType.BEEF_SANDWICH, // 5 Beef Sandwiches
CardType.FRIED_CHICKEN, // 14 Fried Chicken
CardType.DEVILLED_EGGS, // 14 Devilled Eggs
CardType.MAYONNAISE, // 6 Jars of Mayonnaise
CardType.CUPCAKE, // 10 Cupcakes
CardType.PIZZA, // 14 Pizzas
CardType.FORK // 4 Forks
};
return cardTypes;
}
/*
* initializeDeck Method:
* This method takes a CardType[] as input and does not return anything.
* It loops through each CardType within the array of CardTypes and uses
* it's amountInDeck field to determine how many cards to add to the Deck,
* it then loops through each CardType putting the correct amount in the Deck.
*/
private void initializeDeck(CardType[] cardTypes) {
for (int i = 0; i < cardTypes.length; i++) {
Card nextCard = new Card(cardTypes[i]);
int amountOfCards = nextCard.getAmountInDeck();
for (int j = 0; j < amountOfCards; j++) {
this.cards.addCard(nextCard);
}
}
}
}
| talon-likeaclaw/picnic-go | Deck.java | 842 | // 5 Beef Sandwiches | line_comment | en | false | 783 | 6 | 842 | 8 | 844 | 5 | 842 | 8 | 964 | 8 | false | false | false | false | false | true |
41441_2 | import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.Scanner;
/**
* program name: JobSkills.java
* author Xin Li
* email: [email protected]
*/
public class JobSkills {
/**
* This program takes two or three arguments from the command line.
* The first command-line argument an input file name.
* The second command-line argument will be a command to run on the data
* from the input file, the commands consist of CATCOUNT and LOCATIONS.
* If an unknown command is provided, the program will print "Invalid Command".
*
* CATCOUNT - This command reads an input file and for each job "Category"
* prints out the category and the number of jobs in that category.
* LOCATIONS - For a given category list the locations that have a position
* in that category open. Each location will be followed
* by a number indicating how many positions in that category
* are open in a particular location.
*/
public static void main(String[] args) throws IOException {
String filename = args[0];
String type = args[1];
if (type.equals("CATCOUNT")) {
System.out.println("Number of positions for each category");
System.out.println("-------------------------------------");
HashMap<String,Integer> map = catCoutFromCsv(filename);
sortPrintResult(map);
} else if (type.equals("LOCATIONS")) {
String option = args[2];
System.out.printf("LOCATIONS for category: %s\n", option);
System.out.println("-------------------------------------");
HashMap<String,Integer> map = locationsFromCsv(filename, option);
sortPrintResult(map);
} else {
System.out.println("Invalid Command");
}
}
/**
* This method will sort the keys in place and print the result.
*/
public static void sortPrintResult(HashMap<String,Integer> map) {
ArrayList<String> sortedKeys = new ArrayList<String>(map.keySet());
Collections.sort(sortedKeys);
for (String key: sortedKeys) {
System.out.printf("%s, %d\n", key, map.get(key));
}
}
public static HashMap<String,Integer> catCoutFromCsv(String filePath) throws IOException {
HashMap<String,Integer> map = new HashMap<String, Integer>();
InputStream inputStream =new FileInputStream(filePath);
Scanner scan = new Scanner(inputStream,"UTF-8");
while(scan.hasNext()) {
String line=scan.nextLine();
String category = line.split(",")[2];
if (!category.equals("Category")) {
if (map.containsKey(category)) {
map.put(category, map.get(category)+1);
} else {
map.put(category, 1);
}
}
}
scan.close();
inputStream.close();
return map;
}
public static HashMap<String,Integer> locationsFromCsv(String filePath, String option) throws IOException {
HashMap<String,Integer> map = new HashMap<String, Integer>();
InputStream inputStream =new FileInputStream(filePath);
Scanner scan = new Scanner(inputStream,"UTF-8");
while(scan.hasNext()) {
String line=scan.nextLine();
String category = line.split(",")[2];
String location = line.split(",")[3];
if (!category.equals("Category") && category.equals(option)) {
if (map.containsKey(location)) {
map.put(location, map.get(location)+1);
} else {
map.put(location, 1);
}
}
}
scan.close();
inputStream.close();
return map;
}
}
| xinli2/Job-Skills | JobSkills.java | 944 | /**
* This method will sort the keys in place and print the result.
*/ | block_comment | en | false | 787 | 18 | 944 | 18 | 1,010 | 20 | 944 | 18 | 1,102 | 20 | false | false | false | false | false | true |
41444_0 | import java.util.Arrays;
import java.util.Comparator;
public class Approx {
/**
* The original problem data
*/
private int[][] jobs;
private float epsilon;
public Approx(ProblemInstance instance, float epsilon) {
this.jobs = instance.getJobs();
this.epsilon = epsilon;
// Earliest Due Date order
Arrays.sort(this.jobs, new SortByDeadline()); // O(n log n)
}
/**
* Given EDD order, calculate the maximum tardiness
*/
public int getTmax() {
int completionTime = 0;
int maxTardiness = 0;
for (int[] job : jobs) {
completionTime += job[0];
maxTardiness = Math.max(maxTardiness, completionTime - job[1]);
}
return maxTardiness;
}
/**
* Given a list of job indices, compute the total tardiness of that sequence
*/
public int computeTotalTardiness(int[] sequence) {
int completionTime = 0;
int totalTardiness = 0;
for(int index: sequence) {
completionTime += jobs[index][0];
totalTardiness += Math.max(0, completionTime - jobs[index][1]);
}
return totalTardiness;
}
/**
* Calculate the total tardiness on this problem instance
*/
public int calculateTardiness() throws Exception {
int maxTardiness = getTmax();
if (maxTardiness == 0)
return 0;
// Compute K value according to Lawler (1982)
int n = jobs.length;
float K = maxTardiness * 2 * epsilon / (n * (n + 1));
// Scale all jobs
float[][] jobsScaled = new float[n][2];
for (int i = 0; i < n; i++) {
jobsScaled[i] = new float[]{
(float) Math.floor(jobs[i][0] / K), // pi' = Floor( pi/K )
(jobs[i][1] / K) // di' = di / K
};
}
// Run the exact algorithm on the scaled jobs
DynamicSequence dyn = new DynamicSequence(jobsScaled, true);
int[] seq = dyn.calculateSequence();
// Return the total tardiness of the resulting sequence
return computeTotalTardiness(seq);
}
/**
* Sort the 2D jobs array by deadline (2nd element of each pair)
*/
class SortByDeadline implements Comparator<int[]> {
public int compare(int[] a, int[] b) {
return a[1] - b[1];
}
}
}
| TBruyn/Advanced-Algorithms | src/Approx.java | 621 | /**
* The original problem data
*/ | block_comment | en | false | 588 | 10 | 621 | 9 | 677 | 11 | 621 | 9 | 741 | 11 | false | false | false | false | false | true |
42350_5 | //Binary Representation, learning rate 0.2, momentum 0.0
import java.io.*;
import java.io.FileWriter;
import java.io.IOException;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
public class BPNN
{
private double learningRate, momentum;
private double w[][] = new double[9][9]; //weight
private double delta[][] = new double[9][9];
private double u[] = new double[9];
private double desiredOutput[] = new double[1]; //desired output value
private double s[] = new double[9];
private double e[] = new double[9];
private static final String LINE_SEPARATOR = System.getProperty("line.separator");
public BPNN()
{
u[0] = 1.0; u[3] = 1.0; //bias term
learningRate = 0.2;
momentum = 0.0;
weightInitialization();
}
public static void main(String args[]) throws Exception
{
BPNN neuron = new BPNN();
FileWriter fw = new FileWriter("/home/lili/workspace/EECE592/BPNN/src/result.txt",true);
for(int i=0; i<10000; i++)
{
double error[] = {0.0, 0.0, 0.0, 0.0};
double totalError =0.0;
neuron.u[1] = 1;
neuron.u[2] = 1;
neuron.desiredOutput[0] = 0;
neuron.output(neuron.u);
neuron.backpropagation(neuron.desiredOutput);
error[0] = Math.pow(neuron.desiredOutput[0]-neuron.u[8], 2); //error
neuron.train();
neuron.u[1] = 0;
neuron.u[2] = 0;
neuron.desiredOutput[0] = 0;
neuron.output(neuron.u);// a forward and backward iteration
neuron.backpropagation(neuron.desiredOutput);
error[1] = Math.pow(neuron.desiredOutput[0] - neuron.u[8], 2);
neuron.train(); //update weight
neuron.u[1] = 1;
neuron.u[2] = 0;
neuron.desiredOutput[0] = 1;
neuron.output(neuron.u);// a forward and backward iteration
neuron.backpropagation(neuron.desiredOutput);
error[2] = Math.pow(neuron.desiredOutput[0] - neuron.u[8], 2);
neuron.train();
neuron.u[1] = 0;
neuron.u[2] = 1;
neuron.desiredOutput[0] = 1;
neuron.output(neuron.u);// a forward and backward iteration
neuron.backpropagation(neuron.desiredOutput);
error[3] = Math.pow(neuron.desiredOutput[0] - neuron.u[8], 2);
neuron.train();
for (int j = 0; j < 4; j++)
{
totalError = totalError + 0.5 * error[j];
}
System.out.println(i + " " + totalError);
if (totalError < 0.05)
break;
fw.write(i+LINE_SEPARATOR+totalError);
}
fw.flush();
fw.close();
}
/**
* Return a binary binarySigmoid of the input X
* @param x The input
* @return f(x) = 1 / (1+e(-x))
*/
public double binarySigmoid(double x)
{
return 1/(1+Math.exp(-x));
}
public double bipolarSigmoid(double x)
{
return 2/(1+Math.exp(-x))-1;
}
private void weightInitialization()
{
for (int i =4; i < 8; i++)
{
for(int j=0; j<3; j++)
{
while(w[i][j]==0.0)
{
w[i][j] = Math.random()-0.5; //Initialize the bias units with a random number between -0.5 and 0.5
}
}
}
for(int j = 3; j<8; j++)
{
while(w[8][j]==0.0)
{
w[8][j] = Math.random()-0.5; //Initialize the bias units with a random number between -0.5 and 0.5
System.out.println(" " + w[8][j]);
}
}
}
public double output(double u[])
{
for(int i=4; i<8; i++)
{
s[i]=0.0;
for(int j=0; j<3; j++)
{
s[i]=s[i]+w[i][j]*u[j];
}
u[i] = binarySigmoid(s[i]);
}
s[8] = 0.0;
for (int j = 3; j < 8; j++)
{
s[8] = s[8] + w[8][j] * u[j];
}
u[8] = binarySigmoid(s[8]);
return u[8];
}
public void backpropagation(double c[])
{
e[8] = u[8]*(1-u[8]) * (desiredOutput[0]-u[8]);
for (int i = 4; i < 8; i++)
{
e[i] = u[i]*(1-u[i])* w[8][i] * e[8];
}
}
public void train ()
{
for (int i = 4; i< 8; i++)
{
for (int j = 0; j < 3; j++)
{
w[i][j] = w[i][j] + learningRate * e[i] * u[j] + momentum * delta[i][j];
delta[i][j] = learningRate * e[i] * u[j] + momentum * delta[i][j];
}
}
for (int j = 3; j < 8; j++)
{
w[8][j] = w[8][j] + learningRate * e[8] * u[j] + momentum * delta[8][j];
delta[8][j] = learningRate * e[8] * u[j] + momentum * delta[8][j];
}
}
}
| LiliMeng/BPNN | BPNN.java | 1,711 | // a forward and backward iteration | line_comment | en | false | 1,546 | 6 | 1,711 | 6 | 1,739 | 6 | 1,711 | 6 | 2,169 | 7 | false | false | false | false | false | true |
42910_2 | package lab2;
public class Canada {
private final Province[] provinces;
/**
* default constructor
*/
Canada(){
this.provinces = new Province[10];
provinces[0] = new Province("Ontario", "Toronto", 14_223_942);
provinces[1] = new Province("Quebec", "Quebec City", 8_501_833);
provinces[2] = new Province("British Columbia", "Victoria", 5_000_879);
provinces[3] = new Province("Alberta", "Edmonton", 4_262_635);
provinces[4] = new Province("Manitoba", "Winnipeg", 1_342_153);
provinces[5] = new Province("Saskatchewan", "Regina", 1_132_505);
provinces[6] = new Province("Nova Scotia", "Halifax", 969_383);
provinces[7] = new Province("New Brunswick", "Fredericton", 775_610);
provinces[8] = new Province("Newfoundland and Labrador", "St. John's", 510_550);
provinces[9] = new Province("Prince Edward Island", "Charlottetown", 154_331);
}
/**
* method to display all provinces' details
*/
public void displayAllProvinces(){
for (Province province: provinces) {
System.out.println(province.getDetails());
}
}
/**
* method to return the number of province which has a certain population
* @param min minimum number of population
* @param max maximum number of population
* @return the number of provinces which meets the condition
*/
public int getNumOfProvincesBetween(int min, int max){
int count = 0;
min *= 1_000_000;
max *= 1_000_000;
for (int i = 0; i < 10; i++){
if (provinces[i].getPopulation() >= min && provinces[i].getPopulation() <= max){
count ++;
}
}
return count;
}
}
| DaweUrbi/exercise1 | src/lab2/Canada.java | 588 | /**
* method to return the number of province which has a certain population
* @param min minimum number of population
* @param max maximum number of population
* @return the number of provinces which meets the condition
*/ | block_comment | en | false | 515 | 51 | 588 | 50 | 557 | 52 | 588 | 50 | 603 | 52 | false | false | false | false | false | true |
44846_13 | import java.awt.event.MouseEvent;
import java.util.ArrayList;
import java.util.List;
/*
Chap Class
- position
- velocity
- bool (on board)
- color (could be an int value, denotes team)
*/
public class Chap {
private double[] position = new double[3]; //position vector
private double[] velocity = new double[3]; //velocity vector
private boolean onBoard;
private int team; //int so we could possibly have 2+ teams.
private boolean isMoving;
private double[] angularV = new double[3]; //angular velocity vector.
public Event type1;
public Event[] type2;
private List<Event> type2liquid= new ArrayList<Event>();
public Chap(double[] pos, double[] vel, int team) {
this.position = pos;
this.velocity = vel;
this.onBoard = true;
this.angularV = new double[]{0,0,0};
this.isMoving = false;
this.team = team;
}
public void FinishStructure(){
this.type1.type = 1;
this.type1.p1 = this;
}
public void printInfo() {
System.out.println("---------------------------");
System.out.println("pos: (" + position[0] + "," + position[1] + "," + position[2] + ")");
System.out.println("vel: (" + velocity[0] + "," + velocity[1] + "," + velocity[2] + ")");
System.out.println("onBoard: " + onBoard);
System.out.println("team: " + team);
System.out.println("---------------------------");
}
public double[] whereAt(double t){
//returns where it will be in t time units.
double[] p = position;
double[] v = velocity;
return new double[]{p[0]+v[0]*t, p[1]+v[1]*t, p[2]+v[2]*t};
}
public void addType2(Event e){
//add type 2 event to mutable array list
type2liquid.add(e);
}
public void solidify(){
//convert type2liquid arryalist to type2 Array. no longer mutable so structure
// is solid and cannot change!
type2 = new Event[type2liquid.size()];
for(int i = 0; i<type2.length; i++){
type2[i] = type2liquid.get(i);
}
}
public double[] getAngularV(){
return this.angularV;
}
public void setAngularV(double[] angularV){
this.angularV = angularV;
}
public double stopTime(double time) { //tells when the chap will stop moving assuming no collisions.
//TODO: MAKE SURE TO ADD the CURRENT TIME FROM PARAMETERS!
double[] zero = {0,0};
if(velocity == zero) {
return -1;
}
return -1;
//TODO: MAKE SURE TO ADD the CURRENT TIME FROM PARAMETERS!
}
public double[] move(double time) { //use the friction # to simulate movement
return this.position; //placeholder until we code this
}
public double[] getPosition() {
return this.position;
}
public void setPosition(double[] pos) {
this.position = pos;
}
public double[] getVelocity() {
return this.velocity;
}
public void setVelocity(double[] velocity) {
this.velocity = velocity;
}
public boolean isOnBoard() {
return this.onBoard;
}
public boolean isMoving() {
return this.isMoving;
}
public int getTeam() {
return this.team;
}
public void setTeam(int team) {
this.team = team;
}
public boolean isClicked(MouseEvent e) {
if(e.getX() <= this.position[0] + Constants.RADIUS && e.getX() >= this.position[0] - Constants.RADIUS &&
e.getY() >= this.position[1] - Constants.RADIUS && e.getY() <= this.position[1] + Constants.RADIUS) {
return true;
}
return false;
}
}
| Aviel-Resnick/chaps | Chap.java | 990 | //placeholder until we code this
| line_comment | en | false | 891 | 7 | 990 | 7 | 1,123 | 7 | 990 | 7 | 1,223 | 7 | false | false | false | false | false | true |
45223_2 | //pls run the file using command:
//java -Xss512m gui
//or else it results in stackoverflow exception
import java.io.*;
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import javax.swing.SwingUtilities;
import javax.swing.filechooser.*;
public class gui extends JPanel implements ActionListener
{
JButton selectButton, compressButton,decompressButton,closeButton;
JTextArea log;
JFrame frame;
String fullpath;
JFileChooser fc;
HuffmanTree filetodecompress;
File file1,file2;
public gui()
{
super(new BorderLayout());
log = new JTextArea(20,40);
log.setMargin(new Insets(5,5,5,5));
log.setEditable(false);
JScrollPane logScrollPane = new JScrollPane(log);
fc = new JFileChooser();
selectButton = new JButton("Select File");
selectButton.addActionListener(this);
compressButton = new JButton("Compress");
compressButton.addActionListener(this);
compressButton.setEnabled(false);
decompressButton = new JButton("Decompress");
decompressButton.addActionListener(this);
decompressButton.setEnabled(false);
closeButton = new JButton("Close");
closeButton.addActionListener(this);
closeButton.setEnabled(true);
JPanel buttonPanel = new JPanel();
buttonPanel.add(selectButton);
buttonPanel.add(compressButton);
buttonPanel.add(decompressButton);
buttonPanel.add(closeButton);
add(buttonPanel, BorderLayout.PAGE_START);
add(logScrollPane, BorderLayout.CENTER);
}
public void actionPerformed(ActionEvent e)
{
if (e.getSource() == selectButton)
{
log.append("\nNEW FILE:\n");
int returnVal1 = fc.showOpenDialog(gui.this);
if (returnVal1 == JFileChooser.APPROVE_OPTION)
{
file1 = fc.getSelectedFile();
compressButton.setEnabled(true);
fullpath=file1.getAbsolutePath();
log.append("\nFile selected: " + fullpath + "." +"\n");
JOptionPane.showMessageDialog(null, "File Selected Successfully");
}
else log.append("Select command cancelled by user." +"\n");
log.setCaretPosition(log.getDocument().getLength());
}
else if (e.getSource() == compressButton)
{
String destinationfile="";
try {destinationfile=Client.Compress(fullpath,file1.getName());}
catch(Exception m){}
log.append("\nCOMPRESSION:\n");
log.append("........................\n");
JOptionPane.showMessageDialog(null, "File Compression Successful!!");
log.append("compressed filelocation: "+destinationfile+"\n\n");
log.append("Compression Statistics:\n"+Client.display()+"\n\n");
decompressButton.setEnabled(true);
log.setCaretPosition(log.getDocument().getLength());
compressButton.setEnabled(false);
}
else if (e.getSource() == decompressButton)
{
decompressButton.setEnabled(false);
int returnVal2 = fc.showOpenDialog(gui.this);
if (returnVal2 == JFileChooser.APPROVE_OPTION)
{
file2 = fc.getSelectedFile();
File f=null;
String destinationdecompress="";
String decompresspath=file2.getAbsolutePath();
log.append("\nDECOMPRESSION:\n");
log.append(".........................\n");
try { destinationdecompress=Client.Decompress(decompresspath,file2.getName());}
catch(Exception m){}
log.append("File selected for decompression: " + decompresspath + "." +"\n");
JOptionPane.showMessageDialog(null, "File Decompression Successful!!\nPlease check the directory");
try
{
f = new File("Files/");
Desktop.getDesktop().open(f);
}
catch(Exception r){}
log.append("Decompressed File saved in location:"+destinationdecompress+"\n");
}
else
{
log.append("Decompress command cancelled by user." +"\n");
decompressButton.setEnabled(true);
}
log.setCaretPosition(log.getDocument().getLength());
}
else if(e.getSource()==closeButton)
{
System.exit(0);
}
}
private void createAndShowGUI()
{
frame = new JFrame("HUFFMAN CODING");
frame.setExtendedState( frame.getExtendedState()|JFrame.MAXIMIZED_BOTH );
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.add(new gui());
frame.pack();
frame.setVisible(true);
}
public static void main(String[] args)
{
gui x=new gui();
x.createAndShowGUI();
}
}
| Sunil-Pai-G/Huffman-Compression | gui.java | 1,175 | //or else it results in stackoverflow exception | line_comment | en | false | 998 | 9 | 1,175 | 9 | 1,321 | 9 | 1,175 | 9 | 1,561 | 8 | false | false | false | false | false | true |
46073_2 | import java.awt.Color;
import java.awt.Graphics;
import java.util.ArrayList;
class Game {
private static final int SHIP_RADIUS = 20;
private static final int HAZARD_RADIUS = 20;
private static final int GOAL_RADIUS = 10;
private static final Color SHIP_COLOR = Color.WHITE;
private static final Color HAZARD_COLOR = Color.RED;
private static final Color GOAL_COLOR = Color.GREEN;
private static final int NUM_HAZARDS = 5;
private static final int NUM_GOALS = 5;
private static final double ACCEL_FACTOR = 50.0;
private int width;
private int height;
public static int score = 0;
public static int lives = 3;
public static int level = 0;
private ArrayList<BouncingDisk> hazards = new ArrayList<BouncingDisk>();
private ArrayList<BouncingDisk> goals = new ArrayList<BouncingDisk>();
private BouncingDisk ship;
public Game(int width, int height){
this.width = width;
this.height = height;
ship = new BouncingDisk(this, SHIP_RADIUS, SHIP_COLOR, new Pair(width / 2, height / 2));
reset(level);
}
/*
* Method: reset()
*
* Removes all hazards and goals (if any), then repopulates the
* game with new hazards and goals in new locations. The number of
* goals should be NUM_GOALS, while the number of hazards should
* be NUM_HAZARDS.
*/
private void reset (int l) {
// complete this method
hazards.clear();
goals.clear();
for(int i = 0; i < (NUM_HAZARDS + l); i++){
BouncingDisk hazard = new BouncingDisk(this, HAZARD_RADIUS + (level * 5) , HAZARD_COLOR);
hazards.add(hazard);
}
for(int i = 0; i < (NUM_GOALS - l); i++){
BouncingDisk goal = new BouncingDisk(this, GOAL_RADIUS - (level * 2), GOAL_COLOR);
goals.add(goal);
}
}
public int getWidth() { return width; }
public int getHeight() { return height; }
/*
* Method: drawShapes(Graphics g)
*
* This method draws all of the shapes on the screen: the ship,
* all hazards, and goals.
*/
public void drawShapes(Graphics g){
// complete this method
ship.draw(g);
for(int i = 0; i < hazards.size(); i++){
hazards.get(i).draw(g);
}
for(int i = 0; i < goals.size(); i++){
goals.get(i).draw(g);
}
}
/*
* Method setShipVertAccel (int amount)
*
* Sets the vertical (y) component of the ship's acceleration. The
* ship's acceleration should always be an integer multiple of
* ACCEL_FACTOR.
*/
public void setShipVertAccel (int amount) {
// complete this method
Pair v = new Pair(0, amount * ACCEL_FACTOR);
ship.setAcceleration(v);
}
/*
* Method setShipHorAccel (int amount)
*
* Sets the horizontal (x) component of the ship's
* acceleration. The ship's acceleration should always be an
* integer multiple of ACCEL_FACTOR.
*/
public void setShipHorAccel (int amount) {
// complete this method
Pair h = new Pair(amount * ACCEL_FACTOR, 0);
ship.setAcceleration(h);
}
public void update(double time){
ship.update(this, time);
checkGoalCollision();
checkHazardCollision();
}
/*
* Method: checkGoalCollision ()
*
* Checks for a collision (overlap) between ship and a goal
* disk. If a collision is detected, the goal disk should be
* removed from goals. If after removal, goals is empty, the game
* should be repopulated by calling the reset() method.
*/
private void checkGoalCollision () {
// complete this method
for(int i = 0; i < goals.size(); i++){
if(ship.overlaps(goals.get(i))){
score += 1;
goals.remove(goals.get(i));
}
}
if(goals.isEmpty()){
level += 1;
reset(level);
}
else if(level == 4){
System.out.println("You Won!");
System.out.println("Your score is " + score);
System.exit(0);
}
}
/*
* Method: checkHazardCollision ()
*
* Checks for a collision (overlap) between ship and a hazard
* disk. If a collision is detected, the method should print a
* message to the console saying that a hazard collision occurred,
* then exit the game (or some other behavior).
*/
private void checkHazardCollision () {
// complete this method
for(int i = 0; i < hazards.size(); i++){
if(ship.overlaps(hazards.get(i))){
lives -= 1;
reset(0);
}
if(lives == 0){
System.out.println("You Lost Three lives!");
System.out.println("Your score is " + score);
System.exit(0);
}
}
}
}
| Amana28/Polka-Dot | Game.java | 1,308 | /*
* Method: drawShapes(Graphics g)
*
* This method draws all of the shapes on the screen: the ship,
* all hazards, and goals.
*/ | block_comment | en | false | 1,181 | 38 | 1,308 | 42 | 1,402 | 44 | 1,308 | 42 | 1,616 | 48 | false | false | false | false | false | true |
46665_7 | import greenfoot.*; // (World, Actor, GreenfootImage, Greenfoot and MouseInfo)
/**
* Flame coming out from the top
*
* @author (Vanessa)
* @version (June 2023)
*/
public class FlameT extends Attack
{
GreenfootImage[]flame =new GreenfootImage[4];
SimpleTimer animationTimer = new SimpleTimer();
/**
* Act - do whatever the Flame wants to do. This method is called whenever
* the 'Act' or 'Run' button gets pressed in the environment.
*/
public void act()
{
//Animate the flame
animateFlame();
}
public FlameT(){
for(int i=0;i<flame.length;i++)
{
flame[i]=new GreenfootImage("images/flame/00"+i+".png");
flame[i].scale(30,60);
}
//Reset the timer
animationTimer.mark();
//Initial flame image
setImage(flame[3]);
}
/**
* Animate the flame
*/
int imageIndex=0;
public void animateFlame()
{
//Allow the last image (imageIndex=3) to stay longer during animation
//It's the state where no flame is coming out and player can go
if(imageIndex==0){
if(animationTimer.millisElapsed()<1600)
{
return;
}
}
else if(imageIndex!=0){
if(animationTimer.millisElapsed()<200)
{
return;
}
}
animationTimer.mark();
setImage(flame[imageIndex]);
imageIndex=(imageIndex + 1) % flame.length;
}
//Return current imageIndex
public int getIndex(){
return imageIndex;
}
}
| yrdsb-peths/final-greenfoot-project-Vanessa-Huo | FlameT.java | 425 | //Allow the last image (imageIndex=3) to stay longer during animation | line_comment | en | false | 400 | 16 | 425 | 16 | 466 | 16 | 425 | 16 | 502 | 16 | false | false | false | false | false | true |
46666_0 | /**
* A class that contains 3 generics that are stored as x, y, and z.
*
* @author Peterson Guo
* @version June 15, 2023
*/
public class Triple<T, U, V> {
public T x;
public U y;
public V z;
/**
* A constructor that takes 3 generic types and sets them as x, y, and z.
*
* @param x One generic type
* @param y Another generic type
* @param z Another genertic type
*/
public Triple(T x, U y, V z) {
this.x = x;
this.y = y;
this.z = z;
}
/**
* A method that returns x, y, and z as a string
*
* @return String A string that contains x, y, and z
*/
public String toString() {
return x + ", " + y + ", " + z;
}
} | PetersonGuo/CandyCrush | Triple.java | 231 | /**
* A class that contains 3 generics that are stored as x, y, and z.
*
* @author Peterson Guo
* @version June 15, 2023
*/ | block_comment | en | false | 227 | 44 | 231 | 48 | 256 | 47 | 231 | 48 | 262 | 49 | false | false | false | false | false | true |
46668_3 | /**
* Cat is a subclass of Animal and implements Trainable
*
* @author Bhavyai Gupta
* @version 1.0
* @since June 4, 2021
*/
public class Cat extends Animal implements Trainable {
/**
* Cat() constructor sets its kind variable
*/
public Cat() {
kind = "cat";
}
/**
* speak() implements the Animal speak() method. When a cat speaks it says meow.
*/
@Override
public String speak() {
return "meow";
}
/**
* eat() implements the Animal eat() method. Cat eats mice.
*/
@Override
public String eat() {
return "mice";
}
/**
* doATrick() implements the Trainable doATrick() method. Cat can play drum.
*/
@Override
public String doATrick() {
return "I do tricks. I can play drum.";
}
} | meng-ucalgary/ensf-593-assignment-4 | src/Cat.java | 219 | /**
* eat() implements the Animal eat() method. Cat eats mice.
*/ | block_comment | en | false | 211 | 18 | 219 | 20 | 235 | 20 | 219 | 20 | 247 | 22 | false | false | false | false | false | true |
46722_7 | //package converter; // NetBeans IDE
/**
* Donee. Donee composed of Donee attributes.
* @author Kai W, Emilio E, Phillip N
* @version 20.October.2018
*/
public class Donee
{
// TODO Private intilialization of all other attributes
private final String[] visitDate, creationDate;
private final int houseHoldTotal;
private boolean newClient;
/**
* Donee. Constructor for Donee.
* @param attributeArr array of Donee attributes
*/
public Donee(String[] attributeArr)
{
// TODO Every other attributes
visitDate = attributeArr[0].split(" ");
houseHoldTotal = Integer.parseInt(attributeArr[1]);
creationDate = attributeArr[11].split(" ");
if(visitDate[0].equals(creationDate[0]))
{
newClient = true;
}
else
{
newClient = false;
}
}
/**
*
* @return newClient
*/
public boolean getNewClient()
{
return newClient;
}
/**
*
* @return visistDate
*/
public String[] getVisitDate()
{
return visitDate;
}
/**
*
* @return housHoldTotal
*/
public int getHouseHoldTotal()
{
return houseHoldTotal;
}
/**
*
* @return creationDate
*/
public String[] getCreationDate()
{
return creationDate;
}
// TODO Get method for every other attributes
}
| 2018-Arizona-Opportunity-Hack/Team23 | Donee.java | 353 | /**
*
* @return housHoldTotal
*/ | block_comment | en | false | 363 | 13 | 353 | 13 | 428 | 15 | 353 | 13 | 441 | 15 | false | false | false | false | false | true |
46998_5 | import java.util.ArrayList;
import java.util.HashMap;
import java.util.Random;
import java.util.Map.Entry;
import Environment.GlobalVariables;
import Libraries.SparkDB;
import Libraries.Statistics;
import Objects.Agent;
import Operations.Calculation;
import Operations.Demand;
import Operations.Filter;
import Operations.Reproduction;
import Operations.Supply;
/**
* Main instance
* @author Morad A.
*/
public class App {
/* PRNG */
static Random R = new Random();
/* Market Product Listing */
static SparkDB Market = new SparkDB();
/* The list of Agents */
static HashMap<Long, Agent> AgentList = new HashMap<>();
public static void main(String[] args) throws Exception {
/* Initialize Economy */
init();
/* The economic cycle */
for(int iteration = 0; iteration < GlobalVariables.iterations; iteration ++) {
/* 1. Produce */
for(Entry<Long, Agent> E : AgentList.entrySet()) Supply.run(E.getKey(), E.getValue(), Market);
/* 2. Demand */
for(Entry<Long, Agent> E : AgentList.entrySet()) Demand.run(E.getValue(), Market);
/* 3. Calculation */
for(Entry<Long, Agent> E : AgentList.entrySet()) Calculation.run(E, Market);
Market.clearRows(); // Clear all offers
/* 4. Filter out dead agents */
Filter.run(AgentList);
/* 5. Reproduction for the remaining folks after initial calibration */
if(iteration > 5) Reproduction.run(AgentList);
/* 6. Show statistics after initial calibration */
if(iteration > 10) Statistics.run(AgentList.values());
}
}
/**
* Initalize the Economy
*/
static void init() throws Exception {
/* Initalize the Market table */
Market.create(new ArrayList<>() {{
add("ProducerID"); /* In order to attach Agent to his offer */
add("Price");
add("AvailableUnits");
}});
/* Initalize the starting Agent List based on GlobalVariables */
for(long AgentID = 0; AgentID < GlobalVariables.startingPopulation; AgentID ++) {
Agent A = new Agent();
/* Initialize agents with 50% variability (25% below normal and 25% above normal) */
A.baseInflatorSensitivity = GlobalVariables.startingBaseInflatorSensitivity * R.nextDouble(0.75, 1.25);
A.baseSupplyCapacity = (int) (GlobalVariables.startingBaseSupplyCapacity * R.nextDouble(0.75, 1.25));
A.baseDemandCapacity = GlobalVariables.startingBaseDemandCapacity * R.nextDouble(0.75, 1.25);
A.demandCapacity = (int) (A.baseDemandCapacity * A.baseSupplyCapacity);
A.supplyCapacity = A.baseSupplyCapacity;
A.wealth = GlobalVariables.startingPrice * A.supplyCapacity;
AgentList.put(AgentID, A);
}
/* CSV Headers */
System.out.println("GDPInUnits,CoefficientOfVariationWealth,AveragePanicCoefficient,AverageDemand,AverageSupply,Population,AverageWealth,gene-baseInflatorSensitivity,gene-baseSupplyCapacity,gene-baseDemandCapacity,medianInflationRate");
}
}
| Zelakolase/Simuconomy | src/App.java | 785 | /* The economic cycle */ | block_comment | en | false | 704 | 5 | 785 | 6 | 809 | 5 | 785 | 6 | 934 | 5 | false | false | false | false | false | true |
48118_21 | // Piece.java
import java.util.*;
/**
An immutable representation of a tetris piece in a particular rotation.
Each piece is defined by the blocks that make up its body.
Typical client code looks like...
<pre>
Piece pyra = new Piece(PYRAMID_STR); // Create piece from string
int width = pyra.getWidth(); // 3
Piece pyra2 = pyramid.computeNextRotation(); // get rotation, slow way
Piece[] pieces = Piece.getPieces(); // the array of root pieces
Piece stick = pieces[STICK];
int width = stick.getWidth(); // get its width
Piece stick2 = stick.fastRotation(); // get the next rotation, fast way
</pre>
*/
public class Piece {
// Starter code specs out a few basic things, leaving
// the algorithms to be done.
private TPoint[] body;
private int[] skirt;
private int width;
private int height;
private Piece next; // "next" rotation
static private Piece[] pieces; // singleton static array of first rotations
/**
Defines a new piece given a TPoint[] array of its body.
Makes its own copy of the array and the TPoints inside it.
*/
public Piece(TPoint[] points) {
body = new TPoint [points.length];
for (int i = 0 ; i < points.length ; i++)
{
body[i] = new TPoint(points[i]);
}
computeHeightAndWidth();
computeSkirt();
}
/**
* Private helper method that computes the skirt of the piece.
*/
private void computeSkirt() {
skirt = new int[width];
Arrays.fill(skirt, height-1);
for (TPoint pt : body)
{
if(skirt[pt.x]>pt.y)
skirt[pt.x]=pt.y;
}
}
/**
* Private helper method that computes the height and width of the piece.
*/
private void computeHeightAndWidth() {
int xMax,yMax;
xMax = yMax =0;
for (TPoint pt : body)
{
if(xMax < pt.x)
xMax = pt.x;
if(yMax < pt.y)
yMax = pt.y;
}
width = xMax + 1;
height = yMax + 1;
}
/**
* Alternate constructor, takes a String with the x,y body points
* all separated by spaces, such as "0 0 1 0 2 0 1 1".
* (provided)
*/
public Piece(String points) {
this(parsePoints(points));
}
/**
Returns the width of the piece measured in blocks.
*/
public int getWidth() {
return width;
}
/**
Returns the height of the piece measured in blocks.
*/
public int getHeight() {
return height;
}
/**
Returns a pointer to the piece's body. The caller
should not modify this array.
*/
public TPoint[] getBody() {
return body;
}
/**
Returns a pointer to the piece's skirt. For each x value
across the piece, the skirt gives the lowest y value in the body.
This is useful for computing where the piece will land.
The caller should not modify this array.
*/
public int[] getSkirt() {
return skirt;
}
/**
Returns a new piece that is 90 degrees counter-clockwise
rotated from the receiver.
*/
public Piece computeNextRotation() {
TPoint[] rotatedBody = new TPoint[body.length];
for (int i = 0 ; i < body.length ; i++)
{
rotatedBody[i] = new TPoint(height - body[i].y - 1, body[i].x);
}
Piece computedNext = new Piece(rotatedBody);
return computedNext ;
}
/**
Returns a pre-computed piece that is 90 degrees counter-clockwise
rotated from the receiver. Fast because the piece is pre-computed.
This only works on pieces set up by makeFastRotations(), and otherwise
just returns null.
*/
public Piece fastRotation() {
return next;
}
/**
Returns true if two pieces are the same --
their bodies contain the same points.
Interestingly, this is not the same as having exactly the
same body arrays, since the points may not be
in the same order in the bodies. Used internally to detect
if two rotations are effectively the same.
*/
@Override
public boolean equals(Object obj) {
// standard equals() technique 1
if (obj == this) return true;
// standard equals() technique 2
// (null will be false)
if (!(obj instanceof Piece)) return false;
Piece other = (Piece)obj;
if(other.body.length != body.length) return false;
// cast the body arrays to a list and use containsAll
// method to ensure that both arrays contain same points
// irrespective of the order
List<TPoint> myPoints = Arrays.asList(body);
List<TPoint> otherPoints = Arrays.asList(other.body);
return myPoints.containsAll(otherPoints);
}
// String constants for the standard 7 tetris pieces
public static final String STICK_STR = "0 0 0 1 0 2 0 3";
public static final String L1_STR = "0 0 0 1 0 2 1 0";
public static final String L2_STR = "0 0 1 0 1 1 1 2";
public static final String S1_STR = "0 0 1 0 1 1 2 1";
public static final String S2_STR = "0 1 1 1 1 0 2 0";
public static final String SQUARE_STR = "0 0 0 1 1 0 1 1";
public static final String PYRAMID_STR = "0 0 1 0 1 1 2 0";
// Indexes for the standard 7 pieces in the pieces array
public static final int STICK = 0;
public static final int L1 = 1;
public static final int L2 = 2;
public static final int S1 = 3;
public static final int S2 = 4;
public static final int SQUARE = 5;
public static final int PYRAMID = 6;
/**
Returns an array containing the first rotation of
each of the 7 standard tetris pieces in the order
STICK, L1, L2, S1, S2, SQUARE, PYRAMID.
The next (counterclockwise) rotation can be obtained
from each piece with the fastRotation() message.
In this way, the client can iterate through all the rotations
until eventually getting back to the first rotation.
(provided code)
*/
public static Piece[] getPieces() {
// lazy evaluation -- create static array if needed
if (Piece.pieces==null) {
// use makeFastRotations() to compute all the rotations for each piece
Piece.pieces = new Piece[] {
makeFastRotations(new Piece(STICK_STR)),
makeFastRotations(new Piece(L1_STR)),
makeFastRotations(new Piece(L2_STR)),
makeFastRotations(new Piece(S1_STR)),
makeFastRotations(new Piece(S2_STR)),
makeFastRotations(new Piece(SQUARE_STR)),
makeFastRotations(new Piece(PYRAMID_STR)),
};
}
return Piece.pieces;
}
/**
Given the "first" root rotation of a piece, computes all
the other rotations and links them all together
in a circular list. The list loops back to the root as soon
as possible. Returns the root piece. fastRotation() relies on the
pointer structure setup here.
*/
/*
Implementation: uses computeNextRotation()
and Piece.equals() to detect when the rotations have gotten us back
to the first piece.
*/
private static Piece makeFastRotations(Piece root) {
Piece curPiece = new Piece(root.body);
Piece myRoot = curPiece;
while (true){
Piece nextRotation = curPiece.computeNextRotation();
if(myRoot.equals(nextRotation))
{
curPiece.next = myRoot;
break;
}
curPiece.next = nextRotation;
curPiece = curPiece.next;
}
return myRoot;
}
/**
Given a string of x,y pairs ("0 0 0 1 0 2 1 0"), parses
the points into a TPoint[] array.
(Provided code)
*/
private static TPoint[] parsePoints(String string) {
List<TPoint> points = new ArrayList<TPoint>();
StringTokenizer tok = new StringTokenizer(string);
try {
while(tok.hasMoreTokens()) {
int x = Integer.parseInt(tok.nextToken());
int y = Integer.parseInt(tok.nextToken());
points.add(new TPoint(x, y));
}
}
catch (NumberFormatException e) {
throw new RuntimeException("Could not parse x,y string:" + string);
}
// Make an array out of the collection
TPoint[] array = points.toArray(new TPoint[0]);
return array;
}
}
| harshpai/Tetris | Piece.java | 2,342 | // method to ensure that both arrays contain same points | line_comment | en | false | 2,086 | 10 | 2,342 | 10 | 2,366 | 10 | 2,342 | 10 | 2,763 | 10 | false | false | false | false | false | true |
48185_1 | import java.util.ArrayList;
import java.util.Random;
/**
* Generates the pseudorandom list of possible colours, and the pseudorandom
* code.
*
* @author Elise Ratcliffe - enr24
* @version 1.0
*/
public class Code {
/**
* Generates a random number between 0 and a max provided by caller.
*
* @param max
* Maximum number the random number generated can be.
* @return Pseudorandom number in the range 0-max.
*/
public static int getRandomInt(int max) {
Random randomGenerator = new Random();
int randomNum = randomGenerator.nextInt(max);
return randomNum;
}
/**
* Makes a list of possible colours to be chosen from when creating
* the code.
*
* @param numOfColours
* The number of colours in the list of possible colours to
* choose from when guessing or making the code.
* @return List of possible colours.
*/
public static ArrayList<String> makeList(int numOfColours) {
ArrayList<String> allColours = new ArrayList<String>();
ArrayList<String> ourColours = new ArrayList<String>();
allColours.add("red");
allColours.add("blue");
allColours.add("green");
allColours.add("yellow");
allColours.add("purple");
allColours.add("orange");
allColours.add("brown");
allColours.add("pink");
// Keep looping until we have the correct number of unique colours.
while (ourColours.size() != numOfColours)
{
int index = getRandomInt(allColours.size());
String colour = allColours.get(index);
if (!ourColours.contains(colour))
ourColours.add(colour);
}
return ourColours;
}
/**
* Makes a code based of list of possible colours to choose from.
*
* @param length
* The length of the code.
* @param possibleColours
* List of possible colours to choose from when making or
* guessing the code.
* @return The pseudorandom code generated.
*/
public static ArrayList<String> getCode(int length, ArrayList<String> possibleColours) {
// DEBUG only - do some checks on input
assert(length <= Constants.MAX_NUM_OF_PEGS);
assert(length >= Constants.MIN_NUM_OF_PEGS);
ArrayList<String> code = new ArrayList<String>();
// Generate pseudorandom code, by selecting "random" colours
// from possible colours.
for (int i=0; i<length; i++) {
int randomInt = getRandomInt(possibleColours.size());
String colour = possibleColours.get(randomInt);
code.add(colour);
}
return code;
}
}
| 1orwell/Mastermind | Code.java | 698 | /**
* Generates a random number between 0 and a max provided by caller.
*
* @param max
* Maximum number the random number generated can be.
* @return Pseudorandom number in the range 0-max.
*/ | block_comment | en | false | 615 | 56 | 698 | 56 | 704 | 61 | 698 | 56 | 777 | 63 | false | false | false | false | false | true |
48431_3 | /**
* Menu class for controlling the program.
*
* @author Josh Rivett
* @version 1.0
*/
public class Menu {
//Creates an instance of an employee.
Employee employee = new Employee();
/**
* Displays the menu options to the user.
*/
public static void displayMenu() {
System.out.println("\nPlease select one of the options below.");
System.out.println("\n1. Add Meeting");
System.out.println("2. Edit Meeting");
System.out.println("3. Delete Meeting");
System.out.println("4. Search Meetings");
System.out.println("5. Print Meetings");
System.out.println("6. Undo Action");
System.out.println("0. Exit Program");
System.out.print("\nEnter menu option: ");
}
/**
* Processes a menu choice from the user.
*/
public void processMenuChoices() {
//Initialises required variables
int choice = 0;
boolean exit = false;
do {
displayMenu();
//Receives a menu choice from the user
choice = Validation.validInt();
//Validates whether the choice is a valid menu option
while (choice < 0 || choice > 6) {
System.out.print("Enter valid menu option: ");
choice = Validation.validInt();
}
//Processes the user's menu input
switch (choice) {
case 1:
employee.addMeeting();
break;
case 2:
employee.editMeeting();
break;
case 3:
employee.deleteMeeting();
break;
case 4:
employee.searchMeeting();
break;
case 5:
employee.printMeetings();
break;
case 6:
employee.undo();
break;
case 0:
System.out.println("\nGoodbye...");
exit = true;
break;
}
} while (exit == false);
}
/**
* Main method of the program.
*
* @param args Standard main method arguments
*/
public static void main(String[] args) {
Menu menu = new Menu();
menu.processMenuChoices();
}
}
| sebt32/Team5 | Menu.java | 562 | /**
* Processes a menu choice from the user.
*/ | block_comment | en | false | 479 | 13 | 562 | 14 | 586 | 15 | 562 | 14 | 755 | 17 | false | false | false | false | false | true |
49009_40 | package mars.venus;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import javax.swing.Action;
import javax.swing.Icon;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.Timer;
import javax.swing.WindowConstants;
///////////////////////////// CREDIT /////////////////////////////////////
// http://forums.sun.com/thread.jspa?threadID=499183&messageID=2505646
// bsampieri, 4 March 2004
// Java Developer Forum, Useful Code of the Day: Button Fires Events While Held
// Adopted/adapted by DPS 20 July 2008
//
// This is NOT one of the MARS buttons! It is a subclass of JButton that can
// be used to create buttons that fire events after being held down for a
// specified period of time and at a specified rate.
/**
* <code>RepeatButton</code> is a <code>JButton</code> which contains a timer
* for firing events while the button is held down. There is a default initial
* delay of 300ms before the first event is fired and a 60ms delay between
* subsequent events. When the user holds the button down and moves the mouse
* out from over the button, the timer stops, but if the user moves the mouse
* back over the button without having released the mouse button, the timer
* starts up again at the same delay rate. If the enabled state is changed while
* the timer is active, it will be stopped. NOTE: The normal button behavior is
* that the action event is fired after the button is released. It may be
* important to konw then that this is still the case. So in effect, listeners
* will get 1 more event then what the internal timer fires. It's not a "bug",
* per se, just something to be aware of. There seems to be no way to suppress
* the final event from firing anyway, except to process all ActionListeners
* internally. But realistically, it probably doesn't matter.
*/
public class RepeatButton extends JButton implements ActionListener, MouseListener {
/**
*
*/
private static final long serialVersionUID = -3268582477859945783L;
/**
* The pressed state for this button.
*/
private boolean pressed = false;
/**
* Flag to indicate that the button should fire events when held. If false, the
* button is effectively a plain old JButton, but there may be times when this
* feature might wish to be disabled.
*/
private boolean repeatEnabled = true;
/**
* The hold-down timer for this button.
*/
private Timer timer = null;
/**
* The initial delay for this button. Hold-down time before first timer firing.
* In milliseconds.
*/
private int initialDelay = 300;
/**
* The delay between timer firings for this button once the delay period is
* past. In milliseconds.
*/
private int delay = 60;
/**
* Holder of the modifiers used when the mouse pressed the button. This is used
* for subsequently fired action events. This may change after mouse pressed if
* the user moves the mouse out, releases a key and then moves the mouse back
* in.
*/
private int modifiers = 0;
/**
* Creates a button with no set text or icon.
*/
public RepeatButton() {
super();
init();
}
/**
* Creates a button where properties are taken from the Action supplied.
*
* @param a the button action
*/
public RepeatButton(final Action a) {
super(a);
init();
}
/**
* Creates a button with an icon.
*
* @param icon the button icon
*/
public RepeatButton(final Icon icon) {
super(icon);
init();
}
/**
* Creates a button with text.
*
* @param text the button text
*/
public RepeatButton(final String text) {
super(text);
init();
}
/**
* Creates a button with initial text and an icon.
*
* @param text the button text
* @param icon the button icon
*/
public RepeatButton(final String text, final Icon icon) {
super(text, icon);
init();
}
/**
* Initializes the button.
*/
private void init() {
addMouseListener(this);
// initialize timers for button holding...
timer = new Timer(delay, this);
timer.setRepeats(true);
}
/**
* Gets the delay for the timer of this button.
*
* @return the delay
*/
public int getDelay() { return delay; }
/**
* Set the delay for the timer of this button.
*
* @param d the delay
*/
public void setDelay(final int d) { delay = d; }
/**
* Gets the initial delay for the timer of this button.
*
* @return the initial delay
*/
public int getInitialDelay() { return initialDelay; }
/**
* Sets the initial delay for the timer of this button.
*
* @param d the initial delay
*/
public void setInitialDelay(final int d) { initialDelay = d; }
/**
* Checks if the button should fire events when held. If false, the button is
* effectively a plain old JButton, but there may be times when this feature
* might wish to be disabled.
*
* @return if true, the button should fire events when held
*/
public boolean isRepeatEnabled() { return repeatEnabled; }
/**
* Sets if the button should fire events when held. If false, the button is
* effectively a plain old JButton, but there may be times when this feature
* might wish to be disabled. If false, it will also stop the timer if it's
* running.
*
* @param en if true, the button should fire events when held
*/
public void setRepeatEnabled(final boolean en) {
if (!en) {
pressed = false;
if (timer.isRunning()) { timer.stop(); }
}
repeatEnabled = en;
}
/**
* Sets the enabled state of this button. Overridden to stop the timer if it's
* running.
*
* @param en if true, enables the button
*/
@Override
public void setEnabled(final boolean en) {
if (en != super.isEnabled()) {
pressed = false;
if (timer.isRunning()) { timer.stop(); }
}
super.setEnabled(en);
}
/**
* Handle action events. OVERRIDE THIS IN SUBCLASS!
*
* @param ae the action event
*/
@Override
public void actionPerformed(final ActionEvent ae) {
// process events only from this components
if (ae.getSource() == timer) {
final ActionEvent event = new ActionEvent(this, ActionEvent.ACTION_PERFORMED, super.getActionCommand(),
modifiers);
super.fireActionPerformed(event);
}
// testing code...
else if (testing && ae.getSource() == this) { System.out.println(ae.getActionCommand()); }
}
/**
* Handle mouse clicked events.
*
* @param me the mouse event
*/
@Override
public void mouseClicked(final MouseEvent me) {
// process events only from this components
if (me.getSource() == this) {
pressed = false;
if (timer.isRunning()) { timer.stop(); }
}
}
/**
* Handle mouse pressed events.
*
* @param me the mouse event
*/
@Override
public void mousePressed(final MouseEvent me) {
// process events only from this components
if (me.getSource() == this && isEnabled() && isRepeatEnabled()) {
pressed = true;
if (!timer.isRunning()) {
modifiers = me.getModifiers();
timer.setInitialDelay(initialDelay);
timer.start();
}
}
}
/**
* Handle mouse released events.
*
* @param me the mouse event
*/
@Override
public void mouseReleased(final MouseEvent me) {
// process events only from this components
if (me.getSource() == this) {
pressed = false;
if (timer.isRunning()) { timer.stop(); }
}
}
/**
* Handle mouse entered events.
*
* @param me the mouse event
*/
@Override
public void mouseEntered(final MouseEvent me) {
// process events only from this components
if (me.getSource() == this && isEnabled() && isRepeatEnabled()) {
if (pressed && !timer.isRunning()) {
modifiers = me.getModifiers();
timer.setInitialDelay(delay);
timer.start();
}
}
}
/**
* Handle mouse exited events.
*
* @param me the mouse event
*/
@Override
public void mouseExited(final MouseEvent me) {
// process events only from this components
if (me.getSource() == this) { if (timer.isRunning()) { timer.stop(); } }
}
/**
* Testing flag. Set in main method.
*/
private static boolean testing = false;
/**
* Main method, for testing. Creates a frame with both styles of menu.
*
* @param args the command-line arguments
*/
public static void main(final String[] args) {
testing = true;
final JFrame f = new JFrame("RepeatButton Test");
f.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
final JPanel p = new JPanel();
final RepeatButton b = new RepeatButton("hold me");
b.setActionCommand("test");
b.addActionListener(b);
p.add(b);
f.getContentPane().add(p);
f.pack();
f.setVisible(true);
}
}
| aeris170/MARS-Theme-Engine | mars/venus/RepeatButton.java | 2,418 | /**
* Handle mouse entered events.
*
* @param me the mouse event
*/ | block_comment | en | false | 2,153 | 21 | 2,418 | 20 | 2,493 | 24 | 2,418 | 20 | 2,773 | 24 | false | false | false | false | false | true |
49296_1 | /*
* Class Name: Vigenere
*
* @author Thomas McKeesick
* Creation Date: Wednesday, September 24 2014, 14:33
* Last Modified: Saturday, January 10 2015, 23:24
*
* Class Description: Java implementation of the Vigenere cipher
*/
import java.lang.Character;
import java.util.Scanner;
public class Vigenere {
/** Variable representing the number of letters in the English Alphabet */
public static final int ALPHABET_SIZE = 26;
public static void main(String[] args) {
Scanner keyboard = new Scanner(System.in);
System.out.println("Welcome to the Vigenere decrypter\n" +
"Enter the encoded message: ");
String message = keyboard.nextLine();
System.out.println("Enter the key: ");
String key = keyboard.nextLine();
String decrypted = decrypt(message, key);
System.out.println("DECRYPTED MESSGAE: " + decrypted);
}
/**
* Decrypts a string via the Vigenere cipher
* @param str The encrypted string
* @param key The key to decode the encrypted string with
* @return The decrypted string
*/
public static String decrypt(String str, String key)
{
String decrypted = "";
key = key.toUpperCase();
int keyIndex = 0;
for (char c : str.toUpperCase().toCharArray()) {
if(Character.isLetter(c)) {
decrypted +=
(char) ((c - key.charAt(keyIndex)
+ ALPHABET_SIZE) % ALPHABET_SIZE + 'A');
keyIndex = ++keyIndex % key.length();
} else {
decrypted += c;
}
}
return decrypted;
}
}
| tmck-code/Ciphers | Vigenere.java | 423 | /** Variable representing the number of letters in the English Alphabet */ | block_comment | en | false | 390 | 13 | 428 | 14 | 453 | 13 | 423 | 14 | 503 | 14 | false | false | false | false | false | true |
49750_13 | package scripts;
import org.testng.annotations.Test;
import org.testng.annotations.BeforeMethod;
import static org.testng.Assert.*;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
import org.testng.annotations.AfterClass;
import org.testng.annotations.AfterMethod;
import org.testng.annotations.BeforeClass;
public class MyFirstTestNGTest {
WebDriver driver;
@Test //Test annotation
public void wikiTest() {
//All the test steps will go here
driver.get("https://www.wikipedia.org/");
driver.findElement(By.id("js-link-box-en")).click();
driver.findElement(By.id("searchInput")).sendKeys("Selenium");
driver.findElement(By.id("searchButton")).click();
String expectedOutput = "Selenium";
String actualOutput = driver.findElement(By.id("firstHeading")).getText();
assertEquals(actualOutput,expectedOutput);
/* if (expectedOutput.equals(actualOutput)) {
System.out.println("Heading Test Case Passed");
}
else {
System.out.println("Heading Test Case Failed");
}*/
String expectedPageTitle = "Selenium - Wikipedia1";
String actualPageTitle = driver.getTitle();
/* if (expectedPageTitle.equals(actualPageTitle)) {
System.out.println("Page Title Test Case Passed");
}
else {
System.out.println("Page Title Test Case Failed");
}*/
// assertEquals(actualPageTitle,expectedPageTitle);
assertEquals(actualPageTitle,expectedPageTitle, "Expected Title does not match with actual on page");
}
// @Test
public void googleTest() {
driver.get("http://www.google.com");
driver.findElement(By.name("q")).sendKeys("Selenium Jobs");
}
// @Test
public void yahooTest() {
driver.get("http://www.yahoo.com");
//driver.findElement(By.tagName("q")).sendKeys("Selenium Jobs");
}
@BeforeMethod //before method annotation
public void beforeMethod() {
//You should code pre-requisite here
//Open the browser
/* System.setProperty("webdriver.chrome.driver","C:\\temp\\webdrivertraining\\test\\resources\\chromedriver.exe");
driver = new ChromeDriver();
*/
System.out.println("Inside Before Method");
}
@BeforeClass
public void onlyOnceBeforeFirstMethod() {
System.setProperty("webdriver.chrome.driver","C:\\temp\\webdrivertraining\\test\\resources\\chromedriver.exe");
driver = new ChromeDriver();
}
@AfterMethod //after method annotation
public void afterMethod() {
//test case cleanup will happen here
//close the browser
// driver.quit();
System.out.println("Inside After Method");
}
@AfterClass
public void afterLastTest() {
driver.quit();
}
}
| SachinJadhav222/hrms | MyFirstTestNGTest.java | 718 | //Open the browser | line_comment | en | false | 592 | 4 | 718 | 4 | 745 | 4 | 718 | 4 | 866 | 4 | false | false | false | false | false | true |
50912_0 |
/**
* This class models and implements a cart which carries goods of type String
*
*/
public class Cart implements Comparable<Cart> {
private String cargo; // a String representation of the goods carried
// by this cart
/**
* Creates a new Cart carrying a given data
*
* @param cargo string representation of the good which are going to be carried by this cart
*/
public Cart(String cargo) {
this.cargo = cargo;
}
/**
* Returns String representation of the goods carried by this cart
*
* @return a String representation of the cargo carried by this cart
*/
@Override
public String toString() {
return cargo;
}
/**
* Returns the cargo carried by this cart
*
* @return a the cargo carried by this cart
*/
public String getCargo() {
return cargo;
}
/**
* Compares this cart with the specified object for order.
*
* @return a negative integer, zero, or a positive integer as this cart has a cargo which is less
* than, equal to, or greater than the specified other cart's cargo.
*/
@Override
public int compareTo(Cart other) {
return cargo.compareTo(other.cargo);
}
}
| anmehta4/Introduction-to-Programming-II | P06 Alphabet Train/src/Cart.java | 278 | /**
* This class models and implements a cart which carries goods of type String
*
*/ | block_comment | en | false | 281 | 18 | 278 | 21 | 317 | 20 | 278 | 21 | 333 | 21 | false | false | false | false | false | true |
50945_3 | /**
* Driver
*/
import java.util.*;
public class Driver {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.println("Enter");
System.out.println("1)To create a student");
System.out.print("2)To create an employee:");
int method = promptForInt(1, 2, input);
// clear buffer
input.nextLine();
System.out.print("Enter name:");
String name = input.nextLine();
System.out.print("Enter address:");
String address = input.nextLine();
System.out.print("Enter phone number:");
String phone = input.nextLine();
System.out.print("Enter email:");
String email = input.nextLine();
if (method == 1) {
System.out.print("Enter student's status:");
String status = input.nextLine();
Student student = new Student(name, address, phone, email, status);
System.out.print(student.toString());
}
else {
System.out.println("Enter");
System.out.println("1)To create a faculty member");
System.out.print("2)To create a staff member:");
method = promptForInt(1, 2, input);
// clear buffer
input.nextLine();
System.out.print("Enter office number:");
int officeNumber = input.nextInt();
input.nextLine();
System.out.print("Enter salary:");
int salary = input.nextInt();
input.nextLine();
System.out.print("Enter date hired (mm/dd/yy):");
String date = input.nextLine();
if (method == 1) {
System.out.print("Enter office hours:");
String officeHours = input.nextLine();
System.out.print("Enter rank:");
String rank = input.nextLine();
Faculty faculty = new Faculty(name, address, phone, email, officeNumber, salary, date, officeHours, rank);
System.out.print(faculty.toString());
}
else {
System.out.print("Enter title:");
String title = input.nextLine();
Staff staff = new Staff(name, address, phone, email, officeNumber, salary, date, title);
System.out.print(staff.toString());
}
}
}
public static int promptForInt(int min, int max, Scanner input) {
int num;
do {
try {
num = input.nextInt();
if (num < min || num > max) {
System.out.print("Invalid. Enter 1 or 2: ");
}
}
catch(Exception e) {
// This consumes the existing input so that we don't have an infinite loop!
input.nextLine();
System.out.print("Invalid. Enter 1 or 2: ");
num = max + 1;
}
} while (num < min || num > max);
return num;
}
public static class Person {
protected String name;
protected String address;
protected String phone;
protected String email;
public Person(String name, String address, String phone, String email) {
this.name = name;
this.address = address;
this.phone = phone;
this.email = email;
}
@Override
public String toString() {
String s = "Address: " + this.address + "\n"
+ "Phone Number: " + this.phone + "\n"
+ "Email: " + this.email + "\n";
return s;
}
}
public static class Student extends Person {
protected String status;
protected final String FRESHMAN = "Freshman";
protected final String SOPHMORE = "Sophmore";
protected final String JUNIOR = "Junior";
protected final String SENIOR = "Senior";
public Student(String name, String address, String phone, String email, String status) {
super(name, address, phone, email);
this.status = status;
}
@Override
public String toString() {
String s = "Student: " + this.name + "\n"
+ "Status: " + this.status + "\n"
+ super.toString();
return s;
}
}
public static class Employee extends Person {
protected int officeNumber;
protected int salary;
protected MyDate dateHired;
public Employee(String name, String address, String phone, String email,
int officeNumber, int salary, String date) {
super(name, address, phone, email);
this.officeNumber = officeNumber;
this.salary = salary;
this.dateHired = new MyDate(date);
}
@Override
public String toString() {
String s = "Office: " + this.officeNumber + "\n"
+ super.toString();
return s;
}
}
public static class Faculty extends Employee {
protected String officeHours;
protected String rank;
public Faculty(String name, String address, String phone, String email,
int officeNumber, int salary, String date, String officeHours, String rank) {
super(name, address, phone, email, officeNumber, salary, date);
this.officeHours = officeHours;
this.rank = rank;
}
@Override
public String toString() {
String s = "Faculty: " + this.name + "\n"
+ "Rank: " + this.rank + "\n"
+ "Salary: $" + this.salary + "\n"
+ "Date Hired: " + this.dateHired.date + "\n\n"
+ "Office Hours: " + this.officeHours + "\n"
+ super.toString();
return s;
}
}
public static class Staff extends Employee {
protected String title;
public Staff(String name, String address, String phone, String email,
int officeNumber, int salary, String date, String title) {
super(name, address, phone, email, officeNumber, salary, date);
this.title = title;
}
@Override
public String toString() {
String s = "Staff: " + this.name + "\n"
+ "Salary: $" + this.salary + "\n"
+ "Date Hired: " + this.dateHired.date + "\n\n"
+ super.toString();
return s;
}
}
public static class MyDate {
private String date; // date in the form mm/dd/yy
public MyDate(String date) {
this.date = date;
}
public String getDate() {
return date;
}
}
} | joshuasells/javaSchoolProjects | Driver.java | 1,501 | // This consumes the existing input so that we don't have an infinite loop! | line_comment | en | false | 1,369 | 16 | 1,501 | 17 | 1,653 | 17 | 1,501 | 17 | 1,774 | 18 | false | false | false | false | false | true |
51274_1 | /**
* Guess object for the Mastermind game. The Board class contains a stack of these
* Consists of two combinations:
* <ul>
* <li>The actual guess. This is added at construction</li>
* <li>The feedback on the guess. This is added at a later time, not at construction</li>
* </ul>
*
* @author Matt Buckley
* @since 24/12/2015
*/
public class Guess {
private Combination guess;
private Combination feedback;
/**
* Sets the guess variable using the given combination
*
* @param guess The guess Combination
*/
public Guess(Combination guess) {
this.guess = guess;
}
public Combination getGuess() {
return (guess);
}
public Combination getFeedback() {
return (feedback);
}
/**
* Sets the feedback on the guess
* This is done after construction, because the feedback is entered by the Player after they have seen the guess
*
* @param feedback The player's feedback
*/
public void setFeedback(Combination feedback) {
this.feedback = feedback;
}
} | mbuckley2000/Mastermind | src/Guess.java | 281 | /**
* Sets the guess variable using the given combination
*
* @param guess The guess Combination
*/ | block_comment | en | false | 243 | 25 | 281 | 24 | 280 | 27 | 281 | 24 | 316 | 30 | false | false | false | false | false | true |
52025_7 | /**
* Created by samuelshen on 3/31/18.
* A case-sensitive Trie implementation
*/
import java.lang.reflect.Array;
import java.util.ArrayList;
import java.util.List;
import java.util.Iterator;
public class Trie implements Iterable<String> {
//private ArrayList<TrieNode> heads;
private TrieNode head;
private ArrayList<String> values;
//empty constructor
public Trie(){
head = new TrieNode();
values = new ArrayList<>();
}
//constructor given @new_head
public Trie(TrieNode new_head){
head = new_head;
values = new ArrayList<>();
}
//constructor given a list of Strings @words
public Trie(List<String> words){
//TODO: IMPLEMENT
}
//add a word
//return true if word is added, false if already present
public boolean addWord(String word){
boolean shortWord = word.length() == 1;
if(values.contains(word)){
return false;
}
values.add(word);
TrieNode first_char = new TrieNode(word.charAt(0), shortWord);
try {
word = word.substring(1);
} catch (IndexOutOfBoundsException e){
word = "";
}
TrieNode temp_node = new TrieNode();
if(head.leadsTo(first_char)){
temp_node = head.getChild(first_char);
} else {
temp_node = first_char;
head.addChild((temp_node));
}
while(word.length() > 0){
char temp_char = word.charAt(0);
if(word.length() > 1) {
temp_node = temp_node.addChild(temp_char, false);
} else {
temp_node = temp_node.addChild(temp_char, true);
}
try {
word = word.substring(1);
} catch (IndexOutOfBoundsException e){
word = "";
}
}
return true;
}
public ArrayList<String> complete (TrieNode start_node){
ArrayList<String> completions = new ArrayList<>();
String val = String.valueOf(start_node.getValue());
//base case
if(start_node.isEnd()){
completions.add(val);
} else {
for(TrieNode child_node: start_node.getChildren()) {
ArrayList<String> child_call = complete(child_node);
for (String child_completion : child_call) {
completions.add(val + child_completion);
}
}
}
return completions;
}
public ArrayList<String> complete (String wordNub){
TrieNode temp = head;
for(char c: wordNub.toCharArray()){
temp = temp.getChild(c);
if(temp == null){ //no completions case
return new ArrayList<String>();
}
}
ArrayList<String> endings = complete(temp); //these are completions sans wordNub
ArrayList<String> completions = new ArrayList<>();
for(String post: endings){
completions.add(wordNub + post.substring(1)); //substringed to cut repeated letter resultant from recursive call
}
return completions;
}
//just returns the iterator for a list of all the words
public Iterator<String> iterator(){
return values.iterator();
}
//testmain
public static void main(String [] args){
Trie test_trie = new Trie();
test_trie.addWord("Hello");
test_trie.addWord("hello");
test_trie.addWord("Goodbye");
test_trie.addWord("Heat");
System.out.println(test_trie.complete("He"));
}
} | samuelwshen/Chry | Trie.java | 869 | //return true if word is added, false if already present | line_comment | en | false | 744 | 12 | 869 | 12 | 935 | 12 | 869 | 12 | 1,014 | 12 | false | false | false | false | false | true |
52493_1 | package game;
import java.util.Iterator;
import game.ids.PlayerID;
import game.ids.StringID;
import game.xui.SettingsGui;
import game.xui.Window;
public class MiscCmd {
/** Change the player's face.
* @param x,y unused
* @param p1 unused
* @param p2 face bitmasked
*/
static int CmdSetPlayerFace(int x, int y, int flags, int p1, int p2)
{
if(0 != (flags & Cmd.DC_EXEC)) {
Player.GetCurrentPlayer().face = p2;
Hal.MarkWholeScreenDirty();
}
return 0;
}
/** Change the player's company-colour
* @param x,y unused
* @param p1 unused
* @param p2 new colour for vehicles, property, etc.
*/
static int CmdSetPlayerColor(int x, int y, int flags, int p1, int p2)
{
Player p;
byte colour;
if (p2 >= 16) return Cmd.CMD_ERROR; // max 16 colours
colour = (byte) p2;
p = Player.GetCurrentPlayer();
/* Ensure no two companies have the same colour */
//FOR_ALL_PLAYERS(pp)
Iterator<Player> ii = Player.getIterator();
while(ii.hasNext())
{
Player pp = ii.next();
if (pp.is_active && pp != p && pp.player_color == colour)
return Cmd.CMD_ERROR;
}
if(0 != (flags & Cmd.DC_EXEC)) {
Global.gs._player_colors[PlayerID.getCurrent().id] = colour;
p.player_color = colour;
Hal.MarkWholeScreenDirty();
}
return 0;
}
/** Increase the loan of your company.
* @param x,y unused
* @param p1 unused
* @param p2 when set, loans the maximum amount in one go (press CTRL)
*/
static int CmdIncreaseLoan(int x, int y, int flags, int p1, int p2)
{
Player p;
p = Player.GetCurrentPlayer();
if (p.current_loan >= Global.gs._economy.getMax_loan()) {
Global.SetDParam(0, Global.gs._economy.getMax_loan());
return Cmd.return_cmd_error(Str.STR_702B_MAXIMUM_PERMITTED_LOAN);
}
if(0 != (flags & Cmd.DC_EXEC)) {
/* Loan the maximum amount or not? */
final int v = (PlayerID.getCurrent().IS_HUMAN_PLAYER() || Global._patches.ainew_active) ? 10000 : 50000;
int loan = (p2 != 0) ? Global.gs._economy.getMax_loan() - p.current_loan : v;
p.money64 += loan;
p.current_loan += loan;
//p.UpdatePlayerMoney32();
p.InvalidatePlayerWindows();
}
return 0;
}
/** Decrease the loan of your company.
* @param x,y unused
* @param p1 unused
* @param p2 when set, pays back the maximum loan permitting money (press CTRL)
*/
static int CmdDecreaseLoan(int x, int y, int flags, int p1, int p2)
{
Player p;
long loan;
p = Player.GetCurrentPlayer();
if (p.current_loan == 0) return Cmd.return_cmd_error(Str.STR_702D_LOAN_ALREADY_REPAYED);
loan = p.current_loan;
/* p2 is true while CTRL is pressed (repay all possible loan, or max money you have)
* Repay any loan in chunks of 10.000 pounds */
if (p2 != 0) {
loan = Math.min(loan, p.getMoney());
loan = Math.max(loan, 10000);
loan -= loan % 10000;
} else {
loan = Math.min(loan, (PlayerID.getCurrent().IS_HUMAN_PLAYER() || Global._patches.ainew_active) ? 10000 : 50000);
}
if (p.getMoney() < loan) {
Global.SetDParam(0, (int)loan); // TODO long -> int
return Cmd.return_cmd_error(Str.STR_702E_REQUIRED);
}
if(0 != (flags & Cmd.DC_EXEC)) {
p.money64 -= loan;
p.current_loan -= loan;
//p.UpdatePlayerMoney32();
p.InvalidatePlayerWindows();
}
return 0;
}
/** Change the name of the company.
* @param x,y unused
* @param p1 unused
* @param p2 unused
*/
static int CmdChangeCompanyName(int x, int y, int flags, int p1, int p2)
{
StringID str;
Player p;
if (Global._cmd_text == null) return Cmd.CMD_ERROR;
str = Global.AllocateNameUnique(Global._cmd_text, 4);
if (str == null) return Cmd.CMD_ERROR;
if(0 != (flags & Cmd.DC_EXEC)) {
p = Player.GetCurrentPlayer();
Global.DeleteName(p.name_1);
p.name_1 = str.id;
Hal.MarkWholeScreenDirty();
} else
Global.DeleteName(str);
return 0;
}
/** Change the name of the president.
* @param x,y unused
* @param p1 unused
* @param p2 unused
*/
static int CmdChangePresidentName(int x, int y, int flags, int p1, int p2)
{
StringID str;
Player p;
if (Global._cmd_text == null) return Cmd.CMD_ERROR;
str = Global.AllocateNameUnique(Global._cmd_text, 4);
if (str == null) return Cmd.CMD_ERROR;
if(0 != (flags & Cmd.DC_EXEC)) {
p = Player.GetCurrentPlayer();
Global.DeleteName(p.president_name_1);
p.president_name_1 = str.id;
if (p.name_1 == Str.STR_SV_UNNAMED) {
Global._cmd_text = String.format("%s Transport", Global._cmd_text);
Cmd.DoCommandByTile(new TileIndex(0), 0, 0, Cmd.DC_EXEC, Cmd.CMD_CHANGE_COMPANY_NAME);
}
Hal.MarkWholeScreenDirty();
} else
Global.DeleteName(str);
return 0;
}
/** Pause/Unpause the game (server-only).
* Increase or decrease the pause counter. If the counter is zero,
* the game is unpaused. A counter is used instead of a booleanean value
* to have more control over the game when saving/loading, etc.
* @param x,y unused
* @param p1 0 = decrease pause counter; 1 = increase pause counter
* @param p2 unused
*/
static int CmdPause(int x, int y, int flags, int p1, int p2)
{
if(0 != (flags & Cmd.DC_EXEC) ) {
Global._pause += (p1 == 1) ? 1 : -1;
if (Global._pause == -1) Global._pause = 0;
Window.InvalidateWindow(Window.WC_STATUS_BAR, 0);
Window.InvalidateWindow(Window.WC_MAIN_TOOLBAR, 0);
}
return 0;
}
/** Change the financial flow of your company.
* This is normally only enabled in offline mode, but if there is a debug
* build, you can cheat (to test).
* @param x,y unused
* @param p1 the amount of money to receive (if negative), or spend (if positive)
* @param p2 unused
*/
static int CmdMoneyCheat(int x, int y, int flags, int p1, int p2)
{
/*#ifndef _DEBUG
if (_networking) return Cmd.CMD_ERROR;
#endif*/
Player.SET_EXPENSES_TYPE(Player.EXPENSES_OTHER);
return p1;
}
/** Transfer funds (money) from one player to another.
* To prevent abuse in multiplayer games you can only send money to other
* players if you have paid off your loan (either explicitely, or implicitely
* given the fact that you have more money than loan).
* @param x,y unused
* @param p1 the amount of money to transfer; max 20.000.000
* @param p2 the player to transfer the money to
*/
static int CmdGiveMoney(int x, int y, int flags, int p1, int p2)
{
final Player p = Player.GetCurrentPlayer();
int amount = Math.min(p1, 20000000);
Player.SET_EXPENSES_TYPE(Player.EXPENSES_OTHER);
/* You can only transfer funds that is in excess of your loan */
if (p.money64 - p.current_loan < amount || amount <= 0) return Cmd.CMD_ERROR;
if (!Global._networking || p2 >= Global.MAX_PLAYERS) return Cmd.CMD_ERROR;
if(0 != (flags & Cmd.DC_EXEC)) {
/* Add money to player */
PlayerID old_cp = PlayerID.getCurrent();
PlayerID.setCurrent( PlayerID.get( p2 ) );
Player.SubtractMoneyFromPlayer(-amount);
PlayerID.setCurrent(old_cp);
}
/* Subtract money from local-player */
return amount;
}
/** Change difficulty level/settings (server-only).
* We cannot really check for valid values of p2 (too much work mostly); stored
* in file 'settings_gui.c' _game_setting_info[]; we'll just trust the server it knows
* what to do and does this correctly
* @param x,y unused
* @param p1 the difficulty setting being changed. If it is -1, the difficulty level
* itself is changed. The new value is inside p2
* @param p2 new value for a difficulty setting or difficulty level
*/
static int CmdChangeDifficultyLevel(int x, int y, int flags, int p1, int p2)
{
if (p1 != (int)-1L && (p1 >= Global.GAME_DIFFICULTY_NUM || p1 < 0)) return Cmd.CMD_ERROR;
if(0 != (flags & Cmd.DC_EXEC)) {
if (p1 != (int)-1L) {
// ((int*)&GameOptions._opt_ptr.diff)[p1] = p2;
GameOptions._opt_ptr.diff.setAsInt(p1, p2);
GameOptions._opt_ptr.diff_level = 3; // custom difficulty level
} else
GameOptions._opt_ptr.diff_level = (byte) p2;
/* If we are a network-client, update the difficult setting (if it is open).
* Use this instead of just dirtying the window because we need to load in
* the new difficulty settings */
if (Global._networking && !Global._network_server && Window.FindWindowById(Window.WC_GAME_OPTIONS, 0) != null)
SettingsGui.ShowGameDifficulty();
}
return 0;
}
}
| dzavalishin/jdrive | src/game/MiscCmd.java | 2,882 | /** Change the player's company-colour
* @param x,y unused
* @param p1 unused
* @param p2 new colour for vehicles, property, etc.
*/ | block_comment | en | false | 2,524 | 42 | 2,882 | 40 | 2,905 | 45 | 2,882 | 40 | 3,415 | 48 | false | false | false | false | false | true |
52992_5 | //This program tallys a bill composed of 3 purchesed items.
import java.util.*;
public class Bill {
public static void main(String[] args) {
//The following prompts the user to input the item name, quantity, and price for 3 items. The are all saved as variables.
Scanner console = new Scanner (System.in);
System.out.print("Item 1: ");
String item1 = console.nextLine();
System.out.print("Quantity: ");
int quantity1 = console.nextInt();
System.out.print("Price: ");
double price1 = console.nextDouble();
System.out.print("Item 2: ");
String item2 = console.next();
System.out.print("Quantity: ");
int quantity2 = console.nextInt();
System.out.print("Price: ");
double price2 = console.nextDouble();
System.out.print("Item 3: ");
String item3 = console.next();
System.out.print("Quantity: ");
int quantity3 = console.nextInt();
System.out.print("Price: ");
double price3 = console.nextDouble();
//Methods are called and saved as variables.
double total1 = totalOne(quantity1, price1);
double total2 = totalTwo(quantity2, price2);
double total3 = totalTwo(quantity3, price3);
double totaltotal = totalAll(total1, total2, total3);
double totaltax = totalTax(total1, total2, total3);
double totaltwo;
double totalthree;
//Strings are saved to format the columns of the bill.
String item = "Item";
String quantity = "Quantity";
String price = "Price";
String total = "Total";
String subtotal = "Subtotal";
String tax = "6.25% sales tax";
//The bill is printed as each variable is spaced out on the screen.
System.out.println();
System.out.println("Your bill:");
System.out.printf("%-30s%-10s%-10s%-10s\n", item, quantity, price, total);
System.out.printf("%-30s%-10s%-10s%-10s\n", item1, quantity1, price1, total1);
System.out.printf("%-30s%-10s%-10s%-10s\n", item2, quantity2, price2, total2);
System.out.printf("%-30s%-10s%-10s%-10s\n", item3, quantity3, price3, total3);
System.out.println();
System.out.printf("%-50s%-10.2f", subtotal, totaltotal);
System.out.println();
System.out.printf("%-50s%-10.2f", tax, totaltax);
System.out.println();
System.out.printf("%-50s%-10.2f", total, totaltotal+totaltax);
System.out.println();
}
public static double totalOne(int quantity1, double price1) {
//This method calculated the total of item 1.
double total1 = quantity1*price1;
return total1;
}
public static double totalTwo(int quantity2, double price2) {
//This method calculated the total of item 2.
double total2 = quantity2*price2;
return total2;
}
public static double totalThree(int quantity3, double price3) {
//This method calculated the total of item 3.
double total3 = quantity3*price3;
return total3;
}
public static double totalAll(double total1, double total2, double total3) {
//This method calculated the total of all the items.
double totaltotal = (total1+total2+total3);
return totaltotal;
}
public static double totalTax(double total1, double total2, double total3) {
//This method calculated the total tax of all the items.
double totaltax = (total1+total2+total3)*0.0625;
return totaltax;
}
}
| philosophercode/JavaApps | Bill.java | 977 | //This method calculated the total of item 1. | line_comment | en | false | 870 | 11 | 977 | 11 | 1,020 | 11 | 977 | 11 | 1,060 | 11 | false | false | false | false | false | true |
53093_22 | // Yousef Alawi
import java.util.ArrayList;
import java.util.Scanner;
public class Project1 {
public static void main(String[] args) {
// creating an arraylist to store every Person
ArrayList<Student> arrayOfStudent = new ArrayList<>();
ArrayList<Staff> arrayOfStaff = new ArrayList<>();
ArrayList<Faculty> arrayOfFaculty = new ArrayList<>();
System.out.println(" Welcome to my Personal Management Program\n");
Scanner sc = new Scanner(System.in);
boolean loop = true;
// Creating a loop to keep the program running
while(loop) {
Options();
int choice = sc.nextInt();
switch (choice) {
case 1:
// Reading input from the user
System.out.print("\n\nEnter the faculty info: ");
System.out.print("\n Name of faculty: ");
sc.nextLine().trim();
String facultyName = sc.nextLine().trim();
System.out.print("\n ID: ");
String facultyID = sc.nextLine().trim();
System.out.print("\n Rank: ");
String rank = sc.nextLine().trim();
System.out.print("\n Department: ");
String department = sc.nextLine().trim();
System.out.print("\nFaculty added!\n\n");
// Adding the information
Faculty faculty = new Faculty(facultyName, facultyID, rank, department);
arrayOfFaculty.add(faculty);
break;
case 2:
// Reading the students input
System.out.print("\n\nEnter the student info:");
System.out.print("\n Name of Student: ");
sc.nextLine().trim();
String studentName = sc.nextLine();
System.out.print("\n ID: ");
String ID = sc.nextLine();
System.out.print("\n Gpa: ");
double GPA = sc.nextDouble();
System.out.print("\n Credit hours: ");
int creditHours = sc.nextInt();
System.out.print("\nStudent added!\n\n");
// Adding the students information
Student student = new Student(studentName, ID, GPA, creditHours);
arrayOfStudent.add(student);
break;
case 3:
// Output the information back to the user
System.out.print("Enter the student's id: ");
sc.nextLine().trim();
String getStudentId = sc.nextLine().trim();
for(int i = 0; i < arrayOfStudent.size(); i++){
Student current = arrayOfStudent.get(i);
if (current.getID().equals(getStudentId)){
current.printInformation();
}
else {
System.out.println("No student matched!\n\n");
}
}
break;
case 4:
// Output the information back to the user
System.out.print("Enter the Faculty's id: ");
sc.nextLine().trim();
String getFacultyId = sc.nextLine().trim();
for(int i = 0; i < arrayOfFaculty.size(); i++){
Faculty current = arrayOfFaculty.get(i);
if (current.getID().equals(getFacultyId)){
current.printInformation();
}
else {
System.out.println("No Faculty matched!\n\n");
}
}
break;
case 5:
// Reading the information from the Staff
System.out.print("\nName of the staff member: ");
sc.nextLine().trim();
String staffName = sc.nextLine().trim();
System.out.print("\nEnter the id: ");
String staffID = sc.nextLine().trim();
System.out.print("\nDepartment: ");
String staffDepartment = sc.nextLine().trim();
System.out.print("\nStatus, Enter P for Part Time, or Enter F for Full Time: ");
String status = sc.nextLine().trim();
System.out.print("\nStaff member added!\n\n");
// Adding the staff info
Staff staff = new Staff(staffName, staffID, status, staffDepartment);
arrayOfStaff.add(staff);
break;
case 6:
// Output the information back to the user
System.out.print("Enter the Staff's id: ");
sc.nextLine().trim();
String getStaffId = sc.nextLine().trim();
for(int i = 0; i < arrayOfStaff.size(); i++){
Staff current = arrayOfStaff.get(i);
if (current.getID().equals(getStaffId)){
current.printInformation();
}
else {
System.out.println("No Staff matched!\n\n");
}
}
break;
case 7:
// exiting the program
loop = false;
break;
default:
System.out.println("invalid input");
break;
}
}
System.out.println("Goodbye!");
}
public static void Options() {
System.out.println("1- Enter the information a faculty");
System.out.println("2- Enter the information of a student");
System.out.println("3- Print tuition invoice for a student");
System.out.println("4- Print faculty information");
System.out.println("5- Enter the information of a staff member");
System.out.println("6- Print the information of a staff member");
System.out.println("7- Exit Program ");
System.out.print(" Enter your selection: ");
}
}
abstract class Person{
private String Name;
private String ID;
// Constructor
public Person(String Name, String ID) {
this.Name = Name;
this.ID = ID;
}
abstract void printInformation();
// Make the getters and setters
public String getName()
{
return Name;
}
public void setName(String Name)
{
this.Name = Name;
}
public String getID()
{
return ID;
}
public void setID(String ID)
{
this.ID = ID;
}
}
class Student extends Person{
// Specified attributes
double gpa;
int noOfCreditHours;
// Declaring a discount variable because we have to show it
public double discount = 0.00;
// constructor
public Student(String fullName, String ID, double gpa, int noOfCreditHours) {
super(fullName, ID);
this.gpa = gpa;
this.noOfCreditHours = noOfCreditHours;
}
// Adding in the getters and setters
public int getNoOfCreditHours()
{
return noOfCreditHours;
}
// Overriding all methods of Parent class
@Override
public String getName()
{
return super.getName();
}
@Override
public void setName(String Name)
{
super.setName(Name);
}
@Override
public String getID()
{
return super.getID();
}
@Override
public void setID(String ID)
{
super.setID(ID);
}
// A method tuition invoice for calculating total payment & return it
public double tuitionInvoice(){
// Students pay $236.45 per credit hour in addition to a $52 administrative fee
double total = ( noOfCreditHours * 236.45) + 52.00;
// implement the 25% off discount if the gpa is above 3.85
if(this.gpa >= 3.85){
discount = total * (25.0 / 100.0);
total -= discount;
}
return total;
}
// @Override
void printInformation() {
System.out.println("\nHere is the tuition invoice for "+getName()+" :");
System.out.println("---------------------------------------------------------------------------\n");
System.out.println(getName()+"\t"+getID() +"\n"+
"Credit Hours: "+getNoOfCreditHours()+" ($236.45/credit hour)\n"+
"Fees: $52\nTotal Payment: $"+tuitionInvoice()+"\t"+"($"+discount+" discount applied)");
System.out.println("---------------------------------------------------------------------------\n");
}
}
abstract class Employee extends Person{
private String department;
// Creating my constructor
public Employee(String fullName, String ID, String department) {
super(fullName, ID);
this.department = department;
}
// Adding the getters and setters
public String getDepartment()
{
return department;
}
public void setDepartment(String department)
{
this.department = department;
}
// Overriding all methods of Parent class
@Override
public String getName()
{
return super.getName();
}
@Override
public void setName(String Name)
{
super.setName(Name);
}
@Override
public String getID()
{
return super.getID();
}
@Override
public void setID(String ID)
{
super.setID(ID);
}
@Override
void printInformation(){
}
}
class Faculty extends Employee {
String rank;
// constructor
public Faculty(String name, String ID, String rank, String department){
super(name, ID, department);
this.rank = rank;
}
// Overriding all methods of Parent class
@Override
public String getDepartment()
{
return super.getDepartment();
}
@Override
public void setDepartment(String Name)
{
super.setDepartment(Name);
}
@Override
public String getName()
{
return super.getName();
}
@Override
public void setName(String Name)
{
super.setName(Name);
}
@Override
public String getID()
{
return super.getID();
}
@Override
public void setID(String ID)
{
super.setID(ID);
}
@Override
void printInformation(){
System.out.println("---------------------------------------------------------------------------");
System.out.println(getName() +"\t" +getID());
System.out.println(getDepartment()+" Department \t," +this.rank);
System.out.println("---------------------------------------------------------------------------");
}
}
class Staff extends Employee {
String status;
// constructor
public Staff(String name, String ID, String status, String department){
super(name, ID, department);
this.status = status;
}
// Overriding all methods of Parent class
@Override
public String getDepartment()
{
return super.getDepartment();
}
@Override
public void setDepartment(String Name)
{
super.setDepartment(Name);
}
@Override
public String getName()
{
return super.getName();
}
@Override
public void setName(String Name)
{
super.setName(Name);
}
@Override
public String getID()
{
return super.getID();
}
@Override
public void setID(String ID)
{
super.setID(ID);
}
@Override
void printInformation(){
String time;
if(this.status.equals("F")){
time = "Full Time";
}
else {
time = "Part Time";
}
System.out.println("---------------------------------------------------------------------------");
System.out.println(getName() +"\t" +getID());
System.out.println(getDepartment() +" Department \t," +time);
System.out.println("---------------------------------------------------------------------------");
}
}
| yalawi1/UniversityManagement | Main.java | 2,594 | // implement the 25% off discount if the gpa is above 3.85 | line_comment | en | false | 2,364 | 20 | 2,594 | 20 | 2,895 | 20 | 2,594 | 20 | 3,283 | 21 | false | false | false | false | false | true |
53457_0 | /**
* A class representing a cafe.
*/
public class Cafe extends Building {
/**
* The number of coffee ounces, sugar packets, splashes of cream, and cups remaining in the inventory.
* */
private int nCoffeeOunces; // The number of ounces of coffee remaining in inventory
private int nSugarPackets; // The number of sugar packets remaining in inventory
private int nCreams; // The number of "splashes" of cream remaining in inventory
private int nCups; // The number of cups remaining in inventory
/**
* Constructs a Cafe object with the given name, address, and number of floors.
* Initializes the inventory with default values.
* @param name the name of the cafe
* @param address the address of the cafe
* @param nFloors the number of floors in the cafe
* */
public Cafe(String name, String address, int nFloors) {
super(name, address, nFloors);
System.out.println("You have built a cafe: ☕");
this.nCoffeeOunces = 15;
this.nSugarPackets = 15;
this.nCreams = 15;
this.nCups = 20;
}
/**
* Sells coffee to a customer with the given size, number of sugar packets, and number of cream splashes.
* If the cafe is out of any inventory items, restocks them before fulfilling the order.
* If the cafe is out of cups, the order cannot be fulfilled.
* @param size the size of the coffee (in ounces)
* @param nSugarPackets the number of sugar packets in the coffee
* @param nCreams the number of cream splashes in the coffee
*/
public void sellCoffee(int size, int nSugarPackets, int nCreams) {
if (this.nCoffeeOunces < size || this.nSugarPackets < nSugarPackets || this.nCreams < nCreams || this.nCups < 1) {
restock(size, nSugarPackets, nCreams, 1);
System.out.println("Restock needed! Please wait a minute.");
}
this.nCoffeeOunces -= size;
this.nSugarPackets -= nSugarPackets;
this.nCreams -= nCreams;
this.nCups -= 1;
System.out.println("Here's your order! Enjoy.");
}
/**
* Sells coffee to a customer with a non-dairy preference. Overloaded sellCoffee(..) method for non-dairy options.
* If the cafe is out of any inventory items, restocks them before fulfilling the order.
* If the cafe is out of cups, the order cannot be fulfilled.
* @param size the size of the coffee (in ounces)
* @param nSugarPackets the number of sugar packets in the coffee
* @param nonDairyOption the boolean indicating if there's a non-dairy request
*/
public void sellCoffee(int size, int nSugarPackets, boolean nonDairyOption) {
int nCreams = nonDairyOption ? 0 : 1; // Set number of creams based on nonDairyOption flag
if (this.nCoffeeOunces < size || this.nSugarPackets < nSugarPackets || this.nCreams < nCreams || this.nCups < 1) {
restock(size, nSugarPackets, nCreams, 1);
System.out.println("Restock needed! Please wait a minute.");
}
this.nCoffeeOunces -= size;
this.nSugarPackets -= nSugarPackets;
this.nCreams -= nCreams;
this.nCups -= 1;
System.out.println("Here's your non-dairy order! Enjoy.");
}
/**
* Sells coffee to a customer with a non-sweet preference. Overloaded sellCoffee(..) method for non-sweet options.
* If the cafe is out of any inventory items, restocks them before fulfilling the order.
* If the cafe is out of cups, the order cannot be fulfilled.
* @param size the size of the coffee (in ounces)
* @param nSugarPackets the number of sugar packets in the coffee
*/
public void sellCoffee(int size, int nCreams) {
if (this.nCoffeeOunces < size || this.nSugarPackets < nSugarPackets || this.nCreams < nCreams || this.nCups < 1) {
restock(size, nSugarPackets, nCreams, 1);
System.out.println("Restock needed! Please wait a minute.");
}
this.nCoffeeOunces -= size;
this.nSugarPackets -= nSugarPackets;
this.nCreams -= nCreams;
this.nCups -= 1;
System.out.println("Here's your non-sweetened order! Enjoy.");
}
/**
* Navigates to a specified floor.
* @param floorNum the floor number to navigate to
* @throws RuntimeException if the user is not currently inside the building or the specified floor number is invalid
* @throws RuntimeException if the floor is below or above the 1st floor
*/
public void goToFloor(int floorNum) {
if (this.activeFloor == -1) {
throw new RuntimeException("You are not inside this Building. Must call enter() before navigating between floors.");
}
if (floorNum < 1) {
throw new RuntimeException("You are not permitted to go to this floor.");
}
if (floorNum > 1) {
throw new RuntimeException("You are not permitted to go to this floor.");
}
System.out.println("You are now on floor #" + floorNum + " of " + this.name);
this.activeFloor = floorNum;
}
/**
* Restocks the cafe's inventory with the given number of coffee ounces, sugar packets, cream splashes, and cups.
* @param nCoffeeOunces the number of coffee ounces to restock
* @param nSugarPackets the number of sugar packets to restock
* @param nCreams the number of cream splashes to restock
* @param nCups the number of cups to restock
*/
private void restock(int nCoffeeOunces, int nSugarPackets, int nCreams, int nCups) {
this.nCoffeeOunces += nCoffeeOunces * 10;
this.nSugarPackets += nSugarPackets * 10;
this.nCreams += nCreams * 10;
this.nCups += nCups * 10;
}
/*
* Shows the options that one has at the cafe.
*/
public void showOptions() {
System.out.println("Available options at " + this.name + ":\n + enter() \n + exit() \n + goUp() \n + goDown()\n + goToFloor(n)\n + buyCoffee()");
}
/**
* Main method for testing the Library class.
*/
public static void main(String[] args) {
Cafe campusCafe = new Cafe("Campus Cafe", "100 Green Street Northampton, MA 01063", 1);
System.out.println(campusCafe);
campusCafe.sellCoffee(15, 6, 9);
campusCafe.sellCoffee(15, 6, false);
campusCafe.sellCoffee(15, 6, 9);
campusCafe.sellCoffee(15, 6, 9);
campusCafe.sellCoffee(15, 6);
campusCafe.showOptions();
campusCafe.enter();
}
} | lpham-creator/CSC120-A7 | Cafe.java | 1,897 | /**
* A class representing a cafe.
*/ | block_comment | en | false | 1,708 | 9 | 1,897 | 12 | 1,872 | 11 | 1,897 | 12 | 2,171 | 12 | false | false | false | false | false | true |
53845_1 | import java.util.Set;
public class Program {
// Set field to connect it through the Interface with the parameter in the constructor below
Set<Equipment> equipment;
// reaching the equipmentFromFile(); method through the Interface so I can manipulate, print and do what I want with it
public Program(EquipmentSupply supply) throws Exception {
equipment = supply.equipmentFromFile();
}
// I would have used this class mainly if I wanted to manipulate the program more,
// therefore the class Print.java has only one responsibility, to print and nothing else.
// task 2) this method is in this location because it has nothing to do with task 3 and 4
public void printAllEquipmentToTerminal() {
System.out.println("Printing every object that is in the Set below:\n");
for (Equipment e : equipment) {
System.out.println(e);
}
System.out.println();
}
}
| runejac/PGR103-OOP-JavaExamSpring21 | src/Program.java | 207 | // reaching the equipmentFromFile(); method through the Interface so I can manipulate, print and do what I want with it | line_comment | en | false | 194 | 23 | 207 | 24 | 220 | 23 | 207 | 24 | 241 | 24 | false | false | false | false | false | true |
53847_14 | import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.util.ArrayList;
/**
* Class that represents Batman's utility belt. Stores the list of all equipment
* in the belt and computes statistics about the equipment.
*
* Reads in equipment information from files and outputs stats to other files.
*
* @author Stephen
* @version 2018-01-27
*/
public class UtilityBelt
{
/**
* The list of equipment in the utility belt.
* Don't worry about the "protected" for now; this is done to make tests easier.
*/
protected ArrayList<Equipment> equipment = new ArrayList<Equipment>();
/**
* THIS METHOD IS PROVIDED TO YOU.
* YOU SHOULD NOT MODIFY IT!
*
* Constructor, takes in a csv file of Equipment and stores them in a list.
*
* @param filename The name of the csv file containing a list of Equipment, one Equipment on each line.
* Assumes that the csv file is at the top level of the project
* (not within any folders; at the same level as src and TODO.json - this will be handled automatically
* in Zylabs).
*/
public UtilityBelt(String filename)
{
// Attempt to read a csv file, catch an error if something goes wrong:
try
{
read(filename);
}
catch(IOException e)
{
System.out.println("Error reading from file!\n");
e.printStackTrace();
}
}
/**
* Loads a list of equipment from a CSV file. Each line of the csv represents a single Equipment.
* The first line of the csv denotes the order of the fields, you should not
* construct a player from the first line.
*
* @param filename The file to read from.
* @throws IOException Throw this exception if a major issue with the file occurs.
*/
public void read(String filename) throws IOException
{
// Use a buffered Reader on the file:
BufferedReader br = new BufferedReader(new FileReader(filename));
String strg;
// Throw out header
strg = br.readLine();
// First row containing data
strg = br.readLine();
// Loop over the lines in the file
while (strg != null)
{
equipment.add(new Equipment(strg));
strg = br.readLine();
}
br.close();
}
/**
* Writes out information about the Equipment in the UtilityBelt.
* Specifically, loop through the list of equipments write out each equipment's toString().
* A newline is added after each toString (using BufferedWriter's newLine() method).
*
* @param filename the file to write out to (should be a .txt file).
* When you run this method locally this file may not load into eclipse. You should use
* File>Refresh on the project to view the files in eclipse.
*/
public void writeEquipment(String filename) throws IOException
{
// Set up the writer:
BufferedWriter bw = new BufferedWriter(new FileWriter(filename));
// Write out each equipment, adding a newline between toStrings:
for (int i = 0; i < equipment.size(); i++)
{
bw.write(equipment.get(i).toString());
bw.newLine();
}
// Close the writer:
bw.close();
}
/**
* Formats and writes out information about the statistics of a UtilityBelt.
* Specifically, write out information in the following format:
*
* "Total Weight: (total weight)\nMost Expensive Equipment: (name of the most expensive equipment)\n""
*
* @param filename the file to write out to (should be a .txt file).
* When you run this method locally this file may not load into eclipse. You should use
* File>Refresh on the project to view the files in eclipse.
*/
public void writeStatistics(String filename) throws IOException
{
// Set up the writer and string to output:
BufferedWriter bw = new BufferedWriter(new FileWriter(filename));
String out = "";
// Build the output string:
out += "Total Weight: " + computeTotalWeight() + "\n";
out += "Most Expensive Equipment: " + findMostExpensiveEquipment().getName() + "\n";
// Write out the output string and close:
bw.write(out);
bw.close();
}
/**
* Gives the total weight of the UtilityBelt.
*
* @return Sum of the weights of the Equipment in the UtilityBelt.
*/
public double computeTotalWeight()
{
double weight = 0;
for (Equipment equip : equipment)
{
weight += equip.getTotalWeight();
}
return weight;
}
/**
* Find equipment with the same name.
*
* @param name The name to compare to.
* @return The equipment with the same name, ignoring case. Return null if
* no equipment has the same name.
*/
public Equipment getNamedEquipment(String name)
{
for (Equipment equip : equipment)
{
if (equip.getName().equalsIgnoreCase(name))
{
return equip;
}
}
return null;
}
/**
* Calculates the subset of equipments which have a count above a certain amount.
*
* @param state Equipment with a count variable above the input amount should be aggregated and returned.
* @return An arraylist containing all equipments whose count is above the input variable "count".
*/
public ArrayList<Equipment> equipmentAboveCount(int count)
{
ArrayList<Equipment> subset = new ArrayList<Equipment>();
for (Equipment equip : equipment)
{
if (equip.getCount() > count)
{
subset.add(equip);
}
}
return subset;
}
/**
* Finds the most expensive Equipment (highest total price variable).
*
* @return A Equipment object that has the highest total price variable out of all Equipment recorded.
* If there are no equipment in the utility belt, return null.
*/
public Equipment findMostExpensiveEquipment()
{
// Set arbitrarily high:
double highestPrice = Double.NEGATIVE_INFINITY;
Equipment mostExpensive = null;
for (Equipment equip : equipment)
{
double price = equip.getTotalPrice();
if (price > highestPrice)
{
// Update what the highest price is and what equipment has that price:
highestPrice = price;
mostExpensive = equip;
}
}
return mostExpensive;
}
}
| mattWhitehead0250/lab4 | lab4/src/UtilityBelt.java | 1,558 | // Set up the writer and string to output:
| line_comment | en | false | 1,463 | 11 | 1,558 | 11 | 1,742 | 10 | 1,558 | 11 | 1,963 | 11 | false | false | false | false | false | true |
54326_6 | // shopping cart for specific fruit shop
// import java.util for ArrayList to store store items
import java.util.ArrayList;
// shoppingCart class made public
public class ShoppingCart {
// ArrayList called items to store items for the shopping cart
ArrayList<String> items;
// shopping cart() constructor where items is equal to new arraylist<string>()
public ShoppingCart(){
items = new ArrayList<String>();
}
// add()add method to array list items use the add function
public void add(String item) {
items.add(item);
}
// remove() add to array list items use the remove function
public void remove(String item)
{
items.remove(item);
}
// getTotalItems made public int returns size of array list when called
public int getTotalItems() {
return items.size();
}
// Boolen doesContain returns item name from array list items
public Boolean doesContain(String itemName) {
return items.contains(itemName);
}
// checkout method total is initialized as 0. for loop checks array list items for shop items such
// Apple,Orange and Pear.
//if value found , a double value is assigned, apples cost 1 euro, orange 60 cent and pear 40 cent.
// the total value is returned when called
public Double checkout() {
double total = 0;
for(String item: items){
if(item.equals("Apple")){
total += 1.0;
}else if(item.equals("Orange")){
total += 0.6;
}else if(item.equals("Pear")){
total += 0.4;
}
}
return total;
}
// offers method contains calls to getTotalItems and checkout methods in this class ShoppingCart
// the first if statement checks if the getTotalItems equals to 3 then the total value is subtracted from getTotalItems and 2.0(euro)
//the first if statement checks if the getTotalItems equals to 2 then the total value is subtracted from getTotalItems and 0.5(euro)
// total value is return when method is called
public double offers(){
this.getTotalItems();
this.checkout();
double total= 0;
//double dealA = 1.0; // not used (testing)
// double dealB = 0.6; // not used (testing)
if(getTotalItems()== 3){
//dealA -1.0;
total = getTotalItems()- 2.0; // 1 euro/pound off
}else if(getTotalItems()== 2){
//dealA -1.0;
total = getTotalItems()- 0.5; // 1 euro/pound off
}
return total;
}
//getTestApplication returns app working message when called in the application class in the main method
public String getTestApplication() {
return "App working!";
}
} | conorH22/ShoppingCart | ShoppingCart.java | 678 | // remove() add to array list items use the remove function | line_comment | en | false | 607 | 12 | 678 | 12 | 705 | 12 | 678 | 12 | 773 | 12 | false | false | false | false | false | true |
54885_3 | import java.util.Set;
import java.util.HashMap;
import java.util.HashSet;
/**
* Class Room - a room in an adventure game.
*
* This class is the main class of the "Game of Rings" application.
* "Game of Rings" is a very simple, text based adventure game. Users
* are after a great mission of saving the world!
*
* A "Room" represents one location in the scenery of the game. It is
* connected to other rooms via exits. For each existing exit, the room
* stores a reference to the neighboring room.
*
* @author Michael Kölling and David J. Barnes
* @author Berke Müftüoğlu
* @version 2020.11.21
*/
public class Room
{
private String description;
private HashMap<String, Room> exits; // stores exits of this room.
private String name;
private boolean dark;
/**
* Create a room described "description". Initially, it has
* no exits. "description" is something like "a kitchen" or
* "an open court yard".
* @param description The room's description.
*/
public Room(String name, String description, boolean dark)
{
this.description = description;
this.name = name;
this.dark = dark;
exits = new HashMap<>();
}
/**
* @return the name of the room
*/
public String getName(){
return name;
}
/**
* @return wheter the room is dark or not
*/
public boolean isDark(){
return dark;
}
/**
* Change the darkness of the room
*/
public void changeDark(){
dark = !dark;
}
/**
* Define an exit from this room.
* @param direction The direction of the exit.
* @param neighbor The room to which the exit leads.
*/
public void setExit(String direction, Room neighbor)
{
exits.put(direction, neighbor);
}
/**
* @return The short description of the room
* (the one that was defined in the constructor).
*/
public String getShortDescription()
{
return name + " " + description;
}
/**
* Return a description of the room in the form:
* You are in the kitchen.
* Exits: north west
* @return A long description of this room
*/
public String getLongDescription()
{
return "You are at " + name + " " + description + ".\n" + getExitString();
}
/**
* Return a string describing the room's exits, for example
* "Exits: north west".
* @return Details of the room's exits.
*/
private String getExitString()
{
String returnString = "Exits:";
Set<String> keys = exits.keySet();
for(String exit : keys) {
returnString += " " + exit;
}
return returnString;
}
/**
* Return the room that is reached if we go from this room in direction
* "direction". If there is no room in that direction, return null.
* @param direction The exit's direction.
* @return The room in the given direction.
*/
public Room getExit(String direction)
{
return exits.get(direction);
}
}
| berkemuftuoglu/terminal_game | Room.java | 776 | /**
* @return the name of the room
*/ | block_comment | en | false | 743 | 13 | 776 | 12 | 865 | 14 | 776 | 12 | 902 | 14 | false | false | false | false | false | true |
55136_10 | // Java program to implement
// traveling salesman problem
// using naive approach.
import java.util.*;
class GFG{
static int V = 4;
// implementation of traveling
// Salesman Problem
static int travllingSalesmanProblem(int graph[][],
int s)
{
// store all vertex apart
// from source vertex
ArrayList<Integer> vertex =
new ArrayList<Integer>();
for (int i = 0; i < V; i++)
if (i != s)
vertex.add(i);
// store minimum weight
// Hamiltonian Cycle.
int min_path = Integer.MAX_VALUE;
do
{
// store current Path weight(cost)
int current_pathweight = 0;
// compute current path weight
int k = s;
for (int i = 0;
i < vertex.size(); i++)
{
current_pathweight +=
graph[k][vertex.get(i)];
k = vertex.get(i);
}
current_pathweight += graph[k][s];
// update minimum
min_path = Math.min(min_path,
current_pathweight);
} while (findNextPermutation(vertex));
return min_path;
}
// Function to swap the data
// present in the left and right indices
public static ArrayList<Integer> swap(
ArrayList<Integer> data,
int left, int right)
{
// Swap the data
int temp = data.get(left);
data.set(left, data.get(right));
data.set(right, temp);
// Return the updated array
return data;
}
// Function to reverse the sub-array
// starting from left to the right
// both inclusive
public static ArrayList<Integer> reverse(
ArrayList<Integer> data,
int left, int right)
{
// Reverse the sub-array
while (left < right)
{
int temp = data.get(left);
data.set(left++,
data.get(right));
data.set(right--, temp);
}
// Return the updated array
return data;
}
// Function to find the next permutation
// of the given integer array
public static boolean findNextPermutation(
ArrayList<Integer> data)
{
// If the given dataset is empty
// or contains only one element
// next_permutation is not possible
if (data.size() <= 1)
return false;
int last = data.size() - 2;
// find the longest non-increasing
// suffix and find the pivot
while (last >= 0)
{
if (data.get(last) <
data.get(last + 1))
{
break;
}
last--;
}
// If there is no increasing pair
// there is no higher order permutation
if (last < 0)
return false;
int nextGreater = data.size() - 1;
// Find the rightmost successor
// to the pivot
for (int i = data.size() - 1;
i > last; i--) {
if (data.get(i) >
data.get(last))
{
nextGreater = i;
break;
}
}
// Swap the successor and
// the pivot
data = swap(data,
nextGreater, last);
// Reverse the suffix
data = reverse(data, last + 1,
data.size() - 1);
// Return true as the
// next_permutation is done
return true;
}
// Driver Code
public static void main(String args[])
{
// matrix representation of graph
int graph[][] = {{0, 10, 15, 20},
{10, 0, 35, 25},
{15, 35, 0, 30},
{20, 25, 30, 0}};
int s = 0;
System.out.println(
travllingSalesmanProblem(graph, s));
}
}
// This code is contributed by adityapande88
| Saqib928/Hacktoberfest2022 | Add Code Here/JAVA/tsp.java | 1,003 | // compute current path weight | line_comment | en | false | 794 | 5 | 1,003 | 5 | 972 | 5 | 1,003 | 5 | 1,084 | 5 | false | false | false | false | false | true |
56071_0 | import java.io.File;
import java.util.*;
public class Movie{
private String filePath;
private File movieFile;
private final MovieFormat format;
//A variable that determines whether the filepath exists.
//Private so client can't manually change it.
private boolean valid;
//Required information.
private String title;
private String language;
private String publishingStudio;
//Custom information. I used a Hashmap to store the information with key-value pairs.
//Client can modify it with methods provided (line 50).
private Map<String, String> customInformation = new HashMap<>();
//Constructor.
//Once created, the information about a movie will not be modifiable (except for custom info) as fields are private.
//The movie format is parsed from the path (lines 33-36)
/**
* @pre path != null
*/
public Movie(String path, String title, String language, String publishingStudio){
assert path != null && title != null && language != null && publishingStudio != null;
this.filePath = path;
this.movieFile = new File(path);
//Get the last three characters of the path
String extension = path.substring(path.length() - 3).toUpperCase(Locale.ROOT);
//Convert the String extension to ENUM type
//If the format is different from our enums, program will send an error.
this.format = MovieFormat.valueOf(extension);
assert format != null;
this.title = title;
this.language = language;
this.publishingStudio = publishingStudio;
if(this.movieFile.exists()){
this.valid = true;}
else{
this.valid = false;}
}
//Methods to add and remove custom information about the movie.
public void addCustomInfo(String title, String info){
this.customInformation.put(title, info);
}
public void removeCustomInfo(String title){
this.customInformation.remove(title);
}
//Client method to check if the filePath exists.
public boolean isValid(){
if(this.movieFile.exists()){
this.valid = true;}
else{
this.valid = false;}
return this.valid;
}
//Method to get the video format
public MovieFormat getFormat(){
return this.format;
}
//Method to get title (used in Watchlist.getMovies())
public String getTitle(){
return this.title;
}
//Method to get file path (used in Watchlist.getMovies())
//Returns a copy so the client can't modify the path
public String getPath(){
return this.filePath;
}
//Method to get publishing Studio (used in Watchlist.allStudios())
public String getStudio(){
return this.publishingStudio;
}
//Method to get language (used in Watchlist.allLanguages())
public String getLanguage(){
return this.language;
}
} | alexsaussier/COMP303_Assignment1 | Movie.java | 650 | //A variable that determines whether the filepath exists.
| line_comment | en | false | 603 | 11 | 650 | 11 | 756 | 10 | 650 | 11 | 804 | 12 | false | false | false | false | false | true |
56521_0 | import java.util.ArrayList;
public class Room{
private String roomType;
private int minOccAdult;
private int minOccChild;
private int maxOccAdult;
private int maxOccChild;
private double[] rates = new double[7];
private int maxNoRooms;
private ArrayList<Reservation> booked = new ArrayList<Reservation>();
/*
Creates a room object details of which are extracted from the csv elsewhere.
*/
public Room(String roomType, int minOccAdult, int minOccChild, int maxOccAdult, int maxOccChild, double[] rates, int maxNoRooms) {
this.roomType = roomType;
this.minOccAdult = minOccAdult;
this.minOccChild = minOccChild;
this.maxOccAdult = maxOccAdult;
this.maxOccChild = maxOccChild;
this.rates = rates;
this.maxNoRooms = maxNoRooms;
}
public ArrayList<Reservation> getBooked() {
return booked;
}
public String getRoomType() {
return roomType;
}
public int getMinOccAdult() {
return minOccAdult;
}
public int getMinOccChild() {
return minOccChild;
}
public int getMaxOccAdult() {
return maxOccAdult;
}
public int getMaxOccChild() {
return maxOccChild;
}
public double[] getRates() {
return rates;
}
public int getMaxNoRooms() {
return maxNoRooms;
}
} | ShaneWhelan/Hotel-Reservation-System | Room.java | 396 | /*
Creates a room object details of which are extracted from the csv elsewhere.
*/ | block_comment | en | false | 311 | 19 | 396 | 20 | 380 | 20 | 396 | 20 | 438 | 21 | false | false | false | false | false | true |
56742_0 | public class LRUCache {
class DLinkedNode {
int key;
int value;
DLinkedNode prev;
DLinkedNode next;
}
private void addNode(DLinkedNode node) {
/**
* Always add the new node right after head.
*/
node.prev = head;
node.next = head.next;
head.next.prev = node;
head.next = node;
}
private void removeNode(DLinkedNode node){
/**
* Remove an existing node from the linked list.
*/
DLinkedNode prev = node.prev;
DLinkedNode next = node.next;
prev.next = next;
next.prev = prev;
}
private void moveToHead(DLinkedNode node){
/**
* Move certain node in between to the head.
*/
removeNode(node);
addNode(node);
}
private DLinkedNode popTail() {
/**
* Pop the current tail.
*/
DLinkedNode res = tail.prev;
removeNode(res);
return res;
}
private Map<Integer, DLinkedNode> cache = new HashMap<>();
private int size;
private int capacity;
private DLinkedNode head, tail;
public LRUCache(int capacity) {
this.size = 0;
this.capacity = capacity;
head = new DLinkedNode();
// head.prev = null;
tail = new DLinkedNode();
// tail.next = null;
head.next = tail;
tail.prev = head;
}
public int get(int key) {
DLinkedNode node = cache.get(key);
if (node == null) return -1;
// move the accessed node to the head;
moveToHead(node);
return node.value;
}
public void put(int key, int value) {
DLinkedNode node = cache.get(key);
if(node == null) {
DLinkedNode newNode = new DLinkedNode();
newNode.key = key;
newNode.value = value;
cache.put(key, newNode);
addNode(newNode);
++size;
if(size > capacity) {
// pop the tail
DLinkedNode tail = popTail();
cache.remove(tail.key);
--size;
}
} else {
// update the value.
node.value = value;
moveToHead(node);
}
}
}
| liweilili110/Coding | 146LRUCacheBetter.java | 549 | /**
* Always add the new node right after head.
*/ | block_comment | en | false | 501 | 14 | 549 | 14 | 625 | 16 | 549 | 14 | 676 | 16 | false | false | false | false | false | true |
56806_3 | package game2048;
import ucb.gui2.TopLevel;
import ucb.gui2.LayoutSpec;
import java.util.Observable;
import java.util.Observer;
import java.util.concurrent.ArrayBlockingQueue;
import java.awt.event.KeyEvent;
/** The GUI controller for a 2048 board and buttons.
* @author P. N. Hilfinger
*/
class GUI extends TopLevel implements Observer {
/** Minimum size of board in pixels. */
private static final int MIN_SIZE = 500;
/** A new window with given TITLE providing a view of MODEL. */
GUI(String title, Model model) {
super(title, true);
addMenuButton("Game->New", this::newGame);
addMenuButton("Game->Quit", this::quit);
addLabel("", "Score", new LayoutSpec("y", 1));
_model = model;
_model.addObserver(this);
_widget = new BoardWidget(model.size());
add(_widget,
new LayoutSpec("y", 0,
"height", "REMAINDER",
"width", "REMAINDER"));
_widget.requestFocusInWindow();
_widget.setKeyHandler("keypress", this::keyPressed);
setPreferredFocus(_widget);
setScore(0, 0);
}
/** Response to "Quit" button click. */
public void quit(String dummy) {
_pendingKeys.offer("Quit");
_widget.requestFocusInWindow();
}
/** Response to "New Game" button click. */
public void newGame(String dummy) {
_pendingKeys.offer("New Game");
_widget.requestFocusInWindow();
}
/** Respond to the user pressing key E by queuing the key on our
* queue of pending keys.*/
public void keyPressed(String unused, KeyEvent e) {
_pendingKeys.offer(e.getKeyText(e.getKeyCode()));
}
/** Return the next pending event, waiting for it as necessary.
* Ordinary key presses are reported as the key codes of the
* character pressed. In addition, menu-button clicks result in
* the messages "Quit" or "New Game". */
String readKey() {
try {
return _pendingKeys.take();
} catch (InterruptedException excp) {
throw new Error("unexpected interrupt");
}
}
/** Set the current score being displayed to SCORE and the current
* maximum score to MAXSCORE. */
public void setScore(int score, int maxScore) {
setLabel("Score", String.format("Score: %6d / Max score: %6d",
score, maxScore));
}
/** The model notifies me that is has changed when its notifyObservers
* method is called, because my constructor registered me as an
* Observer of the model. */
@Override
public void update(Observable model, Object arg) {
_widget.update(_model);
setScore(_model.score(), _model.maxScore());
}
/** The board widget. */
private BoardWidget _widget;
/** The game model being viewed. */
private Model _model;
/** Queue of pending key presses. */
private ArrayBlockingQueue<String> _pendingKeys =
new ArrayBlockingQueue<>(5);
}
| hxt616/CS61B-Spring-2021 | proj0/game2048/GUI.java | 761 | /** Response to "Quit" button click. */ | block_comment | en | false | 695 | 10 | 761 | 10 | 851 | 10 | 761 | 10 | 924 | 11 | false | false | false | false | false | true |
58892_4 | // *** imports *** //
import java.awt.Color;
import java.util.Random;
import java.util.Timer;
import java.util.TimerTask;
/** Road.java
* An class representing all the roads on the map
* @author Katherine Liu and Rachel Liu
* @version 1.0 May 25, 2021
*/
public class Road extends Row {
/*
* CLASS VARIABLE
*/
private Random rand = new Random();
private int seconds;
private int vehicleType = rand.nextInt(3);
private int delay;
/**
* Road
* This constructor ensures each Road is created with the necessary attributes
* including the collection of vehicles on the Road
* @param x The top left x-coordinate of the road's row
* @param y The top left y-coordinate of the road's row
* @param direction The direction the vehicles on the road moves toward ("left" or "right")
*/
Road(int x, int y, String direction) {
super(x,y,new Color(73,80,87), direction);
placeCar();
}
/**
* placeCar
* This method ensures the next vehicle is placed after a certain amount of time
*/
public void placeCar() {
TimerTask task = new TimerTask() { // creating a task to place vehciles onto the screen
public void run() {
elements.add(nextVehicle());
}
};
//** generating the seconds and delay for each car *//
//small car
if (vehicleType == 0) {
seconds = rand.nextInt(2) + 2;
delay = rand.nextInt(3) + 1;
// normal car
} else if (vehicleType == 1) {
seconds = rand.nextInt(3) + 2;
delay = rand.nextInt(3) + 1;
//truck
} else if (vehicleType == 2) {
seconds = rand.nextInt(3) + 3;
delay = rand.nextInt(3) + 2;
}
Timer timer = new Timer();
timer.scheduleAtFixedRate(task, delay * 1000, seconds * 1000);
// actually running the task depending on the generated seconds and delay
}
/**
* nextVehicle
* This method calculates what vehicle should be placed next (small car, normal car or truck).
* @return The vehicle which will be drawn next
*/
public Vehicle nextVehicle() {
int xCoordinate = 0;
if (getDirection().equals("left")) {
xCoordinate = SCREEN_WIDTH;
}
//** creating cars based on generated number*//
//small car
if (vehicleType == 0) {
SmallCar smallCar = new SmallCar (xCoordinate, getY(), getDirection());
if (getDirection().equals("right")) {
smallCar.setX(-smallCar.getWidth());
}
return smallCar;
// normal car
} else if (vehicleType == 1) {
NormalCar normalCar = new NormalCar (xCoordinate, getY(), getDirection());
if (getDirection().equals("right")) {
normalCar.setX(-normalCar.getWidth());
}
return normalCar;
//truck
} else if (vehicleType == 2) {
Truck truck = new Truck(xCoordinate, getY(), getDirection());
if (getDirection().equals("right")) {
truck.setX(-truck.getWidth());
}
return truck;
}
return null;
}
} | kkatherineliu/roadbound401 | Road.java | 810 | /**
* placeCar
* This method ensures the next vehicle is placed after a certain amount of time
*/ | block_comment | en | false | 774 | 25 | 810 | 23 | 884 | 26 | 810 | 23 | 957 | 27 | false | false | false | false | false | true |
59178_60 | package application;
import javafx.animation.KeyFrame;
import javafx.animation.Timeline;
import javafx.application.Application;
import javafx.fxml.FXMLLoader;
import javafx.geometry.Point2D;
import javafx.scene.Parent;
import javafx.scene.Scene;
import javafx.scene.image.Image;
import javafx.scene.image.ImageView;
import javafx.scene.paint.Color;
import javafx.scene.shape.Rectangle;
import javafx.stage.Stage;
import javafx.util.Duration;
import java.util.ArrayList;
//TODO: create a junit testing file.
public class main extends Application {
private Stage stage;
@Override
public void start(Stage stage){
try {
Parent root = FXMLLoader.load(getClass().getResource("first_scrn.fxml"));
Scene first_scrn = new Scene(root);
//first_scrn.getStylesheets().add(getClass().getResource("application.css").toExternalForm());
String css = this.getClass().getResource("application.css").toExternalForm();
first_scrn.getStylesheets().add(css);
stage.setScene(first_scrn);
Image icon = new Image(getClass().getResourceAsStream("game_icon2.jpg"));
stage.getIcons().add(icon);
stage.setTitle("Stick Hero Game");
stage.show();
}catch(Exception e) {
e.printStackTrace();
}
}
public static void main(String[] args) {
launch(args);
}
class Animations {
private Stick stick;
//private Player player;
private Cherry cherry;
public Animations() {
stick = new Stick();
//player = new Player();
cherry = new Cherry(0, 0);
// // Set up mouse event handlers
// stick.setOnMousePressed(this::handleMousePressed);
// stick.setOnMouseReleased(this::handleMouseReleased);
}
// private void handleMousePressed(MouseEvent event) {
// if (event.getButton() == MouseButton.PRIMARY) {
// startStickGrowth(); // Start stretching the stick
// }
// }
// private void handleMouseReleased(MouseEvent event) {
// if (event.getButton() == MouseButton.PRIMARY) {
// stopStickGrowth(); // Stop stretching the stick
// }
// }
//
// private void startStickGrowth() {
// stick.startStretch(); // Correctly start the stick growth animation
// }
private void stopStickGrowth() {
//stick.stopStretch(); // Stop the stick growth animation
// Rotate the stick by 90 degrees when growth stops
stick.setRotate(stick.getRotate() + 90);
}
public Stick getStick() {
return stick;
}
// private void player_moving() {
// // Code to move the player using the player object
// player.moveCharacter();
// }
private void button_hovering() {
// Code for button hovering animation
}
private void cherry_hovering() {
// Code for cherry hovering using the cherry object
cherry.hover();
}
}
//animation of player:
class Plyr extends ImageView {
private boolean isCollided;
public Plyr(Image image) {
super(image);
}
// public void handleCollision() {
// if (isCollided) {
// // Assuming new coordinates for translation
// double newX = getLayoutX() + 50;
// double newY = getLayoutY() + 50;
//
// // Create a TranslateTransition for the player ImageView
// TranslateTransition translateTransition = new TranslateTransition(Duration.seconds(1), this);
//
// // Set the new coordinates as the destination for translation
// translateTransition.setToX(newX);
// translateTransition.setToY(newY);
//
// // Set up an event handler for when the animation finishes
// translateTransition.setOnFinished(event -> {
// // Code to execute after the animation finishes
// });
//
// // Play the translation animation
// translateTransition.play();
//
// // Reset the collision flag
// isCollided = false;
// }
// }
public void move(double dest){
// Update the player's position here
// You can modify this code to move the player in the desired way
double currentX = getX();
double newX = currentX;
while(newX<dest) {
newX = newX + 1; // deltaX is the amount to move in the x-direction
}
setX(newX);
};
public void changeSize(double width, double height) {
this.setFitWidth(width);
this.setFitHeight(height);
}
}
//animated stick :
class Stick extends Rectangle {
private static final double MAX_HEIGHT = 300.0;
private static final double GROWTH_STEP = 1.0;
private static final double ROTATION_DURATION = 500; // Milliseconds for rotation duration
private Timeline growthAnimation;
private Timeline rotationAnimation;
private boolean isGrowing = false; // Flag to manage the stick's growth state
public boolean isCollided = false;
public Stick() {
super(50, 340, 5, 10);
this.setFill(Color.BLACK);
growthAnimation = new Timeline(new KeyFrame(Duration.millis(20), e -> grow()));
growthAnimation.setCycleCount(Timeline.INDEFINITE);
rotationAnimation = new Timeline(new KeyFrame(Duration.millis(ROTATION_DURATION), e -> rotate()));
rotationAnimation.setCycleCount(1); // Only rotate once
this.setOnMousePressed(event -> handleMousePressed());
}
private void grow() {
if (this.getHeight() + GROWTH_STEP <= MAX_HEIGHT) {
this.setHeight(this.getHeight() + GROWTH_STEP);
this.setY(this.getY() - GROWTH_STEP);
} else {
stopStretch();
}
}
private void handleMousePressed() {
if (!isGrowing) {
startStretch();
} else {
stopStretch();
fall();
}
}
private void startStretch() {
isGrowing = true;
growthAnimation.play();
}
private void stopStretch() {
isGrowing = false;
growthAnimation.stop();
}
private void fall() {
rotationAnimation.setOnFinished(event -> rotate());
rotationAnimation.play();
rotationAnimation.setOnFinished(event -> {
isCollided = true; // Set flag to true after rotation completes
});
}
private void rotate() {
this.setRotate(90);
this.setTranslateX(this.getHeight()/2-2.5);
this.setTranslateY(this.getHeight()/2);
}
public double getCurrentHeight() {
return this.getHeight();
}
// Method to check if the stick has collided (completed its rotation)
public boolean hasCollided() {
return isCollided;
}
}
class Cherry {
private Point2D location;
public Cherry(double x, double y) {
location = new Point2D(x, y);
}
public Point2D getLocation() {
return location;
}
public void hover() {
}
}
class CherryManager {
private ArrayList<Cherry> cherries;
private int cherryCount;
public void addCherry(double x, double y) {
cherries.add(new Cherry(x, y));
}
public void collectCherry() {
cherryCount++;
}
public void useCherries(int amount) {
cherryCount -= amount;
}
public ArrayList<Cherry> getCherries() {
return cherries;
}
public int getCherryCount() {
return cherryCount;
}
}
}
| Saarthakkj/stickhero_game | main.java | 1,933 | // Flag to manage the stick's growth state
| line_comment | en | false | 1,601 | 10 | 1,933 | 10 | 2,074 | 11 | 1,933 | 10 | 2,319 | 11 | false | false | false | false | false | true |
59717_3 | /*
* Course: SE 2030 - 041
* Fall 22-23
* GTFS Project
* Created by: Christian Basso, Ian Czerkis, Matt Wehman, Patrick McDonald.
* Created on: 09/10/22
* Copyright 2022 Ian Czerkis, Matthew Wehman, Patrick McDonald, Christian Basso
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
/**
* This is the stop class and represents the places at which the buses stop
* @author czerkisi
* @version 1.0
* @created 05-Oct-2022 12:59:52 PM
*/
public class Stop {
private String stopDesc;
private String stopID;
private double stopLat;
private double stopLong;
private String stopName;
public String getStopDesc() {
return stopDesc;
}
public void setStopDesc(String stopDesc) {
this.stopDesc = stopDesc;
}
public String getStopID() {
return stopID;
}
public void setStopID(String stopID) {
this.stopID = stopID;
}
public double getStopLat() {
return stopLat;
}
public void setStopLat(int stopLat) {
this.stopLat = stopLat;
}
public double getStopLong() {
return stopLong;
}
public void setStopLong(int stopLong) {
this.stopLong = stopLong;
}
public String getStopName() {
return stopName;
}
public void setStopName(String stopName) {
this.stopName = stopName;
}
/**
* Creates an instance of the Stop Object
* @param stopID
* @param stopName
* @param stopDesc
* @param stopLat
* @param stopLong
*/
public Stop(String stopID, String stopName, String stopDesc, double stopLat, double stopLong) {
this.stopDesc = stopDesc;
this.stopID = stopID;
this.stopLat = stopLat;
this.stopLong = stopLong;
this.stopName = stopName;
}
/**
* Changes the Longitude and Latitude of a Stop
* This method has not been implemented yet
* @param longitude
* @param latitude
* @return boolean
*/
public boolean changeLocation(int longitude, int latitude) {
return false;
}
/**
* Takes in a new Stop object in place of the old Stop, this will update the certain
* attributes that need tobe updated
* This method has not been implemented yet
* @param newStop
* @return boolean
*/
public boolean update(Stop newStop) {
return false;
}
/**
* ensures all required fields are filled in
* @throws CSVReader.MissingRequiredFieldException if a required field is empty
*/
public void checkRequired() throws CSVReader.MissingRequiredFieldException {
if (stopID.isEmpty()){
throw new CSVReader.MissingRequiredFieldException("Missing a required field");
}
}
@Override
public String toString() {
return stopID + "," +
stopName + "," +
stopDesc + "," +
stopLat + "," +
stopLong;
}
} | cjbass02/milwaukee-google-transit-feed | Stop.java | 869 | /**
* Changes the Longitude and Latitude of a Stop
* This method has not been implemented yet
* @param longitude
* @param latitude
* @return boolean
*/ | block_comment | en | false | 844 | 42 | 869 | 39 | 1,009 | 48 | 869 | 39 | 1,073 | 52 | false | false | false | false | false | true |
59908_11 | import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
public class Solution {
public List<List<Integer>> fourSum(int[] nums, int target) {
Arrays.sort(nums); // Sort the input array in ascending order.
List<List<Integer>> result = new ArrayList<>();
List<Integer> temp = new ArrayList<>();
helper(nums, (long) target, 0, result, temp, 4); // Use long data type for target.
return result; // Return the result list containing unique quadruplets.
}
private void helper(int[] nums, long target, int start, List<List<Integer>> result, List<Integer> temp, int numNeed) {
if (numNeed != 2) {
for (int i = start; i < nums.length - numNeed + 1; i++) {
if (i > start && nums[i] == nums[i - 1]) {
continue; // Skip duplicates to avoid duplicate combinations.
}
temp.add(nums[i]); // Add the current number to the combination.
helper(nums, target - nums[i], i + 1, result, temp, numNeed - 1); // Recursively find the next number(s).
temp.remove(temp.size() - 1); // Remove the last number to backtrack.
}
return;
}
// If we need exactly 2 numbers, perform a two-pointer approach.
int l = start;
int r = nums.length - 1;
while (l < r) {
long total = (long) nums[l] + nums[r];
if (total < target) {
l++;
} else if (total > target) {
r--;
} else {
temp.add(nums[l]); // Add the left number to the combination.
temp.add(nums[r]); // Add the right number to the combination.
result.add(new ArrayList<>(temp)); // Store the valid quadruplet in the result list.
temp.remove(temp.size() - 1); // Remove the right number to backtrack.
temp.remove(temp.size() - 1); // Remove the left number to backtrack.
l++;
r--;
while (l < r && nums[l] == nums[l - 1]) {
l++; // Skip duplicates on the left.
}
}
}
}
}
| viveksharma62/leetcode_problem_solves | 18. 4Sum | 549 | // Remove the right number to backtrack. | line_comment | en | false | 489 | 8 | 549 | 9 | 588 | 9 | 549 | 9 | 627 | 9 | false | false | false | false | false | true |
60242_0 | package burp;
class Cookie {
public String name;
public String sameSite;
public boolean issue = false;
public Cookie(String setCookie) {
String name;
name = setCookie.substring(0, setCookie.indexOf("="));
this.name = name;
// Iterate on cookie flag delimiters
for (String flag : setCookie.split(";")) {
flag = flag.replaceAll("\\s+", "");
flag = flag.toLowerCase();
// only parse flags with `key=val' notation
int equalDelimiter = flag.indexOf("=");
if (equalDelimiter != -1) {
String key_name = flag.substring(0, equalDelimiter);
String key_val = flag.substring(equalDelimiter + 1, flag.length());
if (key_name.equals("samesite")) {
switch(key_val) {
case "lax":
case "strict":
break;
case "none":
this.sameSite = "none";
this.issue = true;
}
return;
}
}
}
this.sameSite = "missing";
this.issue = true;
}
}
| ldionmarcil/burp-samesite-reporter | Cookie.java | 258 | // Iterate on cookie flag delimiters | line_comment | en | false | 237 | 7 | 258 | 7 | 293 | 7 | 258 | 7 | 327 | 9 | false | false | false | false | false | true |
60277_7 | import java.sql.SQLException;
/**
* Models Loan in a library
*
* @author konulv
*
*/
/*
*/
public class Loan {
private static int nextLoanID;
private String loanID = ("L" + nextLoanID);
private String copyID;
private Date issueDate;
private String username;
private Date returnDate;
private boolean isReturned;
/**
* creates a new loan
*
* @param copyID of a copy to be loaned
* @param username of a user who is getting the loan
* @throws SQLException if connection to database fails
*/
public Loan(String copyID, String username) throws SQLException {
DatabaseRequest db = new DatabaseRequest();
this.copyID = copyID;
this.issueDate = new Date();
this.username = username;
this.isReturned = false;
this.returnDate = issueDate;
this.returnDate.forwardDate(db.getCopy(copyID).getLoanTime());
nextLoanID++;
}
/**
* Used by databaseRequest for getting a loan from database
*
* @param loanID the loan ID
* @param issueDate the issue date
* @param username the username
* @param copyID the copy ID
* @param returnDate the return date
* @param isReturned the is returned
*/
public Loan(String loanID, Date issueDate, String username, String copyID,
Date returnDate, boolean isReturned) {
this.loanID = loanID;
this.issueDate = issueDate;
this.username = username;
this.copyID = copyID;
this.returnDate = returnDate;
this.isReturned = isReturned;
}
/**
* Gets the loan ID.
*
* @return loan ID
*/
public String getLoanID() {
return loanID;
}
/**
* Checks if loan is returned.
*
* @return true, if returned
*/
public boolean isReturned() {
return isReturned;
}
/**
* Return resource.
*/
public void returnResource() {
isReturned = true;
}
/**
* Sets the loan ID.
*
* @param loanID the new loan ID
*/
public void setLoanID(String loanID) {
this.loanID = loanID;
}
/**
* Gets the copy ID.
*
* @return the copy ID
*/
public String getCopyID() {
return copyID;
}
/**
* Sets the copy ID.
*
* @param copyID the new copy ID
*/
public void setCopyID(String copyID) {
this.copyID = copyID;
}
/**
* Gets the issue date.
*
* @return issue date
*/
public Date getIssueDate() {
return issueDate;
}
/**
* Sets the issue date.
*
* @param issueDate
*/
public void setIssueDate(Date issueDate) {
this.issueDate = issueDate;
}
/**
* Gets the username.
*
* @return username
*/
public String getUsername() {
return username;
}
/**
* Sets the username.
*
* @param username the new username
*/
public void setUsername(String username) {
this.username = username;
}
/**
* Gets the return date.
*
* @return the return date
*/
public Date getReturnDate() {
return returnDate;
}
/**
* Sets the return date.
*
* @param returnDate the new return date
*/
public void setReturnDate(Date returnDate) {
this.returnDate = returnDate;
}
/**
* Sets the loan status.
*
* @param isOnLoan the new loan status
* @throws SQLException if cannot connect to Database
*/
public void setLoanStatus(boolean isOnLoan) throws SQLException {
Copy c = new DatabaseRequest().getCopy(copyID);
c.setOnLoan(isOnLoan);
new DatabaseRequest().editCopy(c);
}
/**
* Sets the reservation status.
*
* @param isReserved the is reserved
* @param newUsername the new username
* @throws SQLException if cannot connect to Database
*/
public void setReservationStatus(boolean isReserved, String newUsername) throws SQLException {
Copy c = new DatabaseRequest().getCopy(copyID);
c.setReserved(isReserved);
c.setReservingUser(newUsername);
new DatabaseRequest().editCopy(c);
}
}
| mhmatthall/tawe-lib | Loan.java | 1,120 | /**
* Sets the loan ID.
*
* @param loanID the new loan ID
*/ | block_comment | en | false | 982 | 23 | 1,120 | 22 | 1,184 | 26 | 1,120 | 22 | 1,306 | 27 | false | false | false | false | false | true |
60710_1 | /**
* CIS 120 Game HW
* (c) University of Pennsylvania
* @version 2.0, Mar 2013
*/
import java.awt.*;
/**
* A basic game object displayed as a black square, starting in the upper left
* corner of the game court.
*
*/
public class Square extends GameObj {
public static final int SIZE = 20;
public static final int INIT_X = 0;
public static final int INIT_Y = 0;
public static final int INIT_VEL_X = 0;
public static final int INIT_VEL_Y = 0;
/**
* Note that, because we don't need to do anything special when constructing
* a Square, we simply use the superclass constructor called with the
* correct parameters
*/
public Square(int courtWidth, int courtHeight) {
super(INIT_VEL_X, INIT_VEL_Y, INIT_X, INIT_Y, SIZE, SIZE, courtWidth,
courtHeight);
}
@Override
public void draw(Graphics g) {
g.setColor(Color.BLACK);
g.fillRect(pos_x, pos_y, width, height);
}
}
| jbecke/Java-Chess | Square.java | 297 | /**
* A basic game object displayed as a black square, starting in the upper left
* corner of the game court.
*
*/ | block_comment | en | false | 244 | 28 | 297 | 30 | 295 | 31 | 297 | 30 | 326 | 31 | false | false | false | false | false | true |
60746_1 | /*
Write a program DayOfWeek.java that takes a date as input and prints the day of the week that date falls on.
Your program should take three command-line arguments: m (month), d (day), and y (year). For m use 1 for January, 2 for February, and so forth.
Use the following formulas, for the Gregorian calendar (where / denotes integer division):
y0 = y - (14 - m) / 12
x = y0 + y0 / 4 - y0 / 100 + y0 / 400
m0 = m + 12 ((14 - m) / 12) - 2
d0 = (d + x + 31m0 / 12) mod 7
The value d0=0 for Sunday, d0=1 for Monday, 2 for Tuesday, and so forth. For example, on which day of the week did February 14, 2000 fall?
y0 = 2000 - 1 = 1999
x = 1999 + 1999/4 - 1999/100 + 1999/400 = 2483
m0 = 2 + 12*1 - 2 = 12
d0 = (13 + 2483 + (31*12) / 12) mod 7 = 2528 mod 7 = 1 (Monday)
*/
public class DayOfWeek
{
public static void main(String[] args)
{
// Taking month, day and year as an input
int m = Integer.parseInt(args[0]);
int d = Integer.parseInt(args[1]);
int y = Integer.parseInt(args[2]);
String day = "";
// Calculation
int y0 = y - (14 - m) / 12;
int x = y0 + y0 / 4 - y0 / 100 + y0 / 400;
int m0 = m + 12 * ((14 - m) / 12) - 2;
int d1 = (d + x + (31 * m0) / 12);
int d0 = d1 % 7;
// Checking day of the week
if (d0 == 1) day = "Monday";
else if (d0 == 2) day = "Tuesday";
else if (d0 == 3) day = "Wednesday";
else if (d0 == 4) day = "Thursday";
else if (d0 == 5) day = "Friday";
else if (d0 == 6) day = "Saturday";
else if (d0 == 7) day = "Sunday";
// Displaying
System.out.println(day);
}
}
| Zohaib58/Solutions-to-JAVA-Projects-of-Intro-to-CS-by-Princeton-University | DayOfWeek.java | 682 | // Taking month, day and year as an input | line_comment | en | false | 649 | 10 | 682 | 11 | 707 | 10 | 682 | 11 | 738 | 11 | false | false | false | false | false | true |
63234_6 | public class Rogue extends Card {
/* Default Constructor */
public Rogue(){
}
// DEVELOPED BY: BEAUTY
/* Initialize the the count of special, attack, defense and heal for Rogue
* @param specialCount - number of special cards
* @param attackCount - number of damage cards
* @param defenseCount - number of defense cards and sheild
* @param healCount - number of heal cards
*/
public Rogue(int specialCount, int attackCount, int defenseCount, int healCount){
super( specialCount, attackCount, defenseCount, healCount);
}
// DEVELOPED BY: BEAUTY
/* Attacks the selected player depending on the special count
* @param special - numnber of special
* @param p - player to attack
* @param players - all players present
*/
public void MightyPower(int special,Player p, Player[] players){
// apply this power only when the special is not zero
if(special != 0 ){
// attack the player depending on how many specials it has
super.Attack(GetSpecialCount(), p);
}
}
} | xieAmara/Dungeon-Mayhem | Rogue.java | 277 | // attack the player depending on how many specials it has | line_comment | en | false | 263 | 12 | 277 | 13 | 280 | 12 | 277 | 13 | 308 | 14 | false | false | false | false | false | true |
64074_4 | import java.util.Scanner;
//import Pet.java;
public class Dog {
Scanner scnr = new Scanner(System.in);
Dog(){
String name = scnr.nextLine();
setDogWeight();
setDogSpaceNumber();
setGrooming();
}
public static void main(String[] args) {
/*init variables for dog*/
int dogSpaceNumber = 0;//get space number
double dogWeight = 0;//get dog weight
boolean grooming = false;//set deafualt to false unless otherwise stated
}
public int getDogSpaceNumber() {
return Pet.dogSpaceNumber;
}
private void setDogSpaceNumber() {
Pet.dogSpaceNumber = scnr.nextInt();
}
public double getDogWeight() {
return Pet.dogWeight;
}
private void setDogWeight() {
this.dogWeight = scnr.nextDouble();
}
public boolean getGrooming() {
return this.grooming;
}
private void setGrooming() {
this.grooming = scnr.nextBoolean();
}
} | lavaya-s/IT-145 | Dog.java | 280 | //set deafualt to false unless otherwise stated | line_comment | en | false | 239 | 10 | 280 | 11 | 271 | 10 | 280 | 11 | 326 | 11 | false | false | false | false | false | true |
64577_0 | import java.util.Arrays;
import java.util.Collections;
import java.util.Scanner;
import java.io.FileNotFoundException; // Import this class to handle errors
import java.io.File;
class MF_k {
static int mostKFit(Integer item[], int n, int cap) {
int numberOfBins = 0;
int[] resCap = new int[n];
resCap[0] = cap;
n -= 1;
for (int i = 0; i < n; i++) {
int j;
for (j = 0; j < numberOfBins; j++) {
int initialBacktrack = 0;
if (item[n] == 0){
while (item[n - initialBacktrack] == 0) {
initialBacktrack++;
if (initialBacktrack == n) break;
}
}
if (resCap[j] >= item[n - initialBacktrack]){
// this holds: highest feasible value found, k value, l value, number of elements (if single element or pair)
int []replacer = {0, 0, 0, 0};
for (int k = n - initialBacktrack; k > 0; k--){
int pair = item[k];
if (pair > replacer[0] && resCap[j] >= pair) {
replacer[0] = pair;
replacer[1] = k;
replacer[3] = 1;
}
for (int l = n - initialBacktrack; l > 0; l--) {
pair = item[k] + item[l];
if (pair > replacer[0] && resCap[j] >= pair && (item[k] != 0 && item[l] != 0) && k != l){
replacer[0] = pair;
replacer[1] = k;
replacer[2] = l;
replacer[3] = 2;
}
}
}
if (replacer[0] != 0){
if (replacer[3] == 1){
resCap[j] -= replacer[0];
item[replacer[1]] = 0;
}
else{
resCap[j] -= replacer[0];
item[replacer[1]] = 0;
item[replacer[2]] = 0;
}
}
}
}
if (j == numberOfBins && item[i] != 0) {
resCap[numberOfBins] = cap - item[i];
item[i] = 0;
numberOfBins++;
}
}
return numberOfBins;
}
static int mostKFitDecreasing(Integer item[], int n, int cap) {
Arrays.sort(item, Collections.reverseOrder());
return mostKFit(item, n, cap);
}
public static void main(String[] args) {
try {
File binText = new File("Testing-Data/binpack4.txt");
try (Scanner textReader = new Scanner(binText)) {
int problems = Integer.parseInt(textReader.nextLine());
for (int i = 0; i < problems; i++) {
System.out.print("Problem:" + textReader.nextLine() + "\n");
String data = textReader.nextLine().trim();
int cap = Integer.parseInt(data.substring(0, 3));
int n = Integer.parseInt(data.substring(4, 8));
Integer[] item = new Integer[n];
for (int j = 0; j < n; j++) {
data = textReader.nextLine();
item[j] = Integer.parseInt(data);
}
System.out.print("Number of bins required in Most K Fit Decreasing: " + mostKFitDecreasing(item, n, cap) + "\n");
}
} catch (NumberFormatException e) {
e.printStackTrace();
}
} catch (FileNotFoundException e) {
System.out.print("An error occured.\n");
e.printStackTrace();
}
}
} | rayaanrizwan1234/Bin-Packing-Algorithms | MF_k.java | 924 | // Import this class to handle errors | line_comment | en | false | 854 | 7 | 924 | 7 | 1,011 | 7 | 924 | 7 | 1,107 | 7 | false | false | false | false | false | true |
64795_0 | public class hash {
public static void main(String[] args) {
// Create a HashMap object called capitalCities
HashMap<String, String> capitalCities = new HashMap<String, String>();
// Add keys and values (Country, City)
capitalCities.put("England", "London");
capitalCities.put("Germany", "Berlin");
capitalCities.put("Norway", "Oslo");
capitalCities.put("USA", "Washington DC");
System.out.println(capitalCities);
}
}
| anjanisinghal21/HacktoberfestChamps | hash.java | 126 | // Create a HashMap object called capitalCities | line_comment | en | false | 104 | 8 | 126 | 9 | 122 | 8 | 126 | 9 | 140 | 9 | false | false | false | false | false | true |
65999_7 | package org.fleen.maximilian;
import java.util.ArrayList;
import java.util.List;
import org.fleen.geom_2D.DYard;
/*
* A polygonal shape pierced by 1..n polygonal shapes (holes)
* It can come in several varieties. Specifics are denoted by tag.
* ie :
* "bagel" : a polygon pierced by 1 similar polygon creating a bagel-like shape with a uniform wraparound shape
* "sponge" " a polygon pierced in such a way, by 1 or more polygons, as to create a pretty irregular space
*
*/
public class MYard extends MShape{
private static final long serialVersionUID=-726090849488448340L;
/*
* ################################
* CONSTRUCTORS
* ################################
*/
/*
* the first polygon is the outer edge, the rest are holes
* There is only ever at most just 1 yard in a jig-generated geometry
* system, so we assign the chorus index automatically.
* We use our reserved chorus index for yards
*/
public MYard(List<MPolygon> mpolygons,int chorusindex,List<String> tags){
super(MYARDCHORUSINDEX,tags);
//create a new list to decouple param, for safety
this.mpolygons=new ArrayList<MPolygon>(mpolygons);}
public MYard(MPolygon outer,List<MPolygon> inner,int chorusindex,List<String> tags){
super(MYARDCHORUSINDEX,tags);
this.mpolygons=new ArrayList<MPolygon>(inner.size()+1);
this.mpolygons.add(outer);
this.mpolygons.addAll(inner);}
/*
* ################################
* GEOMETRY
* ################################
*/
public List<MPolygon> mpolygons;
public DYard getDYard(){
DYard y=new DYard(mpolygons.size());
for(MPolygon p:mpolygons)
y.add(p.dpolygon);
return y;}
/*
* ++++++++++++++++++++++++++++++++
* DETAIL SIZE
* smallest distance between component polygons
* ++++++++++++++++++++++++++++++++
*/
Double detailsize=null;
public double getDetailSize(){
if(detailsize==null)initDetailSize();
return detailsize;}
private void initDetailSize(){
double smallest=Double.MAX_VALUE,test;
for(MPolygon p0:mpolygons){
for(MPolygon p1:mpolygons){
if(p0!=p1){
test=p0.getDistance(p1);
if(test<smallest)
smallest=test;}}}
detailsize=smallest;}
/*
* ++++++++++++++++++++++++++++++++
* DISTORTION LEVEL
* the distortion level of this yard's most distorted component polygon
* ++++++++++++++++++++++++++++++++
*/
Double distortionlevel=null;
public double getDistortionLevel(){
if(distortionlevel==null)
initDistortionLevel();
return distortionlevel;}
private void initDistortionLevel(){
double largest=Double.MIN_VALUE,test;
for(MPolygon p:mpolygons){
test=p.getDistortionLevel();
if(test>largest)
largest=test;}
distortionlevel=largest;}
/*
* ################################
* CHORUS INDEX
* ################################
*/
public static final int MYARDCHORUSINDEX=Integer.MAX_VALUE;
}
| johnalexandergreene/Maximilian | MYard.java | 840 | /*
* ################################
* CHORUS INDEX
* ################################
*/ | block_comment | en | false | 754 | 18 | 841 | 15 | 908 | 21 | 840 | 15 | 1,060 | 28 | false | false | false | false | false | true |
66878_0 |
public class Model {
private double learningRate;
private double dropoutRate;
private int iterationCount;
private boolean verbose;
private int numLabels;
public Matrix W;
public Matrix B;
/**
* Constructor for neural network-based predictive model class.
*
* @param learningRate Step size at each iteration.
* @param iterationCount Number of epochs for training.
* @param verbose For logging to stdout.
*/
public Model(double learningRate, double dropoutRate, int iterationCount, boolean verbose) {
this.learningRate = learningRate;
this.dropoutRate = dropoutRate;
this.iterationCount = iterationCount;
this.verbose = verbose;
}
/**
* Fits model to training data.
*
* @param trainX Training features matrix.
* @param trainY Training labels matrix.
*/
public void fit(Matrix trainX, Matrix trainY) throws Exception {
Matrix[] results =
Optimizers.parallel(trainX, trainY, this.learningRate, this.dropoutRate, this.iterationCount, this.verbose);
this.W = results[0];
this.B = results[1];
this.numLabels = trainY.unique();
}
/**
* Predicts class probabilities of test data.
*
* @param testX Test features matrix.
* @return Matrix Class probabilities.
*/
public Matrix probabilities(Matrix testX) {
int numRows = testX.shape()[0];
int numColumns = testX.shape()[1];
Matrix values = new Matrix(numRows, this.numLabels);
for (int i = 0; i < numRows; i++) {
Matrix rowData = testX.row(i).transpose();
Matrix result = this.W.times(rowData).plus(this.B);
result = result.relu().softmax();
for (int j = 0; j < this.numLabels; j++) {
values.entries[i][j] = result.entries[j][0];
}
}
return values;
}
/**
* Predicts class labels of test data.
*
* @param testX Test features matrix.
* @return Matrix Class labels.
*/
public Matrix predict(Matrix testX) {
int numRows = testX.shape()[0];
int numColumns = testX.shape()[1];
Matrix predictionY = new Matrix(numRows, 1);
Matrix values = probabilities(testX);
for (int i = 0; i < numRows; i++) {
Matrix rowData = values.row(i).transpose();
predictionY.entries[i][0] = (double) rowData.argmax()[0];
}
return predictionY;
}
}
| savarin/deep-matrix-java | Model.java | 613 | /**
* Constructor for neural network-based predictive model class.
*
* @param learningRate Step size at each iteration.
* @param iterationCount Number of epochs for training.
* @param verbose For logging to stdout.
*/ | block_comment | en | false | 560 | 50 | 613 | 52 | 679 | 57 | 613 | 52 | 729 | 60 | false | false | false | false | false | true |
67151_3 | import java.util.Comparator;
import java.util.Objects;
/**
* Details of a single delivery.
* If the inTheWarehouse flag is set then the items have already been
* stored in the warehouse. Otherwise, they are awaiting transfer.
*/
public class Delivery extends Consignment implements Comparable<Delivery>
{
private final int deliveryNumber;
/**
* @param deliveryNumber The delivery number.
* @param dateDelivered The date of the delivery.
* @param itemInventory The items delivered.
* @param inTheWarehouse Whether the delivery has been put in the warehouse.
*/
public Delivery(int deliveryNumber, Date dateDelivered,
ItemInventory itemInventory, boolean inTheWarehouse)
{
super(dateDelivered, itemInventory, inTheWarehouse);
this.deliveryNumber = deliveryNumber;
}
@Override
public String toString()
{
return String.format("Delivery: %d %s %s",
deliveryNumber,
isFulfilled() ? "in the warehouse" : "to be unloaded",
super.toString());
}
@Override
public int compareTo(Delivery that)
{
return Objects.compare(this, that,
Comparator.comparing(Delivery::deliveryNumber));
}
/**
* Get the delivery number.
* @return the delivery number.
*/
public int deliveryNumber()
{
return deliveryNumber;
}
/**
* Check whether the items in the delivery have been put
* into the warehouse.
* @return true if the items are in the warehouse.
*/
public boolean isInTheWarehouse()
{
return isFulfilled();
}
/**
* Indicate that the delivery is now in the warehouse.
*/
public void setInTheWarehouse()
{
setFulfilled();
}
} | Pythonwithsean/Java-Assignment | src/Delivery.java | 401 | /**
* Check whether the items in the delivery have been put
* into the warehouse.
* @return true if the items are in the warehouse.
*/ | block_comment | en | false | 378 | 35 | 401 | 34 | 441 | 38 | 401 | 34 | 508 | 42 | false | false | false | false | false | true |
67625_2 | import java.util.HashMap;
import java.util.Map;
public class Stories {
private static Map<Integer, Integer> memo = new HashMap<>();
public static int numberOfArrangements(int numberOfStories) {
if (numberOfStories <= 0) {
return 1; // Base case: There's only one way to arrange zero stories.
} else if (numberOfStories == 1) {
return 1; // Base case: There's only one way to arrange one story.
} else {
// Check if the result is already memoized
if (memo.containsKey(numberOfStories)) {
return memo.get(numberOfStories);
} else {
// Calculate the number of arrangements for (n-1) and (n-2) stories
int result = numberOfArrangements(numberOfStories - 1) + numberOfArrangements(numberOfStories - 2);
// Memoize the result
memo.put(numberOfStories, result);
return result;
}
}
}
public static void main(String[] args) {
System.out.println(numberOfArrangements(50)); // Example with a large number of stories
}
}
| muza-k/Challenges | java/Stories.java | 265 | // Check if the result is already memoized | line_comment | en | false | 246 | 9 | 265 | 8 | 273 | 8 | 265 | 8 | 317 | 10 | false | false | false | false | false | true |
69204_2 | /**
* File: P2GUI.java
* Author: Deepak Galami
* Date: 04 Feb 2017
* Purpose: Write a program that implemants an ATM machine. The Interafce of the
* program should be a java Swing GUI and should be hand coded. The first class P2GUI
* should define GUI and must cotain Account objects, one for checking and another for
* saving Account. The program should perform Withdraw, Deposit, Transfer to and balance
* of each account. It also have InsufficientFunds class which is user defined checked
* exception.
*
* ***/
//import java class for GUI and event handling
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.*;
public class P2GUI extends JFrame implements ActionListener{ //inheriting JFrame and implementing ActionListener(multiple inheritance)
//default witdth and height of frame
static final int WIDTH = 500, HEIGHT = 250;
//create jbutton
private JButton withdrawButton = new JButton("Withdraw");
private JButton depositButton = new JButton("Deposit");
private JButton transferButton = new JButton("Transfer To");
private JButton balanceButton = new JButton("Balance");
private JRadioButton checkingRadio = new JRadioButton("Checking");
private JRadioButton savingRadio = new JRadioButton("Savings");
private JTextField textField = new JTextField("",25);
//create checking and saving account of Account type
Account checking = new Account();
Account saving = new Account();
//default constructor
P2GUI(){
super("ATM Machine");
setFrame(WIDTH, HEIGHT);
}
public void setFrame(int width, int height){
//add properties to frame
setSize(width, height);
setLocationRelativeTo(null);
setPreferredSize(new Dimension(491,252));
this.setResizable(false);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
//craete panel and add components
JPanel mainPanel = new JPanel();
mainPanel.setLayout(new FlowLayout()); //set layout manager
getContentPane().add(mainPanel);
withdrawButton.setPreferredSize(new Dimension(150,50));
depositButton.setPreferredSize(new Dimension(150,50));
mainPanel.add(withdrawButton);
mainPanel.add(depositButton);
JPanel secondPanel = new JPanel(new FlowLayout());
mainPanel.add(secondPanel);
transferButton.setPreferredSize(new Dimension(150,50));
balanceButton.setPreferredSize(new Dimension(150,50));
secondPanel.add(transferButton);
secondPanel.add(balanceButton);
ButtonGroup radioGroup = new ButtonGroup(); //grouping radio button
radioGroup.add(checkingRadio);
radioGroup.add(savingRadio);
JPanel radioPanel = new JPanel(new GridLayout(1,1, 90, 5)); //panel for radio buton with gridlayout
mainPanel.add(radioPanel);
checkingRadio.setSelected(true);
radioPanel.add(checkingRadio);
radioPanel.add(savingRadio);
JPanel textPanel = new JPanel(new FlowLayout());
mainPanel.add(textPanel);
textField.setHorizontalAlignment(JTextField.CENTER);
textField.setPreferredSize(new Dimension(150,30));
textPanel.add(textField);
//add action lister of this class
withdrawButton.addActionListener(this);
depositButton.addActionListener(this);
balanceButton.addActionListener(this);
transferButton.addActionListener(this);
}
//catch the action event in this class and perform the task.
public void actionPerformed(ActionEvent e){
Object COMPONENT = e.getSource();
//perform withdraw balance when withdraw button clicked.
//throw exception if insufficient fund
//throw exception of invalid input in text box.
if(COMPONENT == withdrawButton){
try{
String value = textField.getText();
//withdraw from checking account
if(isPositiveNumber(value) && checkingRadio.isSelected()){
int dialogResult = JOptionPane.showConfirmDialog(null, "Confirmed Withdraw Amount" ,"WITHDRAW", JOptionPane.OK_CANCEL_OPTION ,JOptionPane.INFORMATION_MESSAGE);
if(dialogResult == JOptionPane.OK_OPTION){ //perform only when ok button is clicked
checking.serviceCharge(value);
checking.withdrawProcess(value);
JOptionPane.showMessageDialog(null, "Withdraw Successful from Checking Account","WITHDRAW", JOptionPane.INFORMATION_MESSAGE);
}
textField.setText(null);
//withdraw from saving account
} else if(isPositiveNumber(value) && savingRadio.isSelected()){
int dialogResult = JOptionPane.showConfirmDialog(null, "Confirmed Withdraw Amount" ,"WITHDRAW", JOptionPane.OK_CANCEL_OPTION ,JOptionPane.INFORMATION_MESSAGE);
if(dialogResult == JOptionPane.OK_OPTION){ //perform only when ok button is clicked
saving.serviceCharge(value);
saving.withdrawProcess(value);
JOptionPane.showMessageDialog(null, "Withdraw Successful from Saving Account","WITHDRAW", JOptionPane.INFORMATION_MESSAGE);
}
textField.setText(null);
} else {
throw new IllegalArgumentException(); //throw exception if invalid input.
}
//catch exceptions
} catch(InsufficientFunds x){
JOptionPane.showMessageDialog(null, "Sorry your balance is low", "INSUFFICIENT FUNDS", JOptionPane.ERROR_MESSAGE);
textField.setText(null);
} catch(IllegalArgumentException x){
JOptionPane.showMessageDialog(null, "Invalid Input! Try Again", "ERROR", JOptionPane.ERROR_MESSAGE);
textField.setText(null);
}
}
//perform deposit amount in selected account when deposit button clicked
if(COMPONENT == depositButton){
String value = textField.getText();
//diposit in checking account
if(isPositiveNumber(value) && checkingRadio.isSelected()){
int okResult = JOptionPane.showConfirmDialog(null, "Confirmed Deposit" ,"CHECKING ACCOUNT DEPOSIT",JOptionPane.OK_CANCEL_OPTION, JOptionPane.INFORMATION_MESSAGE);
if(okResult == 0){ //only if ok button is clicked then perform deposit
checking.depositProcess(value);
JOptionPane.showMessageDialog(null, "Balance Deposited Successfully", "BALANCE DEPOSIT",JOptionPane.INFORMATION_MESSAGE);
}
textField.setText(null);
}
//deposit in saving account
else if(isPositiveNumber(value) && savingRadio.isSelected()){
int okResult = JOptionPane.showConfirmDialog(null, "Confirmed Deposit" ,"SAVING ACCOUNT DEPOSIT",JOptionPane.OK_CANCEL_OPTION, JOptionPane.INFORMATION_MESSAGE);
if(okResult == 0){ //only if ok button is clicked then perform deposit
saving.depositProcess(value);
JOptionPane.showMessageDialog(null, "Balance Deposited Successfully", "BALANCE DEPOSIT",JOptionPane.INFORMATION_MESSAGE);
}
textField.setText(null);
} else {
JOptionPane.showMessageDialog(null, "Invalid Input! Try Again", "ERROR", JOptionPane.ERROR_MESSAGE);
textField.setText(null);
}
}
//perform balance transfer when transfer button is clicked
//also check if sufficient fund to transfer else throw catch exception
if(COMPONENT == transferButton){
try {
String value = textField.getText();
//for amount transfer from saving to checking account
if(isPositiveNumber(value) && checkingRadio.isSelected()){
int dialogResult = JOptionPane.showConfirmDialog(null, "Amount Transfering from Saving to Checking Account" ,"BALANCE TRANSFER", JOptionPane.OK_CANCEL_OPTION ,JOptionPane.INFORMATION_MESSAGE);
if(dialogResult == JOptionPane.OK_OPTION){ ////perform only when ok button is clicked
checking.depositProcess(saving.transferProcess(value));
JOptionPane.showMessageDialog(null, "Balance Transfered Successfully", "BALANCE TRANSFER",JOptionPane.INFORMATION_MESSAGE);
}
textField.setText(null);
}
//for amount transfer from checking to saving account
else if(isPositiveNumber(value) && savingRadio.isSelected()){
int dialogResult = JOptionPane.showConfirmDialog(null, "Amount Transfering from Checking to Saving Account" ,"BALANCE TRANSFER", JOptionPane.OK_CANCEL_OPTION ,JOptionPane.INFORMATION_MESSAGE);
if(dialogResult == JOptionPane.OK_OPTION){ //perform only when ok button is clicked
saving.depositProcess(checking.transferProcess(value));
JOptionPane.showMessageDialog(null, "Balance Transfered Successfully", "BALANCE TRANSFER",JOptionPane.INFORMATION_MESSAGE);
}
textField.setText(null);
} else {
throw new IllegalArgumentException();
}
//catch exception
} catch(InsufficientFunds x){
JOptionPane.showMessageDialog(null, "Sorry your balance is low", "INSUFFICIENT FUNDS", JOptionPane.ERROR_MESSAGE);
textField.setText(null);
} catch(IllegalArgumentException x){
JOptionPane.showMessageDialog(null, "Invalid Input! Try Again", "ERROR", JOptionPane.ERROR_MESSAGE);
textField.setText(null);
}
}
//show balance of the selected account when balance button is clicked
if(COMPONENT == balanceButton){
//display balance of checking account in text field
if(checkingRadio.isSelected()){
double checkingBalance = checking.getBalance();
JOptionPane.showMessageDialog(null, "Checking Account balance: $" + checkingBalance, "CHECKING ACCOUNT", JOptionPane.INFORMATION_MESSAGE);
}
//display balance of saving account in text field
if(savingRadio.isSelected()){
double savingBalance = saving.getBalance();
JOptionPane.showMessageDialog(null, "Saving Account balance: $" + savingBalance, "SAVING ACCOUNT", JOptionPane.INFORMATION_MESSAGE);
}
}
}
//method to check if input text is positive number
public boolean isPositiveNumber(String value){
if(value == null){
return false;
}
int size = value.length();
if(size == 0){
return false;
}
if(value.charAt(0) == '-'){
return false;
}
if(!isNumber(value)){
return false;
}
return true;
}
//check if input text is double
public boolean isNumber(String value){
try {
Double.parseDouble(value);
return true;
} catch (NumberFormatException nfe){
return false;
}
}
//display frame
public void displayFrame(){
setVisible(true);
}
//main method
public static void main(String[] args){
P2GUI test = new P2GUI(); //create object of P2GUI class
test.displayFrame(); //display frame
}
}
| dgalami/SimpleATMMachine_JavaSwing | P2GUI.java | 2,550 | //inheriting JFrame and implementing ActionListener(multiple inheritance) | line_comment | en | false | 2,250 | 12 | 2,550 | 12 | 2,569 | 11 | 2,550 | 12 | 3,647 | 14 | false | false | false | false | false | true |