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 |
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
96285_5 | package Final;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.Arrays;
import java.util.LinkedHashMap;
import java.util.LinkedList;
import javafx.geometry.Insets;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.control.ComboBox;
import javafx.scene.control.Label;
import javafx.scene.control.TextField;
import javafx.scene.layout.GridPane;
import javafx.stage.Stage;
import Final.Final;
/*
* this class contains only static methods intended to be used for building and working with UI components
*
*/
public class UIService {
//appends message to main TextArea
public static void appendMessage(String message){
Final.mainPane.textArea.appendText(message + '\n');
}
//standard validation used application-wide for a user-entered value that will be used in a query
public static boolean isValidSearch(String id){
boolean isValid = true;
String regex = "[0-9]+"; //allow only numbers
if(id == null || id.equals("") || !id.matches(regex)){isValid = false;}
return isValid;
}
//generically designed method for iterating over a map of properties in a TableModel instance,
//this function will return a new grid pane containing each property's key and a text field object
//which is automatically bound to the data model object's observable property value
public static GridPane buildGrid(TableModel model){
GridPane grid = new GridPane();
int i = 0;
for(String propName : model.properties.keySet()){
grid.add(new Label(propName), 0, i);
TextField textField = new TextField();
textField.textProperty().bindBidirectional(model.properties.get(propName));
grid.add(textField, 1, i);
i++;
}
Button search = new Button("Search by " + model.searchKey);
search.setOnAction((e) -> {
try {
String resultText = model.search();
appendMessage(resultText);
} catch (Exception e1) {
model.clear();
e1.printStackTrace();
}
});
grid.add(search, 0, i);
return grid;
}
}
| cornelius-k/Library-Catalog | UIService.java | 588 | //this function will return a new grid pane containing each property's key and a text field object | line_comment | en | false | 466 | 19 | 588 | 19 | 594 | 20 | 588 | 19 | 667 | 21 | false | false | false | false | false | true |
97520_30 | package A3;
import java.util.Random;
/*
* @author Matthew Pan 40135588
*
* Jobs class which represent the processes in the priority queue.
* */
public class Job implements Comparable<Job> {
//"JOB_(arrayIndexNb+1)"
private String jobName;
//needed CPU cycles for this job, randomize between 1 and 70 cycles
private int jobLength;
//remaining job length at any time
private int currentJobLength;
//initial priority, randomize between 1 (highest) and 40
private int jobPriority;
//final priority at termination time
private int finalPriority;
//time of when job entered PQ, set to currentTime when inserted
private long entryTime;
//time of when job terminated, currenTime when executed
private long endTime;
//total amount of wait time before execution, doesn't include execution time
//(endTime - entryTime - jobLength) does not include execution's time, maybe endTime-1
private long waitTime;
//counter to track current time (CPU cycles);
//+1 for every PQ insertion, job execution and search for starved process
private static long currentTime = 0;
/* default constructor */
Job() { }
/* param constructor: initialize job with name, the
* priority is randomized.
*
* @param index the index in the array where the job is */
Job(int index) {
Random prio = new Random();
jobName = "JOB_" + index;
jobPriority = prio.nextInt(41) + 1;
finalPriority = jobPriority;
jobLength = prio.nextInt(71) + 1;
currentJobLength = jobLength;
entryTime = 0;
endTime = 0;
waitTime = 0;
};
//test constructor for non-random priority------------------------
Job(int index, int priority) {
Random prio = new Random();
jobName = "JOB_" + index;
jobPriority = priority;
finalPriority = jobPriority;
jobLength = prio.nextInt(71) + 1;
currentJobLength = jobLength;
entryTime = 0;
endTime = 0;
waitTime = 0;
};
/**
* decrements job length, sets end time and wait time.
* @return true if the job has terminated completely, false otherwise
*/
public boolean execute() {
if(currentJobLength > 0) {
currentJobLength--;
System.out.print(" -> Now executing ");
System.out.println(this.toString());
}
//if job terminated
if(currentJobLength <= 0) {
endTime = currentTime;
waitTime = endTime - entryTime - jobLength;
currentTime++;
return true;
}
//if job needs to be put back in PQ
else {
currentTime++;
return false;
}
}
/**
* compares the priority of two jobs, if same = FIFO order
* @return -1 if this job is higher priority or equal to the passed one (no swap)
*/
public int compareTo(Job o) {
if(this.finalPriority < o.getFinalPriority())
return -1;
else if(this.finalPriority == o.getFinalPriority())
return 0;
else
return 1;
}
/**
* @param o job to compare with
* @return true if they are the same job
*/
public boolean equals(Job o) {
return jobName.equals(o.getJobName());
}
/** print the job */
public String toString() {
return jobName + ": [Job length - " + jobLength + " cycles]" + " [Remaining length - " + currentJobLength + " cycles]"
+ " [Initial priority - " +Integer.toString(jobPriority) + "]" + " [Current priority - " + finalPriority + "]" + " [Current time - " + currentTime + "]";
}
/**
* @return the jobName
*/
public String getJobName() {
return jobName;
}
/**
* @param jobName the jobName to set
*/
public void setJobName(String jobName) {
this.jobName = jobName;
}
/**
* @return the jobLength
*/
public int getJobLength() {
return jobLength;
}
/**
* @param jobLength the jobLength to set
*/
public void setJobLength(int jobLength) {
this.jobLength = jobLength;
}
/**
* @return the currentJobLength
*/
public int getCurrentJobLength() {
return currentJobLength;
}
/**
* @param currentJobLength the currentJobLength to set
*/
public void setCurrentJobLength(int currentJobLength) {
this.currentJobLength = currentJobLength;
}
/**
* @return the jobPriority
*/
public int getJobPriority() {
return jobPriority;
}
/**
* @param jobPriority the jobPriority to set
*/
public void setJobPriority(int jobPriority) {
this.jobPriority = jobPriority;
}
/**
* @return the finalPriority
*/
public int getFinalPriority() {
return finalPriority;
}
/**
* @param finalPriority the finalPriority to set
*/
public void setFinalPriority(int finalPriority) {
this.finalPriority = finalPriority;
}
/**
* @return the entryTime
*/
public long getEntryTime() {
return entryTime;
}
/**
* @param entryTime the entryTime to set
*/
public void setEntryTime(long entryTime) {
this.entryTime = entryTime;
}
/**
* @return the endTime
*/
public long getEndTime() {
return endTime;
}
/**
* @param endTime the endTime to set
*/
public void setEndTime(long endTime) {
this.endTime = endTime;
}
/**
* @return the waitTime
*/
public long getWaitTime() {
return waitTime;
}
/**
* @param waitTime the waitTime to set
*/
public void setWaitTime(long waitTime) {
this.waitTime = waitTime;
}
/**
* @return the currentTime
*/
public static long getCurrentTime() {
return currentTime;
}
public static void setCurrentTime(long n) {
currentTime = n;
}
}
| Fryingpannn/DataStructures-Algorithms | A3/Job.java | 1,599 | /**
* @param finalPriority the finalPriority to set
*/ | block_comment | en | false | 1,403 | 15 | 1,599 | 14 | 1,658 | 16 | 1,599 | 14 | 1,848 | 18 | false | false | false | false | false | true |
97893_0 |
public class Validator {
//checks to make sure the email being checked is a vaild email based on the standards in the method
public static boolean isEmail(String check){
int count = 0;
for(int i = 0; i < check.length(); i++){
if(check.substring(i, i+1).compareTo("@") == 0) //contains an @ character
count++;
}
if(count == 1){
if(check.length() <= 10)
return false;
else{
//makes sure ending matches one of these internet protocols
if(check.substring(check.length()-4, check.length()).compareTo(".com") == 0 ||
check.substring(check.length()-4, check.length()).compareTo(".net") == 0 ||
check.substring(check.length()-4, check.length()).compareTo(".org") == 0||
check.substring(check.length()-4, check.length()).compareTo(".edu") == 0 ||
check.substring(check.length()-4, check.length()).compareTo(".gov") == 0 ||
check.substring(check.length()-4, check.length()).compareTo(".mil") == 0 ||
check.substring(check.length()-4, check.length()).compareTo(".int") == 0)
return true;
else
return false;
}
}
else
return false;
}
//makes sure the phone number being checked is a valid phone number (contains 10 integers)
public static boolean isPhone(String check){
if(check.length() != 10)
return false;
else{
for(int i = 0; i < check.length(); i++){
if(!check.substring(i, i+1).equals("0") &&
!check.substring(i, i+1).equals("1") &&
!check.substring(i, i+1).equals("2") &&
!check.substring(i, i+1).equals("3") &&
!check.substring(i, i+1).equals("4") &&
!check.substring(i, i+1).equals("5") &&
!check.substring(i, i+1).equals("6") &&
!check.substring(i, i+1).equals("7") &&
!check.substring(i, i+1).equals("8") &&
!check.substring(i, i+1).equals("9"))
return false;
}
return true;
}
}
}
| GWest58/CSE-360-Project | src/Validator.java | 642 | //checks to make sure the email being checked is a vaild email based on the standards in the method | line_comment | en | false | 546 | 22 | 642 | 22 | 714 | 21 | 642 | 22 | 832 | 23 | false | false | false | false | false | true |
98649_1 | import java.util.Arrays;
public class LCS {
}
/*
* Tabulation -> Bottom-up
* TC -> O(m*n)
* SC -> O(m*n) + O(m+n)
* Rules:
* 1) Copy the base case
* a) Base case issue coz we cannot store dp[-1] so we do shifting of index
* b) Every i and j will be treated as i-1 and j-1
* c) we will use f(m,n) insted of m-1 and n-1
* d) Base case will be if i==0 || j==0 return 0
* e) In Tabulation
* f) dp[0][j] = 0
* g) dp[i][0] = 0
* h) i = j = 0-m && 0-n
* 2) Write down the changing paramater in opposite direction
* a) i = 1 -> m
* b) j = 1 -> n
* 3) Copy the recurrace
*/
class Solution {
public int longestCommonSubsequence(String text1, String text2) {
int n = text1.length();
int m = text2.length();
int dp[][] = new int[n+1][m+1];
for(int j = 0; j<= m; j++){
dp[0][j] = 0;
}
for(int i = 0; i<= n; i++){
dp[i][0] = 0;
}
for(int i = 1; i<= n; i++){
for(int j = 1; j<= m; j++){
if(text1.charAt(i-1)==text2.charAt(j-1)){
dp[i][j] = 1 + dp[i-1][j-1];
}else{
dp[i][j] =Math.max(dp[i-1][j],dp[i][j-1]);
}
}
}
return dp[n][m];
}
}
/*
* Base shift
* Tabulation -> Bottom-up
* TC -> O(m*n)
* SC -> O(m*n) + O(m+n)
*/
class SolutionBaseShift {
public int longestCommonSubsequence(String text1, String text2) {
int m = text1.length();
int n = text2.length();
int[][] dp = new int[m+1][n+1];
for(int[] d: dp){
Arrays.fill(d,-1);
}
return lcsbaseshift(text1,text2, m, n, dp);
}
private int lcsbaseshift(String str1,String str2, int ind1, int ind2, int[][] dp){
if(ind1 == 0 || ind2 ==0){
return 0;
}
if(dp[ind1][ind2] != -1){
return dp[ind1][ind2];
}
if(str1.charAt(ind1-1) == str2.charAt(ind2-1) ){
return dp[ind1][ind2] = 1+ lcsbaseshift(str1,str2, ind1-1, ind2-1, dp);
}
return dp[ind1][ind2] = Math.max(lcsbaseshift(str1,str2, ind1-1, ind2, dp),lcsbaseshift(str1,str2, ind1, ind2-1, dp));
}
}
/*
* Memoization -> Top-Down
* TC -> O(m*n)
* SC -> O(m*n) + O(m+n)
* Rules:
* 1)
*/
class SolutionDPMemoization {
public int longestCommonSubsequence(String text1, String text2) {
int m = text1.length();
int n = text2.length();
int dp[][] = new int[m][n];
for(int[] d: dp){
Arrays.fill(d,-1);
}
return lcsmemo(text1,text2,m-1,n-1,dp);
}
private int lcsmemo(String s1, String s2, int ind1, int ind2, int[][] dp){
if(ind1 < 0 || ind2 < 0){
return 0;
}
if(dp[ind1][ind2] != -1){
return dp[ind1][ind2];
}
if(s1.charAt(ind1) == s2.charAt(ind2)){
return dp[ind1][ind2] = 1+ lcsmemo(s1,s2,ind1-1,ind2-1,dp);
}
return dp[ind1][ind2] = Math.max(lcsmemo(s1,s2,ind1-1,ind2,dp),lcsmemo(s1,s2,ind1,ind2-1,dp));
}
}
// Recursion
class SolutionRecursion {
public int longestCommonSubsequence(String text1, String text2) {
int m = text1.length();
int n = text2.length();
return lcsmemo(text1,text2,m-1,n-1);
}
private int lcsmemo(String s1, String s2, int ind1, int ind2){
if(ind1 < 0 || ind2 < 0){
return 0;
}
if(s1.charAt(ind1) == s2.charAt(ind2)){
return 1+ lcsmemo(s1,s2,ind1-1,ind2-1);
}
return Math.max(lcsmemo(s1,s2,ind1-1,ind2),lcsmemo(s1,s2,ind1,ind2-1));
}
}
| scorcism/CP | LCS.java | 1,358 | /*
* Base shift
* Tabulation -> Bottom-up
* TC -> O(m*n)
* SC -> O(m*n) + O(m+n)
*/ | block_comment | en | false | 1,213 | 33 | 1,358 | 42 | 1,445 | 43 | 1,358 | 42 | 1,545 | 45 | false | false | false | false | false | true |
99015_9 | /**
* Represents a customer.
* @author Sol Boucher <[email protected]>
*/
public class Customer extends User
{
/** The name by which cash customers are known. */
public static final String CASH_NAME="Anonymous"; //if this is null, constructor will fail
/** The ID reserved for cash customers. */
public static final int CASH_ID=Integer.MAX_VALUE;
/** The person's account balance. */
private int money;
/**
* Default (cash customer) constructor.
* Creates a special <i>cash</i> customer with the ability to change its balance on the fly.
* The balance starts out at <tt>0</tt>, however, and remains there until funds are added.
* @throws BadArgumentException on internal failure
*/
public Customer() throws BadArgumentException
{
super(CASH_NAME);
try
{
setId(CASH_ID);
}
catch(BadStateException impossible) //we just created the parent, so this can't happen
{
System.err.println("CRITICAL : Model detected a problem not previously thought possible!");
System.err.print(" DUMP : ");
impossible.printStackTrace();
System.err.println();
}
money=0;
}
/**
* Fresh (account-backed customer) constructor.
* Creates an instance with the specified initial balance.
* @param name the <tt>Customer</tt>'s name
* @param money the <tt>Customer</tt>'s initial balance
* @throws BadArgumentException if the <tt>name</tt> is invalid or the <tt>money</tt> is negative
*/
public Customer(String name, int money) throws BadArgumentException
{
super(name);
if(money<0)
throw new BadArgumentException("Money must not be negative");
this.money=money;
}
/**
* Copy constructor.
* Creates a copy of the supplied instance.
* @param existing the instance to clone
*/
public Customer(Customer existing)
{
super(existing);
this.money=existing.money;
}
/**
* Note that <tt>deductMoney(int)</tt> is more appropriate for fulfilling purchases.
* @param money the new balance
* @throws BadArgumentException if a negative value is supplied
*/
public void setMoney(int money) throws BadArgumentException
{
if(money<0)
throw new BadArgumentException("Money must not be negative");
this.money=money;
}
/**
* @return the account balance
*/
public int getMoney()
{
return money;
}
/**
* Deducts the specified amount from the account.
* This amount may be positive, negative, or zero, but must not cause the balance to go negative.
* @param change the value by which to diminish the balance
* @return whether the operation succeeded (i.e. didn't exceed the available funds)
*/
public boolean deductMoney(int change)
{
if(change<=money) //balance wouldn't go negative
{
money-=change;
return true;
}
else
return false;
}
/**
* Indicates whether this customer is a cash customer.
* @return the answer to The Question
*/
public boolean isCashCustomer()
{
try
{
return getId()==CASH_ID;
}
catch(BadStateException noneSet) //ID was unset
{
return false; //not a cash customer
}
}
/**
* Checks whether two instances contain the same data.
* @param another another instance
* @return whether their contents match
*/
@Override
public boolean equals(Object another)
{
if(!(another instanceof Customer))
return false;
Customer other=(Customer)another;
return super.equals(another) && this.money==other.money;
}
/** @inheritDoc */
@Override
public String toString() {
return super.toString() + " " + String.format("%.2f", ((double)money) / 100);
}
}
| bitbanger/hclc_vending_machine | src/Customer.java | 997 | /**
* Note that <tt>deductMoney(int)</tt> is more appropriate for fulfilling purchases.
* @param money the new balance
* @throws BadArgumentException if a negative value is supplied
*/ | block_comment | en | false | 889 | 46 | 997 | 47 | 1,031 | 50 | 997 | 47 | 1,185 | 56 | false | false | false | false | false | true |
100514_0 | import java.io.BufferedReader;
import java.io.File;
import java.io.FileOutputStream;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.Formatter;
public class Commit
{
/*A prerequisite of a commit is that you need a Tree's SHA1 file location. In order to get this you you must...
create a Tree object and save it to the objects folder
(Trees can be blank and have no entries for this part of the code)
A Commit also has a few other entries
String 'summary'
String 'author'
String 'date'
A commit constructor takes an optional String of the SHA1 of a parent Commit, and two Strings for author and summary
A commit contains a method to generate a SHA1 String
The inputs for the SHA1 are the SUBSET OF FILE CONTENTS file:
Summary, Date, Author, Tree, and (possibly null) pointer to parent Commit file
(so all the file contents except line 3)
Has a method getDate()
It gets the date as a String in whatever format you like
Has a method to create a Tree which is used in the constructor
Returns the SHA1 of the Tree*/
String summary, author, date, parent, sha;
File commit;
public Commit (String summary, String author, String date) throws Throwable
{
//commit is stored in the objects folder
//create tree in constructor
Tree tree = new Tree();
tree.addTree("");
sha = tree.getCurrentFileName();
this.author = author;
this.date = date;
this.summary = summary;
parent = tree.getCurrentFileName();
File path = new File ("objects");
path.mkdirs();
FileOutputStream stream = new FileOutputStream(new File(path , "Commit"));
//File commit = new File("Commit");
FileWriter writer - new FileWriter("Commit");
wri
writer.close();
}
public Commit (String summary, String author, String date, String parent) throws Throwable
{
Tree tree = new Tree();
tree.addTree("");
sha = tree.getCurrentFileName();
this.summary = summary;
this.author = author;
this.date = date;
this.parent = parent;
File path = new File ("objects");
path.mkdirs();
FileOutputStream stream = new FileOutputStream(new File(path , "Commit"));
//File commit = new File("Commit");
}
public void generateShaString() throws IOException
{
int line = 1;
String contents = "";
String sha1;
BufferedReader reader = new BufferedReader(new FileReader("Commit"));
while (reader.ready())
{
if (line == 3)
{
reader.readLine();
}
else
{
contents += reader.readLine();
}
line++;
}
reader.close();
try
{
MessageDigest crypt = MessageDigest.getInstance("SHA-1");
crypt.reset();
crypt.update(contents.getBytes("UTF-8"));
sha1 = byteToHex(crypt.digest());
}
catch(NoSuchAlgorithmException e)
{
e.printStackTrace();
}
catch(UnsupportedEncodingException e)
{
e.printStackTrace();
}
//return sha1;
}
private static String byteToHex(final byte[] hash)
{
Formatter formatter = new Formatter();
for (byte b : hash)
{
formatter.format("%02x", b);
}
String result = formatter.toString();
formatter.close();
return result;
}
public String getDate()
{
return date;
}
} | mgober1/BlobAndIndex-MG | Commit.java | 835 | /*A prerequisite of a commit is that you need a Tree's SHA1 file location. In order to get this you you must...
create a Tree object and save it to the objects folder
(Trees can be blank and have no entries for this part of the code)
A Commit also has a few other entries
String 'summary'
String 'author'
String 'date'
A commit constructor takes an optional String of the SHA1 of a parent Commit, and two Strings for author and summary
A commit contains a method to generate a SHA1 String
The inputs for the SHA1 are the SUBSET OF FILE CONTENTS file:
Summary, Date, Author, Tree, and (possibly null) pointer to parent Commit file
(so all the file contents except line 3)
Has a method getDate()
It gets the date as a String in whatever format you like
Has a method to create a Tree which is used in the constructor
Returns the SHA1 of the Tree*/ | block_comment | en | false | 751 | 198 | 835 | 215 | 907 | 207 | 835 | 215 | 1,012 | 231 | true | true | true | true | true | false |
100812_8 | import java.util.List;
/**
* This file is part of the Predator-Prey Simulation.
*
* An PoisonBerry plant present in the simulation.
*
* @author Ubayd Khan (k20044237) and Omar Ahmad (k21052417)
* @version 2022.03.02
*/
public class PoisonBerry extends Plant {
// define fields
private static final double MAX_SIZE = 10.0;
private static final int MAX_AGE = 20;
private static final int BREEDING_AGE = 16;
private static final double LOW_BREEDING_PROBABILITY = 0.104;
private static final double HIGH_BREEDING_PROBABILITY = 0.2;
private static final int MAX_LITTER_SIZE = 3;
private static final double DEFAULT_SIZE = 1.00;
private static final int DEFAULT_FOOD_VALUE = 5;
private static final double DEFAULT_GROWTH_RATE = 1.2;
/**
* Constructor for a plant in the simulation.
*
* @param foodValue The food value of this plant.
* @param size The initial size of this plant.
* @param randomAge Whether the animal should have a random age or not.
* @param field The field in which the plant resides.
* @param location The location in which the plant spawns into.
*/
public PoisonBerry(int foodValue, double size, boolean randomAge, Field field, Location location) {
super(true, foodValue, size, randomAge, field, location);
setGrowthRate(DEFAULT_GROWTH_RATE);
setBreedingProbability(LOW_BREEDING_PROBABILITY);
}
/**
* Getter method for the maximum age of the berry.
*
* @return An integer value representing the maximum age.
*/
@Override
public int getMaxAge() {
return MAX_AGE;
}
/**
* Getter method for the age of breeding of the berry.
*
* @return A double value representing the breeding age.
*/
@Override
public int getBreedingAge() {
return BREEDING_AGE;
}
/**
* Create a new instance of this berry.
* @param field The field in which the spawn will reside in.
* @param location The location in which the spawn will occupy.
* @return A new PoisonBerry instance.
*/
@Override
protected Organism createNewOrganism(Field field, Location location) {
return new PoisonBerry(DEFAULT_FOOD_VALUE, DEFAULT_SIZE, true, field, location);
}
/**
* Abstract method for what the PoisonBerry does, i.e. what is always run at every step.
*
* @param newBerries A list of all newborn berries in this simulation step.
* @param weather The current state of weather in the simulation.
* @param time The current state of time in the simulation.
*/
@Override
public void act(List<Entity> newBerries, Weather weather, TimeOfDay time) {
if (isAlive()) {
setBreedingProbability(LOW_BREEDING_PROBABILITY);
//If it has recently rained or is snowy, grow at a higher growth rate
if (weather.getRecentWeather().contains(WeatherType.RAIN) ||
weather.getRecentWeather().contains(WeatherType.SNOW)){
setBreedingProbability(HIGH_BREEDING_PROBABILITY);
}
grow();
giveBirth(newBerries);
}
}
/**
* Get maximum size of the berry.
*
* @return A double representing maximum size.
*/
@Override
public double getMaxSize() {
return MAX_SIZE;
}
/**
* Getter method for the maximum litter size of the berry's newborns.
*
* @return An integer value representing the maximum allowed litter size.
*/
@Override
public int getMaxLitterSize() {
return MAX_LITTER_SIZE;
}
}
| ubkh/PPA-CW3 | PoisonBerry.java | 952 | /**
* Get maximum size of the berry.
*
* @return A double representing maximum size.
*/ | block_comment | en | false | 876 | 24 | 952 | 25 | 977 | 28 | 952 | 25 | 1,103 | 29 | false | false | false | false | false | true |
101614_8 | package AStar;
import java.util.*;
/**
* This is the class for representing a single state of the rush hour puzzle.
* Methods are provided for constructing a state, for accessing information
* about a state, for printing a state, and for expanding a state (i.e.,
* obtaining a list of all states immediately reachable from it).
* <p>
* Every car is constrained to only move horizontally or vertically. Therefore,
* each car has one dimension along which it is fixed, and another dimension
* along which it can be moved. This variable dimension is stored here as part
* of the state. A link to the puzzle with which this state is associated is
* also stored. Note that the goal car is always assigned index 0.
* <p>
* To make it easier to use <tt>State</tt> objects with some of the data
* structures provided as part of the Standard Java Platform, we also have
* provided <tt>hashCode</tt> and <tt>equals</tt> methods. You probably will not
* need to access these methods directly, but they are likely to be used
* implicitly if you take advantage of the Java Platform. These methods define
* two <tt>State</tt> objects to be equal if they refer to the same
* <tt>Puzzle</tt> object, and if they indicate that the cars have the identical
* variable positions in both states. The hashcode is designed to satisfy the
* general contract of the <tt>Object.hashCode</tt> method that it overrides,
* with regard to the redefinition of <tt>equals</tt>.
*/
public class State {
private Puzzle puzzle;
private int varPos[];
/**
* The main constructor for constructing a state. You probably will never
* need to use this constructor.
*
* @param puzzle
* the puzzle that this state is associated with
* @param varPos
* the variable position of each of the cars in this state
*/
public State(Puzzle puzzle, int varPos[]) {
this.puzzle = puzzle;
this.varPos = varPos;
computeHashCode();
}
/** Returns true if and only if this state is a goal state. */
public boolean isGoal() {
return (varPos[0] == puzzle.getGridSize() - 1);
}
/** Returns the variable position of car <tt>v</tt>. */
public int getVariablePosition(int v) {
return varPos[v];
}
/** Returns the puzzle associated with this state. */
public Puzzle getPuzzle() {
return puzzle;
}
/**
* Prints to standard output a primitive text representation of the state.
*/
public void print() {
int grid[][] = getGrid();
int gridsize = puzzle.getGridSize();
System.out.print("+-");
for (int x = 0; x < gridsize; x++) {
System.out.print("--");
}
System.out.println("+");
for (int y = 0; y < gridsize; y++) {
System.out.print("| ");
for (int x = 0; x < gridsize; x++) {
int v = grid[x][y];
if (v < 0) {
System.out.print(". ");
} else {
int size = puzzle.getCarSize(v);
if (puzzle.getCarOrient(v)) {
System.out.print((y == varPos[v] ? "^ " : ((y == varPos[v] + size - 1) ? "v " : "| ")));
} else {
System.out.print(x == varPos[v] ? "< " : ((x == varPos[v] + size - 1) ? "> " : "- "));
}
}
}
System.out.println(
(puzzle.getCarOrient(0) || y != puzzle.getFixedPosition(0)) ? "|" : (isGoal() ? ">" : " "));
}
System.out.print("+-");
for (int x = 0; x < gridsize; x++) {
System.out.print(
(!puzzle.getCarOrient(0) || x != puzzle.getFixedPosition(0)) ? "--" : (isGoal() ? "v-" : " -"));
}
System.out.println("+");
}
/**
* Computes a grid representation of the state. In particular, an nxn
* two-dimensional integer array is computed and returned, where n is the
* size of the puzzle grid. The <tt>(i,j)</tt> element of this grid is equal
* to -1 if square <tt>(i,j)</tt> is unoccupied, and otherwise contains the
* index of the car occupying this square. Note that the grid is recomputed
* each time this method is called.
*/
public int[][] getGrid() {
int gridsize = puzzle.getGridSize();
int grid[][] = new int[gridsize][gridsize];
for (int i = 0; i < gridsize; i++)
for (int j = 0; j < gridsize; j++)
grid[i][j] = -1;
int num_cars = puzzle.getNumCars();
for (int v = 0; v < num_cars; v++) {
boolean orient = puzzle.getCarOrient(v);
int size = puzzle.getCarSize(v);
int fp = puzzle.getFixedPosition(v);
if (v == 0 && varPos[v] + size > gridsize)
size--;
if (orient) {
for (int d = 0; d < size; d++)
grid[fp][varPos[v] + d] = v;
} else {
for (int d = 0; d < size; d++)
grid[varPos[v] + d][fp] = v;
}
}
return grid;
}
/**
* Computes all of the states immediately reachable from this state and
* returns them as an array of states. You probably will not need to use
* this method directly, since ordinarily you will be expanding
* <tt>Node</tt>s, not <tt>State</tt>s.
*/
public State[] expand() {
int gridsize = puzzle.getGridSize();
int grid[][] = getGrid();
int num_cars = puzzle.getNumCars();
ArrayList new_states = new ArrayList();
for (int v = 0; v < num_cars; v++) {
int p = varPos[v];
int fp = puzzle.getFixedPosition(v);
boolean orient = puzzle.getCarOrient(v);
for (int np = p - 1; np >= 0 && (orient ? grid[fp][np] : grid[np][fp]) < 0; np--) {
int[] newVarPos = (int[]) varPos.clone();
newVarPos[v] = np;
new_states.add(new State(puzzle, newVarPos));
}
int carsize = puzzle.getCarSize(v);
for (int np = p + carsize; (np < gridsize && (orient ? grid[fp][np] : grid[np][fp]) < 0)
|| (v == 0 && np == gridsize); np++) {
int[] newVarPos = (int[]) varPos.clone();
newVarPos[v] = np - carsize + 1;
new_states.add(new State(puzzle, newVarPos));
}
}
puzzle.incrementSearchCount(new_states.size());
return (State[]) new_states.toArray(new State[0]);
}
private int hashcode;
private void computeHashCode() {
hashcode = puzzle.hashCode();
for (int i = 0; i < varPos.length; i++)
hashcode = 31 * hashcode + varPos[i];
}
/**
* Returns a hash code value for this <tt>State</tt> object. Although you
* probably will not need to use it directly, this method is provided for
* the benefit of hashtables given in the Java Platform. See documentation
* on <tt>Object.hashCode</tt>, which this method overrides, for the general
* contract that <tt>hashCode</tt> methods must satisfy.
*/
public int hashCode() {
return hashcode;
}
/**
* Returns <tt>true</tt> if and only if this state is considered equal to
* the given object. In particular, equality is defined to hold if the given
* object is also a <tt>State</tt> object, if it is associated with the same
* <tt>Puzzle</tt> object, and if the cars in both states are in the
* identical positions. This method overrides <tt>Object.equals</tt>.
*/
public boolean equals(Object o) {
State s;
try {
s = (State) o;
} catch (ClassCastException e) {
return false;
}
if (hashcode != s.hashcode || !puzzle.equals(s.puzzle))
return false;
for (int i = 0; i < varPos.length; i++)
if (varPos[i] != s.varPos[i])
return false;
return true;
}
}
| saschazar21/rushhour | AStar/State.java | 2,251 | /**
* Returns a hash code value for this <tt>State</tt> object. Although you
* probably will not need to use it directly, this method is provided for
* the benefit of hashtables given in the Java Platform. See documentation
* on <tt>Object.hashCode</tt>, which this method overrides, for the general
* contract that <tt>hashCode</tt> methods must satisfy.
*/ | block_comment | en | false | 2,004 | 93 | 2,251 | 90 | 2,254 | 95 | 2,251 | 90 | 2,604 | 99 | false | false | false | false | false | true |
104834_1 | package vendingmachine;
public class CoinSum {
int[] coinValues = {200,100,50,20,10,5,2,1};
int[] coins = new int[8];
public CoinSum(int onep, int twop, int fivep, int tenp, int twentyp, int fiftyp, int onePound, int twoPounds) {
coins[0] = twoPounds;
coins[1] = onePound;
coins[2] = fiftyp;
coins[3] = twentyp;
coins[4] = tenp;
coins[5] = fivep;
coins[6] = twop ;
coins[7] = onep;
}
public CoinSum getSum() {
return this;
}
public Integer getTotalValue() {
Integer total = 0;
for (int i = 0; i < coins.length; i++) {
total += coins[i]*coinValues[i];
}
return total;
}
public CoinSum exchange(int price, int totalReceived) {
CoinSum possibleSum = new CoinSum(0,0,0,0,0,0,0,0);
int amountToReturn = totalReceived - price;
//Specific case where we enter exactly the amount
if (amountToReturn == 0) {
return possibleSum;
}
// We're going to decompose the price in coins to add it to vending machine
for (int i = 0; i < coinValues.length; i++) {
if (amountToReturn > 0){
float division = amountToReturn / coinValues[i];
//The amount due can be returned with this type of coin
if (division >= 1) {
int coinsNeeded = Math.round(division);
// We check the change available has enough coin
if (coinsNeeded <= this.coins[i]){
// We remove the coins that were used
int removeValue = coinsNeeded * coinValues[i];
//If there is enough money
if (amountToReturn >= removeValue){
amountToReturn -= removeValue;
possibleSum.coins[i] = coinsNeeded;
this.coins[i] += coinsNeeded;
}
}
}
}
}
// We haven't decompose the price fully
if (amountToReturn > 0) {
return null;
}
return possibleSum;
}
public String showCoins() {
StringBuilder strCoins = new StringBuilder();
for (int i = 0; i < coinValues.length; i++) {
String coinQuantity = Integer.toString(coins[i]);
float coinValue = (float) coinValues[i]/100 ;
String coinValueStr = String.format("%.02f", coinValue);
strCoins.append( coinQuantity + " of £" + coinValueStr);
strCoins.append("\n");
}
return strCoins.toString();
}
}
| H3ll3m4/Vending-Machine | CoinSum.java | 739 | // We're going to decompose the price in coins to add it to vending machine | line_comment | en | false | 675 | 17 | 739 | 18 | 730 | 17 | 739 | 18 | 920 | 20 | false | false | false | false | false | true |
105123_0 | package com.etiaro.facebook;
import android.support.annotation.NonNull;
import android.util.Log;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.util.ArrayList;
import java.util.Comparator;
import java.util.Iterator;
/**
* Created by jakub on 21.03.18.
*/
public class Message implements Comparator<Message>, Comparable<Message>{
public String text, senderID, __typename, message_id, offline_threading_id, conversation_id, sender_email;
public int ttl;
public Long timestamp_precise;
public boolean sent = false, delivered = false, unread, is_sponsored; //Delivered and sent are supported not by counstructor
public ArrayList<Attachment> attachments = new ArrayList<>();
public Message(JSONObject json) throws JSONException {
update(json);
}
public void update(JSONObject json) throws JSONException {
if(json.has("irisSeqId")){
text = json.has("body") ?
json.getString("body") : "";
senderID = json.getJSONObject("messageMetadata").getString("actorFbId");
message_id = json.getJSONObject("messageMetadata").getString("messageId");
offline_threading_id = json.getJSONObject("messageMetadata").getString("offlineThreadingId");
if(json.getJSONObject("messageMetadata").getJSONObject("threadKey").has("threadFbId"))
conversation_id = json.getJSONObject("messageMetadata").getJSONObject("threadKey").getString("threadFbId");
else if(json.getJSONObject("messageMetadata").getJSONObject("threadKey").has("otherUserFbId"))
conversation_id = json.getJSONObject("messageMetadata").getJSONObject("threadKey").getString("otherUserFbId");
timestamp_precise = Long.valueOf(json.getJSONObject("messageMetadata").getString("timestamp"));
unread = true;
return;
}
if(!json.has("message_id")) {
text = json.getString("snippet");
senderID = json.getJSONObject("message_sender").getJSONObject("messaging_actor").getString("id");
}else{
if(json.has("__typename"))
__typename = json.getString("__typename");
message_id = json.getString("message_id");
offline_threading_id = json.getString("offline_threading_id"); //???
senderID = json.getJSONObject("message_sender").getString("id");
if(json.getJSONObject("message_sender").has("email"))
sender_email = json.getJSONObject("message_sender").getString("email");
if(json.has("ttl"))
ttl = json.getInt("ttl");
unread = json.getBoolean("unread");
if(json.has("is_sponsored"))
is_sponsored = json.getBoolean("is_sponsored");
if(json.has("message") && json.getJSONObject("message").has("text"))
text = json.getJSONObject("message").getString("text");
}
if(json.has("blob_attachments") && json.getJSONArray("blob_attachments").length() > 0) {
for(int i = 0; i < json.getJSONArray("blob_attachments").length(); i++){
attachments.add(new Attachment(json.getJSONArray("blob_attachments").getJSONObject(i)));
}
}
if(json.has("sent") && json.has("delivered")) {
sent = json.getBoolean("sent");
delivered = json.getBoolean("delivered");
}
timestamp_precise = Long.valueOf(json.getString("timestamp_precise"));
}
public JSONObject toJSON(){
JSONObject obj = null;
try {
obj = new JSONObject().put("message", new JSONObject().put("text", text)).put("senderID", senderID)
.put("__typename", __typename).put("message_sender", new JSONObject()
.put("email", sender_email).put("id", senderID)
.put("messaging_actor", new JSONObject()
.put("id", senderID)))
.put("message_id", message_id)
.put("offline_threading_id", offline_threading_id).put("ttl", ttl)
.put("sent", sent).put("delivered", delivered).put("unread", unread).put("is_sponsored", is_sponsored)
.put("timestamp_precise", timestamp_precise).put("snippet", text)
.put("messageMetadata", new JSONObject().put("threadKey", new JSONObject().put("threadFbId", conversation_id)));
JSONArray arr = new JSONArray();
Iterator<Attachment> it = attachments.iterator();
while(it.hasNext())
arr.put(it.next().toJSON());
obj.put("blob_attachments", arr);
} catch (JSONException e) {
e.printStackTrace();
}
return obj;
}
public String toString(){
return toJSON().toString();
}
@Override
public int compare(Message m1, Message m2) {
return (int)(m1.timestamp_precise - m2.timestamp_precise);
}
@Override
public int compareTo(@NonNull Message msg) {
return (int)(this.timestamp_precise - msg.timestamp_precise);
}
}
/*{
"commerce_message_type":null,
"customizations":[],
"tags_list":[
"source:messenger:web",
"hot_emoji_size:small",
"inbox"
],
"platform_xmd_encoded":null,
"message_source_data":null,
"montage_reply_data":null,
TODO "message_reactions":[], <-------
"message":{"ranges":[]},
"extensible_attachment":null,
"sticker":null,
}*/ | etiaro/facebook-chat | Message.java | 1,306 | /**
* Created by jakub on 21.03.18.
*/ | block_comment | en | false | 1,133 | 18 | 1,307 | 20 | 1,364 | 20 | 1,306 | 20 | 1,565 | 21 | false | false | false | false | false | true |
105876_4 | /**
* TVSeries is a subclass of Media. The objects of TVSeries contain information about a TV Series.
* Title, series, episode, publish year, rating, genre can be stored in to the objects.
*
* @author Juha Hirvasniemi <[email protected]>, Tapio Korvala <[email protected]>
* @version 1.0
* @since 2013-12-30
*/
public class TVSeries extends Media {
static final long serialVersionUID = 53L;
String episode;
String season;
private int id;
/**
* Constructor for TVSeries class which can store the information about TV series
* without using any setters.
*
* @param title title for the tv series.
* @param season season name for the series or a number.
* @param episode name of the episode or a number.
* @param publishYear the year the current episode was produced.
* @param rating the rating of the episode, 1-10.
* @param genre the genre for the tv series e.x. Action.
*/
public TVSeries(String title, String season, String episode, int publishYear, int rating, String genre) {
super.increaseId();
this.id = super.getId();
super.setTitle(title);
this.season = season;
this.episode = episode;
super.setPublishYear(publishYear);
super.setRating(rating);
super.setGenre(genre);
}
/**
* Returns id of the created object.
*
* @return id id of the current object.
*/
public int getId() {
return id;
}
/**
* Sets the episode name to the wanted value.
*
* @param episode value to set as episode name.
*/
public void setEpisode(String episode) {
this.episode = episode;
}
/**
* Returns the name of the episode.
*
* @return name of the episode.
*/
public String getEpisode() {
return this.episode;
}
/**
* Sets the name of the season.
*
* @param season value to be set as name of the season.
*/
public void setSeason(String season) {
this.season = season;
}
/**
* Returns the name of the season.
*
* @return name of the season.
*/
public String getSeason() {
return season;
}
public void print() {
System.out.println("-------------");
System.out.println("title: " + getTitle() + ", Series: " + getSeason() + ", Episode: " + getEpisode() + ", PublishYear: " + getPublishYear() + ", Rating: " + getRating() + ", Genre: " + getGenre());
System.out.println("-------------");
}
/**
* Returns all the values of the TV Series as string array.
*
* @return values of tv series.
*/
public String[] getRow() {
String [] row = { Integer.toString(getId()), super.getTitle(), season, episode, Integer.toString(super.getPublishYear()), Integer.toString(super.getRating()), super.getGenre() };
return row;
}
}
| korvatap/MediaCollector | src/TVSeries.java | 813 | /**
* Returns the name of the episode.
*
* @return name of the episode.
*/ | block_comment | en | false | 721 | 25 | 813 | 25 | 874 | 29 | 813 | 25 | 947 | 31 | false | false | false | false | false | true |
108779_0 | import java.io.*;
import java.util.*;
public class GetIndex {
public static void main(String [] args) throws IOException{
Scanner initialScan;
ArrayList<String> tokens = new ArrayList<String>();
String wordToken = "";
if (args.length == 0 || args.length < 2 || args.length > 3) {
System.out.println("Enter the sbv.txt, srt.txt, or vtt.txt file for which you wish to scan through.");
System.out.println("Then enter what the type of the file is: either it is sbv, srt, or vtt");
System.out.println("OPTIONAL Enter a fileWithWords.txt or some file that contains a list of words that you wish to scan through");
System.exit(1);
}
if (args.length == 3) { // if a file with just words to find, each word seperated with a new line was given
try {
File fileWithWords = new File(args[2]);
initialScan = new Scanner(fileWithWords);
while(initialScan.hasNextLine()) {
wordToken = initialScan.nextLine();
wordToken = wordToken.toLowerCase();
tokens.add(wordToken);
}
}
catch (FileNotFoundException e) {
System.out.println("File not Found");
}
}
else {
Scanner console = new Scanner(System.in);
System.out.println();
System.out.println();
System.out.println("Enter all words you wish to find.");
System.out.println("Type IAMDONE if you are finished with adding words.");
System.out.println();
String userInput = "";
while(!(userInput.equals("IAMDONE"))) {
if (userInput.equals("IAMDONE")) {
}
else {
userInput = console.nextLine();
tokens.add(userInput);
}
}
}
String info = "";
String info2 = "";
String timeStamp = "";
String testWord = "";
String line = "";
int bmSearch = 0;
BoyerMoore bm = new BoyerMoore();
ArrayList<String> listOfTimeStamps = new ArrayList<String>();
File f = new File(args[0]); // get the fileName
Scanner scan; // scan through file
System.out.println();
System.out.println();
System.out.println("This is your index");
System.out.println();
for (int i = 0; i < tokens.size(); i++) {
scan = new Scanner(f); // reset the scanner's position to the top of file.
testWord = tokens.get(i); // patternToSearch = testWord
if (args[1].equals("sbv")) {
listOfTimeStamps = scanSBV(info, info2, timeStamp, testWord, line, bmSearch, bm, listOfTimeStamps, scan);
}
else if (args[1].equals("srt")) {
listOfTimeStamps = scanSRT(info, info2, timeStamp, testWord, line, bmSearch, bm, listOfTimeStamps, scan);
}
else if (args[1].equals("vtt")) {
listOfTimeStamps = scanVTT(info, info2, timeStamp, testWord, line, bmSearch, bm, listOfTimeStamps, scan, f);
}
showIndex(listOfTimeStamps, testWord);
testWord="";
listOfTimeStamps.clear();
}
}
public static ArrayList<String> scanVTT(String info, String info2, String timeStamp, String testWord,
String line, int bmSearch, BoyerMoore bm,
ArrayList<String> listOfTimeStamps, Scanner scan, File f)
{
testWord = testWord.toLowerCase();
// Check to see if the WEBVTT three lines are on top.
// If so, skip through them, then do normal scanning.
// otherwise, just do normal scanning.
String checkWebVTT = scan.nextLine();
if (checkWebVTT.equals("WEBVTT")) {
scan.nextLine(); // kind: captions
scan.nextLine(); // language: end
scan.nextLine(); // new line space
}
else {
try{
scan = new Scanner(f);
}
catch(FileNotFoundException e) {
System.out.println("Error");
System.exit(0);
}
}
while(scan.hasNextLine()) {
timeStamp = scan.nextLine();
timeStamp = timeStamp.replaceAll(" -->", ","); // replaces all arrows with commas to keep consistency
info = scan.nextLine();
line = info.replaceAll("[\\p{Punct}]", "");
line = line.toLowerCase(); // text = line
bmSearch = bm.findPattern(line, testWord);
if (bmSearch == 1) {
// then match this word that is found with its timestamp.
listOfTimeStamps.add(timeStamp);
}
if (scan.hasNextLine()) {
info2 = scan.nextLine();
}
// want to check if info2 is a whitespace,
// or more words
// if its a whitespace, move on
// if its more words, then run the check for tokens loop again
if (info2.matches("[0-9]+") == false && info2.length() > 0) {
line = info2.replaceAll("[\\p{Punct}]", "");
//line = line.replaceAll("\\s","");
line = line.toLowerCase();
bmSearch = bm.findPattern(line, testWord);
if (bmSearch == 1) {
// then match this word that is found with its timestamp.
listOfTimeStamps.add(timeStamp);
}
if (scan.hasNextLine()) {
scan.nextLine();
}
}
} // end of searching through file
return listOfTimeStamps;
}
public static ArrayList<String> scanSRT(String info, String info2, String timeStamp, String testWord,
String line, int bmSearch, BoyerMoore bm,
ArrayList<String> listOfTimeStamps, Scanner scan)
{
String skipInt = "";
testWord = testWord.toLowerCase();
while(scan.hasNextLine()) {
skipInt = scan.nextLine();
timeStamp = scan.nextLine();
timeStamp = timeStamp.replaceAll(" -->", ","); // replaces all arrows with commas to keep consistency
info = scan.nextLine();
line = info.replaceAll("[\\p{Punct}]", "");
//line = line.replaceAll("\\s","");
line = line.toLowerCase(); // text = line
bmSearch = bm.findPattern(line, testWord);
if (bmSearch == 1) {
// then match this word that is found with its timestamp.
listOfTimeStamps.add(timeStamp);
}
if (scan.hasNextLine()) {
info2 = scan.nextLine();
}
// want to check if info2 is a whitespace,
// or more words
// if its a whitespace, move on
// if its more words, then run the check for tokens loop again
if (info2.matches("[0-9]+") == false && info2.length() > 0) {
line = info2.replaceAll("[\\p{Punct}]", "");
//line = line.replaceAll("\\s","");
line = line.toLowerCase();
bmSearch = bm.findPattern(line, testWord);
if (bmSearch == 1) {
// then match this word that is found with its timestamp.
listOfTimeStamps.add(timeStamp);
}
if (scan.hasNextLine()) {
scan.nextLine();
}
}
} // end of searching through file
return listOfTimeStamps;
}
public static ArrayList<String> scanSBV(String info, String info2, String timeStamp, String testWord,
String line, int bmSearch, BoyerMoore bm,
ArrayList<String> listOfTimeStamps, Scanner scan)
{
testWord = testWord.toLowerCase();
while(scan.hasNextLine()) {
timeStamp = scan.nextLine();
info = scan.nextLine();
line = info.replaceAll("[\\p{Punct}]", "");
//line = line.replaceAll("\\s","");
line = line.toLowerCase(); // text = line
bmSearch = bm.findPattern(line, testWord);
if (bmSearch == 1) {
// then match this word that is found with its timestamp.
listOfTimeStamps.add(timeStamp);
}
if (scan.hasNextLine()) {
info2 = scan.nextLine();
}
// want to check if info2 is a whitespace,
// or more words
// if its a whitespace, move on
// if its more words, then run the check for tokens loop again
if (info2.matches("[0-9]+") == false && info2.length() > 0) {
line = info2.replaceAll("[\\p{Punct}]", "");
//line = line.replaceAll("\\s","");
line = line.toLowerCase();
bmSearch = bm.findPattern(line, testWord);
if (bmSearch == 1) {
// then match this word that is found with its timestamp.
listOfTimeStamps.add(timeStamp);
}
if (scan.hasNextLine()) {
scan.nextLine();
}
}
} // end of searching through file
return listOfTimeStamps;
}
public static void showIndex(ArrayList<String> listOfTimeStamps, String testWord) {
// print index to console
if (listOfTimeStamps.size() == 1) {
System.out.print(testWord + ": " + "(" + listOfTimeStamps.get(0) + ")");
System.out.println();
}
else {
System.out.print(testWord + ": ");
for (int j = 0; j < listOfTimeStamps.size(); j++) {
System.out.print("(" + listOfTimeStamps.get(j) + ")" + ", ");
}
System.out.println();
}
}
}
| CMU-CREATE-Lab/Video-File-Index-Automator | GetIndex.java | 2,247 | // if a file with just words to find, each word seperated with a new line was given | line_comment | en | false | 2,086 | 20 | 2,247 | 20 | 2,456 | 20 | 2,247 | 20 | 2,711 | 21 | false | false | false | false | false | true |
112799_1 | package com.fishercoder.solutions;
/**
* 97. Interleaving String
*
* Given s1, s2, s3, find whether s3 is formed by the interleaving of s1 and s2.
* For example,
* Given:
* s1 = "aabcc",
* s2 = "dbbca",
* When s3 = "aadbbcbcac", return true.
* When s3 = "aadbbbaccc", return false.
*/
public class _97 {
public static class Solution1 {
public boolean isInterleave(String s1, String s2, String s3) {
int m = s1.length();
int n = s2.length();
if (m + n != s3.length()) {
return false;
}
boolean[][] dp = new boolean[m + 1][n + 1];
dp[0][0] = true;
for (int i = 0; i < m; i++) {
if (s1.charAt(i) == s3.charAt(i)) {
dp[i + 1][0] = true;
} else {
//if one char fails, that means it breaks, the rest of the chars won't matter any more.
//Mian and I found one missing test case on Lintcode: ["b", "aabccc", "aabbbcb"]
//if we don't break, here, Lintcode could still accept this code, but Leetcode fails it.
break;
}
}
for (int j = 0; j < n; j++) {
if (s2.charAt(j) == s3.charAt(j)) {
dp[0][j + 1] = true;
} else {
break;
}
}
for (int i = 1; i <= m; i++) {
for (int j = 1; j <= n; j++) {
int k = i + j - 1;
dp[i][j] = (s1.charAt(i - 1) == s3.charAt(k) && dp[i - 1][j])
|| (s2.charAt(j - 1) == s3.charAt(k) && dp[i][j - 1]);
}
}
return dp[m][n];
}
}
}
| gary-x-li/Leetcode | src/main/java/com/fishercoder/solutions/_97.java | 537 | //if one char fails, that means it breaks, the rest of the chars won't matter any more. | line_comment | en | false | 496 | 22 | 537 | 22 | 568 | 23 | 537 | 22 | 608 | 23 | false | false | false | false | false | true |
112922_0 | package gogo;
public class NumbersOfWords {
// billion: 1,000,000,000
// million: 1,000,000
// thousand: 1,000
public String numberToWords(int num) {
if(num==0) return "Zero";
int[] nums = new int[4];
String[] bases=new String[4];
bases[0] ="";
bases[1] = "Thousand";
bases[2] = "Million";
bases[3] = "Billion";
for(int i=0;i<4;i++){
nums[i]=num%1000;
num=num/1000;
}
StringBuilder sb=new StringBuilder();
for(int i=3;i>=0;i--) {
if (nums[i]!=0) {
String hundreds=helper(nums[i]);
if(sb.length()>0) {sb.append(" ");}
sb.append(hundreds.trim());
sb.append(" ");
sb.append(bases[i]);
}
}
return sb.toString().trim();
}
private String helper(int n){
int[] nums = new int[3];
for(int i=0;i<3;i++) {
nums[i]=n%10;
n=n/10;
}
StringBuilder sb=new StringBuilder();
if (nums[2]!=0){
sb.append(ones(nums[2]));
sb.append(" ");
sb.append("Hundred");
}
if (nums[1]>1) {
if(sb.length()>0) sb.append(" ");
sb.append(tens(nums[1]));
if (nums[0] !=0) {
if(sb.length()>0) sb.append(" ");
sb.append(ones(nums[0]));
}
} else if (nums[1]==1) {
if(sb.length()>0) sb.append(" ");
sb.append(teens(nums[0]));
} else {
if(sb.length()>0) sb.append(" ");
sb.append(ones(nums[0]));
}
return sb.toString();
}
private String teens(int n){
switch (n) {
case 0: return "Ten";
case 1: return "Eleven";
case 2: return "Twelve";
case 3: return "Thirteen";
case 4: return "Fourteen";
case 5: return "Fifteen";
case 6: return "Sixteen";
case 7: return "Seventeen";
case 8: return "Eighteen";
case 9: return "Nineteen";
default: return "";
}
}
private String ones(int n){
switch (n) {
case 1: return "One";
case 2: return "Two";
case 3: return "Three";
case 4: return "Four";
case 5: return "Five";
case 6: return "Six";
case 7: return "Seven";
case 8: return "Eight";
case 9: return "Nine";
default: return "";
}
}
private String tens(int n){
switch (n) {
case 2: return "Twenty";
case 3: return "Thirty";
case 4: return "Forty";
case 5: return "Fifty";
case 6: return "Sixty";
case 7: return "Seventy";
case 8: return "Eighty";
case 9: return "Ninety";
default: return "";
}
}
}
| WeizhengZhou/leetcode3 | src/gogo/NumbersOfWords.java | 933 | // billion: 1,000,000,000 | line_comment | en | false | 800 | 17 | 933 | 18 | 989 | 17 | 933 | 18 | 1,118 | 17 | false | false | false | false | false | true |
113485_8 | import java.io.IOException;
import java.util.*;
/**
Class to handle/mock the stream operations
This can be enhanced in the future to read from a real data stream pipeline
This class processes each loan and maps to right facility, and then performs bookkeeping
*/
public class StreamProcessor {
// Facilities sorted by interest rate
private ArrayList<Facility> sortedFacilities;
private TreeMap<Integer, Float> facilityYield = new TreeMap<>();
TreeMap<Integer, Integer> loanFacility = new TreeMap<>();
TreeMap<Integer, Integer> facilityYieldFinal = new TreeMap<>();
/**
* Constructor to setup the stream processing context
* The context is completely in memory - but needs to be more durable in future
*/
public StreamProcessor(String facilityFilePath, String covenantFilePath) {
// Load the processing context in form of facilities and covenants
try {
Hashtable<Integer, Facility> facilities = FileLoader.readFacilities(facilityFilePath, covenantFilePath);
// Once we have all the facilities and its covenants, build a list of faciities
// sorted by the interest rate
// We are optimizing for reading/access of faciities to match incoming loans
// So sort it once - nlg(n)
sortedFacilities = new ArrayList<Facility>(facilities.values());
sortedFacilities.sort((o1, o2) -> Math.round(o1.compareTo(o2)));
} catch (IOException e) {
e.printStackTrace();
}
}
/**
* Method to handle the stream of loans
* Iterate through every object and invoke processing operation
* In future this can be subscribing to a data pipeline
*/
void loanStreamSubscriber(LinkedList<Loan> loans) {
// Check the loan against every facility to match its covenants
// For now we will be looping over
// This can be an actual subscriber to a streaming pipeline
for (Loan l: loans) {
this.computeOnStreamedInstance(l);
}
}
/**
* Operation to handle an instance of the streamed data
*/
private void computeOnStreamedInstance(Loan l) {
for (Facility f: sortedFacilities) {
// Check if loan is eligible - and then book-keeping if yes
if (f.getLoanEligibility(l).isApproved) {
this.manageLoanAssignmentBookKeeping(l, f);
return;
}
}
// Unassigned loan scenario
this.manageLoanAssignmentBookKeeping(l, null);
}
/**
* Manage the book keeping of assigning and updating loan assignments
* @param loan
* @param facility
*/
private void manageLoanAssignmentBookKeeping(Loan loan, Facility facility) {
// Manage unassigned loan
if (facility == null) {
this.loanFacility.put(loan.id, 0);
}
else {
this.loanFacility.put(loan.id, facility.facilityId);
// Reduce the loan amount available to trade
facility.amountAvailableToLoan -= loan.amount;
// Manage loan yield calculation and assign to facility
float yield = this.facilityYield.getOrDefault(facility.facilityId, Float.valueOf("0"));
yield += this.getFacilityYieldForLoan(loan, facility);
this.facilityYield.put(facility.facilityId, yield);
}
}
/**
* Calculate the yield for loan and facility
* @param loan
* @param facility
* @return
*/
private float getFacilityYieldForLoan(Loan loan, Facility facility) {
return (1 - loan.defaultLikelihood) * loan.interestRate * loan.amount
- (loan.defaultLikelihood * loan.amount)
- (facility.interestRate * loan.amount);
}
/**
* Convert hash table into Map<String, String> useful for CSV writing
*/
void roundOffFinalCalculations() {
this.facilityYield.entrySet()
.iterator()
.forEachRemaining(E -> this.facilityYieldFinal.put(
E.getKey(), Math.round(E.getValue())
));
}
}
| devEffort/funLoans | src/StreamProcessor.java | 980 | /**
* Method to handle the stream of loans
* Iterate through every object and invoke processing operation
* In future this can be subscribing to a data pipeline
*/ | block_comment | en | false | 901 | 37 | 980 | 37 | 960 | 38 | 980 | 37 | 1,208 | 41 | false | false | false | false | false | true |
114402_17 | import java.awt.Color;
/**
* Class that references a pixel in a picture. Pixel
* stands for picture element where picture is
* abbreviated pix. A pixel has a column (x) and
* row (y) location in a picture. A pixel knows how
* to get and set the red, green, blue, and alpha
* values in the picture. A pixel also knows how to get
* and set the color using a Color object.
*
* @author Barb Ericson [email protected]
*/
public class Pixel
{
////////////////////////// fields ///////////////////////////////////
/** the digital picture this pixel belongs to */
private Picture picture;
/** the x (column) location of this pixel in the picture; (0,0) is top left */
private int x;
/** the y (row) location of this pixel in the picture; (0,0) is top left */
private int y;
////////////////////// constructors /////////////////////////////////
/**
* A constructor that takes the x and y location for the pixel and
* the picture the pixel is coming from
* @param picture the picture that the pixel is in
* @param x the x location of the pixel in the picture
* @param y the y location of the pixel in the picture
*/
public Pixel(Picture picture, int x, int y)
{
// set the picture
this.picture = picture;
// set the x location
this.x = x;
// set the y location
this.y = y;
}
///////////////////////// methods //////////////////////////////
/**
* Method to get the x location of this pixel.
* @return the x location of the pixel in the picture
*/
public int getX() { return x; }
/**
* Method to get the y location of this pixel.
* @return the y location of the pixel in the picture
*/
public int getY() { return y; }
/**
* Method to get the row (y value)
* @return the row (y value) of the pixel in the picture
*/
public int getRow() { return y; }
/**
* Method to get the column (x value)
* @return the column (x value) of the pixel
*/
public int getCol() { return x; }
/**
* Method to get the amount of alpha (transparency) at this pixel.
* It will be from 0-255.
* @return the amount of alpha (transparency)
*/
public int getAlpha() {
/* get the value at the location from the picture as a 32 bit int
* with alpha, red, green, blue each taking 8 bits from left to right
*/
int value = picture.getBasicPixel(x,y);
// get the alpha value (starts at 25 so shift right 24)
// then and it with all 1's for the first 8 bits to keep
// end up with from 0 to 255
int alpha = (value >> 24) & 0xff;
return alpha;
}
/**
* Method to get the amount of red at this pixel. It will be
* from 0-255 with 0 being no red and 255 being as much red as
* you can have.
* @return the amount of red from 0 for none to 255 for max
*/
public int getRed() {
/* get the value at the location from the picture as a 32 bit int
* with alpha, red, green, blue each taking 8 bits from left to right
*/
int value = picture.getBasicPixel(x,y);
// get the red value (starts at 17 so shift right 16)
// then AND it with all 1's for the first 8 bits to
// end up with a resulting value from 0 to 255
int red = (value >> 16) & 0xff;
return red;
}
/**
* Method to get the red value from a pixel represented as an int
* @param value the color value as an int
* @return the amount of red
*/
public static int getRed(int value)
{
int red = (value >> 16) & 0xff;
return red;
}
/**
* Method to get the amount of green at this pixel. It will be
* from 0-255 with 0 being no green and 255 being as much green as
* you can have.
* @return the amount of green from 0 for none to 255 for max
*/
public int getGreen() {
/* get the value at the location from the picture as a 32 bit int
* with alpha, red, green, blue each taking 8 bits from left to right
*/
int value = picture.getBasicPixel(x,y);
// get the green value (starts at 9 so shift right 8)
int green = (value >> 8) & 0xff;
return green;
}
/**
* Method to get the green value from a pixel represented as an int
* @param value the color value as an int
* @return the amount of green
*/
public static int getGreen(int value)
{
int green = (value >> 8) & 0xff;
return green;
}
/**
* Method to get the amount of blue at this pixel. It will be
* from 0-255 with 0 being no blue and 255 being as much blue as
* you can have.
* @return the amount of blue from 0 for none to 255 for max
*/
public int getBlue() {
/* get the value at the location from the picture as a 32 bit int
* with alpha, red, green, blue each taking 8 bits from left to right
*/
int value = picture.getBasicPixel(x,y);
// get the blue value (starts at 0 so no shift required)
int blue = value & 0xff;
return blue;
}
/**
* Method to get the blue value from a pixel represented as an int
* @param value the color value as an int
* @return the amount of blue
*/
public static int getBlue(int value)
{
int blue = value & 0xff;
return blue;
}
/**
* Method to get a color object that represents the color at this pixel.
* @return a color object that represents the pixel color
*/
public Color getColor()
{
/* get the value at the location from the picture as a 32 bit int
* with alpha, red, green, blue each taking 8 bits from left to right
*/
int value = picture.getBasicPixel(x,y);
// get the red value (starts at 17 so shift right 16)
// then AND it with all 1's for the first 8 bits to
// end up with a resulting value from 0 to 255
int red = (value >> 16) & 0xff;
// get the green value (starts at 9 so shift right 8)
int green = (value >> 8) & 0xff;
// get the blue value (starts at 0 so no shift required)
int blue = value & 0xff;
return new Color(red,green,blue);
}
/**
* Method to set the pixel color to the passed in color object.
* @param newColor the new color to use
*/
public void setColor(Color newColor)
{
// set the red, green, and blue values
int red = newColor.getRed();
int green = newColor.getGreen();
int blue = newColor.getBlue();
// update the associated picture
updatePicture(this.getAlpha(),red,green,blue);
}
/**
* Method to update the picture based on the passed color
* values for this pixel
* @param alpha the alpha (transparency) at this pixel
* @param red the red value for the color at this pixel
* @param green the green value for the color at this pixel
* @param blue the blue value for the color at this pixel
*/
public void updatePicture(int alpha, int red, int green, int blue)
{
// create a 32 bit int with alpha, red, green blue from left to right
int value = (alpha << 24) + (red << 16) + (green << 8) + blue;
// update the picture with the int value
picture.setBasicPixel(x,y,value);
}
/**
* Method to correct a color value to be within 0 to 255
* @param the value to use
* @return a value within 0 to 255
*/
private static int correctValue(int value)
{
if (value < 0)
value = 0;
if (value > 255)
value = 255;
return value;
}
/**
* Method to set the red to a new red value
* @param value the new value to use
*/
public void setRed(int value)
{
// set the red value to the corrected value
int red = correctValue(value);
// update the pixel value in the picture
updatePicture(getAlpha(), red, getGreen(), getBlue());
}
/**
* Method to set the green to a new green value
* @param value the value to use
*/
public void setGreen(int value)
{
// set the green value to the corrected value
int green = correctValue(value);
// update the pixel value in the picture
updatePicture(getAlpha(), getRed(), green, getBlue());
}
/**
* Method to set the blue to a new blue value
* @param value the new value to use
*/
public void setBlue(int value)
{
// set the blue value to the corrected value
int blue = correctValue(value);
// update the pixel value in the picture
updatePicture(getAlpha(), getRed(), getGreen(), blue);
}
/**
* Method to set the alpha (transparency) to a new alpha value
* @param value the new value to use
*/
public void setAlpha(int value)
{
// make sure that the alpha is from 0 to 255
int alpha = correctValue(value);
// update the associated picture
updatePicture(alpha, getRed(), getGreen(), getBlue());
}
/**
* Method to get the distance between this pixel's color and the passed color
* @param testColor the color to compare to
* @return the distance between this pixel's color and the passed color
*/
public double colorDistance(Color testColor)
{
double redDistance = this.getRed() - testColor.getRed();
double greenDistance = this.getGreen() - testColor.getGreen();
double blueDistance = this.getBlue() - testColor.getBlue();
double distance = Math.sqrt(redDistance * redDistance +
greenDistance * greenDistance +
blueDistance * blueDistance);
return distance;
}
/**
* Method to compute the color distances between two color objects
* @param color1 a color object
* @param color2 a color object
* @return the distance between the two colors
*/
public static double colorDistance(Color color1,Color color2)
{
double redDistance = color1.getRed() - color2.getRed();
double greenDistance = color1.getGreen() - color2.getGreen();
double blueDistance = color1.getBlue() - color2.getBlue();
double distance = Math.sqrt(redDistance * redDistance +
greenDistance * greenDistance +
blueDistance * blueDistance);
return distance;
}
/**
* Method to get the average of the colors of this pixel
* @return the average of the red, green, and blue values
*/
public double getAverage()
{
double average = (getRed() + getGreen() + getBlue()) / 3.0;
return average;
}
/**
* Method to return a string with information about this pixel
* @return a string with information about this pixel
*/
public String toString()
{
return "Pixel row=" + getRow() +
" col=" + getCol() +
" red=" + getRed() +
" green=" + getGreen() +
" blue=" + getBlue();
}
}
| SunnyHillsHighSchool/picture-class-rpaik4204 | Pixel.java | 2,840 | // get the alpha value (starts at 25 so shift right 24)
| line_comment | en | false | 2,890 | 19 | 2,840 | 19 | 3,384 | 18 | 2,840 | 19 | 3,454 | 18 | false | false | false | false | false | true |
114580_0 | /**
* The Calculator class in Java performs basic arithmetic operations such as addition, subtraction,
* multiplication, and division.
*/
class Calculator{
float addition(float operand_1,float operand_2){
return(operand_1+operand_2);
}
float substraction(float operand_1,float operand_2){
return(operand_1-operand_2);
}
float multiplication(float operand_1,float operand_2){
return(operand_1*operand_2);
}
float division(float operand_1,float operand_2){
return(operand_1/operand_2);
}
public static void main(String[]args){
Calculator calc=new Calculator();
float operand_1=10;
float operand_2=10;
float add_result=calc.addition(operand_1,operand_2);
System.out.println("result:"+add_result);
float sub_result=calc.substraction(operand_1,operand_2);
System.out.println("result:"+sub_result);
float mult_result=calc.multiplication(operand_1,operand_2);
System.out.println("result:"+mult_result);
float div_result=calc.division(operand_1,operand_2);
System.out.println("result:"+div_result);
}
}
| 01fe22bca153/Calculator | Calci.java | 311 | /**
* The Calculator class in Java performs basic arithmetic operations such as addition, subtraction,
* multiplication, and division.
*/ | block_comment | en | false | 267 | 24 | 311 | 28 | 327 | 27 | 311 | 28 | 369 | 30 | false | false | false | false | false | true |
116517_0 | import javax.swing.JFrame;
/**
This program displays the growth of an investment.
*/
public class InvestmentViewer3
{
public static void main(String[] args)
{
JFrame frame = new InvestmentFrame3();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
}
}
| noahlattari/Java-Appointment-Calendar | src/InvestmentViewer3.java | 84 | /**
This program displays the growth of an investment.
*/ | block_comment | en | false | 64 | 13 | 84 | 14 | 86 | 15 | 84 | 14 | 102 | 16 | false | false | false | false | false | true |
118798_0 | package mediaRentalManager;
/*
* The Album class represents an album in the media database
* The Album class extends the Media class, as it is a type of media
* In addition to a title and number of copies inherited from the Media
* class, an album also has an artist and a list of songs
*/
public class Album extends Media {
private String artist;
private String songs;
public Album(String title, int copiesAvailable, String artist,
String songs) {
super(title, copiesAvailable);
this.artist = artist;
this.songs = songs;
}
public String getArtist() {
return artist;
}
public String getSongs() {
return songs;
}
public String toString() {
return "Title: " + title + ", Copies Available: " +
copiesAvailable + ", Artist: " + artist + ", Songs: "
+ songs;
}
}
| probably-coding/media-rental-manager | Album.java | 224 | /*
* The Album class represents an album in the media database
* The Album class extends the Media class, as it is a type of media
* In addition to a title and number of copies inherited from the Media
* class, an album also has an artist and a list of songs
*/ | block_comment | en | false | 190 | 61 | 224 | 62 | 221 | 63 | 224 | 62 | 257 | 63 | false | false | false | false | false | true |
119135_0 | import krister.Ess.*;
import processing.core.*;
/*
WSound Class
_________________________________
Extends the Ess library by providing
more simple functions to deal with
sound :
* Remove Silence using a threshold
* Add Silence
* Draw a sound wave
* Normalize a sound ( change volume)
* Concatenate two sounds
* Save a sound to a file
*/
public class WSound {
private AudioChannel channel;
private PApplet p;
private String file;
// Constructor to create a WSound out of a file name
public WSound(String file, PApplet p) {
Ess.start(p);
this.p=p;
this.file=file;
this.channel=new AudioChannel(file);
}
// Constructor to create an empty WSound of size size
public WSound(int size, PApplet p) {
Ess.start(p);
this.p=p;
this.channel=new AudioChannel(size);
}
// Constructor to create a WSound out of another WSound
public WSound(WSound sound, PApplet p) {
Ess.start(p);
this.p=p;
this.channel=new AudioChannel(sound.channel.size,sound.channel.sampleRate);
p.arrayCopy(sound.channel.samples, this.channel.samples);
}
public void play() {
if(channel.size!=0)
channel.play();
}
public void playLoop() {
if(channel.size!=0)
channel.play(Ess.FOREVER);
}
// Saves the sound to a file
public void save(String filename) {
if(channel.size!=0)
channel.saveSound(filename);
}
public float maxAmplitude(){
return maximumAbs(channel.samples);
}
// Finds the maximum ( or absolute minimum whichever is bigger) of array values
public float maximumAbs(float [] array){
float maximum=array[0];
for ( int i=1; i<array.length; i++) {
if(p.abs(array[i])>maximum)
maximum=p.abs(array[i]);
}
return maximum;
}
// Finds the position of the first value above a threshold
private int findfirst(float[] array, float threshold) {
for(int i=0; i<array.length; i++)
if(p.abs(array[i])>threshold)
return i;
return 0;
}
// Finds the position of the last value above a threshold
private int findlast(float[] array, float threshold) {
for(int i=0; i<array.length; i++)
if(p.abs(array[array.length-i-1])>threshold)
return i;
return 0;
}
// Draws the wave
public void draw(int x, int y, int w, int h, int c) {
p.stroke(c);
float scale_x=w/((float)(channel.samples.length-1)); //width of the canvas divided by number of data points gives the horizontal scale
float scale_y=h/2; //height of the canvas divided by vertical range gives the vertical scale
for(int i=0; i<channel.size-1; i+=p.floor((float)p.width/w)) {
// y+h is y position of the bottom edge of the canvas, we're drawing in reverse
p.line(i*scale_x+x, (y+h)-(channel.samples[i]+1)*scale_y, (i+1)*scale_x+x, (y+h)-(channel.samples[i+1]+1)*scale_y);
}
}
// Elevates all amplitudes to a value proportional to the maximum given
public void normalize(float maximum) {
if (maximum<0 || maximum >1) {
maximum=1;
p.println("Maximum level out of bounds, setting to 1");
}
//Multiplier is the intensity divided by the maximum or the minimum whichever is bigger
float multiplier=maximum/maxAmplitude();
for (int i=0; i<channel.size; i++ ) {
channel.samples[i]*=multiplier;
}
}
// Removes silence (silence is all sound of amplitude lower than the given threshold)
public void trim(float threshold) {
if(threshold>0 && threshold < maxAmplitude()) {
// adjustChannel adds and removes samples to the sound
channel.adjustChannel(-findfirst(channel.samples, threshold),Ess.BEGINNING);
channel.adjustChannel(-findlast(channel.samples, threshold),Ess.END);
} else {
p.println("Threshold is larger than the maximum amplitude");
channel.initChannel(1);
}
}
// Adds a silence of duration time at the beginning or the end
public void addSilence(float time, boolean beginning) {
int framestoadd=(int)(time*channel.sampleRate); // calculate number of samples to add
float[] newsamples= new float[channel.size+framestoadd]; // create the new sound with added size
for(int i=0; i<channel.size+framestoadd; i++) {
// loop through the old sound and either add empty frames at the beginning or at the end
if(beginning) {
if(i>framestoadd) {
newsamples[i]=channel.samples[i-framestoadd];
} else {
newsamples[i]=0;
}
} else {
if(i>channel.size-1) {
newsamples[i]=0;
} else {
newsamples[i]=channel.samples[i];
}
}
}
channel.initChannel(channel.size+framestoadd);
channel.samples=newsamples;
}
//Concatenate two WSounds
public WSound concat(WSound sound2) {
WSound result=new WSound(channel.size+sound2.channel.size, p); //Create a new WSound with size equal to the sum of both sizes
// concatenate the first samples array with the second one and put them in the new WSound's samples array
// could've looped through the result samples array and added both arrays one sample at a time but the "concat" function is way cleaner
result.channel.samples=p.concat(channel.samples, sound2.channel.samples);
result.channel.sampleRate(sound2.channel.sampleRate);
return result;
}
public int getDuration() {
return channel.duration;
}
public String getFileName() {
return file;
}
public boolean getState() {
return channel.state==Ess.PLAYING;
}
} | wassgha/AudioEditorProcessing | WSound.java | 1,529 | /*
WSound Class
_________________________________
Extends the Ess library by providing
more simple functions to deal with
sound :
* Remove Silence using a threshold
* Add Silence
* Draw a sound wave
* Normalize a sound ( change volume)
* Concatenate two sounds
* Save a sound to a file
*/ | block_comment | en | false | 1,391 | 79 | 1,529 | 75 | 1,695 | 88 | 1,529 | 75 | 1,772 | 93 | false | false | false | false | false | true |
119482_0 |
/**
* Ask the user to choose a phone from the list of at least 5 phones. You must use one switch-case and one conditional statement.
* Name of the phone they are purchasing:
* State where the product is shipped:
*
* Sarah Poravanthattil
* 3/21/22
*/
import java.util.Scanner;
public class PhoneSales
{
public static void main(String[]args){
System.out.println("List of phones: iPhone 6, iPhone 7, iPhone 8, iPhone XR, iPhone 13");
Scanner input = new Scanner(System.in);
System.out.println("Choose one of the options above: ");
String phone = input.nextLine();
System.out.println("What state are you shipping to?(New Jersey;Deleware;Pennsylvania): ");
String state = input.nextLine();
double phonecost = 0;
double tax = 0;
if(phone.equals("iPhone 6")){
phonecost = 199.99;
}
if (phone.equals("iPhone 7")){
phonecost = 499.99;
}
if (phone.equals("iPhone 8")){
phonecost = 599.99;
}
if (phone.equals("iPhone XR")){
phonecost = 749.99;
}
if (phone.equals("iPhone 13")){
phonecost = 899.99;
}
switch(state){
case "New Jersey":
tax = phonecost * 1.06625;
break;
case "Pennsylvania":
tax = phonecost * 1.03;
break;
case "Deleware":
tax = phonecost;
break;
default:
tax = phonecost * 1.075;
}
System.out.println("You bought the " + phone + " and it will be shipped to " + state +".");
System.out.printf("The total cost = $ %.2f%n", tax);
}
}
| mohithn04/APCompSci | PhoneSales.java | 494 | /**
* Ask the user to choose a phone from the list of at least 5 phones. You must use one switch-case and one conditional statement.
* Name of the phone they are purchasing:
* State where the product is shipped:
*
* Sarah Poravanthattil
* 3/21/22
*/ | block_comment | en | false | 437 | 67 | 494 | 76 | 512 | 74 | 494 | 76 | 557 | 82 | false | false | false | false | false | true |
121252_0 |
import java.util.*;
class bubbleSort{
public static void main(String[] args){
int[] arr = {9,8,7,6,5,4,3,2,1};
int n = arr.length;
int tmp;
/*
This sorting algorithm is the simplest sorting algorithm that works by repeatedly
swapping the adjacent elements if they are in the wrong order.
If we have total N elements, then we need to repeat the above process for N-1 times.
We can use Bubble Sort as per below constraints :
It works well with large datasets where the items are almost sorted because it
takes only one iteration to detect whether the list is sorted or not.
But if the list is unsorted to a large extend
then this algorithm holds good for small datasets or lists.
This algorithm is fastest on an extremely small or nearly sorted set of data.
***Worst and Average Case Time Complexity: O(n*n). Worst case occurs when array is reverse sorted.
Best Case Time Complexity: O(n). Best case occurs when array is already sorted.
Auxiliary Space: O(1)
Boundary Cases: Bubble sort takes minimum time (Order of n) when elements are already sorted.
Sorting In Place: Yes
Stable: Yes****(IMP)
*/
for(int i=0;i<n;i++){
for(int j=0;j<n;j++){
if(arr[i]<arr[j]){
tmp = arr[i];
arr[i] = arr[j];
arr[j] = tmp;
}
}
}
for(int i=0;i<n;i++){
System.out.print(arr[i]);
}
}
}
| TusharKukra/Hacktoberfest2021-EXCLUDED | bubblesort.java | 393 | /*
This sorting algorithm is the simplest sorting algorithm that works by repeatedly
swapping the adjacent elements if they are in the wrong order.
If we have total N elements, then we need to repeat the above process for N-1 times.
We can use Bubble Sort as per below constraints :
It works well with large datasets where the items are almost sorted because it
takes only one iteration to detect whether the list is sorted or not.
But if the list is unsorted to a large extend
then this algorithm holds good for small datasets or lists.
This algorithm is fastest on an extremely small or nearly sorted set of data.
***Worst and Average Case Time Complexity: O(n*n). Worst case occurs when array is reverse sorted.
Best Case Time Complexity: O(n). Best case occurs when array is already sorted.
Auxiliary Space: O(1)
Boundary Cases: Bubble sort takes minimum time (Order of n) when elements are already sorted.
Sorting In Place: Yes
Stable: Yes****(IMP)
*/ | block_comment | en | false | 350 | 219 | 393 | 233 | 412 | 234 | 393 | 233 | 437 | 252 | true | true | true | true | true | false |
121456_7 | import sun.reflect.generics.reflectiveObjects.NotImplementedException;
import java.util.ArrayList;
public class Main {
public static void main(String[] args) {
// Use main to run and test the below functions
}
/**
* Puts the elements in the arrayList in sorted order from smallest to greatest.
* This function uses selection sort to sort the arrayList.
* @param arrayList the ArrayList to be sorted. arrayList cannot contain duplicates
*/
public static void selectionSort(ArrayList<Integer> arrayList) {
throw new UnsupportedOperationException("SelectionSort() has not been implemented yet");
}
/**
* Returns the index that value is located in the arrayList. This function searches linearly in
* the arrayList to find the value.
* @param arrayList the ArrayList containing the list of values to search. arrayList cannot contain duplicates
* @param value the value we are looking for in the array list
*/
public static int linearSearch(ArrayList<Integer> arrayList, int value) {
throw new UnsupportedOperationException("LinearSearch() has not been implemented yet");
}
/**
* Returns the index that value is located in the arrayList. This function uses binary search in
* the arrayList to find the value.
* @param arrayList the ArrayList containing the list of values to search. THIS ARRAYLIST MUST BE
* IN SORTED ORDER. arrayList cannot contain duplicates
* @param value the value we are looking for in the array list
*/
public static int binarySearch(ArrayList<Integer> arrayList, int value) {
throw new UnsupportedOperationException("LinearSearch() has not been implemented yet");
}
/**
* Puts the elements in the arrayList in sorted order from smallest to greatest.
* This function uses MergeSort to sort the arrayList.
* @param arrayList the ArrayList to be sorted. arrayList cannot contain duplicates
*/
public static void mergeSort(ArrayList<Integer> arrayList) {
}
/**
* This function is a helper function used to help you implement mergeSort.
* The function sorts the portion of arrayList specified by the range [lo, hi). The range
* includes lo but excludes hi (arrayList[lo] is the first element in the range, but
* arrayList[hi] is the first element after the last element in the range).
* @param arrayList the ArrayList to be sorted.
* @param lo the index of the first element in the range
* @param hi the index of the last element in the range + 1.
*/
public static void sort(ArrayList<Integer> arrayList, int lo, int hi) {
//arrayList.merge();
}
/**
* This function is a helper function used to help you implement mergeSort.
* The function merges two consecutive, sorted ranges in the arrayList into one sorted range. The ranges
* are specified as [lo, mid) and [mid, hi). Each range includes the first element, but excludes
* the last element (the same way as in sort()).
* @param arrayList the ArrayList to be sorted.
* @param lo the index of the first element in the first range
* @param mid the boundary point of the two ranges. arrayList[mid] is in the second range.
* @param hi the index of the last element in the second range + 1.
*/
public static void merge(ArrayList<Integer> arrayList, int lo, int mid, int hi) {
ArrayList<Integer> newArray = new ArrayList<Integer>();
int x = lo;
int y = mid;
int z = hi;
}
}
| HolyNamesAcademy/unit7-mergesort-laurenmiller00 | src/Main.java | 793 | /**
* This function is a helper function used to help you implement mergeSort.
* The function merges two consecutive, sorted ranges in the arrayList into one sorted range. The ranges
* are specified as [lo, mid) and [mid, hi). Each range includes the first element, but excludes
* the last element (the same way as in sort()).
* @param arrayList the ArrayList to be sorted.
* @param lo the index of the first element in the first range
* @param mid the boundary point of the two ranges. arrayList[mid] is in the second range.
* @param hi the index of the last element in the second range + 1.
*/ | block_comment | en | false | 751 | 148 | 793 | 150 | 824 | 154 | 793 | 150 | 886 | 159 | false | false | false | false | false | true |
122489_24 | package utils;
import java.awt.FontMetrics;
import java.awt.Graphics2D;
import java.awt.HeadlessException;
import java.awt.Image;
import java.awt.Toolkit;
import java.awt.datatransfer.DataFlavor;
import java.awt.datatransfer.UnsupportedFlavorException;
import java.awt.geom.AffineTransform;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.ObjectOutputStream;
import java.io.Serializable;
import javax.sound.sampled.Clip;
import javax.sound.sampled.FloatControl;
import engine.Resources;
/**
* Useful utility functions
*/
public class Utils {
/**
* This method makes it easier to draw images centered with rotation and
* scale
*
* @param filename
* name of image file
* @param x
* CENTER x coord
* @param y
* CENTER y coord
* @param rot
* rotation in radians
*/
public static void drawImage(Graphics2D g, String filename, double x,
double y, double rot, double scale) {
Image img = Resources.getImage(filename);
int xs = img.getWidth(null), ys = img.getHeight(null);
// rotation stuff
AffineTransform prevTransform = g.getTransform();
g.translate(x, y);
g.rotate(rot);
g.scale(scale, scale);
// draw the image
g.drawImage(img, (int) -xs / 2, (int) -ys / 2, null);
g.setTransform(prevTransform);
}
/**
* This method makes it easier to draw a rect with rotation and scale
*
* @param x
* CENTER x coord
* @param y
* CENTER y coord
* @param rot
* rotation in radians
*/
public static void fillRect(Graphics2D g, double x, double y, double xs,
double ys, double rot, double scale) {
// rotation stuff
AffineTransform prevTransform = g.getTransform();
g.translate(x, y);
g.rotate(rot);
g.scale(scale, scale);
// fill the rect
g.fillRect((int) -xs / 2, (int) -ys / 2, (int) xs, (int) ys);
g.setTransform(prevTransform);
}
/**
* @return A random value between min and max
*/
public static double randomRange(double min, double max) {
return Math.random() * (max - min) + min;
}
/**
* @return A random value >= min and < max (does not include max
*/
public static int randomRangeInt(int min, int max) {
return (int) Math.floor(randomRange(min, max));
}
/**
* @return The value clamped to the range min to max
*/
public static double clamp(double val, double min, double max) {
return Math.max(Math.min(val, max), min);
}
// /**
// * @return True if the rect (x, y, xs, ys) collides with the rect (x2, y2,
// * xs2, ys2). (x, y) is the top left
// */
// public static boolean rectsCollide(double x, double y, double xs,
// double ys, double x2, double y2, double xs2, double ys2) {
// return (x + xs > x2) && (x < x2 + xs2)
// && (y + ys > y2) && (y < y2 + ys2);
// }
/**
* @return whether the point is inside the rect defined by rx, ry, rw, rh.
* (rx, ry) is the top left corner.
*/
public static boolean pointInRect(double x, double y, double rx, double ry,
double rw,double rh){
return (x >= rx && y >= ry && x <= rx + rw && y <= ry + rh);
}
/**
* Linear interpolate between two values.
* @param t Value between 0 and 1
*/
public static double lerp(double a, double b, double t) {
t = Math.min(t, 1);
return (1 - t) * a + t * b;
}
// Utils.log, Utils.err, and Utils.fatal will pass their string arg
// to these observers when used
public static Observer logObserver = null;
public static Observer errObserver = null;
public static Observer fatalObserver = null;
public static void log(String msg){
System.out.println(msg);
if(logObserver != null)
logObserver.notify(msg);
}
/**
* Log a fatal error and quit
*/
public static void fatal(String msg){
String errMsg = "Fatal error: " + msg;
System.err.println(errMsg);
if(errObserver != null)
errObserver.notify(errMsg);
if(fatalObserver != null){
fatalObserver.notify(null);
} else {
System.exit(1);
}
}
public static void err(String msg){
String errMsg = "Error: " + msg;
System.err.println(errMsg);
if(errObserver != null)
errObserver.notify(errMsg);
}
/**
* Do a mod operation that doesn't return negative values
*/
public static double mod(double a, double b){
return (a % b + b) % b;
}
/**
* Draw the string centered, instead of left justified
*/
public static void drawStringCentered(Graphics2D g, String s, int x, int y){
FontMetrics fm = g.getFontMetrics();
int w = fm.stringWidth(s);
int h = fm.getHeight();
g.drawString(s, x - w/2, y + h/3);
}
/**
* Set the volume of the audio clip
*/
public static void setClipVolume(Clip c, double volume){
FloatControl vol = (FloatControl) c.getControl(FloatControl.Type.MASTER_GAIN);
vol.setValue((float)volume);
}
/**
* Calculate the size of the object after being serialized
*/
public static int calcNetworkSize(Serializable o) {
try {
ByteArrayOutputStream byteOutputStream = new ByteArrayOutputStream();
ObjectOutputStream objectOutputStream = new ObjectOutputStream(
byteOutputStream);
objectOutputStream.writeObject(o);
objectOutputStream.flush();
objectOutputStream.close();
return byteOutputStream.toByteArray().length;
} catch (IOException e) {
Utils.err("Couldn't calculate object size");
return 0;
}
}
/**
* Pack a double into a byte. This is useful for sending doubles over the network when
* you don't need 64 bits of precision. You must supply a min and max value of the double,
* so that it can be packed into a smaller space.
* @return A byte representing the double's location between min and max, packed in the
* lower 'nBits' bits of the byte.
*/
public static byte packRange(double val, double min, double max, int nBits){
if(val < min || val > max){
Utils.err("Couldn't pack byte, value was outside of range! Fix immediately");
return 0;
}
double ratio = (val - min)/(max - min);
int maxBitVal = (int)Math.pow(2, nBits)-1;
byte ret = (byte)Math.round(ratio * maxBitVal);
return ret;
}
/**
* Unpack a double that has been packed using 'packRange'. Note that precision is
* lost when packing and unpacking, so if you packed 0, for example, don't expect
* this method to return exactly 0 when unpacked.
*/
public static double unpackRange(byte val, double min, double max, int nBits){
int maxBitVal = (int)Math.pow(2, nBits)-1;
int vali = val & 0xFF;
double ratio = (double)vali/maxBitVal;
double ret = ratio * (max-min) + min;
return ret;
}
/**
* Pack and unpack a double, then return it. Lets you see how much precision
* is lost when packing/unpacking the value.
*/
public static double testCompression(double val, double min, double max, int nBits){
return unpackRange(packRange(val, min, max, nBits), min, max, nBits);
}
/**
* Smallest difference between 2 angles (in degrees).
*/
public static double angleDifference(double a, double b){
return Utils.mod((b-a) + 180, 360) - 180;
}
/**
* @return the text in the clipboard, or null if couldn't get it.
*/
public static String readClipboard(){
String str = null;
try {
str = (String) Toolkit.getDefaultToolkit()
.getSystemClipboard().getData(DataFlavor.stringFlavor);
} catch (HeadlessException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (UnsupportedFlavorException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return str;
}
}
| m15399/GameDevGame | src/utils/Utils.java | 2,335 | /**
* Do a mod operation that doesn't return negative values
*/ | block_comment | en | false | 2,064 | 16 | 2,335 | 15 | 2,424 | 18 | 2,335 | 15 | 2,727 | 18 | false | false | false | false | false | true |
126555_6 | import java.io.FileWriter;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.Arrays;
/**
*
* @author Arezoo Vejdanparast <[email protected]> & Ali Karami <[email protected]>
*/
public class OneHopOptimal {
private ArrayList<Camera> cameras;
private ArrayList<Object> objects;
private Double[] zooms;
private int steps;
private Double threshold;
private String outputPath;
private int[] step0CamConfig;
private int tempMinK; //for internal use with recursive function
private int[] tempCamConfig; //for internal use with recursive function
/**
* Constructor
* @param settings An instance of Settings class that contains all scenario settings.
* @param steps Number of time steps the simulation will run for.
* @param threshold The selected confidence threshold to determine whether an object
* is detectable or not.
* @param outputPath The path to output folder.
*/
public OneHopOptimal(Settings settings, int steps, Double threshold, String outputPath) {
System.out.println("Running Optimal algorithm ....\n");
this.cameras = settings.cameras;
this.objects = settings.objects;
this.zooms = this.cameras.get(0).zooms;
this.steps = steps;
this.threshold = threshold;
this.outputPath = outputPath;
this.step0CamConfig = new int[cameras.size()];
Arrays.fill(step0CamConfig, 0);
run();
}
/**
* Runs the optimal algorithm simulation
*/
private void run() {
int[] minKCover = new int[steps];
int[] z = new int[cameras.size()];
for (int n=0 ; n<cameras.size() ; n++)
z[n] = -1;
for (int step=0 ; step<steps ; step++) {
tempMinK = 0;
tempCamConfig = new int[cameras.size()];
System.out.print("step "+step+" .... ");
computeMinKCover(cameras.size(), new int[cameras.size()], z);
z = tempCamConfig.clone();
minKCover[step] = tempMinK;
if (step==0)
step0CamConfig = tempCamConfig.clone();
updateObjects();
System.out.println("COMPLETE");
}
long tableCount = (long)Math.pow(zooms.length, cameras.size());
System.out.println("Table Count = "+tableCount+"\n");
exportResult(minKCover);
}
/**
* Computes the minimum k-covers for a given step by finding the table with maximum min k and
* saves the value in a global variable (tempMinK) to be used in run().
* @param size The number of cameras in each (recursive) run.
* @param zoomList An (initially empty) auxiliary list for keeping the configuration indexes.
* @param step The current time step.
*/
private void computeMinKCover(int size, int[] zoomList, int[] zIndex) {
if (size==0) {
int tableResult = getMinK(zoomList);
if (tableResult > tempMinK) {
tempMinK = tableResult;
tempCamConfig = zoomList.clone();
}
}
else {
if (zIndex[0]==-1) {
for (int z=0 ; z<zooms.length ; z++) {
zoomList[size-1] = z;
computeMinKCover(size-1, zoomList, zIndex);
}
}
else {
for (int z=0 ; z<zooms.length ; z++) {
if (Math.abs(z-zIndex[size-1])<2) {
zoomList[size-1] = z;
computeMinKCover(size-1, zoomList, zIndex);
}
}
}
}
}
/**
* Returns the minimum number of cameras that detect each object.
* @param zoomList List of selected cameras' zoom indexes.
* @return the k value of k-cover with a specific (given) camera configuration.
*/
private int getMinK(int[] zoomList) {
int[] objCover = new int[objects.size()];
for (int n=0 ; n<cameras.size() ; n++) {
int z = zoomList[n];
for (int m=0 ; m<objects.size() ; m++) {
if (isDetectable(m, n, z))
objCover[m]++;
}
}
return minimum(objCover);
}
/**
* Checked whether an object is detectable by a camera with a specified zoom (FOV).
* @param m The index of the object in the list of objects
* @param n The index of the camera in the list of cameras
* @param z The index of the zoom level in the list of zoom values
* @return True if the object is within FOV (zoom range) AND the camera can see it
* with a confidence above threshold. False otherwise.
*/
private boolean isDetectable(int m, int n, int z) {
Double distance = Math.sqrt(Math.pow((cameras.get(n).x-objects.get(m).x), 2) + Math.pow((cameras.get(n).y-objects.get(m).y), 2));
if (distance > cameras.get(n).zooms[z])
return false;
else {
double b = 15;
Double conf = 0.95 * (b / (cameras.get(n).zooms[z] * distance)) - 0.15;
return (conf >= threshold);
}
}
/**
* Returns the minimum value of a list of integers < 10000.
* @param list The list of integer
* @return The minimum integer value in the list
*/
private static int minimum(int[] list) {
int min = 10000;
for (int i : list){
if (i < min)
min = i;
}
return min;
}
/**
* Updates all objects one time step.
*/
private void updateObjects() {
for (Object obj : objects)
obj.update();
}
/**
* Writes the result to '*-oneHopOptimal.csv' file.
* @param minKCover The array of minimum k-cover values
*/
private void exportResult(int[] minKCover) {
FileWriter outFile;
try {
outFile = new FileWriter(outputPath+"-oneHopOptimal.csv");
PrintWriter out = new PrintWriter(outFile);
out.println("1-hop optimal");
for (int k : minKCover)
out.println(k);
out.close();
} catch (IOException e) {
e.printStackTrace();
}
}
/**
* Gives read access to the camera configurations that is selected in step 0 of the runtime
* @return A list camera configurations that is optimised for step 0
*/
public int[] getStep0CamConfig() {
return step0CamConfig;
}
}
| alijy/CamSimLite | src/OneHopOptimal.java | 1,783 | /**
* Returns the minimum number of cameras that detect each object.
* @param zoomList List of selected cameras' zoom indexes.
* @return the k value of k-cover with a specific (given) camera configuration.
*/ | block_comment | en | false | 1,579 | 49 | 1,781 | 50 | 1,842 | 54 | 1,783 | 50 | 2,117 | 57 | false | false | false | false | false | true |
127308_3 |
import java.util.ArrayList;
import java.util.Random;
import javax.swing.JOptionPane;
public class Card {
// define data members
private int card_val;
private String suit;
private static int[] num = new int[]{1,2,3,4,5,6,7,8,9,10,11,12,13};
private static String[] suits = new String[]{"spades", "clubs", "hearts","diamonds"};
//default constructor
public Card () {
// initialization
card_val = 0;
suit = "";
}
//Assume one of the suits from {"spades", "clubs", "hearts","diamonds"} will be passed in, not some random string
public Card (int card_val, String suit)
{
this.card_val = card_val;
this.suit = suit;
}
public static void buildDeck(ArrayList<Card> deck) {
// Given an empty deck, construct a standard deck of playing cards
deck.clear(); // clear deck so that when rebuilding the deck, it won't use the deck that remains
//build a 52-card deck, 1-Ace, 11-Jack, 12-Queen, 13-King
for(int i = 0;i < num.length;i++)
{
for(int j = 0;j < suits.length;j++)
{
Card c1 = new Card(num[i],suits[j]); //calling the 2-parameter constructor
deck.add(c1);
}
}
}
public static void initialDeal(ArrayList<Card> deck, ArrayList<Card> playerHand, ArrayList<Card> dealerHand){
// Deal two cards from the deck into each of the player's hand and dealer's hand
//rebuild the deck, or renew the deck, every time a new round starts. so the size of deck is always 52 at the beginning of each round
buildDeck(deck);
//System.out.println(deck.size());
//clear both hands to make sure the hands from last round don't carry on to the new round
playerHand.clear();
dealerHand.clear();
//check if the deck indeed has at least 4 cards to complete the initial deal.
if(deck.size() >= 4)
{
Random rand = new Random();
//no need to use for loops since we're only drawing 2 cards for each side
playerHand.add(deck.remove(rand.nextInt(deck.size()))); //each card is drawn from a random index
playerHand.add(deck.remove(rand.nextInt(deck.size())));
dealerHand.add(deck.remove(rand.nextInt(deck.size())));
dealerHand.add(deck.remove(rand.nextInt(deck.size())));
}
//output a line instead of crashing the program
else
{
System.out.println("There're fewer than 4 cards in the deck");
}
}
public static void dealOne(ArrayList<Card> deck, ArrayList<Card> hand){
// this should deal a single card from the deck to the hand
//check if the deck indeed has at least 1 card to complete the deal.
if(deck.size() >= 1)
{
Random rand = new Random();
hand.add(deck.remove(rand.nextInt(deck.size()))); //draw card from random index
}
//output a line instead of crashing the program
else
{
System.out.println("There's fewer than 1 card in the deck");
}
}
public static boolean checkBust(ArrayList<Card> hand){
// This should return whether a given hand's value exceeds 21
int total = 0;
for(int i = 0; i < hand.size();i++)
{
if(hand.get(i).card_val > 10)
{
total += 10;
}
else
{
total += hand.get(i).card_val;
/* Because we're checking for bust, it's easier(safer) to always
treat Ace as 1 */
}
}
if(total > 21)
{
return true;
}
else{
return false;
}
}
public static boolean dealerTurn(ArrayList<Card> deck, ArrayList<Card> hand){
// This should conduct the dealer's turn and
// Return true if the dealer busts; false otherwise
int total = SumHand(hand);
while(total < 17)
{
dealOne(deck, hand); //draw a card from deck to hand while total is smaller than 17
total = SumHand(hand); //updates total
}
if(total > 21) //bust
{
return true;
}
else{
return false;
}
}
public static int whoWins(ArrayList<Card> playerHand, ArrayList<Card> dealerHand){
// This should return 1 if the player wins and 2 if the dealer wins
if(SumHand(playerHand) <= SumHand(dealerHand)) //compare values for both hands, dealer wins even when they tie
{
return 2;
}
else
{
return 1;
}
}
public static String displayCard(ArrayList<Card> hand){
// Return a string describing the card which has index 1 in the hand
if(hand.get(1).card_val == 1) //1->Ace
{
return "Ace " + "of " + hand.get(1).suit;
}
else if(hand.get(1).card_val == 11) //11->Jack
{
return "Jack " + "of " + hand.get(1).suit;
}
else if(hand.get(1).card_val == 12) //12-->Queen
{
return "Queen " + "of " + hand.get(1).suit;
}
else if(hand.get(1).card_val == 13) //13->King
{
return "King " + "of " + hand.get(1).suit;
}
else //ok to use original numbers to represent value of card
{
return hand.get(1).card_val + " of " + hand.get(1).suit;
}
}
public static String displayHand(ArrayList<Card> hand){
// Return a string listing the cards in the hand
String result = "|"; //to seperate each card with "|"
for(int i = 0; i < hand.size();i++)
{
if(hand.get(i).card_val == 1)
{
result += "Ace of " + hand.get(i).suit + "|"; //1->Ace
}
else if(hand.get(i).card_val == 11)
{
result += "Jack of " + hand.get(i).suit + "|"; //11->Jack
}
else if(hand.get(i).card_val == 12)
{
result += "Queen of " + hand.get(i).suit + "|";//12-->Queen
}
else if(hand.get(i).card_val == 13)
{
result += "King of " + hand.get(i).suit + "|"; //13->King
}
else
{
result += hand.get(i).card_val + " of " + hand.get(i).suit + "|";
}
}
return result;
}
public static int SumHand(ArrayList<Card> hand) //added method that computes the sum in hand
{
int values = 0; //total values of cards in hand
int Ace = 0; //number of aces
for(int i = 0; i < hand.size();i++)
{
if(hand.get(i).card_val == 1)
{
values += 1; //use lower bound of ace value
Ace+=1;
}
else if(hand.get(i).card_val > 10)
{
values += 10; //jack, queen, king = 10
}
else
{
values += hand.get(i).card_val;
}
}
while(values<12 && Ace > 0) //make one ace's value 11 if total value doesn't exceed 12
{
values += 10;
Ace -= 1;
}
return values;
}
//override toString() method to display card objects
@Override
public String toString() {
return card_val + " of " + suit;
}
public static void main(String[] args) {
int playerChoice, winner;
ArrayList<Card> deck = new ArrayList<Card> ();
buildDeck(deck);
playerChoice = JOptionPane.showConfirmDialog(null, "Ready to Play Blackjack?", "Blackjack", JOptionPane.OK_CANCEL_OPTION);
if((playerChoice == JOptionPane.CLOSED_OPTION) || (playerChoice == JOptionPane.CANCEL_OPTION))
System.exit(0);
Object[] options = {"Hit","Stand"};
boolean isBusted, dealerBusted;
boolean isPlayerTurn;
ArrayList<Card> playerHand = new ArrayList<>();
ArrayList<Card> dealerHand = new ArrayList<>();
do{ // Game loop
initialDeal(deck, playerHand, dealerHand);
isPlayerTurn=true;
isBusted=false;
dealerBusted=false;
while(isPlayerTurn){
// Shows the hand and prompts player to hit or stand
playerChoice = JOptionPane.showOptionDialog(null,"Dealer shows " + displayCard(dealerHand) + "\n Your hand is: " + displayHand(playerHand) + "\n What do you want to do?","Hit or Stand",
JOptionPane.YES_NO_OPTION,
JOptionPane.QUESTION_MESSAGE,
null,
options,
options[0]);
if(playerChoice == JOptionPane.CLOSED_OPTION)
System.exit(0);
else if(playerChoice == JOptionPane.YES_OPTION){
dealOne(deck, playerHand);
isBusted = checkBust(playerHand);
if(isBusted){
// Case: Player Busts
playerChoice = JOptionPane.showConfirmDialog(null,"Player has busted!", "You lose", JOptionPane.OK_CANCEL_OPTION);
if((playerChoice == JOptionPane.CLOSED_OPTION) || (playerChoice == JOptionPane.CANCEL_OPTION))
System.exit(0);
isPlayerTurn=false;
}
}
else{
isPlayerTurn=false;
}
}
if(!isBusted){ // Continues if player hasn't busted
dealerBusted = dealerTurn(deck, dealerHand);
if(dealerBusted){ // Case: Dealer Busts
playerChoice = JOptionPane.showConfirmDialog(null, "The dealer's hand: " +displayHand(dealerHand) + "\n \n Your hand: " + displayHand(playerHand) + "\nThe dealer busted.\n Congrautions!", "You Win!!!", JOptionPane.OK_CANCEL_OPTION);
if((playerChoice == JOptionPane.CLOSED_OPTION) || (playerChoice == JOptionPane.CANCEL_OPTION))
System.exit(0);
}
else{ //The Dealer did not bust. The winner must be determined
winner = whoWins(playerHand, dealerHand);
if(winner == 1){ //Player Wins
playerChoice = JOptionPane.showConfirmDialog(null, "The dealer's hand: " +displayHand(dealerHand) + "\n \n Your hand: " + displayHand(playerHand) + "\n Congrautions!", "You Win!!!", JOptionPane.OK_CANCEL_OPTION);
if((playerChoice == JOptionPane.CLOSED_OPTION) || (playerChoice == JOptionPane.CANCEL_OPTION))
System.exit(0);
}
else{ //Player Loses
playerChoice = JOptionPane.showConfirmDialog(null, "The dealer's hand: " +displayHand(dealerHand) + "\n \n Your hand: " + displayHand(playerHand) + "\n Better luck next time!", "You lose!!!", JOptionPane.OK_CANCEL_OPTION);
if((playerChoice == JOptionPane.CLOSED_OPTION) || (playerChoice == JOptionPane.CANCEL_OPTION))
System.exit(0);
}
}
}
}while(true);
}
} | rexzhang123/Blackjack | Card.java | 3,099 | //Assume one of the suits from {"spades", "clubs", "hearts","diamonds"} will be passed in, not some random string | line_comment | en | false | 2,722 | 31 | 3,098 | 34 | 3,187 | 28 | 3,099 | 34 | 3,972 | 34 | false | false | false | false | false | true |
128712_8 | package Survey;
import java.io.*;
import java.util.*;
import java.util.stream.Collectors;
public class Survey implements Serializable {
private static final long serialVersionUID = 6529685098267757690L;
protected String currentFile;
protected final String SURVEYFOLDER = "surveyFiles";
protected final String TAKENSURVEYFOLDER = "takenSurveyFiles";
protected ArrayList<Question> questions = new ArrayList<Question>();
protected Output out = new ConsoleOutput();
protected HashMap<Question, Integer> sameResp = new HashMap<>();
//this will used mainly when there is a user input to do all the error checking
protected ConsoleInput input = new ConsoleInput();
/*used this to store object and load objects with ease*/
public Survey(String currentFile, ArrayList<Question> questions) {
this.questions = questions;
this.currentFile = currentFile;
this.createDir();
}
//Empty Constructer
public Survey() {this.createDir();}
public void setQuestion(ArrayList<Question> questions) {
this.questions = questions;
}
public ArrayList<Question> getQuestion() {return this.questions;}
public String getCurrentFile() {return this.currentFile;}
public String returnPath(String dir, String fileName) {
return dir + File.separator + fileName;
}
//creates Directories surveyfolder and takensurveyfolder
private void createDir() {
try {
File dir = new File(this.SURVEYFOLDER);
if (!dir.exists()) {
boolean flag = dir.mkdirs();
}
dir = new File(this.TAKENSURVEYFOLDER);
if(!dir.exists()) {
boolean flag = dir.mkdirs();
}
}catch (Exception e) {
e.printStackTrace();
}
}
//list the files in the directory
public File[] listFiles(String directory) {
try {
File folder = new File(directory);
return folder.listFiles();
}catch (Exception e) {
e.printStackTrace();
}
return null;
}
//checks if the file exist in the directory
public boolean isExist(String directory) {
try {
File file = new File(returnPath(directory, this.currentFile));
return file.exists();
}catch (Exception e) {
e.printStackTrace();
}
return false;
}
//displays all the questions in the survey
public void display() {
for(int i =0; i < this.questions.size();i++) {
out.print("Question " +(i+1) + ". " );
this.questions.get(i).display();
}
}
//displays all the questions and ask the user which question to modify
public int modify() {
int num;
this.display();
do {
num = input.checkNumChoice("Which question number would you like to modify?") - 1;
if (num >= this.questions.size()) {
out.print("Please select in range");
continue;
}
this.questions.get(num).modify();
break;
}while(true);
return num;
}
//simply ask the user for the answer to the related questions and assign it and stores it in response class
// response class would have saved all the responses so it mostly used for tabulation purposes
public void Take(Responses r1) {
for(int i =0; i < this.questions.size();i++) {
out.print("Question " + (i + 1) + ". ");
this.questions.get(i).userResponse();
out.print("");
}
try {
for (Question question : this.questions)
r1.addHashPrompt(question.prompt, question);
}catch (Exception e){
e.printStackTrace();
}
}
//tabulates all the responses
public void Tabulate(Responses r1) {
//first it prints out all the responses per question
for(Map.Entry<String, ArrayList<Question>> entry : r1.storedResp.entrySet()) {
boolean flag = true;
int numSameValue =0;
for(Question q: entry.getValue()) {
numSameValue++;
if(flag) {
q.display();
out.print("Responses:");
flag = false;
}
if(q.type.equals("Matching")) {
char ch = 'A';
for (String s : q.saveResp) {
out.print(ch + ") " + s);
ch++;
}
}else {
for (String s : q.saveResp) {
out.print(s);
}
}
}
out.print("");
}
//counts the same response it and maps it to the question
ArrayList<Integer> savedIndex = new ArrayList<>();
for(Map.Entry<String, ArrayList<Question>> entry: r1.storedResp.entrySet()) {
ArrayList<Question> q = entry.getValue();
Question temp = null;
int count =1;
if(q.size()==1) {
sameResp.put(q.get(0),1);
}else {
for(int i=0; i < q.size(); i++) {
if(savedIndex.contains(i)) {
continue;
}
if(i==q.size()-1) {
if(!savedIndex.contains(i))
sameResp.put(q.get(i),1);
break;
}
for(int j=i+1; j < q.size(); j++) {
temp = q.get(i);
if(!savedIndex.contains(j)) {
if (isRespSame(q.get(i), q.get(j))) {
savedIndex.add(j);
count++;
}
}
}
sameResp.put(temp,count);
count=1;
}
}
savedIndex.clear();
}
out.print("Tabulation");
//used compareTo method in question classes to order it in alphabetical order
HashMap<Question, Integer> result = sameResp.entrySet()
.stream()
.sorted(Map.Entry.comparingByKey())
.collect(Collectors.toMap(
Map.Entry::getKey,
Map.Entry::getValue,
(oldValue, newValue) -> oldValue, LinkedHashMap::new));
String type = null;
String prompt = null;
//prints out the result, which are number of same responses per questions
for(Map.Entry<Question, Integer> entry: result.entrySet()) {
Question key = entry.getKey();
if(!key.type.equals(type)){
key.display();
type = key.type;
prompt = key.prompt;
}else {
if(!key.prompt.equals(prompt)) {
key.display();
type = key.type;
prompt = key.prompt;
}
}
out.print("Number of same Response: " + Integer.toString(entry.getValue()));
for(String s: key.saveResp) {
out.print(s);
}
out.print("");
}
result.clear();
sameResp.clear();
}
//used to count if the response is the same for tabulation
public boolean isRespSame(Question q1, Question q2) {
for(String s: q1.saveResp) {
if(!q2.saveResp.contains(s)) {
return false;
}
}
return true;
}
//load the object by passing all the saved non taken survey files
public Object Load(String directory) {
int fileChoice;
int count = 1;
File[] listFiles = this.listFiles(directory);
if(listFiles==null) {
return null;
}
if(listFiles.length== 0) {
return null;
}
for(File f: listFiles) {
if(f.isFile()) {
out.print(count + ". "+ f.getName());
count++;
}
}
do {
fileChoice = input.checkNumChoice("Which File: ")-1;
if(fileChoice>=listFiles.length)
out.print("Please choose in range");
else
break;
}while (true);
//this will load by using the file user has selected
try {
File file = new File(String.valueOf(listFiles[fileChoice]));
FileInputStream fis = new FileInputStream(file);
ObjectInputStream ois = new ObjectInputStream(fis);
return ois.readObject();
}catch (Exception e) {
out.print("Error Loading the file." + e);
}
return null;
}
//save the file by using this.currentfile
public void Save(Object obj,String directory) {
try {
File file = new File(returnPath(directory,this.currentFile));
FileOutputStream fos = new FileOutputStream(file);
ObjectOutputStream oos = new ObjectOutputStream(fos);
oos.writeObject(obj);
oos.close();
}catch(Exception e) {
out.print("Error Saving file" + e);
}
}
}
| sarthak263/Projects | Survey/Survey.java | 2,048 | //simply ask the user for the answer to the related questions and assign it and stores it in response class
| line_comment | en | false | 1,852 | 23 | 2,048 | 23 | 2,333 | 22 | 2,048 | 23 | 2,523 | 23 | false | false | false | false | false | true |
129597_1 | package com.sarthak.java.b;
public class Human {
public static void main(String[] args) {
System.out.println("hello world");
}
int birthYear;
String name;
long salary;
boolean married;
static int population;
static void info(){
//System.out.println(this.birthYear);
//we cannot use this keyword inside static function because it is references to an object
}
public Human(int year,String name,int salary,boolean married){//this is a constructor
this.birthYear=year;
this.name=name;
this.salary=salary;
this.married=married;
Human.population+=1;
}
}
| SarthakJaiswal001/javaOOps | b/Human.java | 170 | //we cannot use this keyword inside static function because it is references to an object
| line_comment | en | false | 136 | 17 | 170 | 17 | 178 | 17 | 170 | 17 | 190 | 17 | false | false | false | false | false | true |
130114_0 | // 2870. Minimum Number of Operations to Make Array Empty
class Solution {
public int minOperations(int[] nums) {
HashMap<Integer,Integer> map=new HashMap<>();
for(int i : nums){
if(map.containsKey(i)) map.put(i,map.get(i)+1);
else map.put(i,1);
}
List<Integer> ll=new ArrayList<>();
for(int i : map.keySet()){
ll.add(map.get(i));
}
int ans=0;
for(int i=0;i<ll.size();i++){
if(ll.get(i) == 1 ) return -1;
while(ll.get(i)>1){
ans+=1;
if(ll.get(i) % 3 ==0) ll.set(i,ll.get(i)-3);
else ll.set(i,ll.get(i)-2);
}
}
return ans;
}
} | YatinDora81/Leetcode_Ques | 2870.java | 231 | // 2870. Minimum Number of Operations to Make Array Empty | line_comment | en | false | 187 | 15 | 231 | 15 | 257 | 15 | 231 | 15 | 269 | 18 | false | false | false | false | false | true |
130210_9 | package bomberman;
import javax.swing.*;
import java.awt.event.ActionEvent;
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Collection;
import java.util.logging.Level;
import java.util.logging.Logger;
/**
* This is the engine of the Bomberman-game, where everything is initialised. It calls to Menu, which is the initial gameframe,
* when a game is started it instantiates a Floor and a BombermanFrame. It is also home to the timer-methods that create the
* time-aspects of the game, more specifically, the tick-method that can be viewed as the main loop. With ReadWithScanner and
* WriteToFile Engine manages settings-parameters and highscores. This class is never instantiated, which is why it only has
* static methods.
*/
public final class Engine
{
// LOGGER is static because there should only be one logger per class.
private static final Logger LOGGER = Logger.getLogger(Engine.class.getName() );
// Constants are static by definition.
//Default values if file-reading fails.
private static final int TIME_STEP = 30;
private static final int NANO_SECONDS_IN_SECOND = 1000000000;
// The following fields are static since they they are general settings or properties for the game.
private static int width = 5;
private static int height = 5;
private static int nrOfEnemies = 1;
private static long startTime = 0L;
private static long elapsedTime = 0L;
private static Timer clockTimer = null;
private Engine() {}
// Main methods are static by definition.
public static void main(String[] args) {
// Inspector complains on the result of Menu not being used, as well as the main-method of Engine,
// but a frame is opened within it, and that instance is disposed when the user starts a new game.
// It is unnecessary to store it.
new Menu();
}
// This method is static because it is the "general" instantiation of the game, and is not
// belonging to an Engine-object. Engine is never instantiated.
public static void startGame() {
readSettings();
Floor floor = new Floor(width, height, nrOfEnemies);
BombermanFrame frame = new BombermanFrame("Bomberman", floor);
startTime = System.nanoTime();
floor.addFloorListener(frame.getBombermanComponent());
Action doOneStep = new AbstractAction()
{
public void actionPerformed(ActionEvent e) {
tick(frame, floor);
}
};
clockTimer = new Timer(TIME_STEP, doOneStep);
clockTimer.setCoalesce(true);
clockTimer.start();
}
// Engine is never instantiated, therefore this method needs to be static.
private static void readSettings() {
Parser parser = new Parser("settings.txt");
try {
parser.processLineByLine();
//Set the values read from file.
width = parser.getWidth();
height = parser.getHeight();
nrOfEnemies = parser.getNrOfEnemies();
} catch (IOException ioe) {
JOptionPane.showMessageDialog(null, "Trouble reading from settings file: " + ioe.getMessage() +
". Creating new file with standard settings.");
writeNewSettings();
}
}
// Engine is never instantiated, therefore this method needs to be static.
private static void gameOver(BombermanFrame frame, Floor floor) {
long endTime = System.nanoTime();
elapsedTime = (endTime - startTime) / NANO_SECONDS_IN_SECOND;
clockTimer.stop();
if (floor.getEnemyList().isEmpty()) {
if (getRank() > 10) {
JOptionPane.showMessageDialog(null, "You beat the game! But you didn't make the highscorelist. :(");
} else {
String name =
JOptionPane.showInputDialog("You beat the game and made the highscorelist!\nPlease input your handle");
writeHighscore(name, (int) elapsedTime);
}
} else {
JOptionPane.showMessageDialog(null, "Game over!");
UIManager.put("JOptionPane.okButtonMnemonic", "O"); // for Setting 'O' as mnemonic
}
frame.dispose();
if (askUser("Do you want to play again?")) {
startGame();
}
}
// Engine is never instantiated, therefore this method needs to be static.
private static void writeHighscore(String name, int newHighscore) {
ArrayList<String> highscoreList = HighscoreFrame.readHighscore();
highscoreList.remove(highscoreList.size() - 1);
String newScore = name + ":" + Integer.toString(newHighscore);
highscoreList.add(newScore);
highscoreList = HighscoreFrame.sortHighscore(highscoreList);
WriteToFile.writeToFile(highscoreList, "highscore.txt");
}
// Engine is never instantiated, therefore this method needs to be static.
private static void writeNewSettings() {
Collection<String> settingsList = new ArrayList<>();
String strWidth = "width=" + Integer.toString(width);
settingsList.add(strWidth);
String strHeight = "height=" + Integer.toString(height);
settingsList.add(strHeight);
String strNrOfEnemies = "nrOfEnemies=" + Integer.toString(nrOfEnemies);
settingsList.add(strNrOfEnemies);
WriteToFile.writeToFile(settingsList, "settings.txt");
}
// Engine is never instantiated, therefore this method needs to be static.
private static int getRank() {
try (BufferedReader br = new BufferedReader(new FileReader("highscore.txt"))) {
int positionCounter = 0;
while (br.readLine() != null && positionCounter < 10) {
positionCounter++;
int listedScore = Integer.parseInt(br.readLine().split(":")[1]);
if (elapsedTime < listedScore) {
return positionCounter;
}
}
} catch (IOException ioe) {
LOGGER.log(Level.FINE, "Trouble reading from the file: " + ioe.getMessage() );
System.out.println("Trouble reading from the file: " + ioe.getMessage());
}
return 10 + 1;
}
// Engine is never instantiated, therefore this method needs to be static.
private static boolean askUser(String question) {
return JOptionPane.showConfirmDialog(null, question, "", JOptionPane.YES_NO_OPTION) == JOptionPane.YES_OPTION;
}
// Engine is never instantiated, therefore this method needs to be static.
private static void tick(BombermanFrame frame, Floor floor) {
if (floor.getIsGameOver()) {
gameOver(frame, floor);
} else {
floor.moveEnemies();
floor.bombCountdown();
floor.explosionHandler();
floor.characterInExplosion();
floor.notifyListeners();
}
}
}
| perfall/Bomberman | Engine.java | 1,674 | // This method is static because it is the "general" instantiation of the game, and is not | line_comment | en | false | 1,412 | 20 | 1,674 | 20 | 1,718 | 20 | 1,674 | 20 | 1,927 | 21 | false | false | false | false | false | true |
130605_5 | /**
* @author Pushkar Taday
*/
/**
* This class represents a station where passengers embark the train from
*/
public class Station {
private static int passengerCount=1;
private int totalFirstClassPassengers=0;
private int totalSecondClassPassengers=0;
private PassengerQueue firstClass;
private PassengerQueue secondClass;
private BooleanSource firstArrival;
private BooleanSource secondArrival;
public int firstClassPeopleServed=0;
public int secondClassPeopleServed=0;
public double firstClassTotalWait=0.0;
public double secondClassTotalWait=0.0;
/**
* This is a parameterized constructor for this class which gets instantiated with the appropriate parameters
* @param firstArrivalProbability
* The probability of passengers to arrive in the first class
* @param secondArrivalProbability
* The probability of passengers to arrive in the second class
*/
Station(double firstArrivalProbability,double secondArrivalProbability)
{
firstArrival=new BooleanSource(firstArrivalProbability);
secondArrival=new BooleanSource(secondArrivalProbability);
firstClass=new PassengerQueue();
secondClass=new PassengerQueue();
}
/**
* This method simulates the scenario at the station for each min.
*/
public void simulateTimestep()
{
if(firstArrival.occurs()&&LIRRSimulator.i<=LIRRSimulator.lastArrivalTime)
{
System.out.println("First class passenger "+passengerCount+" ID arrives");
Passenger passenger=new Passenger(passengerCount,LIRRSimulator.i,true);
firstClass.enqueue(passenger);
passengerCount++;
totalFirstClassPassengers++;
}
else
{
System.out.println("No first class passenger arrives");
}
if(secondArrival.occurs()&&LIRRSimulator.i<=LIRRSimulator.lastArrivalTime)
{
System.out.println("Second class passenger "+passengerCount+" ID arrives");
Passenger passenger=new Passenger(passengerCount,LIRRSimulator.i,false);
secondClass.enqueue(passenger);
passengerCount++;
totalSecondClassPassengers++;
}
else
{
System.out.println("No second class passenger arrives");
}
System.out.println("Queues:");
System.out.print("First "+firstClass);
System.out.println();
System.out.println("Second "+secondClass);
System.out.println();
}
/**
* This is an accessor method for the total numbers of passengers which travelled through the trains during entire simulation.
* @return
* total number of passengers
*/
public static int getPassengerCount() {
return passengerCount;
}
/**
* This is an accessor method for the total numbers of passengers which travelled through the first class of the trains during entire simulation.
* @return
* total number of first class passengers
*/
public int getTotalFirstClassPassengers() {
return firstClass.getCount();
}
/**
* This is an accessor method for the total numbers of passengers which travelled through the second class of the trains during entire simulation.
* @return
* total number of second class passengers
*/
public int getTotalSecondClassPassengers() {
return secondClass.getCount();
}
/**
* This is an accessor method for the queue of passengers in the first class
* @return
* first class passengers queue
*/
public PassengerQueue getFirstClass() {
return firstClass;
}
/**
* This is an accessor method for the queue of passengers in the second class
* @return
* second class passengers queue
*/
public PassengerQueue getSecondClass() {
return secondClass;
}
}
| ptaday/LIRR-Simulator | Station.java | 859 | /**
* This is an accessor method for the total numbers of passengers which travelled through the first class of the trains during entire simulation.
* @return
* total number of first class passengers
*/ | block_comment | en | false | 796 | 43 | 859 | 45 | 973 | 47 | 859 | 45 | 1,082 | 50 | false | false | false | false | false | true |
130952_7 | public class Person {
private String name;
private int age;
private String favoriteColor;
/**
* Person constructor.
*
* @param name the name
* @param age the age
* @param favoriteColor the favorite color
*/
public Person(String name, int age, String favoriteColor) {
this.name = name;
this.age = age;
this.favoriteColor = favoriteColor;
}
/**
* Sets the name
*
* @param name the name
*/
public void setName(String name) {
this.name = name;
}
/**
* Sets the age
*
* @param age the age
*/
public void setAge(int age) {
this.age = age;
}
/**
* Sets the favorite color
*
* @param favoriteColor the favorite color
*/
public void setFavoriteColor(String favoriteColor) {
this.favoriteColor = favoriteColor;
}
/**
* Gets the name of the Person
*
* @return the name
*/
public String getName() {
return this.name;
}
/**
* Gets the age of the Person
*
* @return the age
*/
public int getAge() {
return this.age;
}
/**
* Gets the favorite color of the Person
*
* @return the favorite color
*/
public String getFavoriteColor() {
return this.favoriteColor;
}
/**
* Produces a string representation of the Person, e.g. Bob, 30 (favorite color: blue)
*
* @return a string representation of the Person
*/
public String toString() {
return this.name + ", " + this.age + " (favorite color: " + this.favoriteColor + ")";
}
}
| Endeared/CSE174 | Person.java | 409 | /**
* Produces a string representation of the Person, e.g. Bob, 30 (favorite color: blue)
*
* @return a string representation of the Person
*/ | block_comment | en | false | 425 | 42 | 409 | 41 | 507 | 46 | 409 | 41 | 543 | 48 | false | false | false | false | false | true |
135700_0 | package connection;
import java.io.IOException;
public abstract class MenuItem {
/**
* This class represents a menu-item.
* It can be either (sub)menu or menu-point.
* It cannot be instantiated without adding a label to it.
* It also has an instance-method called launch().
* If the instance is a (sub)menu, it gives User the opportunity to choose from preset menu-items.
* If the instance is a menu-point, launch() simply invokes preset method.
*/
protected String label;
public MenuItem(String label) {
this.label = label;
}
public String getLabel() { return label; }
public abstract boolean launch() throws ClassCastException, ClassNotFoundException, IOException;
}
| AdamVegh/Javanymous_Team | connection/MenuItem.java | 175 | /**
* This class represents a menu-item.
* It can be either (sub)menu or menu-point.
* It cannot be instantiated without adding a label to it.
* It also has an instance-method called launch().
* If the instance is a (sub)menu, it gives User the opportunity to choose from preset menu-items.
* If the instance is a menu-point, launch() simply invokes preset method.
*/ | block_comment | en | false | 152 | 92 | 175 | 96 | 188 | 104 | 175 | 96 | 199 | 108 | false | false | false | false | false | true |
135838_2 | import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
public class Modes {
//make a frame to hold the buttons of the modes
//make a button for each mode
//there should be not more than 3 buttons in the same y coordinates
JFrame frame = new JFrame("Modes");
JPanel panel = new JPanel();
JButton classic = new JButton("Classic");
JButton zen = new JButton("Zen");
JButton fast = new JButton("Fast");
JButton back = new JButton("Back");
JButton exit = new JButton("Exit");
JButton classicinfo = new JButton("?");
JButton zeninfo = new JButton("?");
JButton fastinfo = new JButton("?");
public Modes() {
frame.setSize(1000, 650);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setLocationRelativeTo(null);
frame.setResizable(false);
frame.setLayout(null);
ImageIcon logo = new ImageIcon("logo.png");
frame.setIconImage(logo.getImage());
frame.setVisible(true);
panel.setLayout(null);
panel.setBackground(Color.BLACK);
panel.setBounds(0, 0, 1000, 650);
panel.setBorder(BorderFactory.createEmptyBorder(100, 100, 100, 100));
classic.setBackground(Color.GREEN);
classic.setForeground(Color.WHITE);
classic.setFont(new Font("Comic Sans MS", Font.PLAIN, 30));
classic.setBorder(BorderFactory.createEtchedBorder());
classic.setBounds(100, 150, 200, 100);
classic.setFocusable(false);
classic.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
SnakeGameClassic.main(null);
frame.dispose();
}
});
panel.add(classic);
zen.setBackground(Color.GREEN);
zen.setForeground(Color.WHITE);
zen.setFont(new Font("Comic Sans MS", Font.PLAIN, 30));
zen.setBorder(BorderFactory.createEtchedBorder());
zen.setBounds(590, 150, 200, 100);
zen.setFocusable(false);
zen.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
SnakeGameZen.main(null);
frame.dispose();
}
});
panel.add(zen);
fast.setBackground(Color.GREEN);
fast.setForeground(Color.WHITE);
fast.setFont(new Font("Comic Sans MS", Font.PLAIN, 30));
fast.setBorder(BorderFactory.createEtchedBorder());
fast.setBounds(100, 260, 200, 100);
fast.setFocusable(false);
fast.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
SnakeGameFast.main(null);
frame.dispose();
}
});
panel.add(fast);
back.setBackground(Color.GREEN);
back.setForeground(Color.WHITE);
back.setFont(new Font("Comic Sans MS", Font.PLAIN, 30));
back.setBorder(BorderFactory.createEtchedBorder());
back.setBounds(250, 400, 200, 100);
back.setFocusable(false);
back.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
new Menu();
frame.dispose();
}
});
panel.add(back);
exit.setBackground(Color.GREEN);
exit.setForeground(Color.WHITE);
exit.setFont(new Font("Comic Sans MS", Font.PLAIN, 30));
exit.setBorder(BorderFactory.createEtchedBorder());
exit.setBounds(460, 400, 200, 100);
exit.setFocusable(false);
exit.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
frame.dispose();
}
});
panel.add(exit);
classicinfo.setBackground(Color.GREEN);
classicinfo.setForeground(Color.WHITE);
classicinfo.setFont(new Font("Comic Sans MS", Font.PLAIN, 30));
classicinfo.setBorder(BorderFactory.createEtchedBorder());
classicinfo.setBounds(310, 150, 100, 100);
classicinfo.setFocusable(false);
classicinfo.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
ClassicInfoFrame.main(null);
frame.dispose();
}
});
panel.add(classicinfo);
zeninfo.setBackground(Color.GREEN);
zeninfo.setForeground(Color.WHITE);
zeninfo.setFont(new Font("Comic Sans MS", Font.PLAIN, 30));
zeninfo.setBorder(BorderFactory.createEtchedBorder());
zeninfo.setBounds(800, 150, 100, 100);
zeninfo.setFocusable(false);
zeninfo.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
ZenInfoFrame.main(null);
frame.dispose();
}
});
panel.add(zeninfo);
fastinfo.setBackground(Color.GREEN);
fastinfo.setForeground(Color.WHITE);
fastinfo.setFont(new Font("Comic Sans MS", Font.PLAIN, 30));
fastinfo.setBorder(BorderFactory.createEtchedBorder());
fastinfo.setBounds(310, 260, 100, 100);
fastinfo.setFocusable(false);
fastinfo.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
FastInfoFrame.main(null);
frame.dispose();
}
});
panel.add(fastinfo);
frame.add(panel);
}
public static void main(String[] args) {
new Modes();
}
}
| GenDelta/Snake-Game | Modes.java | 1,439 | //there should be not more than 3 buttons in the same y coordinates
| line_comment | en | false | 1,180 | 17 | 1,439 | 16 | 1,559 | 16 | 1,439 | 16 | 1,832 | 16 | false | false | false | false | false | true |
138214_0 | /**
* This class defines attributes of a girl and has
* a constructor method
* @author Anurag Kumar
*/
public class Girl{
String name;
int attractiveness;
int main_budget;
int intelligence;
String bf_name;
int type;
public Girl(String na, int attr,int main,int in){
name = na;
attractiveness= attr;
main_budget = main;
intelligence = in;
bf_name="";
type = (int)(Math.random()*3);
}
}
| PPL-IIITA/ppl-assignment-iit2015143 | q2/Girl.java | 147 | /**
* This class defines attributes of a girl and has
* a constructor method
* @author Anurag Kumar
*/ | block_comment | en | false | 106 | 27 | 147 | 31 | 137 | 29 | 147 | 31 | 153 | 30 | false | false | false | false | false | true |
139285_6 | // 2022.05.27
// Problem Statement:
// https://leetcode.com/problems/reverse-integer/
// idea: from x's lsb to msb,
// 10*answer + x%10 may cause overflow, have to check answer before this operation
class Solution {
public int reverse(int x) {
int answer = 0;
while (x/10!=0) {
// if (answer>(int)Math.pow(2, 31)-1 || answer<-1*(int)Math.pow(2, 31)) return 0;
// but should not use the 'updated' answer, should check the last answer before calculating 10*answer + x%10
if (answer > (0.1*(Math.pow(2, 31)-1) - 0.1*(x%10)) ||
answer < (-0.1*Math.pow(2, 31) - 0.1*(x%10))) return 0; // absolute value will only get larger,
// so an overflow is certain
answer = 10*answer + x%10;
x = x/10;
}
if (answer > (0.1*(Math.pow(2, 31)-1) - 0.1*(x%10)) ||
answer < (-0.1*Math.pow(2, 31) - 0.1*(x%10))) return 0;
answer = answer*10 + x;
return answer;
}
} | ljn1999/LeetCode-problems | Amazon/q7.java | 360 | // but should not use the 'updated' answer, should check the last answer before calculating 10*answer + x%10 | line_comment | en | false | 345 | 28 | 360 | 28 | 380 | 28 | 360 | 28 | 387 | 28 | false | false | false | false | false | true |
139536_1 | package easy;
import java.util.*;
public class Beautiful_word {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
String w = in.next();
boolean b = false;
// int j=0,c=0;
char[] vow = { 'a', 'e', 'i', 'o', 'u', 'y' };
for (int i = 0; i < w.length(); i++) {
if (w.charAt(i) != w.charAt(i + 1)) {
for (int j = 0; j < 6; j++)
if (w.charAt(i) == vow[j]) {
j = 0;
if ((w.charAt(i + 1) == vow[j]) && (j < 6)) {
j++;
b = true;
}
}
}
}
if (b == true) {
System.out.println("no");
} else {
System.out.println("Yes");
}
// Print 'Yes' if the word is beautiful or 'No' if it is not.
in.close();
}
} | jwesly20/HackerRank | Beautiful_word.java | 297 | // Print 'Yes' if the word is beautiful or 'No' if it is not.
| line_comment | en | false | 246 | 20 | 297 | 20 | 299 | 19 | 297 | 20 | 369 | 19 | false | false | false | false | false | true |
145384_15 | import java.util.ArrayList;
/**
* Represents a hand of cards.
*
* @since Fall 2023
* @author Chris Sorros and Michael Plekan
*/
public class Hand {
public ArrayList<Card> hand;
/**
* Constructs a hand with no cards.
*/
public Hand() {
this.hand = new ArrayList<Card>();
}
/**
* Constructs a hand with the given cards.
*
* @param cards the cards to add to the hand
*/
public Hand(Card ...cards) {
this.hand = new ArrayList<Card>();
// Add the cards to the hand
for (Card card : cards) {
this.hand.add(card);
}
}
/**
* Returns the card at the given index.
*
* @param index the index of the card to get.
*
* @return the card at the given index.
*/
public Card getCard(int index){
return hand.get(index);
}
/**
* Adds a card to the hand.
*
* @param card the card to add
*/
public void addCard(Card card) {
this.hand.add(card);
}
/**
* Returns the value of the hand.
*
* @return the value of the hand.
*/
public int getValue() {
int value = 0;
for (Card card : hand) {
value += card.value;
}
return value;
}
/**
* Returns the soft value of the hand.
*
* @return the soft value of the hand
*/
public int getSoftValue() {
int value = 0;
for (Card card : hand) {
// If the card is an ace, add 1 instead of 11
value += card.value != 11 ? card.value : 1;
}
return value;
}
/**
* Returns if the hand is a bust.
*
* @return if the hand is a bust
*/
public boolean isBust() {
return getValue() > 21;
}
/**
* Returns if the hand is a blackjack.
*
* @return if the hand is a blackjack
*/
public boolean isBlackjack() {
return getValue() == 21;
}
/**
* Returns if the hand is a soft hand.
*
* @return if the hand is a soft hand.
*/
public boolean isSoft() {
//check each card in the hand to see if it is an ace
//if it is an ace, return true
//if not, return false
for (int i = 0; i < hand.size(); i++) {
if (hand.get(i).name.equals("Ace")) {
return true;
}
}
return false;
}
/**
* Returns if the hand is a pair.
*
* @return if the hand is a pair.
*/
public boolean isPair() {
if (hand.get(0).value == hand.get(1).value) {
return true;
}
return false;
}
/**
* Returns the string representation of the hand.
*
* @return the string representation of the hand
*/
@Override
public String toString() {
return "" + hand;
}
} | DarrenLim4/BlackjackBot | Hand.java | 747 | /**
* Returns if the hand is a pair.
*
* @return if the hand is a pair.
*/ | block_comment | en | false | 731 | 27 | 747 | 26 | 865 | 31 | 747 | 26 | 894 | 31 | false | false | false | false | false | true |
147014_1 | package pull_model;
import java.util.ArrayList;
/**
* Abstract agent class with no established behavior, to be used in {@link Dynamics}.
*
* To define a behavior, one only needs to extend this class and provide
* implementation for the {@link update(ArrayList) update} method.
*
* @param <T> The type of opinions handled by the agent.
*/
public abstract class Agent<T> {
/**
* The sample size required by the agent.
*/
public final int sampleSize;
/**
* The opinion of the agent.
*/
protected T opinion;
/**
* Constructs an agent with the specified sample size and initial opinion.
*
* @param sampleSize The sample size required by the agent.
* @param initialOpinion The inital opinion of the agent.
*/
public Agent(int sampleSize, T initialOpinion) {
this.sampleSize = sampleSize;
this.opinion = initialOpinion;
}
/**
* Returns the opinion of the agent.
*/
public T output() {
return opinion;
}
/**
* Updates the opinion and memory state of the agent depending on an opinion sample.
* This method must be implemented to define the dynamics.
* @param samples Contains a collections of opinions whose size is always equal to {@link sampleSize}.
*/
public abstract void update(ArrayList<T> samples);
}
| RobinVacus/research | src/pull_model/Agent.java | 331 | /**
* The sample size required by the agent.
*/ | block_comment | en | false | 292 | 13 | 331 | 13 | 349 | 15 | 331 | 13 | 368 | 15 | false | false | false | false | false | true |
147348_0 | /**
* miniJava Abstract Syntax Tree classes
* @author prins
* @version COMP 520 (v2.2)
*/
package miniJava.AbstractSyntaxTrees;
import miniJava.SyntacticAnalyzer.SourcePosition;
public abstract class AST {
public AST (SourcePosition posn) {
this.posn = posn;
}
public String toString() {
String fullClassName = this.getClass().getName();
String cn = fullClassName.substring(1 + fullClassName.lastIndexOf('.'));
if (ASTDisplay.showPosition)
cn = cn + " " + posn.toString();
return cn;
}
public abstract <A,R> R visit(Visitor<A,R> v, A o);
public SourcePosition posn;
}
| kekevi/miniJava-compiler | src/miniJava/AbstractSyntaxTrees/AST.java | 179 | /**
* miniJava Abstract Syntax Tree classes
* @author prins
* @version COMP 520 (v2.2)
*/ | block_comment | en | false | 158 | 30 | 179 | 32 | 203 | 33 | 179 | 32 | 221 | 36 | false | false | false | false | false | true |
147706_5 | public class Account implements java.io.Serializable {
private String number; // 4 digit string
private double balance;
private boolean active;
private int array_number;
private boolean type;
int interest = 5;
public Account(int Account_Number, int total_accounts) {
String Accnt_Num = String.valueOf(Account_Number);
this.number = Accnt_Num;
this.balance = 0;
this.active = true;
this.array_number = total_accounts;
}
//This Method Just Prints Out Account Info and returns the Array Number
int info(){
System.out.println("Account number: " + this.number);
System.out.println("Account balance: " + this.balance);
System.out.println("Active?: " + this.active);
//System.out.println("array number: " + this.array_number);
return this.array_number;
}
//This Method Updates the Deposit Balance for This Account
void addDeposit(double deposit){
System.out.println("\n**Account balance updated**");
this.balance = this.balance + deposit;
this.info();
}
//This Method Updates the Withdraw Balance for This Account
void subWithdraw(double withdraw){
if (withdraw > this.balance){
System.out.println("\nInsufficient Funds!");
}else{
System.out.println("\n**Account balance updated**");
this.balance = this.balance - withdraw;
this.info();
}
}
//This Method Adds To the Balance (Every 5 transactions) The Interest Rate for All Savings Accounts
void addInterest(){
this.balance = this.balance + this.balance * this.interest/100;
}
////////////////////////////////////////////////////////////////////////////////
// Simple Getters and Setters //
////////////////////////////////////////////////////////////////////////////////
int getArray() {
return array_number;
}
String getNumber() {
return this.number;
}
public double getBalance() {
return this.balance;
}
boolean getType() {
return type;
}
void setTypeSavings() {
this.type = true;
}
void setTypeChecking() {
this.type = false;
}
void setActiveFalse() {
this.active = false;
this.balance = 0;
}
boolean getActive() {
return this.active;
}
} | saxena-arpit/ATM-Management-System | p2/Account.java | 607 | //This Method Adds To the Balance (Every 5 transactions) The Interest Rate for All Savings Accounts | line_comment | en | false | 457 | 21 | 607 | 23 | 608 | 21 | 607 | 23 | 723 | 26 | false | false | false | false | false | true |
147996_7 | import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.math.*;
import java.text.*;
import java.util.*;
import java.util.regex.*;
import java.awt.geom.*;
//Scanner in = new Scanner(new BufferedReader(new InputStreamReader(System.in)));
public class commons {
//things to do
//2d boards/circular array/torus
//more advanced data structure
static void common_lines(){
NumberFormat num=NumberFormat.getInstance();
num.setMinimumFractionDigits(3);
num.setMaximumFractionDigits(3);
num.setGroupingUsed(false);
}
public static int digit_sum(int n, int b){
int s = 0;
while(n!=0){
s+=n%b;
n/=b;
}
return s;
}
public static double angle(double x, double y){
if(x>0&&y>=0){
return Math.atan(y/x);
}
if(x>0&&y<0){
return Math.atan(y/x)+2.0*Math.PI;
}
if(x<0){
return Math.atan(y/x)+Math.PI;
}
if(x==0&&y<0){
return 1.5*Math.PI;
}
if(x==0&&y>0){
return Math.PI*0.5;
}
return 0.0;
}
static int[] prime_list(int n){
ArrayList<Integer> a = new ArrayList<Integer>();
for(int i=2;i<=n;i++)
if(isPrime(i)) a.add(i);
int[] r = new int[a.size()];
for(int i=0;i<a.size();i++)
r[i] = a.get(i);
return r;
}
static boolean isPrime(int d){
return BigInteger.valueOf(d).isProbablePrime(32);
}
//likely not useful, java can run for 2 min
static int[] prime_seive(int n){
ArrayList<Integer> p = new ArrayList<Integer>();
boolean[] isPrime = new boolean[n + 1];
for (int i = 2; i <= n; i++) {
isPrime[i] = true;
}
for (int i = 2; i*i <= n; i++) {
if (isPrime[i]) {
for (int j = i; i*j <= n; j++) {
isPrime[i*j] = false;
}
}
}
for (int i = 2; i <= n; i++) {
if (isPrime[i]) {
p.add(i);
}
}
int[] b = new int[p.size()];
for(int i=0;i<b.length;i++){
b[i] = p.get(i);
}
return b;
}
public static int sum(int[] a){
int sum = 0;
for(int i=0;i<a.length;i++){
sum+=a[i];
}
return sum;
}
public static int prod(int[] a){
return prodmod(a,2147483647);
}
public static int prodmod(int[] a, int k){
int prod = 1;
for(int i=0;i<a.length;i++){
prod*=(a[i]%k);
prod%=k;
}
return prod;
}
public static long prod(long[] a){
return prodmod(a,9223372036854775807L);
}
public static long prodmod(long[] a, long k){
long prod = 1;
for(int i=0;i<a.length;i++){
prod*=(a[i]%k);
prod%=k;
}
return prod;
}
static String lastkdigit(int n,int k){
String s = padleft(Integer.toString(n),k,'0');
return s.substring(s.length()-k);
}
//pad the string with a character if length < n, O(n^2)
static String padleft(String s, int n, char c){
return n<=s.length()?s:c+padleft(s,n-1,c);
}
//thx to
static String reverse(String s){
return (new StringBuilder(s)).reverse().toString();
}
//repeat the string n time, for example repeat("ab",3) = "ababab", O(|a|n^2)
static String repeat(String a, int n){
return n<1?"":a+repeat(a,n-1);
}
//check if the character is alphanumberic, O(1)
static boolean isAlphaNumeric(char c){
return "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789".indexOf(c)!=-1;
}
//check if a regular expression matches the entire string. O(|s|)
static boolean regex(String s,String p){
return Pattern.compile(p).matcher(s).matches();
}
//input should be a sorted list of points of the polygonal chain that forms a polygon, exclude the last point
static double polygonArea(ArrayList<Point2D> a){
double s=0;
a.add(a.get(0));
for(int i=0;i<a.size()-1;i++){
s+=a.get(i).getX()*a.get(i+1).getY()-a.get(i+1).getX()*a.get(i).getY();
}
a.remove(a.size()-1);
return 0.5*s;
}
static int gcd(int a, int b){
return a%b==0?b:gcd(b,a%b);
}
static int c(int[][] m, int x, int y){
return m[m.length-(x%m.length)][m[0].length-(y%m.length)];
}
static int c(int[] m, int x){
return m[m.length-(x%m.length)];
}
static void p(int[] a){
for(int i=0;i<a.length;i++){
System.out.print(a[i]+" ");
}
System.out.println();
}
public static int nextInt(InputStream in){
int ret = 0;
boolean dig = false;
try {
for (int c = 0; (c = in.read()) != -1; ) {
if (c >= '0' && c <= '9') {
dig = true;
ret = ret * 10 + c - '0';
} else if (dig) break;
}
} catch (IOException e) {}
return ret;
}
@SuppressWarnings({"unchecked"})
public static <E> E[] CollectionToArray(Collection<E> c){
E[] a =(E[]) new Object[c.size()];
Iterator itr = c.iterator();
int i=0;
while(itr.hasNext()){
a[i] = (E) itr.next();
i++;
}
return a;
}
}
class sorttemplate implements Comparator<int[]>{
public int compare(int[] o1, int[] o2) {
if(o1[0]>o2[0]){
return 1;
}
if(o1[0]<o2[0]){
return -1;
}
return 0;
}
}
class sorttemplate2 implements Comparator<int[]>{
public int compare(int[] o1, int[] o2) {
for(int i=0;i<o1.length;i++){
if(o1[i]>o2[i]){
return 1;
}
if(o1[i]<o2[i]){
return -1;
}
}
return 0;
}
}
//untested
class UnionFind {
int[] s;
UnionFind(int n){
s = new int[n];
for(int i=0;i<n;i++){
s[i]=i;
}
}
public int find(int x){
if(s[x]==x){
return x;
}
s[x]=find(s[x]);
return s[x];
}
public void union(int x, int y){
s[find(x)] = find(y);
}
} | chaoxu/mgccl-oj | commons.java | 2,142 | //repeat the string n time, for example repeat("ab",3) = "ababab", O(|a|n^2) | line_comment | en | false | 1,751 | 29 | 2,142 | 28 | 2,287 | 28 | 2,142 | 28 | 2,573 | 29 | false | false | false | false | false | true |
150697_0 | /**
* Class representing the TodoApp application.
* It is the main entry point for this program.
*/
import java.util.Scanner;
public class App{
public static void main(String[] args) {
boolean end = false;
TodoList todoList = new TodoList();
while (!end) {
System.out.println("Please specify a command [list, add, mark, archive], else the program will quit:");
String command = getInput();
if (command.toLowerCase().equals("list")) {
todoList.listAll();
}
else if (command.toLowerCase().equals("add")) {
System.out.println("Add an item:");
String name = getInput();
todoList.addItem(name);
}
else if (command.toLowerCase().equals("mark")) {
todoList.listAll();
System.out.println("Which one do you want to mark as completed: ");
try {
Integer idx = Integer.parseInt(getInput());
todoList.markItem(idx);
}
catch (NumberFormatException e) {
System.out.println("Please type only integers.");
}
}
else if (command.toLowerCase().equals("archive")) {
todoList.archiveItems();
}
else {
System.out.println("Goodbye!");
end = true;
}
}
}
public static String getInput() {
Scanner scan = new Scanner(System.in);
String input = scan.nextLine();
return input;
}
}
| CodecoolKRK20171/java-todo-app-wutismyname | App.java | 334 | /**
* Class representing the TodoApp application.
* It is the main entry point for this program.
*/ | block_comment | en | false | 294 | 21 | 334 | 24 | 362 | 24 | 334 | 24 | 405 | 25 | false | false | false | false | false | true |
155700_3 | /*
Type.java
Copyright (c) 2009-2012, Morgan McGuire
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are
met:
Redistributions of source code must retain the above copyright notice,
this list of conditions and the following disclaimer.
Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in the
documentation and/or other materials provided with the distribution.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
/**
Types of Entitys that can be in a location.
*/
public enum Type {
/** A square that is empty and can be entered (note that it may no
* longer be empty by the time you actually get around to entering
* it, though!. */
EMPTY,
/** A square that cannot be entered because it is blocked by an
immovable and indestructible wall.*/
WALL,
/** A square that cannot be entered because it is blocked by an immovable
and indestructible hazard. Attempting to move into the hazard
converts a creature into an Apple. */
HAZARD,
CREATURE;
/** @deprecated Old name for HAZARD */
@Deprecated
static final public Type THORN = HAZARD;
}
| brodermar/darwin | src/Type.java | 479 | /** A square that cannot be entered because it is blocked by an
immovable and indestructible wall.*/ | block_comment | en | false | 432 | 24 | 479 | 23 | 508 | 22 | 479 | 23 | 717 | 27 | false | false | false | false | false | true |
156644_7 | /**
File: TimBot.java
Author: Alex Brodsky
Date: September 21, 2015
Purpose: CSCI 1110, Assignment 4 Solution
Description: This class specifies the solution for the TimBot base class.
*/
/**
This is the TimBot base class for representing TimBots and their
behaviours on the planet DohNat.
*/
public class TimBot {
private int myId; // TimBot's ID
protected int energyLevel; // TimBot's energy level
protected char personality = 'N'; // TimBot's personality
protected int [] spressoSensed = new int[5]; // last spresso sensor read
protected boolean [] botsSensed = new boolean[5]; // last adj bot sensor read
/**
This is the only constructor for this class. This constructor
initializes the Tibot and sets its ID and the initial amount of
energy that it has. The ID is between 0 and 99.
parameter: id : ID of the TimBotA
jolts : Initial amount of energy
*/
public TimBot( int id, int jolts ) {
myId = id;
energyLevel = jolts;
}
/**
This method returns the ID of this TimBot, which should be 1 or
greater.
returns: id of TimBot
*/
public int getID() {
return myId;
}
/**
This method is called at the start of the round. The TimBot
uses up one jolt of energy at the start or each round. This
method decrements the energy level and returns true if and
only if the TimBot is still functional.
returns true if energyLevel >= 0
*/
public boolean startRound() {
return useJolt();
}
/**
This method is called during the Sense phase of each round and
informs the TimBot of the districts around it. An integer
array and a boolean array of 5 elements each is passed. The
elements represent the state of the District.CURRENT district
and the districts District.NORTH, District.EAST, District.SOUTH,
and District.WEST of the current district. Each element of
the spresso array stores the number of rounds before the spresso
plants in the corresponding district will be ready for harvest.
I.e., a 0 means that the spresso can be harvested this round.
Each element of the bots array indicates whether a TimBot is
present in the district. E.g., if bots[District.SOUTH] is true,
then there is a TimBot in the district to the south.
It is recommended that this method store the information locally,
in its own boolean variables or arrays to be used in later phases
of the the round.
Params: spresso: a 5 element array of integers indicating when
the ospresso plants will be ready for harvest in
corresponding districts.
bots : a 5 element array of booleans indicating whether
TimBots are present in corresponding districts.
*/
public void senseDistricts( int [] spresso, boolean [] bots ) {
System.arraycopy( spresso, 0, spressoSensed, 0, spresso.length );
System.arraycopy( bots, 0, botsSensed, 0, bots.length );
}
/**
This method is called during the Move phase of each round and
requires the TimBot to decide whether or not to move to another
district. If the TimBot wishes to move, it returns, District.NORTH,
District.EAST, District.SOUTH, or District.WEST, indicating which
direction it wishes to move. If it does not wish to move, it
returns District.CURRENT.
returns: the one of District.NORTH, District.EAST, District.SOUTH,
District.WEST, or District.CURRENT
*/
public int getNextMove() {
// Never move
return District.CURRENT;
}
/**
This method returns true if the TmBot is functional. I.e., it's
energy level is not negative.
returns: energy level >= 0
*/
public boolean isFunctional() {
return energyLevel >= 0;
}
/**
This method is called whenever a TimBot uses a jolt of energy.
It decrements the energy level and returns true if and only
if the TimBot is still functional.
returns true if energyLevel >= 0
*/
private boolean useJolt() {
if( energyLevel >= 0 ) {
energyLevel--;
}
return isFunctional();
}
/**
This method is called when the TimBot has to use its shield.
This costs the TimBot 1 Jolt of energy. If the TimBot has
positive enery, it must use its shield (and use 1 Jolt of
energy). Otherwise, its energy level becomes -1 and it
becomes nonfunctional.
returns: true if the shield was raised.
*/
public boolean useShield() {
return useJolt();
}
/**
This method is called during the Harvest phase if there are
spresso plants to harvest. This allows the TimBot to increase
it's energy reserves by jolts Jolts. The energy level cannot
exceed 99 Jolts.
*/
public void harvestSpresso( int jolts ) {
// add harvest jolts to energy level and ensure it does not exceed 99
energyLevel += jolts;
if( energyLevel > 99 ) {
energyLevel = 99;
}
}
/**
This method is called during the Fire Cannon phase. The TimBot
creates an array of integers, each representing where it wishes
to fire the ion cannon, and decreases its energy reserves by
1 Jolt for each shot. The integers can be one NORTH, EAST,
SOUTH, or WEST. If the TimBot does not wish to fire its cannon,
it returns null;
returns: array of integers representing shots from the cannon
*/
public int [] fireCannon() {
// Never shoots
return null;
}
/**
This method is called at the end of each round to display the state
of the TimBot. The format of the String shoud be:
(P I E)
where
P: is a single Capital letter representing the personality of the TimBot
The default personality is N for do Nothing.
I: is the ID of the TimBot.
E: is the TimBot's energy level in Jolts.
Both the ID and the Energy should have width 2. E.g., if the TimBot's
Personality is A, its ID is 42, and its energy level is 7, then the
string to be returned is:
(A 42 7)
returns: a String representing the state of the TimBot
*/
public String toString() {
return String.format( "(%c %2d %2d)", personality, myId, energyLevel );
}
protected void useMoveEnergy(int move){
if(move != District.CURRENT){
energyLevel--;
}
}
}
| kylecumming/2134A4 | src/TimBot.java | 1,637 | /**
This is the only constructor for this class. This constructor
initializes the Tibot and sets its ID and the initial amount of
energy that it has. The ID is between 0 and 99.
parameter: id : ID of the TimBotA
jolts : Initial amount of energy
*/ | block_comment | en | false | 1,635 | 74 | 1,637 | 70 | 1,756 | 77 | 1,637 | 70 | 1,949 | 80 | false | false | false | false | false | true |
160185_3 | import java.util.Vector;
import javax.swing.DefaultComboBoxModel;
/*****************************************************************
* MyComboBoxModel creates and manages a ComboBox to be used by other parts of
* our program. In its current form relies on UseCase.java; as it's contents are
* generated therein. Extends the DefaultComboBox class. authors Wesley Krug,
* Gabriel Steponovich, Michael Brecker, Halston Raddatz
* @version Winter 2015
*****************************************************************/
public class ActorBox extends DefaultComboBoxModel<String> {
/**
* version id.
*/
private static final long serialVersionUID = 1L;
/**
* @param aName a name
*/
public ActorBox(final Vector<String> aName) {
super(aName);
}
/*****************************************************************
* Returns the currently selected UseCase.
*
* @return selectedUSeCase
*****************************************************************/
@Override
public final String getSelectedItem() {
String selectedName = (String) super.getSelectedItem();
return selectedName;
}
}
| Krugw/Term-Project | ActorBox.Java | 251 | /*****************************************************************
* Returns the currently selected UseCase.
*
* @return selectedUSeCase
*****************************************************************/ | block_comment | en | false | 211 | 25 | 251 | 24 | 264 | 35 | 251 | 24 | 285 | 36 | false | false | false | false | false | true |
160873_0 | package bot.modules;
import java.util.Arrays;
import java.util.HashSet;
public class TagList {
/**
* The list of tags that are the highest severity.
* These will always be warned about / excluded from searches.
*/
private static final HashSet<String> badTags = new HashSet<>(
Arrays.asList(
"netorare", "netori", "scat", "bestiality", "gigantic", "drugs", "blackmail", "horse",
"vore", "guro", "nose hook", "blood", "cheating", "dog", "pig", "corruption", "mind control",
"vomit", "bbm", "cannibalism", "tentacles", "rape", "snuff", "moral degeneration", "mind break", "humiliation",
"chikan", "ryona", "cum bath", "infantilism", "unbirth", "abortion",
"eye penetration", "urethra insertion", "chloroform", "parasite", "public use", "petrification", "necrophilia",
"brain fuck", "daughter", "torture", "birth", "minigirl", "menstruation", "anorexic", "age regression",
"shrinking", "giantess", "navel fuck", "possession", "miniguy", "nipple fuck", "cbt", "low scat", "dicknipples",
"nipple birth", "monkey", "nazi", "triple anal", "triple vaginal", "diaper", "aunt", "mother", "father",
"niece", "uncle", "grandfather", "grandmother", "granddaughter", "insect", "anal birth", "skinsuit", "vacbed",
"sleeping", "worm"
)
);
/**
* The list of unwholesome tags.
* These are slightly lower severity than the bad tags.
*/
private static final HashSet<String> unwholesomeTags = new HashSet<>(
Arrays.asList(
"amputee", "futanari", "gender bender", "human on furry", "group", "lactation", "femdom",
"ffm threesome", "double penetration", "gag", "harem", "strap-on", "inflation", "mmf threesome", "enema",
"bukkake", "bbw", "dick growth", "huge breasts", "slave", "gaping", "pegging", "smegma",
"triple penetration", "prolapse", "human pet", "foot licking", "milking", "bondage", "multiple penises",
"asphyxiation", "stuck in wall", "human cattle", "clit growth", "ttf threesome", "phimosis", "glory hole",
"eggs", "incest", "urination", "prostitution", "fisting", "piss drinking", "inseki", "feminization",
"old lady", "old man", "mmm threesome", "fff threesome", "all the way through", "farting", "tickling"
)
);
/**
* The highest severity of tags.
* A doujin having any of these tags forbids the bot from saying anything about it.
* These tags probably violate the Discord ToS.
*/
private static final HashSet<String> illegalTags = new HashSet<>(
Arrays.asList(
"lolicon", "shotacon", "oppai loli", "low shotacon", "low lolicon"
)
);
/**
* Returns a copy of the illegal tags.
*
* @return The illegal tags.
*/
public static HashSet<String> getIllegalTags() {
return new HashSet<>(illegalTags);
}
/**
* Returns a copy of the bad tags.
*
* @return The bad tags.
*/
public static HashSet<String> getBadTags() {
return new HashSet<>(badTags);
}
/**
* Returns a copy of the unwholesome tags.
*
* @return The unwholesome tags.
*/
public static HashSet<String> getUnwholesomeTags() {
return new HashSet<>(unwholesomeTags);
}
/**
* Returns a copy of the unwholesome tags, WITHOUT any tags contained
* within the query.
*
* @param query The query to be excluded from the tag list.
* @return The tag list without tags contained in the query.
*/
public static HashSet<String> nonWholesomeTagsWithoutQuery(String query) {
HashSet<String> nonWT = getUnwholesomeTags();
// Remove tag if query contains that tag
nonWT.removeIf(query::contains);
return nonWT;
}
}
| WholesomeGodList/h-bot | src/main/java/bot/modules/TagList.java | 1,162 | /**
* The list of tags that are the highest severity.
* These will always be warned about / excluded from searches.
*/ | block_comment | en | false | 1,073 | 28 | 1,162 | 29 | 1,096 | 31 | 1,162 | 29 | 1,363 | 34 | false | false | false | false | false | true |
160949_14 | package tools;
import java.text.SimpleDateFormat;
import java.util.Date;
/**
* This class describes the debt in library system.
*
* @author Lenar Gumerov
* @author Anastasia Minakova
* @author Madina Gafarova
*/
public class Debt {
/**
* tools.Debt ID.
*/
private int debtId;
/**
* Associated patron's ID.
*/
private int patronId;
/**
* Associated document ID.
*/
private int documentId;
/**
* Booking date.
*/
private Date bookingDate;
/**
* Expire date.
*/
private Date expireDate;
/**
* Fee applied to this debt.
*/
private double fee;
/**
* Renew status. Is associated document can be renewed.
*/
private boolean canRenew;
/**
* Initialize new debt.
*
* @param patronId Associated patron ID.
* @param documentId Associated document ID.
* @param bookingDate Booking date.
* @param expireDate Expire date.
* @param fee Fee applied to this debt.
* @param canRenew Renew status.
*/
public Debt(int patronId, int documentId, Date bookingDate, Date expireDate, double fee, boolean canRenew) {
this.patronId = patronId;
this.documentId = documentId;
this.bookingDate = bookingDate;
this.expireDate = expireDate;
this.fee = fee;
this.canRenew = canRenew;
}
/**
* Get this debt in string notation.
*
* @return String with debt description.
*/
public String toString() {
return patronId + " " + documentId + " (" + (new SimpleDateFormat("dd-MMM-yyyy")).format(bookingDate) + ") (" + (new SimpleDateFormat("dd-MMM-yyyy")).format(expireDate) + ") " + fee + " " + canRenew + " ";
}
/**
* Get the associated patron ID.
*
* @return users.Patron ID.
*/
public int getPatronId() {
return patronId;
}
/**
* Set the new associated patron ID.
*
* @param patronId New patron ID.
*/
public void setPatronId(int patronId) {
this.patronId = patronId;
}
/**
* Get the associated document ID.
*
* @return documents.Document ID.
*/
public int getDocumentId() {
return documentId;
}
/**
* Set the new associated document ID.
*
* @param documentId New document ID.
*/
public void setDocumentId(int documentId) {
this.documentId = documentId;
}
/**
* Get the booking date.
*
* @return Booking date.
* @see Date
*/
public Date getBookingDate() {
return bookingDate;
}
/**
* Set the new booking date.
*
* @param bookingDate New booking date.
* @see Date
*/
public void setBookingDate(Date bookingDate) {
this.bookingDate = bookingDate;
}
/**
* Get the expire date.
*
* @return Expire date.
* @see Date
*/
public Date getExpireDate() {
return expireDate;
}
/**
* Set the new expire date.
*
* @param date New expire date.
* @see Date
*/
public void setExpireDate(Date date) {
this.expireDate = date;
}
/**
* Get the fee applied to this debt.
*
* @return Fee.
*/
public double getFee() {
return fee;
}
/**
* Apply the new fee to this debt.
*
* @param fee New fee.
*/
public void setFee(double fee) {
this.fee = fee;
}
/**
* Get the info about ability to renew associated document.
*
* @return Renew status.
*/
public boolean canRenew() {
return canRenew;
}
/**
* Set the new renew status. Info about ability to renew associated document.
*
* @param canRenew New renew status.
*/
public void setCanRenew(boolean canRenew) {
this.canRenew = canRenew;
}
/**
* Get the remaining time to expire date in days.
*
* @return Days remain.
*/
public int daysLeft() {
return (int) ((expireDate.getTime() - System.currentTimeMillis()) / (60 * 60 * 24 * 1000));
}
/**
* Get this debt ID.
*
* @return tools.Debt ID.
*/
public int getDebtId() {
return debtId;
}
/**
* Set the new debt ID.
*
* @param debtId New debt ID.
*/
public void setDebtId(int debtId) {
this.debtId = debtId;
}
/**
* Apply fee for this debt.
*
* @param database tools.Database that stores the documents information.
*/
public void countFee(Database database) {
if (daysLeft() < 0) {
setFee(min(daysLeft() * (-100), database.getDocument(documentId).getPrice()));
}
}
/**
* For internal use.
* Returns the minimal number.
*/
private double min(double a, double b) {
return a < b ? a : b;
}
}
| lenargum/libraryProject | src/tools/Debt.java | 1,401 | /**
* Get the booking date.
*
* @return Booking date.
* @see Date
*/ | block_comment | en | false | 1,203 | 25 | 1,401 | 25 | 1,436 | 29 | 1,401 | 25 | 1,614 | 31 | false | false | false | false | false | true |
163047_1 | import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.util.ArrayList;
/**
* Simple I/O operations.
*
* You do not need to change this class.
*/
public class IO {
/**
*
* @param fileName a maze file name. File should not contain any extra white
* space.
* @return the Maze data structure of the maze represented by the file.
*/
public static Maze readInputFile(String fileName) {
char[][] mazeMatrix = null;
Square playerSquare = null;
Square goalSquare = null;
int noOfRows;
int noOfCols;
try {
ArrayList<String> lines = new ArrayList<String>();
BufferedReader reader = new BufferedReader(new FileReader(fileName));
String line;
while ((line = reader.readLine()) != null)
if (!line.equals(""))
lines.add(line);
noOfRows = lines.size();
noOfCols = lines.get(0).length();
mazeMatrix = new char[noOfRows][noOfCols];
for (int i = 0; i < noOfRows; ++i) {
line = lines.get(i);
for (int j = 0; j < noOfCols; ++j) {
mazeMatrix[i][j] = line.charAt(j);
if (mazeMatrix[i][j] == 'H')
playerSquare = new Square(i, j);
if (mazeMatrix[i][j] == 'C')
goalSquare = new Square(i, j);
}
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return new Maze(mazeMatrix, playerSquare, goalSquare);
}
/**
* Output the necessary information. You do not need to write any
* System.out.println() anywhere.
*
* @param maze
* the maze with each square that is part of the
* solution path
* @param cost
* the cost of the solution path
* @param noOfNodesExpanded
* the number of nodes expanded
* @param maxDepth
* the maximum depth searched
* @param maxFrontierSize
* the maximum size of the frontier list at any point during the
* search
*/
public static void printOutput(Maze maze, int cost, int noOfNodesExpanded) {
char[][] mazeMatrix = maze.getMazeMatrix();
for (int i = 0; i < mazeMatrix.length; ++i) {
for (int j = 0; j < mazeMatrix[0].length; ++j) {
System.out.print(mazeMatrix[i][j]);
}
System.out.println();
}
System.out.println("Total solution cost: " + cost);
System.out.println("Number of nodes expanded: " + noOfNodesExpanded);
}
}
| belostoky/cs540 | hw1/prob3/IO.java | 743 | /**
*
* @param fileName a maze file name. File should not contain any extra white
* space.
* @return the Maze data structure of the maze represented by the file.
*/ | block_comment | en | false | 644 | 45 | 743 | 46 | 735 | 49 | 743 | 46 | 891 | 52 | false | false | false | false | false | true |
163409_18 | import java.io.PrintWriter;
import java.time.LocalDateTime;
import java.util.*;
/**
* @author Nikola Nikolov
* @version 5 May 2021
*/
public class Bank {
private ArrayList<FillTypeQuestion>[] questions;
private ArrayList<Integer> shuffledPosition;
private ArrayList<String> givenAnswers;
private Map<String,Integer> studentResults;
private String id;
private static final int maxAnswersToGive = 10;
Bank() {
this("");
}
Bank(String id) {
this.id = id;
questions = new ArrayList[2];
questions[0] = new ArrayList<FillTypeQuestion>();
questions[1] = new ArrayList<FillTypeQuestion>();
givenAnswers = new ArrayList<String>();
shuffledPosition = new ArrayList<Integer>();
studentResults = new HashMap<>();
}
/**
* Get identifier
* @return id
*/
public String getId() {
return id;
}
/**
* This method sets the value for id
*
* @param id becomes the value
*/
public void setId(String id) {
this.id = id;
}
/**
* This method returns all the Questions
* @param lang the choosed language
* @return ret
*/
public String printAllQuestions(int lang) {
StringBuilder ret = new StringBuilder();
for (int i = 0; i < questions[0].size(); i++) {
ret.append(i + 1);
ret.append(". ");
ret.append(questions[lang].get(i).toString());
}
return ret.toString();
}
/**
* This method add a question (two languages) in the question ArrayList
*
* @param firstLang becomes the value of the fist language
* @param secLang becomes the value of the second language
*/
public void setQuestions(FillTypeQuestion firstLang, FillTypeQuestion secLang) {
questions[0].add(firstLang);
questions[1].add(secLang);
}
/**
* This method adds a new Question in the Quiz
*/
public void addQuestion() {
FillTypeQuestion newQuestion;
FillTypeQuestion newQuestionSecLang;
String response;
System.out.println("What kind of question do you want to create");
System.out.println(" F - Fill-type question");
System.out.println(" C - Choose-type question");
System.out.println(" M - Match-type question");
loop:
while (true) {
Scanner scan = new Scanner(System.in);
response = scan.nextLine().toUpperCase();
switch (response) { //checking what type of question and initialising it
case "F":
newQuestion = new FillTypeQuestion();
newQuestionSecLang = new FillTypeQuestion();
break loop;
case "C":
newQuestion = new ChooseTypeQuestion();
newQuestionSecLang = new ChooseTypeQuestion();
break loop;
case "M":
newQuestion = new MatchTypeQuestion();
newQuestionSecLang = new MatchTypeQuestion();
break loop;
default:
System.out.println("Try Again!");
}
}
newQuestion.createQuestion(); // calls the right method to create the question
System.out.println("Please type the SAME question in Bulgarian");
newQuestionSecLang.createQuestion();
questions[0].add(newQuestion); // store the English version
questions[1].add(newQuestionSecLang); // store the Bulgarian version
//System.out.println(questions[0].size() - 1);
shuffledPosition.add(questions[0].size() - 1);
}
/**
* This methid prints the collected information about the results of the quiz and returns the average result for the Quiz
* @return average result
*/
public int printCollectedResults(){
int average = 0;
for(Map.Entry m:studentResults.entrySet()){
System.out.println(" " + m.getKey() + " - " + m.getValue());
average += (int)(m.getValue());
}
return average/studentResults.size();
}
/**
* Prints the menu that is user can use throughout the quiz
*/
private void printQuizMenu() {
System.out.println("Before you start the quiz you have to know that you can use this commands through the quiz:");
System.out.println(" N - next question (automatically safes the answer)");
System.out.println(" P - previous question (automatically safes the answer)");
System.out.println(" S - Submit & Exit)");
}
/**
* By this method the user can do a quiz
* @param language
* @param username of the user
*/
public void doTheQuiz(int language, String username) {
LocalDateTime now = LocalDateTime.now();
givenAnswers = new ArrayList<String>(); // we store the answers that have been given
for (int i = 0; i < maxAnswersToGive; i++) givenAnswers.add(" "); // making sure that we have added enough elements
int currentQues = 1; // and using " " just so we can check if the user have got and answer
String response;
Scanner scan = new Scanner(System.in);
Collections.shuffle(shuffledPosition); // use shuffeledPosition so we can print them in random order without moving themselves
int maxQtoAnswer = setQNumToDoInQuiz(); // maxQtoAnswer is the nummber of q that user wants to answer from the Quiz
printQuizMenu();
long start = System.currentTimeMillis(); //saving the time so we know when quiz have been started
do {
System.out.println(currentQues + "/" + maxQtoAnswer);
System.out.print(currentQues + ". ");
questions[language].get(shuffledPosition.get(currentQues-1)).printQues();
response = scan.nextLine().toUpperCase();
switch (response) {
case "N":
if (currentQues == maxQtoAnswer) {
System.out.println("That is the last question. You can submit your work by typing 'S'");
break;
}
currentQues++;
break;
case "P":
if (currentQues-1 == 0) {
System.out.println("That is the first question. There is no previous.");
break;
}
currentQues--;
break;
case "S":
break;
default:
givenAnswers.set(shuffledPosition.get(currentQues-1), response);
if (currentQues == maxQtoAnswer) {
System.out.println("That is the last question. You can submit your work by typing 'S'");
break;
}
currentQues++;
}
} while (!(response.equals("S")));
long end = System.currentTimeMillis(); // saving that time when the quiz have been ended
float time = (end - start) / 1000;
int hour = (int) (time/120); time = time -hour*120;
int min = (int) (time/60); time = time-min*60;
System.out.println("You do the quiz for " + hour + ":"+ min + ":"+ (int)time);
int result = calculateQuizResults(maxQtoAnswer);
System.out.println("Your Result is " + result + "% !");
studentResults.put(username, result); //saving the Quiz results
}
/**
* This method asks the user how many questions he wants to answer
* @return num the max number of questions to answer
*/
public int setQNumToDoInQuiz(){
String response;
Scanner scan = new Scanner(System.in);
Integer num = null;
do {
System.out.println("How many questions from the quiz you want to do");
response = scan.nextLine();
try {
// Parse the input if it is successful, it will set a non null value to i
num = Integer.parseInt(response);
} catch (NumberFormatException e) {
// The input value was not an integer so i remains null
System.out.println("That's not a number!");
}
} while (num == null && num >0);
if(num > questions[0].size()){
return questions[0].size();
}else{
return num;
}
}
/**
* Get the num of questions
* @return the num of questions
*/
public int getQuestionsNum(){
return questions[0].size();
}
/**
* This method returns the result of the quiz in %
*
* @param maxQ max questions to answer from the quiz
* @return result - the result of the quiz in %
*/
private int calculateQuizResults(int maxQ) {
float result = 0;
int notAnswered = 0;
for (int i = 0; i < maxAnswersToGive; i++) {
if (givenAnswers.get(i) ==" "){
notAnswered++;
}
else if(questions[0].get(i).isTheRightAnswer(givenAnswers.get(i))) {
result++;
}
}
result = result / maxQ * 100;
System.out.println( (notAnswered-(maxAnswersToGive -maxQ)) + " not answered questions");
return Math.round(result);
}
/**
* This method remove a question
* @param index of the question
*/
public void deleteQuestion(int index) {
questions[0].remove(index);
questions[1].remove(index);
for (int i = 0; i < shuffledPosition.size(); i++) {
if (shuffledPosition.get(i) == index) {
shuffledPosition.remove(i);
break;
}
}
}
/**
* Write information about the bank in the file
*/
public void save(PrintWriter pw) {
pw.println(id);
pw.println(questions[0].size());
for (int i = 0; i < questions[0].size(); i++) {
questions[0].get(i).save(pw);
questions[1].get(i).save(pw);
}
pw.println(studentResults.size());
for(Map.Entry m:studentResults.entrySet()){
pw.println(m.getKey());
pw.println(m.getValue());
}
}
/**
* Reads in information about the Bank from the file
* @param infile
*/
public void load(Scanner infile) {
id = infile.next();
int num = infile.nextInt();
shuffledPosition = new ArrayList<Integer>();
questions = new ArrayList[2];
givenAnswers = new ArrayList<String>();
questions[0] = new ArrayList<FillTypeQuestion>();
questions[1] = new ArrayList<FillTypeQuestion>();
studentResults = new HashMap<>();
for (int oCount = 0; oCount < num; oCount++) {
FillTypeQuestion q = null;
String s = infile.next();
if (s.equals("FILL-TYPE")) {
q = new FillTypeQuestion();
} else if(s.equals("CHOOSE-TYPE")){
q = new ChooseTypeQuestion();
} else {
q = new MatchTypeQuestion();
}
q.load(infile);
questions[0].add(q);
s = infile.next();
if (s.equals("FILL-TYPE")) { //we are doing that second time because otherwise both languages will be the same
q = new FillTypeQuestion();
} else if(s.equals("CHOOSE-TYPE")){
q = new ChooseTypeQuestion();
} else {
q = new MatchTypeQuestion();
}
q.load(infile);
questions[1].add(q);
shuffledPosition.add(questions[0].size() - 1);
}
num = infile.nextInt();
for (int i=0; i<num; i++){
studentResults.put(infile.next(), infile.nextInt());
}
}
}
| nikkola01/Questionnaire-Software | src/Bank.java | 2,735 | // maxQtoAnswer is the nummber of q that user wants to answer from the Quiz | line_comment | en | false | 2,571 | 20 | 2,735 | 21 | 3,009 | 19 | 2,735 | 21 | 3,284 | 21 | false | false | false | false | false | true |
164055_2 | /*
* Click nbfs://nbhost/SystemFileSystem/Templates/Licenses/license-default.txt to change this license
* Click nbfs://nbhost/SystemFileSystem/Templates/Classes/Class.java to edit this template
*/
package com.mycompany.lab7;
/**
*
* @author prabin
*/
/*Create a base class fruit which has name,taste and size as tis attributes.Amethod called eat() is created which describes
the name of the fruit and its taste .Inherit the same in 2 other class Apple and orange and override the eat() method to represent each
fruit taste.*/
class fruit{
String name;
String taste;
String size;
public fruit(String name,String taste, String size){
this.name=name;
this.taste=taste;
this.size=size;
}
void eat(){
System.out.println(name+" Taste "+taste+".It is "+size+" in size.");
}
}
class apple extends fruit{
public apple(String name,String taste,String size){
super(name,taste,size);
}
void displayapple(){
eat();
}
}
class orange extends fruit{
public orange(String name,String taste,String size){
super(name,taste,size);
}
void displayorange(){
eat();
}
}
public class QN1 {
public static void main(String[] args){
apple a=new apple("Apple","Sweet","Small");
a.displayapple();
orange o=new orange("Orange","Sour and Sweet","Medium");
o.displayorange();
}
}
| Prabinpoudel192/java-lab7 | QN1.java | 382 | /*Create a base class fruit which has name,taste and size as tis attributes.Amethod called eat() is created which describes
the name of the fruit and its taste .Inherit the same in 2 other class Apple and orange and override the eat() method to represent each
fruit taste.*/ | block_comment | en | false | 322 | 62 | 382 | 64 | 399 | 61 | 382 | 64 | 429 | 65 | false | false | false | false | false | true |
165560_0 | //Create 15 classes of your choice in each class declare 2 static methods and invoke the method
public class Collegehsn{
public static void students (){
System.out.println("maland college");
}
public static void teachers (){
System.out.println("maland college");
}
}
| jhenkar01/java | Collegehsn.java | 76 | //Create 15 classes of your choice in each class declare 2 static methods and invoke the method | line_comment | en | false | 58 | 21 | 76 | 21 | 74 | 21 | 76 | 21 | 79 | 21 | false | false | false | false | false | true |
166321_6 | /*=============================================
class Warrior -- protagonist of Ye Olde RPG
(_)
__ ____ _ _ __ _ __ _ ___ _ __
\ \ /\ / / _` | '__| '__| |/ _ \| '__|
\ V V / (_| | | | | | | (_) | |
\_/\_/ \__,_|_| |_| |_|\___/|_|
=============================================*/
public class Warrior extends Character {
// ~~~~~~~~~~~ INSTANCE VARIABLES ~~~~~~~~~~~
// inherited from superclass
// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
/*=============================================
default constructor
pre: instance vars are declared
post: initializes instance vars.
=============================================*/
public Warrior() {
super();
_hitPts = 125;
_strength = 100;
_defense = 40;
_attack = .4;
}
/*=============================================
overloaded constructor
pre: instance vars are declared
post: initializes instance vars. _name is set to input String.
=============================================*/
public Warrior( String name ) {
this();
if (!name.equals("")) {
_name = name;
}
}
/*=============================================
void specialize() -- prepares character for special attack
pre:
post: Attack of character is increased, defense is decreased
=============================================*/
public void specialize() {
_attack = .75;
_defense = 20;
}
/*=============================================
void normalize() -- revert stats back to normal
pre:
post: Attack and defense of character is de-specialized
=============================================*/
public void normalize() {
_attack = .45;
_defense = 40;
}
/*=============================================
String about() -- returns descriptions character type
pre:
post: Info is returned
=============================================*/
public String about() {
return "Warriors are fierce and strong fighters, but are slow.";
}
/*==========================
String heroSpecial()
pre:
post: executes a character's special move, for example, a priest would heal itself, and
returns a string summarizing what happened.
========================*/
public String heroSpecial(){
if (((int) (Math.random()*99)) >= 50){
this._strength+=20;
return "your warrior summons a magical steroid and eats it, your warrior's strength has increased to " + this._strength;
}
else {
this._hitPts-=10;
this._defense -=10;
return "your warrior accidentally summons a bad magic steroid, lowering HP and defence by 10" ;
}
}
}//end class Warrior
| siuryan-cs-stuy/YoRPG_FileNotFound | Warrior.java | 646 | /*=============================================
void specialize() -- prepares character for special attack
pre:
post: Attack of character is increased, defense is decreased
=============================================*/ | block_comment | en | false | 590 | 36 | 646 | 38 | 737 | 43 | 646 | 38 | 855 | 51 | false | false | false | false | false | true |
170170_0 | class FoodItem {
private String name;
private double price;
private String description;
private boolean is_available;
private int restaurant_id;
public FoodItem(String name, double price, String description, boolean is_available, int restaurant_id) {
this.name = name;
this.price = price;
this.description = description;
this.is_available = is_available;
this.restaurant_id = restaurant_id;
}
public String getName() {
return name;
}
public String getDescription() {
return description;
}
public double getPrice() {
return price;
}
public boolean isAvailable() {
return is_available;
}
public int getRestaurantId() {
return restaurant_id;
}
public void setPrice(double price) {
this.price = price;
}
public void setDescription(String description) {
this.description = description;
}
public void setAvailability(boolean is_available) {
this.is_available = is_available;
}
public void setName(String name) {
this.name = name;
}
/**
* @return String
*
* This method returns the information about the food item
*/
public String getFoodInfo() {
Restaurant restaurant = CSVOperations.getRestaurantById(this.restaurant_id);
return "\nName: " + this.name + "; Price: " + this.price + "; Description: " + this.description + "; Available: " + this.is_available + "; Restaurant: " + restaurant.getName() + "; Address: " + restaurant.getAddress() + "\n";
}
} | xelilovkamran/food_delivery_system | src/FoodItem.java | 369 | /**
* @return String
*
* This method returns the information about the food item
*/ | block_comment | en | false | 334 | 24 | 369 | 21 | 423 | 26 | 369 | 21 | 454 | 26 | false | false | false | false | false | true |
170302_8 | import java.awt.Color;
import java.awt.Dimension;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.image.BufferedImage;
import javax.swing.JFrame;
import javax.swing.JPanel;
/**
* PixGrid Class
* Holds Pix objects and handles movement
* @author Nic Manoogian <[email protected]>
* @author Mike Lyons
*/
public class PixGrid
{
private BufferedImage canvas;
private Pix[][] grid;
/**
* Constructs a PixGrid with size 640x480
*/
public PixGrid()
{
// Defaults to 640x480
grid = new Pix[640][480];
}
/**
* Constructs a PixGrid with size and 10 Pix objects
* @param xsize width
* @param ysize height
*/
public PixGrid(int xsize, int ysize)
{
grid = new Pix[xsize][ysize];
generate_blank_world();
}
/**
* Constructs a PixGrid with size and n Pix objects
* @param xsize width
* @param ysize height
* @param n number of Pix objects to add
*/
public PixGrid(int xsize, int ysize, int n)
{
grid = new Pix[xsize][ysize];
generate_blank_world();
}
/**
* Fills grid with white Pix of a certain type
*/
public void generate_blank_world()
{
for( int i = 0; i < grid.length; i++ )
{
for( int j = 0; j < grid[0].length; j ++ )
{
grid[i][j] = new Pix(255,255,255);
}
}
}
/**
* Returns the grid
* @return grid
*/
public Pix[][] getGrid()
{
return grid;
}
/**
* Loops through all non-white Pix and transitions them in a random direction (N S E W)
*/
public void update()
{
for( int i = 0; i < grid.length; i++ )
{
for( int j = 0; j < grid[0].length; j ++ )
{
if( !grid[i][j].isWhite() )
{
grid[i][j].update( i , j );
}
}
}
}
/**
* Returns a String representation of a PixGrid
* @return PixGrid String representation
*/
public String toString()
{
String new_string = "";
for( int i = 0; i < grid.length; i++ )
{
for( int j = 0; j < grid[0].length; j ++ )
{
new_string += "(" + grid[i][j] + ") ";
}
new_string += "\n";
}
return new_string;
}
} | nmanoogian/PixelifeJava | PixGrid.java | 772 | /**
* Returns a String representation of a PixGrid
* @return PixGrid String representation
*/ | block_comment | en | false | 652 | 23 | 772 | 23 | 762 | 24 | 772 | 23 | 875 | 26 | false | false | false | false | false | true |
170564_4 | /**
* This class is used to create objects that represent prizes in the
* Lucky Vending Machine. It is used by the PrizeList and Player classes.
*
* @author Bai Chan Kheo 22262407
* @version 1.3 27 May 2015
*/
public class Prize
{
private String name;
private int worth;
private int cost;
/**
* Constructor that takes no arguments.
*/
public Prize()
{
name = "";
worth = 0;
cost = 0;
}
/**
* Constructor that takes arguments for all attributes.
*
* @param newName The name of the prize.
* @param newWorth The prize's worth.
* @param newCost The prize's cost.
*/
public Prize(String newName, int newWorth, int newCost)
{
name = newName;
worth = newWorth;
cost = newCost;
}
/**
* Method that displays the details of the Prize object.
*/
public void displayPrize()
{
System.out.println(name + ", Worth: $" + worth +
", Cost: $" + cost);
}
/**
* Accessor method for cost attribute.
*
* @return The cost of the Prize.
*/
public int getCost()
{
return cost;
}
/**
* Accessor method for name attribute.
*
* @return The name of the Prize.
*/
public String getName()
{
return name;
}
/**
* Accessor method for worth attribute.
*
* @return The prize's worth.
*/
public int getWorth()
{
return worth;
}
/**
* Mutator method for cost attribute.
*
* @param newCost The cost of the prize.
* @return True if the cost is valid.
*/
public boolean setCost(int newCost)
{
boolean valid = false;
if (newCost > 0)
{
cost = newCost;
valid = true;
}
return valid;
}
/**
* Mutator method for name attribute.
*
* @param newName The name of the prize.
* @return True if the name is valid.
*/
public boolean setName(String newName)
{
boolean valid = false;
if (newName.trim().length() > 0 && Character.isLetter(newName.charAt(0)))
{
name = newName;
valid = true;
}
return valid;
}
/**
* Mutator method for worth attribute.
*
* @param newWorth The prize's worth.
* @return True if the worth is valid.
*/
public boolean setWorth(int newWorth)
{
boolean valid = false;
if (newWorth > 0)
{
worth = newWorth;
valid = true;
}
return valid;
}
} | kheob/F9IT131-Assignment-2 | Prize.java | 694 | /**
* Accessor method for cost attribute.
*
* @return The cost of the Prize.
*/ | block_comment | en | false | 675 | 26 | 694 | 26 | 799 | 30 | 694 | 26 | 832 | 30 | false | false | false | false | false | true |
170606_7 | package Maps;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Arrays;
import javax.imageio.ImageIO;
import Geom.Point3D;
/**
*
* @author Netanel Ben-Isahar
* @author daniel abergel
* this class represent a map with objects that represent the edges of the map.
* it also support some conversion functions.
*
*/
public class Map
{
private Point3D StartPoint ;
private Point3D EndPoint ;
private Pixel FrameSize ;
public BufferedImage myImage;
/**
* this constructor build the map with the appropriate values.
*/
public Map()
{
StartPoint = new Point3D(35.20234,32.10584,0);
EndPoint = new Point3D(35.21237,32.10193,0);
FrameSize = new Pixel(1433, 642);
StartPoint.GPS2Meter();
EndPoint.GPS2Meter();
try {
myImage = ImageIO.read(new File("Ariel1.PNG"));
} catch (IOException e) {
e.printStackTrace();
}
}
/**
* this function calculate the gps location after adding pixels distance
* @param PixelXMove represent the move on the x axis
* @param PixelYMove represent the move on the y axis
* @return the new gps point after the move
*/
public Point3D Pixel2GPSPoint( double PixelXMove , double PixelYMove )
{
Pixel p = Pixel2Meter(FrameSize.get_PixelX(), FrameSize.get_PixelY());
PixelXMove = PixelXMove * p.get_PixelX();
PixelYMove = PixelYMove * p.get_PixelY();
Point3D result = new Point3D(PixelXMove + StartPoint.x(),PixelYMove + StartPoint.y(),0);
result.Meter2GPS();
return result ;
}
/**
* this function calculate the pixel location after adding pixels distance
* @param PixelXMove represent the move on the x axis
* @param PixelYMove represent the move on the y axis
* @return the new pixel point after the move
*/
private Pixel Pixel2Meter(double PixelXSize , double PixelYSize )
{
double disX = EndPoint.x() - StartPoint.x() ;
double disY = EndPoint.y() - StartPoint.y();
double PixelAsMeterX = disX / PixelXSize ;
double PixelAsMeterY = disY / PixelYSize ;
Pixel _Pixel = new Pixel(PixelAsMeterX, PixelAsMeterY);
return _Pixel ;
}
/**
* this function convert between gps point to pixels
* @param Point represent the 3D point
* @return the pixel location
*/
public Pixel GPSPoint2Pixel(Point3D Point)
{
Point.GPS2Meter();
Pixel Worth = Pixel2Meter(FrameSize.get_PixelX(), FrameSize.get_PixelY());
double disX = Point.x() - StartPoint.x() ;
double disY = Point.y() - StartPoint.y();
double dx = disX / Worth.get_PixelX() ;
double dy = disY / Worth.get_PixelY() ;
Point.Meter2GPS();
Pixel Pix = new Pixel(dx, dy);
if(isVaildPixel(Pix))
return Pix ;
else
{
// throw new RuntimeException("The Pixel is out of bounds");
}
return Pix ;
}
/**
* this function is checking if the point is in our area
* @param p represent the pixel point
* @return true if the point is in our area
*/
private boolean isVaildPixel(Pixel p)
{
Pixel PSubtract = FrameSize.Subtract(p) ;
return PSubtract.get_PixelX() > 0 && PSubtract.get_PixelY() > 0;
}
/**
* this function calculate the correct pixels position after rescaling the picture
* @param p represent the new end point
* @param PackArr arraylist of packmans
* @param FruitArr arraylist of fruits
*/
public void ChangeFrameSize(Pixel p)
{
FrameSize.set_PixelX(p.get_PixelX());
FrameSize.set_PixelY(p.get_PixelY());
}
}
| DanielAbergel/PackmanGame | src/Maps/Map.java | 1,122 | /**
* this function calculate the correct pixels position after rescaling the picture
* @param p represent the new end point
* @param PackArr arraylist of packmans
* @param FruitArr arraylist of fruits
*/ | block_comment | en | false | 1,010 | 52 | 1,122 | 51 | 1,143 | 54 | 1,122 | 51 | 1,285 | 57 | false | false | false | false | false | true |
170907_8 | /**
Battleship!
KU EECS 448 project 2
TeamName: BigSegFaultEnergy
* \Author: Chance Penner
* \Author: Markus Becerra
* \Author: Sarah Scott
* \Author: Thomas Gardner
* \Author: Haonan Hu
* \File: Ship.java
* \Date: 10/14/2019
* \Brief: This class serves as a the executive class of
Battleship
KU EECS 448 project 1
TeamName: Poor Yorick
* \Author: Max Goad
* \Author: Jace Bayless
* \Author: Tri Pham
* \Author: Apurva Rai
* \Author: Meet Kapadia
* \File: Ship.java
* \Brief: This class serves as a the executive class of
Battleship
*/
//Here are erternal classes that need to be imported
import java.awt.Point;
import java.util.ArrayList;
public class Ship
{
//Declare variables for the ship coordinates, ship size
private ArrayList<Point> shipCoordinates = new ArrayList<Point>();
private int shipSize;
private int shipPieces;
/*
* @ pre none
* @ param Ships' size
* @ post constuctor
* @ return none
*/
public Ship(int size)
{
this.shipSize = size;
this.shipPieces = size;
}
/*
* @ pre none
* @ param none
* @ post gets ship's size
* @ return returns ships size
*/
public int getSize()
{
return shipSize;
}
/*
* @ pre none
* @ param none
* @ post gets ships coordinates
* @ return returns ship's coordinates
*/
public ArrayList<Point> getShipCoordinates() {
return shipCoordinates;
}
/*
* @ pre none
* @ param x and y values of the grid
* @ post adds new coordinates of the ship
* @ return none
*/
public void addCoordinates(int x, int y)
{
shipCoordinates.add(new Point(x, y));
}
/*
* @ pre none
* @ param new x and y values of the grid
* @ post none
* @ return returns true or false on whether or not the ships are in line
*/
public boolean inline(int newX, int newY)
{
if (shipCoordinates.size() == 0)
{
return true;
}
for (Point shipPiece : shipCoordinates)
{
int x = (int) shipPiece.getX();
int y = (int) shipPiece.getY();
if (newX == x && (newY == y + 1 || newY == y - 1))
{
return true;
}
else if (newY == y && (newX == x + 1 || newX == x - 1))
{
return true;
}
}
return false;
}
/*
* @ pre the coordinate an opponenet entered to fire at
* @ param x and y values of the grid
* @ post decreases the number of ships because it was "attacked"
* @ return none
*/
public void hit(int x, int y)
{
shipPieces--;
}
/*
* @ pre none
* @ param x and y values of the grid
* @ post none
* @ return returns true or false on whether or not a specific coordinate exists or not
*/
public boolean containsCoordinate(int x, int y)
{
if (shipCoordinates.size() == 0)
{
return false;
}
if (x >= 0 && x <= 7 && y >= 0 && y <= 7)
{
for (int i = 0; i < shipCoordinates.size(); i++)
{
int cordX = (int) shipCoordinates.get(i).getX();
int cordY = (int) shipCoordinates.get(i).getY();
if (cordX == x && cordY == y)
{
return true;
}
}
}
return false;
}
/*
* @ pre the coordinate an opponenet entered to fire at a specific ship
* @ param none
* @ post none
* @ return returns true or false on whether or not the ship is destroyed or not
*/
public boolean isDestroyed()
{
if (shipPieces <= 0)
{
return true;
}
return false;
}
}
| ChancePenner/Battleship-Java | Ship.java | 1,031 | /*
* @ pre the coordinate an opponenet entered to fire at
* @ param x and y values of the grid
* @ post decreases the number of ships because it was "attacked"
* @ return none
*/ | block_comment | en | false | 1,015 | 51 | 1,031 | 51 | 1,141 | 54 | 1,031 | 51 | 1,225 | 56 | false | false | false | false | false | true |
171408_8 | import java.util.LinkedList;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
/**
* A simple work queue implementation based on the IBM developerWorks article by
* Brian Goetz. It is up to the user of this class to keep track of whether
* there is any pending work remaining.
*
* @see <a href="https://www.ibm.com/developerworks/library/j-jtp0730/">Java
* Theory and Practice: Thread Pools and Work Queues</a>
*/
public class WorkQueue {
/**
* Pool of worker threads that will wait in the background until work is
* available.
*/
private final PoolWorker[] workers;
/** Queue of pending work requests. */
private final LinkedList<Runnable> queue;
/** Used to signal the queue should be shutdown. */
private volatile boolean shutdown;
/** The default number of threads to use when not specified. */
public static final int DEFAULT = 5;
/**
* logger to see what is going on
*/
private Logger log = LogManager.getLogger(); // TODO Use keywords
/**
* variable to keep track of pending work
*/
private int pending;
/**
* Starts a work queue with the default number of threads.
*
* @see #WorkQueue(int)
*/
public WorkQueue() {
this(DEFAULT);
}
/**
* Starts a work queue with the specified number of threads.
*
* @param threads
* number of worker threads; should be greater than 1
*/
public WorkQueue(int threads) {
this.queue = new LinkedList<>();
this.workers = new PoolWorker[threads];
shutdown = false;
pending = 0;
// start the threads so they are waiting in the background
for (int i = 0; i < threads; i++) {
workers[i] = new PoolWorker();
workers[i].start();
}
}
/**
* Adds a work request to the queue. A thread will process this request when
* available.
*
* @param r work request (in the form of a {@link Runnable} object)
*/
public void execute(Runnable r) {
incrementPending();
synchronized (queue) {
queue.addLast(r);
queue.notifyAll();
log.debug("{} being added to work queue ... {} pending jobs", Thread.currentThread().getName(), pending);
}
}
/**
* Asks the queue to shutdown. Any unprocessed work will not be finished,
* but threads in-progress will not be interrupted.
*/
public void shutdown() {
// safe to do unsynchronized due to volatile keyword
shutdown = true;
synchronized (queue) {
queue.notifyAll();
}
}
/**
* Returns the number of worker threads being used by the work queue.
*
* @return number of worker threads
*/
public int size() {
return workers.length;
}
/**
* Signifies the end of work
*/
public synchronized void finish() {
while(pending > 0) {
try {
this.wait();
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
}
}
}
/**
* Adds to the total amount of jobs for workers to execute
*/
private synchronized void incrementPending() {
pending++;
}
/**
* Subtracts the total amount of jobs for workers to execute
*/
private synchronized void decrementPending() {
assert pending > 0;
pending--;
if (pending == 0) {
this.notifyAll();
}
}
/**
* Waits until work is available in the work queue. When work is found, will
* remove the work from the queue and run it. If a shutdown is detected, will
* exit instead of grabbing new work from the queue. These threads will
* continue running in the background until a shutdown is requested.
*/
private class PoolWorker extends Thread {
@Override
public void run() {
Runnable r = null;
while (true) {
synchronized (queue) {
while (queue.isEmpty() && !shutdown) {
try {
queue.wait();
}
catch (InterruptedException ex) {
System.err.println("Warning: Work queue interrupted while waiting.");
Thread.currentThread().interrupt();
}
}
// exit while for one of two reasons:
// (a) queue has work, or (b) shutdown has been called
if (shutdown) {
break;
}
else {
r = queue.removeFirst();
}
}
try {
log.debug("{} starting ... {} pending jobs", Thread.currentThread().getName(), pending);
r.run();
}
catch (RuntimeException ex) {
// catch runtime exceptions to avoid leaking threads
System.err.println("Warning: Work queue encountered an exception while running.");
}
finally {
decrementPending();
log.debug("{} finished ... {} pending jobs", Thread.currentThread().getName(), pending);
}
}
}
}
} | arcSoftworks/search_engine | WorkQueue.java | 1,238 | /**
* Starts a work queue with the default number of threads.
*
* @see #WorkQueue(int)
*/ | block_comment | en | false | 1,104 | 27 | 1,238 | 28 | 1,279 | 32 | 1,238 | 28 | 1,572 | 33 | false | false | false | false | false | true |
171824_0 | package Ch8;
import java.io.File;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Scanner;
/*
Measure the difference when counting long words with a parallelStream
instead of a stream . Call System.currentTimeMillis before and after the call and
print the difference. Switch to a larger document (such as War and Peace)
if you have a fast computer.
*/
public class Ex2 {
public static void main(String[] args) throws Throwable {
String contents = new String(Files.readAllBytes(Paths.get("war and peace.txt")));
List<String> words = Arrays.asList(contents.split("\\PL+"));
long start = System.currentTimeMillis();
long n = words.stream()
.filter(w -> w.length() > 12)
.count();
long end = System.currentTimeMillis();
System.out.println(end - start + "ms");
start = System.currentTimeMillis();
n = words.parallelStream()
.filter(w -> w.length() > 12)
.count();
end = System.currentTimeMillis();
System.out.println(end - start + "ms");
}
}
| siegler/CoreJavaForTheImpatient | src/Ch8/Ex2.java | 301 | /*
Measure the difference when counting long words with a parallelStream
instead of a stream . Call System.currentTimeMillis before and after the call and
print the difference. Switch to a larger document (such as War and Peace)
if you have a fast computer.
*/ | block_comment | en | false | 243 | 52 | 301 | 57 | 318 | 57 | 301 | 57 | 344 | 61 | false | false | false | false | false | true |
171981_2 | package hw8;
import java.util.*;
import hw5.DirectedLabeledEdge;
/**
* CampusPath represented an immutable path on map from location A to location B
* A campusPath is a collection of Edge of PathNode which represent the path from
* A to B if A and B is directly connected by a single road.
*
* Assume an edge from A to B is represent as [A, distance, B]:
* A path from A to D is represented as:
* [A, 0.0, A] [A, distance, B] [B, distance, C] [C, distance, D]
*
* Specification field:
* @specfield path : List of the passed-by location's coordinate and distance between them
* @specfield totalDistance: Double // Distance of a path
* @specfield totalTurns : Double // Number of turns this path has
*
* Abstract Invariant:
* A path must have at least 0 turn and at least 0 distance
*/
public class CampusPath {
/* Abstraction Function:
* AF(r) = CampusPath p such that:
* p.path = r.path
* p.totalDistance = r.totalCost
* p.totalTurns = r.size
*
* Representation Invariant:
* CampusPath != null || path != null || totalCost != null ||
* size >= 0 || totalCost >=0
*/
/**
* Checks that the representation invariant holds (if any).
*/
private void checkRep() {
assert(this != null);
assert(this.path != null);
assert(this.totalCost != null);
assert(this.size >= 0);
assert(this.totalCost >= 0);
}
private final List<DirectedLabeledEdge<PathNode, Double>> path;
private final Double totalCost;
private final int size;
/**
* @requires passed in list of pass is not null
* @param path the collection of edges that represent the location a Campus path passed by and distance between locations
* @effects Construct a new CampusPath with passed-in path
* @modifies this
* @throws IllegalArgumentException if passed in list is null
*/
public CampusPath(List<DirectedLabeledEdge<PathNode, Double>> path) {
if (path == null) {
throw new IllegalArgumentException("Campus path can not build on a null path");
}
this.path = path;
Double cost = 0.0;
for (DirectedLabeledEdge<PathNode, Double> edge : path) {
cost += edge.getLabel();
}
totalCost = cost;
size = path.size();
checkRep();
}
/**
* @return the total turns a campus path has
*/
public int getTotalTurns() {
if (size == 1) {
return 0;
} else {
return this.size - 2;
}
}
/**
* @requires n >= 0 && n < this.size
* @param turn, the number of turns at the target location
* @return the distance from location after n turns to location after n+1 turns, Double
* if path's start location and destination is the same, return 0.0 regardless the parameter
* @throws IllegalArgumentException when n < 0 || n >= this.size
*/
public Double getDistance(int n) {
if (n < 0 || n >= this.size) {
throw new IllegalArgumentException("The number of turns has to be in the range of total path turns");
}
if (this.size == 1) {
return path.get(0).getLabel();
} else {
return path.get(n+1).getLabel();
}
}
/**
* @requires n >= 0 && n < this.size
* @param turn, the number of turns at the target location
* @return the x coordinate of current start position after n turns, Double
* if path's start location and destination is the same, return start location regardless the parameter
* @throws IllegalArgumentException when n < 0 || n >= this.size
*/
public Double getStartLocationX(int n) {
if (n < 0 || n >= this.size) {
throw new IllegalArgumentException("The number of turns has to be in the range of total path turns");
}
if (this.size == 1) {
return path.get(0).getParentNode().getX();
} else {
return path.get(n+1).getParentNode().getX();
}
}
/**
* @requires n >= 0 && n < this.size
* @param turn, int the number of turns already made
* @return the y coordinate of current start position after n turns, Double
* if path's start location and destination is the same, return start location regardless the parameter
* @throws IllegalArgumentException when n < 0 || n >= this.size
*/
public Double getStartLocationY(int n) {
if (n < 0 || n >= this.size) {
throw new IllegalArgumentException("The number of turns has to be in the range of total path turns");
}
if (this.size == 1) {
return path.get(0).getParentNode().getY();
} else {
return path.get(n+1).getParentNode().getY();
}
}
/**
* @requires n >= 0 && n < this.size
* @param turn, int the number of turns already made
* @return the x coordinate of current destination position after n turns, Double
* if path's start location and destination is the same, return dest location regardless the parameter
* @throws IllegalArgumentException when n < 0 || n >= this.size
*/
public Double getDestLocationX(int n) {
if (n < 0 || n >= this.size) {
throw new IllegalArgumentException("The number of turns has to be in the range of total path turns");
}
if (this.size == 1) {
return path.get(0).getChildrenNode().getX();
} else {
return path.get(n+1).getChildrenNode().getX();
}
}
/**
* @requires n >= 0 && n < this.size
* @param turn, int the number of turns already made
* @return the y coordinate of current destination position after n turns, Double
* if path's start location and destination is the same, return dest location regardless the parameter
* @throws IllegalArgumentException when n < 0 || n >= this.size
*/
public Double getDestLocationY(int n) {
if (n < 0 || n >= this.size) {
throw new IllegalArgumentException("The number of turns has to be in the range of total path turns");
}
if (this.size == 1) {
return path.get(0).getChildrenNode().getY();
} else {
return path.get(n+1).getChildrenNode().getY();
}
}
}
| hanyax/CampusMap | hw8/CampusPath.java | 1,724 | /**
* Checks that the representation invariant holds (if any).
*/ | block_comment | en | false | 1,594 | 16 | 1,724 | 15 | 1,808 | 18 | 1,724 | 15 | 2,003 | 19 | false | false | false | false | false | true |
173906_1 | /* package codechef; // don't place package name! */
import java.util.*;
import java.lang.*;
import java.io.*;
/* Name of the class has to be "Main" only if the class is public. */
class Codechef
{
public static void main (String[] args) throws java.lang.Exception
{
// your code goes here
Scanner sc=new Scanner(System.in);
int t=sc.nextInt();
while(t-->0){
int n=sc.nextInt();
if(n>98){
System.out.println("YES");
}else{
System.out.println("NO");
}
}
}
}
| danu20002/code_chef_solutions | fever.java | 164 | /* Name of the class has to be "Main" only if the class is public. */ | block_comment | en | false | 133 | 19 | 164 | 19 | 177 | 19 | 164 | 19 | 196 | 19 | false | false | false | false | false | true |
174402_0 | import java.util.ArrayList;
import java.io.*;
import java.util.*;
import java.text.*;
import java.math.*;
import java.util.regex.*;
import java.util.ArrayList;
import java.util.Scanner;
enum Color {
RED, GREEN
}
abstract class Tree {
private int value;
private Color color;
private int depth;
public Tree(int value, Color color, int depth) {
this.value = value;
this.color = color;
this.depth = depth;
}
public int getValue() {
return value;
}
public Color getColor() {
return color;
}
public int getDepth() {
return depth;
}
public abstract void accept(TreeVis visitor);
}
class TreeNode extends Tree {
private ArrayList<Tree> children = new ArrayList<>();
public TreeNode(int value, Color color, int depth) {
super(value, color, depth);
}
public void accept(TreeVis visitor) {
visitor.visitNode(this);
for (Tree child : children) {
child.accept(visitor);
}
}
public void addChild(Tree child) {
children.add(child);
}
}
class TreeLeaf extends Tree {
public TreeLeaf(int value, Color color, int depth) {
super(value, color, depth);
}
public void accept(TreeVis visitor) {
visitor.visitLeaf(this);
}
}
abstract class TreeVis
{
public abstract int getResult();
public abstract void visitNode(TreeNode node);
public abstract void visitLeaf(TreeLeaf leaf);
}
class SumInLeavesVisitor extends TreeVis { int result=0;
public int getResult() {
return result;
}
public void visitNode(TreeNode node) {
}
public void visitLeaf(TreeLeaf leaf) {
result+=leaf.getValue();
}
}
class ProductOfRedNodesVisitor extends TreeVis { long result=1L;
public int getResult() {
return (int)result;
}
public void visitNode(TreeNode node) {
if(node.getColor()==Color.RED){
result= (result * node.getValue()) % (1000000007);
}
}
public void visitLeaf(TreeLeaf leaf) {
if(leaf.getColor()==Color.RED){
result= (result * leaf.getValue()) % (1000000007);
}
}
}
class FancyVisitor extends TreeVis { int sumOfNode=0; int sumOfLeaf=0; public int getResult() { return Math.abs(sumOfNode-sumOfLeaf); }
public void visitNode(TreeNode node) {
if(node.getDepth()%2==0){
sumOfNode+=node.getValue();
}
}
public void visitLeaf(TreeLeaf leaf) {
if(leaf.getColor()==Color.GREEN){
sumOfLeaf+=leaf.getValue();
}
}
}
public class Solution {
public static Tree solve() {
//read the tree from STDIN and return its root as a return value of this function
Scanner sc = new Scanner(System.in);
int n = sc.nextInt();
int[] vals = new int[n];
for(int i=0; i<n; i++){
vals[i]= sc.nextInt();
}
Color[] colors = new Color[n];
for(int i=0; i<n; i++){
colors[i]= sc.nextInt()==1? Color.GREEN:Color.RED;
}
Map<Integer, Set<Integer>> nodeEdges = new HashMap<>();
for(int i=0; i<n-1; i++){
int u = sc.nextInt();
int v = sc.nextInt();
if(!nodeEdges.containsKey(u)){
nodeEdges.put(u,new HashSet<Integer>());
}
if(!nodeEdges.containsKey(v)){
nodeEdges.put(v,new HashSet<Integer>());
}
nodeEdges.get(u).add(v);
nodeEdges.get(v).add(u);
}
Map<TreeNode, Integer> nodeIndexMap = new HashMap<>();
List<TreeNode> parents = new ArrayList<>();
TreeNode root = new TreeNode(vals[0],colors[0],0);
nodeIndexMap.put(root,1);
parents.add(root);
while(!parents.isEmpty()){
List<TreeNode> nextLevelParents = new ArrayList<>();
for(TreeNode node : parents){
int depth = node.getDepth();
int parentIndex = nodeIndexMap.get(node);
for(int childIndex: nodeEdges.get(parentIndex)){
nodeEdges.get(childIndex).remove(parentIndex);
if(!nodeEdges.get(childIndex).isEmpty()){
TreeNode child = new TreeNode(vals[childIndex-1], colors[childIndex-1],depth+1);
nextLevelParents.add(child);
nodeIndexMap.put(child, childIndex);
node.addChild(child);
}else{
TreeLeaf leaf = new TreeLeaf(vals[childIndex-1], colors[childIndex-1],depth+1);
node.addChild(leaf);
}
}
}
parents = nextLevelParents;
}
sc.close();
return root;
}
public static void main(String[] args) {
Tree root = solve();
SumInLeavesVisitor vis1 = new SumInLeavesVisitor();
ProductOfRedNodesVisitor vis2 = new ProductOfRedNodesVisitor();
FancyVisitor vis3 = new FancyVisitor();
root.accept(vis1);
root.accept(vis2);
root.accept(vis3);
int res1 = vis1.getResult();
int res2 = vis2.getResult();
int res3 = vis3.getResult();
System.out.println(res1);
System.out.println(res2);
System.out.println(res3);
}
}
| AnujPawaadia/HackerRank | day74.java | 1,397 | //read the tree from STDIN and return its root as a return value of this function | line_comment | en | false | 1,146 | 18 | 1,397 | 18 | 1,463 | 18 | 1,397 | 18 | 1,633 | 19 | false | false | false | false | false | true |
174553_6 | __________________________________________________________________________________________________
sample 0 ms submission
class Solution {
public int kthSmallest(int[][] matrix, int k) {
// use binaru search
// the array is not fully sorted
// but when we know lo and hi, we could always know how many entries
// are smaller than mid (in an efficient way), and redefine the search range
int row = matrix.length, col = matrix[0].length;
int lo = matrix[0][0], hi = matrix[row-1][col-1];
while (lo < hi) {
int mid = lo + (hi - lo) / 2;
// now count how many entries are smaller than mid
// you may count row by row, or another way
int count = getLessOrEqual(matrix, mid);
if (count < k) lo = mid + 1;
else hi = mid;
}
// how can you make sure that lo is one of the elements in the matrix?
return lo;
}
private int getLessOrEqual(int[][] matrix, int target) {
// this function is very interesting!
// think about how it works!
int i = matrix.length - 1, j = 0;
int res = 0;
while (i >= 0 && j < matrix[0].length) {
if (matrix[i][j] > target) {
i --;
} else {
res += i + 1;
j++;
}
}
return res;
}
}
__________________________________________________________________________________________________
sample 38732 kb submission
class Solution {
public int kthSmallest(int[][] M, int k) {
int n = M.length;
PriorityQueue<Tuple> Q = new PriorityQueue<>(10000, (a, b) -> M[a.r][a.c] - M[b.r][b.c]);
Tuple t = new Tuple(0, 0);
Q.add(t);
while (k-- > 0) {
t = Q.remove();
if (t.r + 1 < n)
Q.add(new Tuple(t.r + 1, t.c));
if (t.r == 0 && t.c + 1 < n)
Q.add(new Tuple(t.r, t.c + 1));
}
return M[t.r][t.c];
}
class Tuple {
int r;
int c;
Tuple(int r, int c) {
this.r = r;
this.c = c;
}
}
}
__________________________________________________________________________________________________
| strengthen/LeetCode | Java/378.java | 590 | // how can you make sure that lo is one of the elements in the matrix? | line_comment | en | false | 554 | 17 | 590 | 17 | 657 | 17 | 590 | 17 | 684 | 17 | false | false | false | false | false | true |
177866_5 | package selenium;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
public class Methods {
public static void main(String[] args) {
// TODO Auto-generated method stub
System.setProperty("webdriver.chrome.driver", "C:\\Selenium\\Files\\chromedriver_win32\\chromedriver.exe");
WebDriver driver = new ChromeDriver();
driver.get("https://www.google.com");
//Methods
System.out.println(driver.getTitle()); //Get title of current webpage
System.out.println(driver.getCurrentUrl()); //Get Current Url of webpage for validation
System.out.println(driver.getPageSource()); //Get Page Source *(it helpful in some situation, where right click on webpage is disable)
driver.close();
}
}
| katejay/Selenium-Exercise | Basics/Methods.java | 204 | //Get Page Source *(it helpful in some situation, where right click on webpage is disable)
| line_comment | en | false | 159 | 20 | 204 | 20 | 210 | 19 | 204 | 20 | 241 | 20 | false | false | false | false | false | true |
178089_5 | import java.awt.image.BufferedImage;
import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;
/**
* Created by Lee-or on 02/10/2017.
*/
public class Map {
private BufferedImage mapBuffImg;
private byte[][] binaryMap;
private List<Point> criticalPoints;
public Map(BufferedImage givenMap){
this.mapBuffImg = givenMap;
this.criticalPoints = null;
}
/*TODO maybe "pixels" should be a given argument..*/
private byte[][] fromImageToBinaryArray(BufferedImage image){
//BufferedImage image = ImageIO.read(new File("/some.jpg"));
int width = image.getWidth();
int height = image.getHeight();
byte[][] pixels = new byte[width][];
for (int x = 0; x < width; ++x) {
pixels[x] = new byte[height];
for (int y = 0; y < height; ++y) {
pixels[x][y] = (byte) (image.getRGB(x, y) == 0xFFFFFFFF ? 0 : 1);
}
}
return pixels;
}
// "All BufferedImage objects have an upper left corner coordinate of (0, 0)." (javadoc)
// x- row, y- col => x- width, y- height.
/**
* firstPixelOfAnObstacle
* @param map
* @param x x coordinate of the pixel the user wishes to check.
* @param y y coordinate of the pixel the user wishes to check.
* @param width width of the map.
* @param height the height of the map.
* @return true if the given pixel is a critical point. Otherwise, false.
*/
/*TODO --PROBLEM-- this algorithm returns false if there are more than 1 pixel in row in the same column */
/*TODO this algorithm doesn't verify that there are no 2 critical points in the same vertical line*/
private boolean firstPixelOfAnObstacle(byte[][] map, int x, int y, int width, int height){
//if()
}
/**
* findCriticalPointsInMap.
* @return array which holds the coordinates of all critical points in this Map.
*/
private void findCriticalPointsInMap(){
int height = this.mapBuffImg.getHeight();
int width= this.mapBuffImg.getWidth();
for(int i=0; i<height; ++i){
for (int j=0; j<width; ++j){
}
}
}
public List<Point> getCriticalPoints(){
if(this.criticalPoints == null){
this.criticalPoints = new LinkedList<Point>();
this.findCriticalPointsInMap();
}
return getCopyOfCriticalPointsList();
}
/**
* getCopyOfCriticalPointsList.
* @return the copy of the 'criticalPoints' list.
*/
private List<Point> getCopyOfCriticalPointsList(){
List<Point> cloneList = new ArrayList<Point>();
for(Point point : this.criticalPoints) {
cloneList.add(point.clone());
}
return cloneList;
}
}
| Lee-or/find_critical_points | src/Map.java | 726 | /**
* firstPixelOfAnObstacle
* @param map
* @param x x coordinate of the pixel the user wishes to check.
* @param y y coordinate of the pixel the user wishes to check.
* @param width width of the map.
* @param height the height of the map.
* @return true if the given pixel is a critical point. Otherwise, false.
*/ | block_comment | en | false | 676 | 89 | 726 | 89 | 783 | 94 | 726 | 89 | 860 | 96 | false | false | false | false | false | true |
178638_0 | package ch_04;
import java.util.Scanner;
/**
* *4.24 (Order three cities) Write a program that prompts the user to enter three cities and
* displays them in ascending order.
* <p>
* Here is a sample run:
* Enter the first city: Chicago
* Enter the second city: Los Angeles
* Enter the third city: Atlanta
* The three cities in alphabetical order are Atlanta Chicago Los Angeles
*/
public class Exercise04_24 {
public static void main(String[] args) {
String tempCity = "";
Scanner input = new Scanner(System.in);
System.out.print("Enter the name of city 1: ");
String cityOne = input.next();
System.out.print("Enter the name of city 2: ");
String cityTwo = input.next();
System.out.print("Enter the name of city 3: ");
String cityThree = input.next();
if (cityOne.charAt(0) > cityTwo.charAt(0)) {
tempCity = cityTwo;
cityTwo = cityOne;
cityOne = tempCity;
if (cityTwo.charAt(0) > cityThree.charAt(0)) {
tempCity = cityThree;
cityThree = cityTwo;
cityTwo = tempCity;
}
}
System.out.println("The cities in alphabetical order are: "
+ cityOne + " " + cityTwo + " " + cityThree + ".");
}
}
| Taabannn/intro-to-java-programming | ch_04/Exercise04_24.java | 351 | /**
* *4.24 (Order three cities) Write a program that prompts the user to enter three cities and
* displays them in ascending order.
* <p>
* Here is a sample run:
* Enter the first city: Chicago
* Enter the second city: Los Angeles
* Enter the third city: Atlanta
* The three cities in alphabetical order are Atlanta Chicago Los Angeles
*/ | block_comment | en | false | 308 | 82 | 351 | 96 | 359 | 86 | 351 | 96 | 384 | 89 | false | false | false | false | false | true |
178926_8 | /**
* Copyright 2009 The Australian National University (ANU)
*
* 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.
*/
package org.ands.rifcs.base;
import org.w3c.dom.Node;
/**
* Class representing a RIF-CS Subject object.
*
* @author Scott Yeadon
*
*/
public class Subject extends RIFCSElement {
/**
* Construct a Subject object.
*
* @param n
* A w3c Node, typically an Element
*
* @throws RIFCSException A RIFCSException
*/
protected Subject(final Node n) throws RIFCSException {
super(n, Constants.ELEMENT_SUBJECT);
}
/**
* Set the type.
*
* @param type
* The type of subject
*/
public final void setType(final String type) {
super.setAttributeValue(Constants.ATTRIBUTE_TYPE, type);
}
/**
* return the type.
*
* @return
* The type attribute value or empty string if attribute
* is empty or not present
*/
public final String getType() {
return super.getAttributeValue(Constants.ATTRIBUTE_TYPE);
}
/**
* Set the termIdentifier.
*
* @param termIdentifier
* The termIdentifier of subject
*/
public final void setTermIdentifier(final String termIdentifier) {
super.setAttributeValue(Constants.ATTRIBUTE_TERM_IDENTIFIER,
termIdentifier);
}
/**
* return the termIdentifier.
*
* @return
* The termIdentifier attribute value or empty string if attribute
* is empty or not present
*/
public final String getTermIdentifier() {
return super.getAttributeValue(Constants.ATTRIBUTE_TERM_IDENTIFIER);
}
/**
* Set the language.
*
* @param lang
* The xml:lang attribute value
*/
public final void setLanguage(final String lang) {
super.setAttributeValueNS(Constants.NS_XML,
Constants.ATTRIBUTE_LANG, lang);
}
/**
* Obtain the language.
*
* @return
* The language or empty string if attribute
* is empty or not present
*/
public final String getLanguage() {
return super.getAttributeValueNS(Constants.NS_XML,
Constants.ATTRIBUTE_LANG);
}
/**
* Set the content.
*
* @param value
* The content of the subject
*/
public final void setValue(final String value) {
super.setTextContent(value);
}
/**
* Obtain the content.
*
* @return
* The subject string
*/
public final String getValue() {
return super.getTextContent();
}
}
| au-research/ANDS-RIFCS-API | src/org/ands/rifcs/base/Subject.java | 739 | /**
* Obtain the language.
*
* @return
* The language or empty string if attribute
* is empty or not present
*/ | block_comment | en | false | 694 | 36 | 741 | 34 | 815 | 39 | 739 | 33 | 920 | 40 | false | false | false | false | false | true |
180153_5 | package prj5;
import java.util.Comparator;
/**
* Class for Major Percent
*
* @author group48
* @version 04.27.2017
*/
public class MajorPercent implements Comparator<String> {
// ~ Fields
private int[][] like;
private int[][] heard;
// ~ Constructor
/**
* new a majorCount
*/
public MajorPercent() {
like = new int[4][2];
heard = new int[4][2];
}
// ~ Methods
/**
* Increment the results
*
* @param major
* represent the major of a student
* @param answerHeard
* whether that student has heard this song or not
* @param answerLike
* whether that student likes that song or not
*/
public void increment(String major, String answerHeard, String answerLike) {
heard(major, answerHeard);
like(major, answerLike);
}
/**
* increase the heard part
*
* @param major
* represents the major of the student
* @param answer
* answer to like or not
*/
private void heard(String major, String answer) {
if (compare(major, "Computer Science") == 0) {
if (compare(answer, "Yes") == 0) {
heard[0][1]++;
}
else if (compare(answer, "No") == 0) {
heard[0][0]++;
}
}
else if (compare(major, "Other Engineering") == 0) {
if (compare(answer, "Yes") == 0) {
heard[1][1]++;
}
else if (compare(answer, "No") == 0) {
heard[1][0]++;
}
}
else if (compare(major, "Math or CMDA") == 0) {
if (compare(answer, "Yes") == 0) {
heard[2][1]++;
}
else if (compare(answer, "No") == 0) {
heard[2][0]++;
}
}
else if (compare(major, "Other") == 0) {
if (compare(answer, "Yes") == 0) {
heard[3][1]++;
}
else if (compare(answer, "No") == 0) {
heard[3][0]++;
}
}
}
/**
* Increase the like part.
*
* @param major
* the student's major
* @param answer
* answer to like or not
*/
private void like(String major, String answer) {
if (compare(major, "Computer Science") == 0) {
if (compare(answer, "Yes") == 0) {
like[0][1]++;
}
else if (compare(answer, "No") == 0) {
like[0][0]++;
}
}
else if (compare(major, "Other Engineering") == 0) {
if (compare(answer, "Yes") == 0) {
like[1][1]++;
}
else if (compare(answer, "No") == 0) {
like[1][0]++;
}
}
else if (compare(major, "Math or CMDA") == 0) {
if (compare(answer, "Yes") == 0) {
like[2][1]++;
}
else if (compare(answer, "No") == 0) {
like[2][0]++;
}
}
else if (compare(major, "Other") == 0) {
if (compare(answer, "Yes") == 0) {
like[3][1]++;
}
else if (compare(answer, "No") == 0) {
like[3][0]++;
}
}
}
/**
* get the heard or not results in percentages
*
* @return the heard or not results
*/
public int[] getHeard() {
int[] result = new int[4];
result[0] = (int)((1.0 * heard[0][1] / (heard[0][0] + heard[0][1]))
* 100);
result[1] = (int)((1.0 * heard[1][1] / (heard[1][0] + heard[1][1]))
* 100);
result[2] = (int)((1.0 * heard[2][1] / (heard[2][0] + heard[2][1]))
* 100);
result[3] = (int)((1.0 * heard[3][1] / (heard[3][0] + heard[3][1]))
* 100);
return result;
}
/**
* get the like or not results
*
* @return the like or not results
*/
public int[] getLike() {
int[] result = new int[4];
result[0] = (int)((1.0 * like[0][1] / (like[0][0] + like[0][1])) * 100);
result[1] = (int)((1.0 * like[1][1] / (like[1][0] + like[1][1])) * 100);
result[2] = (int)((1.0 * like[2][1] / (like[2][0] + like[2][1])) * 100);
result[3] = (int)((1.0 * like[3][1] / (like[3][0] + like[3][1])) * 100);
return result;
}
/**
* Compare two strings together
*
* @return 0 if equal, neg if major is less than answer, and pos if greater
*/
@Override
public int compare(String major, String answer) {
return major.compareTo(answer);
}
}
| bharathc346-zz/Project5 | src/prj5/MajorPercent.java | 1,356 | /**
* Increment the results
*
* @param major
* represent the major of a student
* @param answerHeard
* whether that student has heard this song or not
* @param answerLike
* whether that student likes that song or not
*/ | block_comment | en | false | 1,351 | 68 | 1,356 | 60 | 1,502 | 69 | 1,356 | 60 | 1,570 | 72 | false | false | false | false | false | true |
181503_0 | package com.view;
import java.awt.*;
import java.io.IOException;
import java.io.InputStream;
/**
* The Roboto font.
*
* @see <a href="https://www.google.com/design/spec/resources/roboto-noto-fonts.html">Roboto & Noto fonts (Google design guidelines)</a>
*/
public class Roboto {
public static final Font BLACK = loadFont("Roboto-Black.ttf").deriveFont(Font.BOLD);
public static final Font BLACK_ITALIC = loadFont("Roboto-BlackItalic.ttf").deriveFont(Font.BOLD | Font.ITALIC);
public static final Font BOLD = loadFont("Roboto-Bold.ttf").deriveFont(Font.BOLD);
public static final Font BOLD_ITALIC = loadFont("Roboto-BoldItalic.ttf").deriveFont(Font.BOLD | Font.ITALIC);
public static final Font ITALIC = loadFont("Roboto-Italic.ttf").deriveFont(Font.ITALIC);
public static final Font LIGHT = loadFont("Roboto-Light.ttf").deriveFont(Font.PLAIN);
public static final Font LIGHT_ITALIC = loadFont("Roboto-LightItalic.ttf").deriveFont(Font.ITALIC);
public static final Font MEDIUM = loadFont("Roboto-Medium.ttf").deriveFont(Font.PLAIN);
public static final Font MEDIUM_ITALIC = loadFont("Roboto-MediumItalic.ttf").deriveFont(Font.ITALIC);
public static final Font REGULAR = loadFont("Roboto-Regular.ttf").deriveFont(Font.PLAIN);
public static final Font THIN = loadFont("Roboto-Thin.ttf").deriveFont(Font.PLAIN);
public static final Font THIN_ITALIC = loadFont("Roboto-ThinItalic.ttf").deriveFont(Font.ITALIC);
private static Font loadFont(String resourceName) {
try (InputStream inputStream = MainUI.class.getResourceAsStream("/lib/Fonts/" + resourceName)) {
return Font.createFont(Font.TRUETYPE_FONT, inputStream);
} catch (IOException | FontFormatException e) {
throw new RuntimeException("Could not load " + resourceName, e);
}
}
} | rsangeethk/uibot | src/com/view/Roboto.java | 499 | /**
* The Roboto font.
*
* @see <a href="https://www.google.com/design/spec/resources/roboto-noto-fonts.html">Roboto & Noto fonts (Google design guidelines)</a>
*/ | block_comment | en | false | 427 | 47 | 499 | 58 | 508 | 57 | 499 | 58 | 620 | 62 | false | false | false | false | false | true |
181612_6 | package priority;
import person.Patient;
import java.util.ArrayList;
/**
* This is an abstract class that creates a PriorityQueue which controls the order in which Patients are admitted
* to or treated at the hospital.
*
* @author Shysta and Justice
* @version 2.0
* @since 1.0
*/
public abstract class Priority {
ArrayList<Patient> patientList;
/**
* A constructor for the Priority Class.
*/
public Priority() {
this.patientList = new ArrayList<>();
}
/**
* Adds a patient to the Priority Queue patientList. This method makes use of the template design pattern.
* It instantiates an algorithm for dynamically ordering the patient's list in the PriorityQueue.
*/
public void add_patient(Patient patient) {
if (this.patientList.isEmpty()) {
this.patientList.add(patient);
}
int i = 0;
while (!this.patientList.contains(patient)) {
if (higherPriority(this.patientList.get(i), patient)) {
int num;
num = this.patientList.indexOf(this.patientList.get(i));
this.patientList.add(num, patient);
} else if (i == this.patientList.size() - 1) {
this.patientList.add(this.patientList.size(), patient);
} else {
i += 1;
}
}
}
public abstract boolean higherPriority(Patient patient, Patient newPatient);
/**
* Removes a patient from the priority queue of patients by reference to the patient.
*
* @param patient patient to be removed from the priority queue of patients.
* @return the patient that was removed.
*/
public Patient delete_patient(Patient patient) {
patientList.remove(patient);
return patient;
}
/**
* Removes the last patient from the list of patients.
*
* @return the patient that was removed.
*/
public Patient delete_patient() {
Patient patient = patientList.get(0);
patientList.remove(patient);
return patient;
}
/**
* Checks whether the hospital's list of patients is empty.
*
* @return true if the list is empty and false if it is not.
*/
public boolean isEmpty() {
return patientList.isEmpty();
}
/**
* Returns a list containing all the patients in the priority queue in the hospital.
*
* @return a list containing all the patients in the priority queue in the hospital.
*/
public ArrayList<Patient> show_patientList() {
return patientList;
}
}
| CSC207-UofT/course-project-all-stars | src/priority/Priority.java | 596 | /**
* Returns a list containing all the patients in the priority queue in the hospital.
*
* @return a list containing all the patients in the priority queue in the hospital.
*/ | block_comment | en | false | 535 | 40 | 596 | 40 | 652 | 44 | 596 | 40 | 720 | 44 | false | false | false | false | false | true |
182661_18 | import java.io.OutputStream;
import java.io.FileOutputStream;
import java.io.BufferedOutputStream;
import java.io.ObjectOutput;
import java.io.ObjectOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.FileInputStream;
import java.io.BufferedInputStream;
import java.io.ObjectInput;
import java.io.ObjectInputStream;
/**
* A supplier may be a manufacturer, distributor, or depot.
* Supplier attributes include:
* name, demand, inventory on hand, maximum storage capacity,
* cost per unit stored, and surplus inventory.
*
* @author CS4050 (design)
* @author Dr. Jody Paul (code)
* @version 20231112
*/
public class Supplier implements java.io.Serializable {
/** Serialization version requirement. */
private static final long serialVersionUID = 405002L;
/** Default file name for serialized object. */
private static final String SERIAL_FILENAME = "supplier.ser";
/** Default maximum capacity. */
public static final int MAX_CAPACITY = Integer.MAX_VALUE;
/** Name of supplier. */
private String name;
/** Cost of storage at supplier's location. */
private int storageCost;
/**
* Direct demand at this supplier's location.
* If direct demand == 0, then is considered a depot.
* If direct demand is less than 0, then is considered a manufacturer.
*/
private int demand;
/** Inventory on hand. */
private int inventory;
/** Maximum amount of inventory that can be held. */
private int maxCapacity;
/**
* Surplus, defined as (inventory - demand).
* If positive, surplus represents the number of
* units subject to storage cost.
* If negative, surplus represents unrealized
* value (units that would otherwise have been sold).
* Storing this value is not necessary because the accessor,
* surplus(), computes this value dynamically.
*/
private int surplus;
/**
* Construct a supplier using default values.
*/
public Supplier() {
this.name = this.toString();
this.storageCost = 0;
this.demand = 0;
this.inventory = 0;
this.maxCapacity = MAX_CAPACITY;
this.surplus = 0;
}
/**
* Fully-parameterized supplier constructor.
* Note that surplus is automatically calculated as the
* difference between inventory and demand.
* @param name the name of this supplier
* @param cost the storage cost per unit stored
* @param demand the expected demand at this distributing supplier
* @param inventory the actual inventory at this supplier
* @param capacity the maximum capacity at this supplier
*/
public Supplier(String name,
int cost,
int demand,
int inventory,
int capacity) {
this.name = name;
this.storageCost = cost;
this.demand = demand;
this.maxCapacity = capacity;
if (inventory > capacity) {
this.inventory = capacity;
} else {
this.inventory = inventory;
}
this.surplus = inventory - demand;
}
/**
* @return this supplier's name
*/
public String name() { return this.name; }
/**
* @return the cost of storage at this supplier's location
*/
public int storageCost() { return this.storageCost; }
/**
* @return the maximum number of units that can be stored
*/
public int maxCapacity() { return this.maxCapacity; }
/**
* @return the demand at this supplier's location.
*/
public int demand() { return this.demand; }
/**
* @return the current inventory at this supplier's location.
*/
public int inventory() { return this.inventory; }
/**
* @return the surplus inventory at this supplier's location.
*/
public int surplus() {
this.surplus = this.inventory - this.demand;
return this.surplus;
}
/**
* Compares this supplier to the specified object.
* The result is <code>true</code> if and only if the argument is
* not <code>null</code> and is a Supplier object with the same
* name, storage cost, demand, and inventory values.
* @param anObject the object to compare with this supplier
* @return <code>true</code> if the given object represents a Supplier
* equivalent to this supplier, <code>false</code> otherwise
*/
@Override
public boolean equals(final Object anObject) {
if ((anObject == null)
|| (this.getClass() != anObject.getClass())) {
return false;
}
Supplier other = ((Supplier) anObject);
return (this.name.equals(other.name)
&& this.storageCost == other.storageCost
&& this.demand == other.demand
&& this.maxCapacity == other.maxCapacity
&& this.inventory == other.inventory);
}
/**
* Returns a hash code value for this supplier.
* @return hash code value for this supplier
*/
@Override
public int hashCode() {
if (name == null) return 43;
return this.name.hashCode();
}
/**
* Save this supplier to a file.
* @param filename the name of the file in which to save this supplier;
* if null, uses default file name
* @return <code>true</code> if successful save;
* <code>false</code> otherwise
* @throws java.io.IOException if unexpected IO error
*/
public final boolean save(final String filename) throws java.io.IOException {
boolean success = true;
String supplierFileName = filename;
if (supplierFileName == null) {
supplierFileName = Supplier.SERIAL_FILENAME;
}
// Serialize the supplier.
try {
OutputStream file = new FileOutputStream(supplierFileName);
OutputStream buffer = new BufferedOutputStream(file);
ObjectOutput output = new ObjectOutputStream(buffer);
try {
output.writeObject(this);
} finally { output.close(); }
} catch (IOException ex) {
System.err.println("Unsuccessful save. " + ex);
throw ex;
}
// Attempt to deserialize the supplier as verification.
try {
InputStream file = new FileInputStream(supplierFileName);
InputStream buffer = new BufferedInputStream(file);
ObjectInput input = new ObjectInputStream(buffer);
try {
@SuppressWarnings("unchecked") // Accommodate type erasure.
Supplier restored = (Supplier) input.readObject();
// Simple check that deserialized data matches original.
if (!this.toString().equals(restored.toString())) {
System.err.println("[1] State restore did not match save!");
success = false;
}
if (!this.equals(restored)) {
System.err.println("[2] State restore did not match save!");
success = false;
}
} finally { input.close(); }
} catch (ClassNotFoundException ex) {
System.err.println(
"Unsuccessful deserialization: Class not found. " + ex);
success = false;
} catch (IOException ex) {
System.err.println("Unsuccessful deserialization: " + ex);
success = false;
}
return success;
}
/**
* Restore this supplier from a file.
* <br /><em>Postconditions:</em>
* <blockquote>If successful, previous contents of this supplier have
* been replaced by the contents of the file.
* If unsuccessful, content of the supplier is unchanged.</blockquote>
* @param filename the name of the file from which to restore this supplier;
* if null, uses default file name
* @return <code>true</code> if successful restore;
* <code>false</code> otherwise
* @throws java.io.IOException if unexpected IO error
*/
public final boolean restore(final String filename) throws
java.io.IOException {
boolean success = false;
String supplierFileName = filename;
if (supplierFileName == null) {
supplierFileName = Supplier.SERIAL_FILENAME;
}
Supplier restored = null;
try {
InputStream file = new FileInputStream(supplierFileName);
InputStream buffer = new BufferedInputStream(file);
ObjectInput input = new ObjectInputStream(buffer);
try {
@SuppressWarnings("unchecked") // Accommodate type erasure.
Supplier retrieved = (Supplier) input.readObject();
restored = retrieved;
} finally {
input.close();
success = true;
}
} catch (ClassNotFoundException ex) {
System.err.println(
"Unsuccessful deserialization: Class not found. " + ex);
success = false;
} catch (IOException ex) {
System.err.println("Unsuccessful deserialization: " + ex);
throw ex;
}
if (restored == null) {
System.err.println(
"Unsuccessful deserialization: restored == null");
success = false;
} else {
this.name = restored.name;
this.storageCost = restored.storageCost;
this.demand = restored.demand;
this.inventory = restored.inventory;
this.maxCapacity = restored.maxCapacity;
this.surplus = restored.surplus;
}
return success;
}
}
| WillMoody27/distribution-project-final-algo-program-4050-ford-fulkerson-and-Dijkstras | src/Supplier.java | 2,091 | /**
* Compares this supplier to the specified object.
* The result is <code>true</code> if and only if the argument is
* not <code>null</code> and is a Supplier object with the same
* name, storage cost, demand, and inventory values.
* @param anObject the object to compare with this supplier
* @return <code>true</code> if the given object represents a Supplier
* equivalent to this supplier, <code>false</code> otherwise
*/ | block_comment | en | false | 1,960 | 112 | 2,091 | 111 | 2,297 | 107 | 2,091 | 111 | 2,547 | 125 | false | false | false | false | false | true |
182902_2 | /*
* Card class
* TODO: In the constructor of the class, check if the passed arguments are in the
* valid range. If not, throw an java.security.InvalidParameterException
*/
// use import statments to specify the package where class is defined
// now you can just refer to the exception by its name InvalidParameterException
import java.security.InvalidParameterException;
public class Card{
private int value;
private char suite;
/*
* Constructor of the Card class
* @param val - card value in the range [2-14], where 11-Jack, 12-Queen, 13-King, 14-Ace
* @param suite - the suite of the card: D - diamonds, H - hearts, S - Spaces, C - clubs
*/
public Card(int val, char s) throws InvalidParameterException
{
// check the input for being in the valid range
if (val < 2 || val > 14)
{
throw new InvalidParameterException("Value must be in the range [2, 14]");
}
// check if the suite is valid
if (s != 'D' && s != 'H' && s != 'S' && s != 'C')
{
throw new InvalidParameterException("Value must be ether 'D', 'H', 'S' or 'C'");
}
value = val;
suite = s;
}
public int getValue(){
return value;
}
public char getSuite(){
return suite;
}
public String toString()
{
String cardDescription = "";
if (value >=2 && value <=10){
cardDescription+=value + " ";
}
else if (value == 11){
cardDescription+="Jack ";
}
else if (value == 12){
cardDescription+="Queen ";
}
else if (value == 13){
cardDescription+="King ";
}
else if (value == 14){
cardDescription+="Ace ";
}
if (suite == 'S'){
cardDescription+="Spades";
}
else if (suite == 'D'){
cardDescription+="Diamonds";
}
else if (suite == 'C'){
cardDescription+="Clubs";
}
else if (suite == 'H'){
cardDescription+="Hearts";
}
return cardDescription;
}
}
| NabeelSait/NabeelSaitCSCI_2300Coursework | lab6/Card.java | 537 | // now you can just refer to the exception by its name InvalidParameterException | line_comment | en | false | 525 | 15 | 537 | 15 | 586 | 15 | 537 | 15 | 625 | 15 | false | false | false | false | false | true |
183517_17 | package plc.project;
import java.math.BigDecimal;
import java.math.BigInteger;
import java.util.List;
import java.util.Optional;
/**
* The parser takes the sequence of tokens emitted by the lexer and turns that
* into a structured representation of the program, called the Abstract Syntax
* Tree (AST).
*
* The parser has a similar architecture to the lexer, just with {@link Token}s
* instead of characters. As before, {@link #peek(Object...)} and {@link
* #match(Object...)} are helpers to make the implementation easier.
*
* This type of parser is called <em>recursive descent</em>. Each rule in our
* grammar will have it's own function, and reference to other rules correspond
* to calling that functions.
*/
public final class Parser {
private final TokenStream tokens;
public Parser(List<Token> tokens) {
this.tokens = new TokenStream(tokens);
parseStatement();
}
/**
* Parses the {@code source} rule.
*/
public Ast.Source parseSource() throws ParseException {
throw new UnsupportedOperationException(); //TODO
}
/**
* Parses the {@code field} rule. This method should only be called if the
* next tokens start a global, aka {@code LIST|VAL|VAR}.
*/
public Ast.Global parseGlobal() throws ParseException {
throw new UnsupportedOperationException(); //TODO
}
/**
* Parses the {@code list} rule. This method should only be called if the
* next token declares a list, aka {@code LIST}.
*/
public Ast.Global parseList() throws ParseException {
throw new UnsupportedOperationException(); //TODO
}
/**
* Parses the {@code mutable} rule. This method should only be called if the
* next token declares a mutable global variable, aka {@code VAR}.
*/
public Ast.Global parseMutable() throws ParseException {
throw new UnsupportedOperationException(); //TODO
}
/**
* Parses the {@code immutable} rule. This method should only be called if the
* next token declares an immutable global variable, aka {@code VAL}.
*/
public Ast.Global parseImmutable() throws ParseException {
throw new UnsupportedOperationException(); //TODO
}
/**
* Parses the {@code function} rule. This method should only be called if the
* next tokens start a method, aka {@code FUN}.
*/
public Ast.Function parseFunction() throws ParseException {
throw new UnsupportedOperationException(); //TODO
}
/**
* Parses the {@code block} rule. This method should only be called if the
* preceding token indicates the opening a block.
*/
public List<Ast.Statement> parseBlock() throws ParseException {
throw new UnsupportedOperationException(); //TODO
}
/**
* Parses the {@code statement} rule and delegates to the necessary method.
* If the next tokens do not start a declaration, if, while, or return
* statement, then it is an expression/assignment statement.
*/
public Ast.Statement parseStatement() throws ParseException {
/*Ast.Expression leftStatement = parseExpression();
if(match("=")){
Ast.Expression rightStatement = parseExpression();
if(match(";")){
return new Ast.Statement.Assignment(leftStatement,rightStatement);
}
else{
throw new ParseException("Missing closing statement ;", tokens.get(0).getIndex());
}
}
if(match(";")){
return new Ast.Statement.Expression(leftStatement);
}
else{
throw new ParseException("Missing closing statement ;", tokens.get(0).getIndex());
}
*/
return null;
}
/**
* Parses a declaration statement from the {@code statement} rule. This
* method should only be called if the next tokens start a declaration
* statement, aka {@code LET}.
*/
public Ast.Statement.Declaration parseDeclarationStatement() throws ParseException {
throw new UnsupportedOperationException(); //TODO
}
/**
* Parses an if statement from the {@code statement} rule. This method
* should only be called if the next tokens start an if statement, aka
* {@code IF}.
*/
public Ast.Statement.If parseIfStatement() throws ParseException {
throw new UnsupportedOperationException(); //TODO
}
/**
* Parses a switch statement from the {@code statement} rule. This method
* should only be called if the next tokens start a switch statement, aka
* {@code SWITCH}.
*/
public Ast.Statement.Switch parseSwitchStatement() throws ParseException {
throw new UnsupportedOperationException(); //TODO
}
/**
* Parses a case or default statement block from the {@code switch} rule.
* This method should only be called if the next tokens start the case or
* default block of a switch statement, aka {@code CASE} or {@code DEFAULT}.
*/
public Ast.Statement.Case parseCaseStatement() throws ParseException {
throw new UnsupportedOperationException(); //TODO
}
/**
* Parses a while statement from the {@code statement} rule. This method
* should only be called if the next tokens start a while statement, aka
* {@code WHILE}.
*/
public Ast.Statement.While parseWhileStatement() throws ParseException {
throw new UnsupportedOperationException(); //TODO
}
/**
* Parses a return statement from the {@code statement} rule. This method
* should only be called if the next tokens start a return statement, aka
* {@code RETURN}.
*/
public Ast.Statement.Return parseReturnStatement() throws ParseException {
throw new UnsupportedOperationException();//TODO
}
/**
* Parses the {@code expression} rule.
*/
public Ast.Expression parseExpression() throws ParseException {
return parseLogicalExpression();//TODO
}
/**
* Parses the {@code logical-expression} rule.
*/
public Ast.Expression parseLogicalExpression() throws ParseException {
Ast.Expression leftExpression = parseComparisonExpression();
while(match("&&") || match("||")){
String operator = tokens.get(-1).getLiteral();
Ast.Expression rightExpression = parseComparisonExpression();
leftExpression = new Ast.Expression.Binary(operator,leftExpression,rightExpression);
}
return leftExpression;
}
/**
* Parses the {@code equality-expression} rule.
*/
public Ast.Expression parseComparisonExpression() throws ParseException {
Ast.Expression leftExpression = parseAdditiveExpression();
while(match("<") || match(">") || match("==") || match("!=")){
String operator = tokens.get(-1).getLiteral();
Ast.Expression rightExpression = parseAdditiveExpression();
leftExpression = new Ast.Expression.Binary(operator,leftExpression,rightExpression);
}
return leftExpression;
}
/**
* Parses the {@code additive-expression} rule.
*/
public Ast.Expression parseAdditiveExpression() {
Ast.Expression leftExpression = parseMultiplicativeExpression();
while(match("+") || match("-")){
String operator = tokens.get(-1).getLiteral();
Ast.Expression rightExpression = parseMultiplicativeExpression();
leftExpression = new Ast.Expression.Binary(operator,leftExpression,rightExpression);
}
return leftExpression;
}
/**
* Parses the {@code multiplicative-expression} rule.
*/
public Ast.Expression parseMultiplicativeExpression() {
Ast.Expression leftExpression = parsePrimaryExpression();
while(match("*") || match("/")|| match("^")){
String operator = tokens.get(-1).getLiteral();
Ast.Expression rightExpression = parsePrimaryExpression();
leftExpression = new Ast.Expression.Binary(operator,leftExpression,rightExpression);
}
return leftExpression;
}
/**
* Parses the {@code primary-expression} rule. This is the top-level rule
* for expressions and includes literal values, grouping, variables, and
* functions. It may be helpful to break these up into other methods but is
* not strictly necessary.
*/
public Ast.Expression parsePrimaryExpression() throws ParseException{
if (match("NIL")) {
return new Ast.Expression.Literal(null);
}
else if (match("TRUE")) {
return new Ast.Expression.Literal(true);
}
else if (match("FALSE")) {
return new Ast.Expression.Literal(false);
}
else if (peek(Token.Type.INTEGER)) {
String literal = tokens.get(0).getLiteral();
match(Token.Type.INTEGER);
return new Ast.Expression.Literal(new BigInteger(literal));
}
else if (peek(Token.Type.DECIMAL)) {
String literal = tokens.get(0).getLiteral();
match(Token.Type.DECIMAL);
return new Ast.Expression.Literal(new BigDecimal(literal));
}
//NEEDS WORKS
else if(match(Token.Type.IDENTIFIER)){
String name = tokens.get(-1).getLiteral();
return new Ast.Expression.Access(Optional.empty(), name);
}
else if(match("(")){
Ast.Expression expression = parseExpression();
if(!match(")")){
throw new ParseException("Expected Closing Parenthesis ",-1);
//TODO
}
return new Ast.Expression.Group(expression);
}
else if (peek(Token.Type.CHARACTER)) {
return new Ast.Expression.Literal('N');
}
else if (peek(Token.Type.STRING)) {
if(match("\"")){
String name = tokens.get(0).getLiteral();
match("\"");
return new Ast.Expression.Access(Optional.empty(), name);
}
throw new ParseException("Not valid string", -1);
}
else if (peek(Token.Type.OPERATOR)) {
new Ast.Expression.Literal(Token.Type.INTEGER);
match(Token.Type.OPERATOR);
Ast.Expression expression = parseExpression();
match(Token.Type.OPERATOR);
return expression;
} else {
throw new ParseException("Invalid primary expression", -1);
//TODO
}
return null;
}
/**
* As in the lexer, returns {@code true} if the current sequence of tokens
* matches the given patterns. Unlike the lexer, the pattern is not a regex;
* instead it is either a {@link Token.Type}, which matches if the token's
* type is the same, or a {@link String}, which matches if the token's
* literal is the same.
*
* In other words, {@code Token(IDENTIFIER, "literal")} is matched by both
* {@code peek(Token.Type.IDENTIFIER)} and {@code peek("literal")}.
*/
private boolean peek(Object... patterns) {
for (int i = 0; i < patterns.length; i++) {
if (!tokens.has(i)) {
return false;
}
else if (patterns[i] instanceof Token.Type) {
if (patterns[i] != tokens.get(i).getType()) {
return false;
}
}
else if (patterns[i] instanceof String) {
if (!patterns[i].equals(tokens.get(i).getLiteral())) {
return false;
}
}
else {
throw new AssertionError("Invalid pattern object: " + patterns[i].getClass());
}
}
return true;
}
/**
* As in the lexer, returns {@code true} if {@link #peek(Object...)} is true
* and advances the token stream.
*/
private boolean match(Object... patterns) {
boolean peek = peek(patterns);
if (peek) {
for (int i = 0; i < patterns.length; i++) {
tokens.advance();
}
}
return peek;
}
private static final class TokenStream {
private final List<Token> tokens;
private int index = 0;
private TokenStream(List<Token> tokens) {
this.tokens = tokens;
}
/**
* Returns true if there is a token at index + offset.
*/
public boolean has(int offset) {
return index + offset < tokens.size();
}
/**
* Gets the token at index + offset.
*/
public Token get(int offset) {
return tokens.get(index + offset);
}
/**
* Advances to the next token, incrementing the index.
*/
public void advance() {
index++;
}
}
}
| jsaarela1/PLC_Project | Parser.java | 2,715 | /**
* Parses a declaration statement from the {@code statement} rule. This
* method should only be called if the next tokens start a declaration
* statement, aka {@code LET}.
*/ | block_comment | en | false | 2,538 | 43 | 2,715 | 42 | 3,037 | 46 | 2,715 | 42 | 3,341 | 49 | false | false | false | false | false | true |
184992_10 | public class Pawn extends ConcretePiece {
private static int pieceCounter = 0; //0-12 Def pieces player 1, 13-36 Att pieces player 2.
public Pawn(Player player){
//define player field
super.player = player;
//enter unicode of pawn
super.pieceType = "♟"; //2659 = pawn unicode
//naming the piece the way they are created, D1 - D13(NO D7 = KING = K7), A1 - A24.
//toString implement at concretePiece and return the pieceName
super.pieceName = setPieceName(); //unique key, is the piece name.
pieceCounter++; //updating the piece counter
}
//piece counter.
private int countPiecesHelper(){
if(pieceCounter == 37) {pieceCounter = 0;} //when the last piece created, reseat the piece counter for the next game.
else if(pieceCounter == 6) pieceCounter++; //since number 6 that is actually number 7 piece, saved for the king.
return pieceCounter;
}
//naming the piece the way they are created, D1 - D13(NO D7 = KING = K7), A1 - A24.
private String setPieceName(){
String prefixAD = this.player.isPlayerOne() ? "D" : "A";
String name = this.player.isPlayerOne() ? prefixAD + (countPiecesHelper() + 1):
prefixAD + (countPiecesHelper() - 12);
return name;
}
}
| AmitGini/Hnefatafl_Vikings_Chess_Game | Pawn.java | 361 | //since number 6 that is actually number 7 piece, saved for the king.
| line_comment | en | false | 346 | 19 | 361 | 19 | 398 | 18 | 361 | 19 | 435 | 18 | false | false | false | false | false | true |
187094_2 |
// Java implementation of finding length of longest
// Common substring using Dynamic Programming
public
class
LongestCommonSubSequence
{
/*
Returns length of longest common substring
of X[0..m-1] and Y[0..n-1]
*/
static
int
LCSubStr(
char
X[],
char
Y[],
int
m,
int
n)
{
// Create a table to store lengths of longest common suffixes of
// substrings. Note that LCSuff[i][j] contains length of longest
// common suffix of X[0..i-1] and Y[0..j-1]. The first row and
// first column entries have no logical meaning, they are used only
// for simplicity of program
int
LCStuff[][] =
new
int
[m +
1
][n +
1
];
int
result =
0
;
// To store length of the longest common substring
// Following steps build LCSuff[m+1][n+1] in bottom up fashion
for
(
int
i =
0
; i <= m; i++)
{
for
(
int
j =
0
; j <= n; j++)
{
if
(i ==
0
|| j ==
0
)
LCStuff[i][j] =
0
;
else
if
(X[i -
1
] == Y[j -
1
])
{
LCStuff[i][j] = LCStuff[i -
1
][j -
1
] +
1
;
result = Integer.max(result, LCStuff[i][j]);
}
else
LCStuff[i][j] =
0
;
}
}
return
result;
}
// Driver Program to test above function
public
static
void
main(String[] args)
{
String X =
"OldSite:GeeksforGeeks.org"
;
String Y =
"NewSite:GeeksQuiz.com"
;
int
m = X.length();
int
n = Y.length();
System.out.println(
"Length of Longest Common Substring is "
+ LCSubStr(X.toCharArray(), Y.toCharArray(), m, n));
}
}
// This code is contributed by Sumit Ghosh | dhyan/code2vec_code_complexity | Dataset/346.java | 589 | /*
Returns length of longest common substring
of X[0..m-1] and Y[0..n-1]
*/ | block_comment | en | false | 497 | 29 | 589 | 32 | 588 | 32 | 589 | 32 | 661 | 36 | false | false | false | false | false | true |
190228_1 |
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import java.util.ArrayList;
import java.util.Dictionary;
import java.util.HashMap;
import java.util.TreeMap;
/**
* Created by dgotbaum on 1/7/14.
*/
public class Market {
public static final String[] HEADER = {"Submarket & Class", "Number of Buildings","Inventory","Direct Available Space"
,"Direct Availability","Sublet Available Space","Sublet Availability","Total Available Space","Total Availability",
"Direct Vacant Space","Direct Vacancy","Sublet Vacant Space","Sublet Vacancy","Total Vacant Space","Total Vacancy","Occupied Space","Net Absorption",
"Weighted Direct Average Rent","Weighted Sublease Average Rent","Weighted Overall Average Rent","Under Construction","Under Construction (SF)"};
public int marketIndex;
public int subMarketIndex;
public int classIndex;
public Workbook wb;
public Sheet s;
public TreeMap<String, TreeMap<String,TreeMap<String,ArrayList<Row>>>> MARKETS;
public Market(Workbook wb) {
this.MARKETS = new TreeMap<String, TreeMap<String, TreeMap<String, ArrayList<Row>>>>();
this.wb = wb;
this.s = wb.getSheetAt(0);
Row headerRow = s.getRow(0);
for (Cell c : headerRow) {
if (c.getRichStringCellValue().getString().contains("Market (my data)"))
this.marketIndex = c.getColumnIndex();
else if (c.getRichStringCellValue().getString().contains("submarket"))
this.subMarketIndex = c.getColumnIndex();
else if (c.getRichStringCellValue().getString().contains("Class"))
this.classIndex = c.getColumnIndex();
}
//Iterates through the rows and populates the hashmap of the buildings by district
for (Row r: this.s) {
if (!(r.getRowNum() == 0) && r.getCell(0) != null) {
String marketName = r.getCell(marketIndex).getStringCellValue();
String subMarketName = r.getCell(subMarketIndex).getStringCellValue();
String Grade = r.getCell(classIndex).getStringCellValue();
if (!MARKETS.containsKey(marketName)) {
TreeMap<String, TreeMap<String,ArrayList<Row>>> sub = new TreeMap<String, TreeMap<String,ArrayList<Row>>>();
TreeMap<String, ArrayList<Row>> classes = new TreeMap<String, ArrayList<Row>>();
classes.put("A", new ArrayList<Row>());
classes.put("B", new ArrayList<Row>());
classes.put("C", new ArrayList<Row>());
classes.get(Grade).add(r);
sub.put(subMarketName, classes);
MARKETS.put(marketName,sub);
}
else {
if (MARKETS.get(marketName).containsKey(subMarketName))
MARKETS.get(marketName).get(subMarketName).get(Grade).add(r);
else {
TreeMap<String, ArrayList<Row>> classes = new TreeMap<String, ArrayList<Row>>();
classes.put("A", new ArrayList<Row>());
classes.put("B", new ArrayList<Row>());
classes.put("C", new ArrayList<Row>());
classes.get(Grade).add(r);
MARKETS.get(marketName).put(subMarketName, classes);
}
}
}
}
}
}
| dgotbaum/MarketReport | src/Market.java | 835 | //Iterates through the rows and populates the hashmap of the buildings by district | line_comment | en | false | 722 | 16 | 835 | 18 | 858 | 17 | 835 | 18 | 1,022 | 17 | false | false | false | false | false | true |
190487_0 | package com.Week8;
/*CD's parameter contains its artist (String), title (String), and publishing year (int). All CDs weigh 0.1 kg.*/
public class CD implements ToBeStored{
private String artist;
private String title;
private int publishingYear;
public CD(String artist, String title, int publishingYear){
this.artist = artist;
this.title = title;
this.publishingYear = publishingYear;
}
@Override
public double weight() {
return 0.1;
}
}
| Ajla115/OOP_LABS_2022 | Week 8/CD.java | 127 | /*CD's parameter contains its artist (String), title (String), and publishing year (int). All CDs weigh 0.1 kg.*/ | block_comment | en | false | 116 | 30 | 127 | 32 | 142 | 30 | 127 | 32 | 149 | 33 | false | false | false | false | false | true |
191520_5 | /**
* An interface describing the functionality of all ClassPeriods
* @author Angie Palm + Ethan Shernan
* @version 42
*/
public interface ClassPeriod {
/**
* Gets the subject of a ClassPeriod
* @return the subject
*/
String getSubject();
/**
* Gets the hours of a ClassPeriod
* @return the hours
*/
int getHours();
/**
* Gets the Student's grade for a ClassPeriod
* @return the grade
*/
double getGrade();
/**
* Gets the Professor for a ClassPeriod
* @return the professor's name
*/
String getProfessor();
/**
* Sets the professor for a ClassPeriod
* @param professor the professor's name
*/
void setProfessor(String professor);
} | alexsaadfalcon/java_intro | hw05/ClassPeriod.java | 182 | /**
* Sets the professor for a ClassPeriod
* @param professor the professor's name
*/ | block_comment | en | false | 177 | 23 | 182 | 24 | 197 | 25 | 182 | 24 | 219 | 26 | false | false | false | false | false | true |
192791_0 | // Satellite class contains the data members and member functions that are used to manipulate the satellite.
import java.util.Arrays;
import java.util.HashSet;
import java.util.Set;
import java.util.logging.Level;
import java.util.logging.Logger;
public class Satellite {
private String orientation;
private String solarPanels;
private int dataCollected;
// Logger object
private static final Logger LOGGER = Logger.getLogger(Satellite.class.getName());
// Constructor to initialize the data members - initial state of the satellite
public Satellite() {
this.orientation = "North";
this.solarPanels = "Inactive";
this.dataCollected = 0;
}
// Function to Rotate the satellite to a given direction
public boolean rotate(String direction) {
Set<String> validDirections = new HashSet<>(Arrays.asList("North", "South", "East", "West"));
// Checks if the satellite is already facing the given direction
if (direction.equals(this.getOrientation())){
LOGGER.warning("Satellite is already facing " + direction);
return true;
}
if (validDirections.contains(direction)) {
this.orientation = direction;
LOGGER.info("Satellite rotated to " + direction);
return true;
}
else{
LOGGER.log(Level.SEVERE, "Invalid direction provided.");
return false;
}
}
public void activatePanels() {
if ("Inactive".equals(this.solarPanels)) {
this.solarPanels = "Active";
LOGGER.info("Solar panels activated");
} else {
LOGGER.warning("Solar panels are already active");
}
}
public void deactivatePanels() {
if ("Active".equals(this.solarPanels)) {
this.solarPanels = "Inactive";
LOGGER.info("Solar panels deactivated");
} else {
LOGGER.warning("Solar panels are already inactive");
}
}
public boolean collectData() {
if ("Active".equals(this.solarPanels)) {
this.dataCollected += 10;
LOGGER.info("Data collected successfully");
return true;
} else {
LOGGER.severe("Cannot collect data. Solar panels are inactive");
return false;
}
}
public String getOrientation() {
return this.orientation;
}
public String getSolarPanels() {
return this.solarPanels;
}
public int getDataCollected() {
return this.dataCollected;
}
}
| VSrihariMoorthy/Satellite-Command-System | Satellite.java | 555 | // Satellite class contains the data members and member functions that are used to manipulate the satellite. | line_comment | en | false | 509 | 18 | 555 | 20 | 600 | 18 | 555 | 20 | 698 | 19 | false | false | false | false | false | true |
194731_1 | //On my honor:
//I have not discussed the Java language code in my program with anyone other than my instructor or the teaching assistants assigned to this course.
//I have not used Java language code obtained from another student, or any other unauthorized source, either modified or unmodified.
//If any Java language code or documentation used in my program was obtained from another source, such as a text book or course notes, that has been clearly noted with a proper citation in the comments of my program.
//I have not designed this program in such a way as to defeat or interfere with the normal operation of the Curator System.
//Clayton Kuchta
/**
* Creator: Clayton Kuchta
* Project: GIS System
* Last Modified: April. 15th, 2015
*
*
* This is the main class for the GIS Project. This project takes in three
* arguments:
*
* <database file name> <command script file name> <log file name>
*
* Where the database file is where you store imported data. The command script
* bides by the commands specified in the project description
* and the log file is the output of this project.
*
*
* Overall Design:
* The overall design is that the main checks and opens all the inputed files. Then
* it constructs a GISSystemConductor object and then it runs.
*
* nameIndex:
* The nameIndex is the layer between the condutorin the hash table.
*
* CoordinateIndex:
* The CoordinateIndex is the layer between the conductor and the pr quad tree.
*
* BufferPool:
* There is also i buffer pool data object that is the layer between the database file
* and the conductor.
*
* DataStructure Element Wrappers:
* All wrapper classes that are stored in the hash table and the quad tree can be found in the package
* DataStructures.Client.
*
* Point:
* This is what is stored in a quad tree.
*
* HashNameIndex:
* This is what is stored in the hash table.
*
* GISRecord:
* When a GIS record is read in it is converted into a GIS Record to easily get all the information
* from the record without having to split the string every time you want data.
*
* Package gisTools:
* This package contains the Command class which holds the information about a command. It makes any information about
* a command easily accessible for the conductor.
*
*/
import java.io.File;
import java.io.RandomAccessFile;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import error.ErrorMessage;
public class GIS {
private static final int RandomAccessFile = 0;
public static void main(String[] args) throws IOException{
// Check the correct amount of arguments
if (args.length < 3){
ErrorMessage.errorMessage("Not enough arguments");
return;
}
// Make database file
File databaseFile = new File(args[0]);
RandomAccessFile databaseRAF;
if(!databaseFile.createNewFile()){
databaseRAF = new RandomAccessFile(databaseFile, "rw");
databaseRAF.setLength(0);
}else{
databaseRAF = new RandomAccessFile(databaseFile, "rw");
}
// Check for command file
File commandFile = new File(args[1]);
if(!commandFile.exists()){
ErrorMessage.errorMessage("Command file not found " + commandFile.getName());
return;
}
FileReader commandFR = new FileReader(commandFile);
// Check and create a logFile
File logFile = new File(args[2]);
FileWriter logRAF;
if(!databaseFile.createNewFile()){
logRAF = new FileWriter(logFile);
logRAF.write("");
}else{
logRAF = new FileWriter(logFile);
}
// Construct the conductor
GISSystemConductor conductor = new GISSystemConductor(databaseRAF, commandFR, logRAF);
// Execute the program.
try{
conductor.run();
}catch(IOException e){
System.out.println("ERROR:\t" + e.getMessage());
}
logRAF.close();
}
}
| clayton8/GIS_Data_Structures | src/GIS.java | 1,054 | //I have not discussed the Java language code in my program with anyone other than my instructor or the teaching assistants assigned to this course. | line_comment | en | false | 930 | 27 | 1,054 | 30 | 1,036 | 27 | 1,054 | 30 | 1,213 | 29 | false | false | false | false | false | true |
195619_3 | package au.edu.unimelb.ai.squatter;
// TODO: Auto-generated Javadoc
/**
* The Piece class has two constant values to represent the color. Each piece
* has an "isEnclosed" value that represents the piece's current state.
*
* @author <Andre Peric Tavares> <aperic>
* @author <Felipe Matheus Costa Silva> <fcosta1>
*
*/
public class Piece {
enum Colour {
WHITE, BLACK
};
Colour colour;
boolean isEnclosed;
/**
* Instantiates a new piece.
*
* @param colour
* @param isEnclosed
*/
public Piece(Colour colour, boolean isEnclosed) {
this.colour = colour;
this.isEnclosed = isEnclosed;
}
/**
* Gets the colour.
*
* @return the colour
*/
public Colour getColour() {
return colour;
}
/**
* Sets the colour.
*
* @param colour
* the new colour
*/
public void setColour(Colour colour) {
this.colour = colour;
}
/**
* Checks if is enclosed.
*
* @return true, if is enclosed
*/
public boolean isEnclosed() {
return isEnclosed;
}
/**
* Sets the enclosed.
*
* @param isEnclosed
*/
public void setEnclosed(boolean isEnclosed) {
this.isEnclosed = isEnclosed;
}
}
| flpmat/aiproj.squatter | Piece.java | 380 | /**
* Gets the colour.
*
* @return the colour
*/ | block_comment | en | false | 331 | 18 | 380 | 17 | 417 | 22 | 380 | 17 | 468 | 25 | false | false | false | false | false | true |
197672_13 | import java.security.SecureRandom;
import java.util.ArrayList;
import java.util.Arrays;
/**
* The type User.
*/
public class User {
private String username;
private int xp;
private int level;
private int title;
private String league;
private ArrayList<Card> cards;
private Card[] currentCards;
private SecureRandom random;
{
cards = new ArrayList<>();
currentCards = new Card[8];
random = new SecureRandom();
username = "";
cards.add(Card.BARBARIANS);
cards.add(Card.ARCHERS);
cards.add(Card.BABYDRAGON);
cards.add(Card.WIZARD);
cards.add(Card.MINIPEKKA);
cards.add(Card.GIANT);
cards.add(Card.VALKYRIE);
cards.add(Card.RAGE);
cards.add(Card.FIREBALL);
cards.add(Card.ARROWS);
cards.add(Card.CANNON);
cards.add(Card.INFERNOTOWER);
}
/**
* Instantiates a new User.
*/
public User() {
xp = 0;
level = 1;
title = 0;
league = getLeague(title);
}
/**
* Instantiates a new User.
*
* @param level the level
*/
public User(int level) {
xp = 0;
title = 1;
this.level = level;
league = getLeague(title);
}
/**
* Instantiates a new User.
*
* @param username the username
* @param xp the xp
*/
public User(String username, int xp) {
this.username = username;
this.xp = xp;
if (xp < 300) {
level = 1;
} else if (xp < 500) {
level = 2;
} else if (xp < 900) {
level = 3;
} else if (xp < 1700) {
level = 4;
} else {
level = 5;
}
league = getLeague(title);
}
/**
* Instantiates a new User.
*
* @param username the username
* @param xp the xp
* @param currentCards the current cards
* @param title the title
*/
public User(String username, int xp, String[] currentCards, int title) {
this(username, xp);
int i = 0;
for (String cardName : currentCards) {
for (Card card : cards) {
if (card.toString().equalsIgnoreCase(cardName)) {
this.currentCards[i] = card;
}
}
i++;
}
this.title = title;
league = getLeague(title);
}
/**
* Get current cards card [ ].
*
* @return the card [ ]
*/
public Card[] getCurrentCards() {
return currentCards;
}
/**
* Gets level.
*
* @return the level
*/
public int getLevel() {
return level;
}
/**
* Gets xp.
*
* @return the xp
*/
public int getXp() {
return xp;
}
/**
* Sets xp.
*
* @param xp the xp
*/
public void setXp(int xp) {
this.xp = xp;
if (xp < 300) {
level = 1;
} else if (xp < 500) {
level = 2;
} else if (xp < 900) {
level = 3;
} else if (xp < 1700) {
level = 4;
} else {
level = 5;
}
}
/**
* Gets title.
*
* @return the title
*/
public int getTitle() {
return title;
}
/**
* Gets random card.
*
* @return the random card
*/
public Card getRandomCard() {
//return cards.get(random.nextInt(12)); // 8
return currentCards[random.nextInt(8)];
}
/**
* Gets cards.
*
* @return the cards
*/
public ArrayList<Card> getCards() {
return cards;
}
/**
* Gets username.
*
* @return the username
*/
public String getUsername() {
return username;
}
@Override
public String toString() {
return "User{" +
"username='" + username + '\'' +
", currentCards=" + Arrays.toString(currentCards) +
'}';
}
/**
* Increase xp.
*
* @param addedXp the added xp
*/
public void increaseXp(int addedXp) {
xp += addedXp;
if (xp < 300) {
level = 1;
} else if (xp < 500) {
level = 2;
} else if (xp < 900) {
level = 3;
} else if (xp < 1700) {
level = 4;
} else {
level = 5;
}
}
/**
* Increase title.
*
* @param addedTitle the added title
*/
public void increaseTitle(int addedTitle) {
title += addedTitle;
league = getLeague(title);
}
private String getLeague(int title) {
String league = "";
if (title <= 10) {
league = "Goblins";
}
if (11 <= title && title <= 30) {
league = "Archers";
}
if (31 <= title && title <= 100) {
league = "Barbars";
}
if (101 <= title && title <= 300) {
league = "Wizards";
}
if (301 <= title && title <= 1000) {
league = "Princes";
}
if (1001 <= title) {
league = "Legends";
}
league += " League";
return league;
}
/**
* Gets league.
*
* @return the league
*/
public String getLeague() {
return league;
}
} | AshkanShakiba/Clash-Royale | src/User.java | 1,464 | /**
* Gets username.
*
* @return the username
*/ | block_comment | en | false | 1,389 | 17 | 1,464 | 16 | 1,666 | 20 | 1,464 | 16 | 1,789 | 21 | false | false | false | false | false | true |
199003_1 | // BUGBUG: yuck :(
import java.util.Map.Entry;
/**
* A simple module to encapsulate using HTML tags.
*
* Note, makes use of CSS styling in an effort ease changing the style later.
*
* @author Robert C. Duvall
*/
public class HTMLPage {
/**
* @return tags to be included at top of HTML page
*/
public static String startPage (int numSizes, int startSize, int increment) {
StringBuilder style = new StringBuilder();
for (int k = 0; k < numSizes; k++) {
style.append(" .size-" + k + " { font-size: " + (startSize + increment * (k - 1)) + "px; }");
}
return "<html><head><style>" + style + "</style></head><body><p>\n";
}
/**
* @return tags to be included at bottom of HTML page
*/
public static String endPage () {
return "</p></body></html>";
}
/**
* @return tags to display a single styled word
*/
public static String formatWord (String word, int cssSize) {
return " <span class=\"size-" + cssSize + "\">" + word + "</span>\n";
}
/**
* @return tags to display a single styled word
*/
public static String formatWord (Entry<String, Integer> wordCount) {
return formatWord(wordCount.getKey(), wordCount.getValue());
}
}
| duke-compsci308-spring2015/example_wordcloud | src/HTMLPage.java | 341 | /**
* A simple module to encapsulate using HTML tags.
*
* Note, makes use of CSS styling in an effort ease changing the style later.
*
* @author Robert C. Duvall
*/ | block_comment | en | false | 326 | 42 | 341 | 47 | 367 | 46 | 341 | 47 | 385 | 49 | false | false | false | false | false | true |
201117_7 | /*
* Argus Open Source
* Software to apply Statistical Disclosure Control techniques
*
* Copyright 2014 Statistics Netherlands
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the European Union Public Licence
* (EUPL) version 1.1, as published by the European Commission.
*
* You can find the text of the EUPL v1.1 on
* https://joinup.ec.europa.eu/software/page/eupl/licence-eupl
*
* This software is distributed on an "AS IS" basis without
* warranties or conditions of any kind, either express or implied.
*/
package muargus;
import argus.model.ArgusException;
import argus.utils.SystemUtils;
import com.ibm.statistics.util.Utility;
import java.awt.Color;
import java.awt.Font;
import java.awt.Graphics2D;
import java.awt.SplashScreen;
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Locale;
import javax.swing.UnsupportedLookAndFeelException;
import muargus.extern.dataengine.CMuArgCtrl;
import muargus.model.ClassPathHack;
import muargus.view.MainFrameView;
import org.apache.commons.io.FilenameUtils;
/**
* Main class of Mu-Argus.
*
* @author Statistics Netherlands
*/
public class MuARGUS {
// Version info
public static final int MAJOR = 5;
public static final int MINOR = 1;
public static final String REVISION = "7";
public static final int BUILD = 4;
public static final int MAXDIMS = 10;
private static final String MESSAGETITLE = "Mu Argus";
private static final int NHISTOGRAMCLASSES = 10;
private static final int NCUMULATIVEHISTOGRAMCLASSES = 100;
private static final String DEFAULTSEPARATOR = ",";
private static final String LOOKANDFEEL = "Windows";
private static final File MANUAL = new File("resources/MUmanual5.1.3.pdf");
private static final int SLEEPTIME = 2000;
private static Process helpViewerProcess;
static {
System.loadLibrary("numericaldll");
System.loadLibrary("muargusdll");
}
private static final CalculationService calcService = new CalculationService(new CMuArgCtrl());
private static SpssUtils spssUtils;
private static String tempDir;
static {
setTempDir(System.getProperty("java.io.tmpdir"));
}
/**
* Gets the calculations service.
*
* @return CalculationService.
*/
public static CalculationService getCalculationService() {
return MuARGUS.calcService;
}
private static String getSpssVersion()
{
Utility FindSpss = new Utility();
return FindSpss.getStatisticsLocationLatest();
}
static{
try{
ClassPathHack.addFile(getSpssVersion() + "\\spssjavaplugin.jar");
}catch (IOException ex){System.out.print(ex.toString());}
}
/**
* Gets the instance of SpssUtils.
*
* @return SpssUtils, or null if the Spss plugin cannot be loaded
*/
public static SpssUtils getSpssUtils() {
try {
if (MuARGUS.spssUtils == null) {
MuARGUS.spssUtils = new SpssUtils();
}
return MuARGUS.spssUtils;
} catch (NoClassDefFoundError err) {
return null;
}
}
/**
* Gets the full version.
*
* @return String containing the full version.
*/
public static String getFullVersion() {
return "" + MuARGUS.MAJOR + "." + MuARGUS.MINOR + "." + MuARGUS.REVISION;
}
/**
* Gets the message title.
*
* @return String containing the message title.
*/
public static String getMessageTitle() {
return MuARGUS.MESSAGETITLE;
}
/**
* Gets the number of histogram classes.
*
* @param cumulative Boolean indicating whether the number of cumulative or
* normal histogram classes are requested.
* @return Integer containing the number of histogram classes.
*/
public static int getNHistogramClasses(boolean cumulative) {
return cumulative ? MuARGUS.NCUMULATIVEHISTOGRAMCLASSES : MuARGUS.NHISTOGRAMCLASSES;
}
/**
* Gets the Locale.
*
* @return Locale containing the English locale.
*/
public static Locale getLocale() {
return Locale.ENGLISH;
}
/**
* Gets the default separator.
*
* @return String containing the default separator.
*/
public static String getDefaultSeparator() {
return MuARGUS.DEFAULTSEPARATOR;
}
/**
* Gets the temp directory.
*
* @return String containing the temp directory.
*/
public static String getTempDir() {
return MuARGUS.tempDir;
}
/**
* Sets the temp directory.
*
* @param tempDir String containing the temp directory.
*/
public static void setTempDir(String tempDir) {
MuARGUS.tempDir = FilenameUtils.normalizeNoEndSeparator(tempDir);
}
/**
* Gets a temp file.
*
* @param fileName String containing the temp file name.
* @return String containing the path to the filename.
*/
public static String getTempFile(String fileName) {
return FilenameUtils.concat(MuARGUS.tempDir, fileName);
}
/**
* Shows the build info on the splash screen.
*/
public static void showBuildInfoInSplashScreen() {
final SplashScreen splash = SplashScreen.getSplashScreen();
if (splash == null) {
System.out.println("SplashScreen.getSplashScreen() returned null");
} else {
Graphics2D g = splash.createGraphics();
if (g == null) {
System.out.println("g is null");
} else {
g.setPaintMode();
g.setColor(new Color(255, 0, 0));
Font font = g.getFont().deriveFont(Font.BOLD, 14.0f);
g.setFont(font);
String version = "Version " + getFullVersion() + " (Build " + MuARGUS.BUILD + ")";
g.drawString(version, (splash.getSize().width / 2) - (version.length()*3), (3*splash.getSize().height/4));
splash.update();
sleepThread(MuARGUS.SLEEPTIME);
}
}
}
/**
* Shows the content sensitive help.
*
* @param namedDest String containing the named destination.
* @throws ArgusException Throws an ArgusException when an error occurs
* while trying to display the help file.
*/
public static void showHelp(String namedDest) throws ArgusException {
ArrayList<String> args = new ArrayList<>();
args.add("-loadfile");
args.add(MuARGUS.MANUAL.getAbsolutePath());
if (namedDest != null) {
args.add("-nameddest");
args.add(namedDest);
}
try {
execClass(
"org.icepdf.ri.viewer.Main",
"lib/ICEpdf.jar",
args);
} catch (IOException | InterruptedException ex) {
throw new ArgusException("Error trying to display help file");
}
}
/**
* Creates a new process starting with the class with the given name and
* path
*
* @param className Fully qualified name of the class
* @param classPath Path to the directory or jar file containing the class
* @param arguments List of commandline arguments given to the new instance
* @throws IOException Occurs when de class cannot be loaded
* @throws InterruptedException Occurs when the new process is interrupted
*/
public static void execClass(String className, String classPath, List<String> arguments) throws IOException,
InterruptedException {
if (MuARGUS.helpViewerProcess != null) {
MuARGUS.helpViewerProcess.destroy();
MuARGUS.helpViewerProcess = null;
}
String javaHome = System.getProperty("java.home");
String javaBin = javaHome
+ File.separator + "bin"
+ File.separator + "java";
arguments.add(0, javaBin);
arguments.add(1, "-cp");
arguments.add(2, classPath);
arguments.add(3, className);
ProcessBuilder builder = new ProcessBuilder(arguments);
MuARGUS.helpViewerProcess = builder.start();
}
/**
* Starts a sleep thread for a given amount of time.
*
* @param milliSecs Integer containing the number of milli seconds that the
* program will sleep.
*/
private static void sleepThread(int milliSecs) {
try {
Thread.sleep(milliSecs);
} catch (InterruptedException ex) {
// Do something, if there is a exception
System.out.println(ex.toString());
}
}
/**
* Main method for running Mu-Argus.
*
* @param args the command line arguments
*/
public static void main(String[] args) {
/* Set the look and feel */
try {
for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
if (MuARGUS.LOOKANDFEEL.equals(info.getName())) {
javax.swing.UIManager.setLookAndFeel(info.getClassName());
break;
}
}
} catch (ClassNotFoundException | InstantiationException | IllegalAccessException | UnsupportedLookAndFeelException ex) {
java.util.logging.Logger.getLogger(MainFrameView.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
}
//</editor-fold>
SystemUtils.setRegistryRoot("muargus");
SystemUtils.setLogbook(SystemUtils.getRegString("general", "logbook", getTempFile("MuLogbook.txt")));
SystemUtils.writeLogbook(" ");
SystemUtils.writeLogbook("Start of MuArgus run");
SystemUtils.writeLogbook("Version " + MuARGUS.getFullVersion() + " build " + MuARGUS.BUILD);
SystemUtils.writeLogbook("--------------------------");
showBuildInfoInSplashScreen();
/* Create and display the form */
java.awt.EventQueue.invokeLater(new Runnable() {
@Override
public void run() {
new MainFrameView().setVisible(true);
}
});
}
}
| sdcTools/muargus | src/muargus/MuARGUS.java | 2,453 | /**
* Gets the number of histogram classes.
*
* @param cumulative Boolean indicating whether the number of cumulative or
* normal histogram classes are requested.
* @return Integer containing the number of histogram classes.
*/ | block_comment | en | false | 2,246 | 48 | 2,453 | 47 | 2,657 | 53 | 2,453 | 47 | 2,990 | 59 | false | false | false | false | false | true |
201409_17 | import java.util.ArrayList;
import java.util.HashMap;
/**
* This class is used to model a hand of Full House in Big Two Game.
* It is a subclass of the class Hand. It stores the information of
* the player who plays his / her hand. It provides concrete implementations of
* two abstract methods in the superclass and overrides several methods for its use.
* This class also provides a static method for checking whether a given hand is
* a Full House.
* <br>
* <p>
* A Full House is five Big Two Cards with three of the same rank and another
* two of the same rank.
*
* <br>
* <p> <b>Copyright Information</b>
* <br> <br> <i> COMP 2396 OOP & Java Assignment #3 </i>
* <br> <i> ZHANG, Jiayao Johnson / 3035233412 </i>
* <br> Department of Computer Science, The University of Hong Kong
* <br> <a href = "[email protected]"> Contact me via email </a>
* <br> <a href = "http://i.cs.hku.hk/~jyzhang/"> Visit my webpage </a>
*
* @author ZHANG, Jiayao Johnson
* @version 0.1
* @since 2016-10-09
*/
public class FullHouse extends Hand
{
// Private variable storing the type of this hand in String
private String type;
/**
* This constructor construct a FullHouse object with specified player and list
* of cards.
* <br>
* @param player The player who plays his / her hand
* @param cards the list cards that the player plays
*/
public FullHouse(CardGamePlayer player, CardList cards)
{
// Call super constructor first
super(player,cards);
this.type = "FullHouse";
// Storing the type(s) of hand FullHouse can beat
// A Full House can beat, apart from a Pass,
// any Straight and any Flush.
this.beatList.add("Straight");
this.beatList.add("Flush");
}
/**
* This method is used to check if this is a valid FullHouse.
* <br>
* @return a boolean value specifying whether this hand is a valid FullHouse
*/
public boolean isValid()
{
return FullHouse.isValid(this);
}
/**
* This method is used to check whether a given hand is a valid FullHouse hand.
* This method is a static method.
* <br>
* @param hand a given hand to be checked validity
* @return the boolean value to specify whether the given hand is a valid
* FullHouse in Big Two Game.
*/
public static boolean isValid(CardList hand)
{
int numOfCards = hand.size();
// First check the number of cards
if(numOfCards == 5)
{
// Using a HashMap to associate the number of occurrence of a
// particular suit to this particular suit
HashMap<Integer,Integer> cardsRank = new HashMap<Integer,Integer>();
for(int i = 0; i < numOfCards; ++i)
{
Card card = hand.getCard(i);
int suit = card.getSuit();
int rank = card.getRank();
if(!(-1 < suit && suit < 4 && -1 < rank && rank < 13))
{
return false;
}
// Add or update the occurrence of the rank
if(!cardsRank.containsKey(rank))
{
cardsRank.put(rank,1);
} else {
cardsRank.replace(rank,cardsRank.get(rank) + 1);
}
}
// A Full House has two different ranks and the occurrence of the ranks
// is either (2,3) or (3,2). Thus conditioning whether the product of
// the number of occurrence is six to determine whether this is a
// valid Full House given the total number of cards is five.
if((cardsRank.size() == 2)
&& (((int) cardsRank.values().toArray()[0] * (int) cardsRank.values().toArray()[1]) == 6))
{
return true;
}
}
return false;
}
/**
* This method is used to retrieve the top card of this Full House.
* <b> Important Note: This method assumes this hand is a valid Full House. </b>
* <br>
* @return the top card of this hand
*/
public Card getTopCard()
{
// Create two lists to hold cards according to rank
CardList firstList = new CardList();
CardList secondList = new CardList();
// Get one rank for comparison
int firstRank = this.getCard(0).getRank();
// Divide the cards into two lists according to the rank obtained
for(int i = 0; i < this.getNumOfCards(); ++i)
{
Card card = this.getCard(i);
int rank = card.getRank();
if(rank == firstRank)
{
firstList.addCard(card);
} else {
secondList.addCard(card);
}
}
// Get the triplet in Full House
CardList finalList = firstList.size() > secondList.size() ? firstList : secondList;
// Get the top card in the triplet, which is the top card in this Full House
finalList.sort();
return finalList.getCard(0);
}
/**
* This method is used to return the type of this hand in
* String representation.
* @return the String specification of the type of this hand
*/
public String getType()
{
return this.type;
}
}
| zjiayao/BigTwoGame | src/FullHouse.java | 1,433 | /**
* This method is used to retrieve the top card of this Full House.
* <b> Important Note: This method assumes this hand is a valid Full House. </b>
* <br>
* @return the top card of this hand
*/ | block_comment | en | false | 1,277 | 52 | 1,433 | 58 | 1,396 | 55 | 1,433 | 58 | 1,628 | 58 | false | false | false | false | false | true |
202045_3 | package rsa;
/**
*
* Copyright (c) 2023 Archerxy
*
* 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
* 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.
*
* @author archer
*
*/
import java.math.BigInteger;
import java.security.SecureRandom;
import java.util.Collections;
import java.util.LinkedList;
import java.util.List;
/***
* n = p1 * p2 ; (p1,p2 are prime numbers)
*
* φ(n) = (p1 - 1) * (p2 - 1) ; Euler's formula
*
* e * d - k * φ(n) = 1 ; e = random(1~φ(n)), d is calculated
*
* message ^ e = cipher (mod n) ;
*
* cipher ^ d = message (mod n) ;
*
* */
public class RSA {
private static final int BITS = 512;
/***
* generate (e, d, n) pk = (n, e), sk = (n, d)
* @return BigInteger[3] [e, d, n]
* */
public static BigInteger[] genEDN() {
SecureRandom sr = new SecureRandom();
BigInteger p1 = BigInteger.probablePrime(BITS >> 1, sr);
BigInteger p2 = BigInteger.probablePrime(BITS >> 1, sr);
BigInteger n = p1.multiply(p2);
BigInteger fiN = p1.subtract(BigInteger.ONE).multiply(p2.subtract(BigInteger.ONE));
BigInteger e = BigInteger.probablePrime(fiN.bitLength() - 1, sr);
while(e.compareTo(fiN) >= 0) {
e = BigInteger.probablePrime(fiN.bitLength() - 1, sr);
}
/**
* Actually, d can be calculated with {@code BigInteger d = e.modInverse(fiN);}.
* Euclid's algorithm to calculate d.
* */
List<BigInteger[]> rs = new LinkedList<>();
BigInteger r1 = e, r2 = fiN;
boolean b = false;
while(!r1.equals(BigInteger.ONE) && !r2.equals(BigInteger.ONE)) {
rs.add(new BigInteger[] {r1, r2});
if(b) {
r1 = r1.mod(r2);
b = false;
} else {
r2 = r2.mod(r1);
b = true;
}
}
rs.add(new BigInteger[] {r1, r2});
Collections.reverse(rs);
BigInteger d = BigInteger.valueOf(1), k = BigInteger.valueOf(0);
b = r1.equals(BigInteger.ONE);
for(BigInteger[] r : rs) {
if(b) {
d = k.multiply(r[1]).add(BigInteger.ONE).divide(r[0]);
b = false;
} else {
k = d.multiply(r[0]).subtract(BigInteger.ONE).divide(r[1]);
b = true;
}
}
return new BigInteger[] {e, d, n};
}
/**
* rsa encryption,
* @param e
* @param n
* @param message
*
* **/
public static BigInteger encrypt(BigInteger e, BigInteger n, BigInteger message) {
return message.modPow(e, n);
}
/**
* rsa decryption,
* @param d
* @param n
* @param cipher
*
* **/
public static BigInteger decrypt(BigInteger d, BigInteger n, BigInteger cipher) {
return cipher.modPow(d, n);
}
/**
* test
* */
public static void main(String[] args) {
String msg = "hello";
BigInteger[] edn = genEDN();
BigInteger e = edn[0], d = edn[1], n = edn[2];
//encrypt
BigInteger cipher = encrypt(e, n, new BigInteger(1, msg.getBytes()));
System.out.println(cipher.toString(16));
//decrypt
BigInteger message = decrypt(d, n, cipher);
System.out.println(new String(message.toByteArray()));
}
}
| Archerxy/RSA_java | rsa/RSA.java | 1,228 | /**
* Actually, d can be calculated with {@code BigInteger d = e.modInverse(fiN);}.
* Euclid's algorithm to calculate d.
* */ | block_comment | en | false | 1,085 | 35 | 1,228 | 39 | 1,262 | 40 | 1,228 | 39 | 1,560 | 47 | false | false | false | false | false | true |
202685_5 | import java.io.FileInputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.LinkedList;
import java.util.Queue;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import org.apache.commons.io.IOUtils;
import com.itextpdf.text.DocumentException;
public class ParseFile {
public static String openFile(String filePath) throws IOException{
FileInputStream inputStream = new FileInputStream(filePath);
String file;
try {
file = IOUtils.toString(inputStream);
} finally {
inputStream.close();
}
return file;
}
public static ArrayList<Measure> sortMeasure(String body) {
String line = "";
int indexOfNewLine = 0;
int indexOfVerticalLine = 0;
String checkString = "";
Pattern pattern = Pattern.compile("\\|?(\\||([0-9]))(-|\\*)");
Pattern pattern2 = Pattern.compile("\\|?(\\|)(-|\\*)");
ArrayList<String> blockOfMeasures = new ArrayList<String>();
ArrayList<Measure> measures = new ArrayList<Measure>();
// forgot why body length > 0 is used, check again later
while (indexOfNewLine != -1 && body.length() > 0) {
for (int i = 0; i < 6; i ++) {
Matcher matcher = pattern.matcher(body);
if (matcher.find()) {
indexOfVerticalLine = matcher.start();
indexOfNewLine = body.indexOf('\n', indexOfVerticalLine + 1);
int check2 = body.indexOf('\n', indexOfNewLine + 1);
checkString = body.substring(indexOfNewLine, check2).trim();
Matcher check = pattern2.matcher(checkString);
if (!check.find() && i != 5) {
blockOfMeasures.clear();
break;
}
line = body.substring(indexOfVerticalLine, indexOfNewLine).trim();
if (line.lastIndexOf("| ") > 0)
line = line.substring(0, line.lastIndexOf("| ") + 2).trim();
body = body.substring(indexOfNewLine + 1);
blockOfMeasures.add(line);
}
}
if (unevenBlockLengthCheck(blockOfMeasures)) {
String message = "";
for (String s : blockOfMeasures) {
message = message + s + '\n';
}
throw new InvalidMeasureException("This measure is formatted incorrectly.\n" + message);
}
if (blockOfMeasures.size() > 0)
measures.addAll(convertToMeasures(blockOfMeasures));
blockOfMeasures.clear();
body = body.substring(body.indexOf('\n') + 1);
if (body.indexOf('\n') <= 1) { // something idk check again later
while (body.indexOf('\n') >= 0 && body.indexOf('\n') <= 1)
body = body.substring(body.indexOf('\n') + 1);
}
}
return measures;
}
public static ArrayList<String> parse(String string) {
ArrayList<String> token = new ArrayList<String>();
String hyphen = "";
Pattern isDigit = Pattern.compile("^[0-9]");
for (int i = 0; i < string.length(); i++) {
Matcher matcher = isDigit.matcher(string);
if (string.charAt(i) == '|') {
if ((i + 1 < string.length()) && (i + 2 < string.length()) && string.charAt(i+1) == '|' && string.charAt(i+2) == '|') {
token.add("|||");
i = i + 2;
}
else if ((i + 1 < string.length()) && string.charAt(i+1) == '|') {
token.add("||");
i++;
}
else if ((i + 1 < string.length()) && (i + 2 < string.length()) && string.charAt(i+1) == '|' && string.charAt(i+2) == '|') {
token.add("|||");
i = i + 2;
}
else if ((i + 1 < string.length()) && (string.charAt(i+1) >= '0' && (string.charAt(i+1) <= '9'))) {
token.add("|" + string.charAt(i+1));
i++;
}
else
token.add("|");
}
else if (string.charAt(i) == '-') {
while (string.charAt(i) == '-') {
hyphen = hyphen + "-"; // use stringbuilder or something for this later
i++;
if (i == string.length())
break;
}
token.add(hyphen);
hyphen = "";
i--;
}
else if (string.charAt(i) == ' ') {
i++;
while (string.charAt(i) == ' ') {
hyphen = hyphen + "-";
i++;
if (i == string.length())
break;
}
token.add(hyphen);
hyphen = "";
i--;
}
else if ((string.charAt(i) >= '0' && (string.charAt(i) <= '9')) && i > 0) {
//check the second digit only if index + 1 is not equal to the length of the string
if (i + 1 < string.length())
// if the second digit is a number, we will treat it as a two-digit number.
if (string.charAt(i + 1) >= '0' && (string.charAt(i + 1) <= '9')) {
if (string.charAt(i-1) == '<') {
token.add(string.substring(i-1, i+3));
i = i + 2;
}
else {
token.add(string.substring(i, i+2));
i = i + 1;
}
}
// if the character ahead is not a digit, we check if the previous character is a angle bracket
else if (string.charAt(i-1) == '<') {
token.add(string.substring(i-1,i+2));
i = i + 1;
}
// if not we just add the number itself.
else {
token.add("" + string.charAt(i));
}
}
else if (string.charAt(i) == 's')
token.add("s");
else if (string.charAt(i) == '*')
token.add("*");
else if (string.charAt(i) == 'h')
token.add("h");
else if (string.charAt(i) == 'p')
token.add("p");
else if (matcher.find()) {
token.add("" + string.charAt(i));
}
else {
if (string.charAt(i) != '>' && string.charAt(i) != '<')
token.add("-");
}
}
return token;
}
public static ArrayList<Measure> convertToMeasures(ArrayList<String> block) {
Pattern separator = Pattern.compile("(\\||^[0-9])([0-9]|\\|)?\\|?");
Matcher matcher = separator.matcher(block.get(2));
ArrayList<String> measure = new ArrayList<String>();
ArrayList<Measure> newMeasures = new ArrayList<Measure>();
int indexOfBeginningStaff = 0;
matcher.find();
while (matcher.find()) {
for (String s : block) {
measure.add(s.substring(indexOfBeginningStaff, matcher.end()));
}
newMeasures.add(new Measure(measure));
measure.clear();
indexOfBeginningStaff = matcher.start();
}
return newMeasures;
}
public static boolean unevenBlockLengthCheck(ArrayList<String> blockOfMeasures) {
HashSet<Integer> lengths = new HashSet<Integer>();
for (String s : blockOfMeasures) {
lengths.add(s.length());
}
if (lengths.size() > 1)
return true;
return false;
}
}
| Hayawi/TAB2PDF | src/ParseFile.java | 2,022 | // if the character ahead is not a digit, we check if the previous character is a angle bracket
| line_comment | en | false | 1,731 | 21 | 2,022 | 21 | 2,067 | 21 | 2,022 | 21 | 2,710 | 22 | false | false | false | false | false | true |
204664_0 | package irvine.oeis.a069;
import irvine.math.IntegerUtils;
import irvine.math.partition.IntegerPartition;
import irvine.math.predicate.Predicates;
import irvine.math.z.Z;
import irvine.oeis.Sequence1;
import irvine.util.Permutation;
import irvine.util.bumper.Bumper;
import irvine.util.bumper.BumperFactory;
/**
* A069672 Largest n-digit triangular number with minimum digit sum.
* @author Sean A. Irvine
*/
public class A069672 extends Sequence1 {
// After Robert Israel
private static final int[] S = {1, 3, 6, 9};
private int mD = 0;
@Override
public Z next() {
++mD;
final Bumper bumper = BumperFactory.increasing(mD);
for (final int s : S) {
final IntegerPartition part = new IntegerPartition(s);
int[] q;
Z best = Z.ZERO;
while ((q = part.next()) != null) {
final Permutation perm = new Permutation(q);
int[] p;
while ((p = perm.next()) != null) {
final int[] pos = IntegerUtils.identity(new int[p.length]);
do {
if (pos[pos.length - 1] == mD - 1) {
Z x = Z.ZERO;
for (int k = 0; k < pos.length; ++k) {
x = x.add(Z.TEN.pow(pos[k]).multiply(p[k]));
}
if (x.compareTo(best) > 0 && Predicates.TRIANGULAR.is(x)) {
best = x;
}
}
} while (bumper.bump(pos));
}
}
if (!best.isZero()) {
return best;
}
}
throw new UnsupportedOperationException();
}
}
| archmageirvine/joeis | src/irvine/oeis/a069/A069672.java | 481 | /**
* A069672 Largest n-digit triangular number with minimum digit sum.
* @author Sean A. Irvine
*/ | block_comment | en | false | 402 | 28 | 481 | 36 | 492 | 31 | 481 | 36 | 548 | 37 | false | false | false | false | false | true |
204913_9 | // Stefan Miklosovic
// [email protected]
import java.io.*;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
import java.util.LinkedList;
// this class represents a process in a system
public class Process implements MsgHandler {
// process id for process identification
protected int pid;
// number of processes in a system in Ricart-Agrawala's algorithm
protected int numOfProcesses;
// state of critical section from processes view
protected State state;
// port of process it is listening for incomming messages at
protected int port;
// ports of other processes for udp communication
LinkedList<Pair> ports;
// length of a input buffer for message recieving
protected final static int bufferLength = 100;
Process(int id, int n, int p, LinkedList<Pair> ports) {
// state is firstly set to the RELEASED, look at State's constructor
state = new State();
pid = id;
numOfProcesses = n;
port = p;
this.ports = ports;
}
// waiting method for a process thread, typically it waits for a message
public synchronized void processWait() {
try {
wait();
} catch (Exception e) {
System.err.println(e);
}
}
// multicasting of messages to the other processes
public void multicastMessage(Msg message) {
for (int i = 1; i <= numOfProcesses; i++) {
if (i != this.pid) {
sendMessage(ports.get(i-1).getPort(), message);
}
}
}
// sending of a message to another process
public void sendMessage(int port, Msg m) {
DatagramSocket aSocket = null;
try {
aSocket = new DatagramSocket();
InetAddress aHost = InetAddress.getByAddress(
new byte[] {(byte)127, (byte)0, (byte)0 ,(byte) 1});
DatagramPacket message =
new DatagramPacket(m.toBytes(), m.toBytes().length, aHost, port);
// actual sending of a message
aSocket.send(message);
}
catch (IOException ex) { }
finally { if(aSocket != null) aSocket.close(); }
}
// receiving of a message form a network
@Override
public Msg recieveMessage(DatagramSocket aSocket) {
DatagramPacket message = null;
byte[] buffer = null;
try {
buffer = new byte[bufferLength];
message = new DatagramPacket(buffer, buffer.length);
aSocket.receive(message);
}
catch (IOException ex) {
}
return new Msg(message);
}
@Override
public void handleMessage(Msg message) {
// this method is empty since it is overriden in MutexProcess class
}
}
| smiklosovic/ramutex | Process.java | 689 | // state is firstly set to the RELEASED, look at State's constructor | line_comment | en | false | 614 | 15 | 689 | 16 | 738 | 16 | 689 | 16 | 791 | 18 | false | false | false | false | false | true |
205488_5 | /*
Copyright 2018-19 Mark P Jones, Portland State University
This file is part of mil-tools.
mil-tools is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
mil-tools is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with mil-tools. If not, see <https://www.gnu.org/licenses/>.
*/
package mil;
import compiler.*;
import core.*;
import java.io.PrintWriter;
public class Sel extends Tail {
private Cfun cf;
private int n;
private Atom a;
/** Default constructor. */
public Sel(Cfun cf, int n, Atom a) {
this.cf = cf;
this.n = n;
this.a = a;
}
/** Test to determine whether a given tail expression has no externally visible side effect. */
boolean hasNoEffect() {
return true;
}
/** Test if this Tail expression includes a free occurrence of a particular variable. */
boolean contains(Temp w) {
return a == w;
}
/**
* Test if this Tail expression includes an occurrence of any of the variables listed in the given
* array.
*/
boolean contains(Temp[] ws) {
return a.occursIn(ws);
}
/** Add the variables mentioned in this tail to the given list of variables. */
Temps add(Temps vs) {
return a.add(vs);
}
/** Test if two Tail expressions are the same. */
boolean sameTail(Tail that) {
return that.sameSel(this);
}
boolean sameSel(Sel that) {
return this.cf == that.cf && this.n == that.n && this.a.sameAtom(that.a);
}
/** Find the dependencies of this AST fragment. */
Defns dependencies(Defns ds) {
return a.dependencies(ds);
}
/** Display a printable representation of this MIL construct on the specified PrintWriter. */
void dump(PrintWriter out, Temps ts) {
out.print(cf + " " + n + " " + a.toString(ts));
}
/**
* Apply a TempSubst to this Tail, forcing construction of a new Tail, even if the substitution is
* empty.
*/
Tail apply(TempSubst s) {
return new Sel(cf, n, a.apply(s));
}
private AllocType type;
/** The type tuple that describes the outputs of this Tail. */
private Type outputs;
/** Calculate the list of unbound type variables that are referenced in this MIL code fragment. */
TVars tvars(TVars tvs) {
return type.tvars(outputs.tvars(tvs));
}
/** Return the type tuple describing the result that is produced by executing this Tail. */
Type resultType() {
return outputs;
}
Type inferType(Position pos) throws Failure {
type = cf.checkSelIndex(pos, n).instantiate();
type.resultUnifiesWith(pos, a.instantiate());
return outputs = Type.tuple(type.storedType(n));
}
/**
* Generate code for a Tail that appears as a regular call (i.e., in the initial part of a code
* sequence). The parameter o specifies the offset for the next unused location in the current
* frame; this will also be the first location where we can store arguments and results.
*/
void generateCallCode(MachineBuilder builder, int o) {
a.load(builder);
builder.sel(n, o);
}
/**
* Generate code for a Tail that appears in tail position (i.e., at the end of a code sequence).
* The parameter o specifies the offset of the next unused location in the current frame. For
* BlockCall and Enter, in particular, we can jump to the next function instead of doing a call
* followed by a return.
*/
void generateTailCode(MachineBuilder builder, int o) {
a.load(builder);
builder.sel(n, 0);
builder.retn();
}
/**
* Skip goto blocks in a Tail (for a ClosureDefn or TopLevel). TODO: can this be simplified now
* that ClosureDefns hold Tails rather than Calls?
*/
public Tail inlineTail() {
return thisUnless(rewriteSel(null));
}
/**
* Find the variables that are used in this Tail expression, adding them to the list that is
* passed in as a parameter. Variables that are mentioned in BlockCalls or ClosAllocs are only
* included if the corresponding flag in usedArgs is set; all of the arguments in other types of
* Call (i.e., PrimCalls and DataAllocs) are considered to be "used".
*/
Temps usedVars(Temps vs) {
return a.add(vs);
}
/**
* Test to determine whether a given tail expression may be repeatable (i.e., whether the results
* of a previous use of the same tail can be reused instead of repeating the tail). TODO: is there
* a better name for this?
*/
public boolean isRepeatable() {
return true;
}
/**
* Test to determine whether a given tail expression is pure (no externally visible side effects
* and no dependence on other effects).
*/
public boolean isPure() {
return true;
}
public Code rewrite(Defn d, Facts facts) {
Tail t = rewriteSel(facts);
return (t == null) ? null : new Done(t);
}
/** Liveness analysis. TODO: finish this comment. */
Temps liveness(Temps vs) {
a = a.shortTopLevel();
return a.add(vs);
}
/**
* Attempt to rewrite this selector if the argument is known to have been constructed using a
* specific DataAlloc. TODO: find a better name?
*/
Tail rewriteSel(Facts facts) {
DataAlloc data = a.lookForDataAlloc(facts); // is a a known data allocator?
if (data != null) {
Atom a1 = data.select(cf, n); // find matching component
if (a1 != null) {
MILProgram.report("rewriting " + cf + " " + n + " " + a + " -> " + a1);
return new Return(a1);
}
}
return null;
}
/**
* Compute an integer summary for a fragment of MIL code with the key property that alpha
* equivalent program fragments have the same summary value.
*/
int summary() {
return 4 + cf.summary() + n;
}
/** Test to see if two Tail expressions are alpha equivalent. */
boolean alphaTail(Temps thisvars, Tail that, Temps thatvars) {
return that.alphaSel(thatvars, this, thisvars);
}
/** Test two items for alpha equivalence. */
boolean alphaSel(Temps thisvars, Sel that, Temps thatvars) {
return this.cf == that.cf && this.n == that.n && this.a.alphaAtom(thisvars, that.a, thatvars);
}
/** Collect the set of types in this AST fragment and replace them with canonical versions. */
void collect(TypeSet set) {
a.collect(set);
if (outputs != null) {
outputs = outputs.canonType(set);
}
if (type != null) {
type = type.canonAllocType(set);
}
cf = cf.canonCfun(set);
}
/**
* Eliminate a call to a newtype constructor or selector in this Tail by replacing it with a tail
* that simply returns the original argument of the constructor or selector.
*/
Tail removeNewtypeCfun() {
if (cf.isNewtype()) { // Look for use of a newtype constructor
if (n != 0) {
debug.Internal.error("newtype selector for arg!=0");
}
return new Return(a);
}
// No point looking for a selector of a singleton type because they do not have any fields.
return this;
}
/** Generate a specialized version of this Tail. */
Tail specializeTail(MILSpec spec, TVarSubst s, SpecEnv env) {
return new Sel(cf.specializeCfun(spec, type, s), n, a.specializeAtom(spec, s, env));
}
Tail bitdataRewrite(BitdataMap m) {
BitdataRep r = cf.findRep(m); // Look for a possible change of representation
if (r == null) { // No new representation for this type
return this;
} else if (cf.getArity()
== 0) { // Representation change, but nullary so there is no layout constructor
return new Sel(cf.bitdataRewrite(r), n, a);
} else { // Representation change, requires layout constructor
return new BlockCall(cf.bitdataSelBlock(r, n)).withArgs(a);
}
}
Tail mergeRewrite(MergeMap mmap) {
return new Sel(cf.lookup(mmap), n, a);
}
Tail repTransform(RepTypeSet set, RepEnv env) {
return cf.repTransformSel(set, env, n, a);
}
/**
* Apply a representation transformation to this Tail value in a context where the result of the
* tail should be bound to the variables vs before continuing to execute the code in c. For the
* most part, this just requires the construction of a new Bind object. Special treatment,
* however, is required for Selectors that access data fields whose representation has been spread
* over multiple locations. This requires some intricate matching to check for selectors using
* bitdata names or layouts, neither of which require this special treatment.
*/
Code repTransform(RepTypeSet set, RepEnv env, Temp[] vs, Code c) {
return cf.repTransformSel(set, env, vs, n, a, c);
}
/**
* Generate LLVM code to execute this Tail with NO result from the right hand side of a Bind. Set
* isTail to true if the code sequence c is an immediate ret void instruction.
*/
llvm.Code toLLVMBindVoid(LLVMMap lm, VarMap vm, TempSubst s, boolean isTail, llvm.Code c) {
debug.Internal.error("Sel does not return void");
return c;
}
/**
* Generate LLVM code to execute this Tail and return a result from the right hand side of a Bind.
* Set isTail to true if the code sequence c will immediately return the value in the specified
* lhs.
*/
llvm.Code toLLVMBindCont(
LLVMMap lm, VarMap vm, TempSubst s, boolean isTail, llvm.Local lhs, llvm.Code c) { // cf n a
llvm.Type objt = lm.cfunLayoutType(this.cf).ptr();
llvm.Local base = vm.reg(objt); // register to hold a pointer to a structure for cfun this.cf
llvm.Type at = lhs.getType().ptr();
llvm.Local addr = vm.reg(at); // register to hold pointer to the nth component of this.c
return new llvm.Op(
base,
new llvm.Bitcast(a.toLLVMAtom(lm, vm, s), objt),
new llvm.Op(
addr,
new llvm.Getelementptr(at, base, llvm.Word.ZERO, new llvm.Index(n + 1)),
new llvm.Op(lhs, new llvm.Load(addr), c)));
}
}
| habit-lang/mil-tools | src/mil/Sel.java | 2,687 | /** Add the variables mentioned in this tail to the given list of variables. */ | block_comment | en | false | 2,557 | 16 | 2,687 | 16 | 2,918 | 16 | 2,687 | 16 | 3,190 | 16 | false | false | false | false | false | true |
205516_3 | /*
Copyright 2018 Mark P Jones, Portland State University
This file is part of minitour.
minitour is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
minitour is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with minitour. If not, see <https://www.gnu.org/licenses/>.
*/
package ast;
import compiler.Position;
/** Abstract syntax for greater than or equal expressions.
*/
public class Gte extends BinCompExpr {
/** Default constructor.
*/
public Gte(Position pos, Expr left, Expr right) {
super(pos, left, right);
}
/** Return a string that provides a simple description of this
* particular type of operator node.
*/
String label() { return "Gte"; }
/** Generate a pretty-printed description of this expression
* using the concrete syntax of the mini programming language.
*/
public void print(TextOutput out) { binary(out, ">="); }
/** Constant folding for binary operators with two known integer
* arguments.
*/
Expr fold(int n, int m) { return new BoolLit(pos, n>=m); }
}
| zipwith/minitour | 19/ast/Gte.java | 359 | /** Return a string that provides a simple description of this
* particular type of operator node.
*/ | block_comment | en | false | 345 | 23 | 359 | 22 | 385 | 24 | 359 | 22 | 435 | 24 | false | false | false | false | false | true |
206027_0 | package mdt.smarty;
import net.sf.json.JSONObject;
/**
* This class provides key definitions and cover methods for accessing
* LiveAddress results JSON.
*
* @author Eric Robinson
*/
public class JLiveAddressResult {
public static final String INPUT_INDEX = "input_index";
public static final String CANDIDATE_INDEX = "candidate_index";
public static final String ADDRESSEE = "addressee";
public static final String DELIVERY_LINE_1 = "delivery_line_1";
public static final String DELIVERY_LINE_2 = "delivery_line_2";
public static final String LAST_LINE = "last_line";
public static final String DELIVERY_POINT_BARCODE = "delivery_point_barcode";
public static final String COMPONENTS = "components";
public static final String METADATA = "metadata";
public static final String ANALYSIS = "analysis";
public static final String URBANIZATION = "urbanization";
public static final String PRIMARY_NUMBER = "primary_number";
public static final String STREET_NAME = "street_name";
public static final String STREET_PREDIRECTION = "street_predirection";
public static final String STREET_POSTDIRECTION = "street_postdirection";
public static final String STREET_SUFFIX = "street_suffix";
public static final String SECONDARY_NUMBER = "secondary_number";
public static final String SECONDARY_DESIGNATOR = "secondary_designator";
public static final String PMB_DESIGNATOR = "pmb_designator";
public static final String PMB_NUMBER = "pmb_number";
public static final String CITY_NAME = "city_name";
public static final String STATE_ABBREVIATION = "state_abbreviation";
public static final String ZIPCODE = "zipcode";
public static final String PLUS4_CODE = "plus4_code";
public static final String DELIVERY_POINT = "delivery_point";
public static final String DELIVERY_POINT_CHECK_DIGIT = "delivery_point_check_digit";
public static final String RECORD_TYPE = "record_type";
public static final String COUNTRY_FIPS = "country_fips";
public static final String COUNTRY_NAME = "country_name";
public static final String CARRIER_ROUTE = "carrier_route";
public static final String CONGRESSIONAL_DISTRICT = "congressional_district";
public static final String BUILDING_DEFAULT_INDICATOR = "building_default_indicator";
public static final String RDI = "rdi";
public static final String LATITUDE = "latitude";
public static final String LONGITUDE = "longitude";
public static final String PRECISION = "precision";
public static final String DPV_MATCH_CODE = "dpv_match_code";
public static final String DPV_FOOTNOTES = "dpv_footnotes";
public static final String DPV_CMRA = "dpv_cmra";
public static final String DPV_VACANT = "dpv_vacant";
public static final String ACTIVE = "active";
public static final String EWS_MATCH = "ews_match";
public static final String FOOTNOTES = "footnotes";
public static final String LACSLINK_CODE = "lacslink_code";
public static final String LACSLINK_INDICATOR = "lacslink_indicator";
JSONObject _addressJSON;
/**
* Create a JLiveAddressResult from the provided json
*
* @param addressJSON
*/
public JLiveAddressResult(JSONObject addressJSON) {
_addressJSON = addressJSON;
}
/**
* get a value from the address JSON
*
* @param key
* @return
*/
public String get(String key) {
return _addressJSON.optString(key);
}
/**
* utility method to get a value from the results "components" map
*
* @param key
* @return
*/
public String getComponent(String key) {
return _addressJSON.optJSONObject(COMPONENTS).optString(key);
}
/**
* utility method to get a value from the results "metadata" map
*
* @param key
* @return
*/
public Object getMetadata(String key) {
return _addressJSON.optJSONObject(METADATA).opt(key);
}
/**
* utility method to get a value from the results "analysis" map
*
* @param key
* @return
*/
public String getAnalysis(String key) {
return _addressJSON.optJSONObject(ANALYSIS).optString(key);
}
/**
* get the raw json
*
* @return
*/
public JSONObject getAddressJSON() {
return _addressJSON;
}
/**
* set the raw json
*
* @param addressJSON
*/
public void setAddressJSON(JSONObject addressJSON) {
_addressJSON = addressJSON;
}
}
| eric-robinson/JLiveAddress | src/mdt/smarty/JLiveAddressResult.java | 1,208 | /**
* This class provides key definitions and cover methods for accessing
* LiveAddress results JSON.
*
* @author Eric Robinson
*/ | block_comment | en | false | 985 | 28 | 1,208 | 32 | 1,178 | 31 | 1,208 | 32 | 1,376 | 31 | false | false | false | false | false | true |
207231_3 | import javax.swing.JLabel;
/**
* A simple bank account. NSFCA (not safe for concurrent access).
*
* @author original unknown
* Updated for Java Swing, Jim Teresco, The College of Saint Rose, Fall
* 2013
* @version Spring 2022
*/
public class Account {
private int balance;
private JLabel display; // label on screen for balance
/**
* Construct a new account with the given starting balance, which
* will be displayed on the given label.
*
* @param start initial account balance
* @param aDisplay the label where the balance will be displayed
*/
public Account(int start, JLabel aDisplay) {
balance = start;
display = aDisplay;
display.setText("" + balance);
}
/**
* Get the current balance.
*
* @return the current balance
*/
public int getBalance() {
return balance;
}
/**
* Set the balance to a new value and update the label.
*
* @param newBalance the new balance
*/
public void setBalance(int newBalance) {
balance = newBalance;
display.setText("" + newBalance);
}
}
| SienaCSISAdvancedProgramming/ATMConcurrency | Danger1/Account.java | 277 | /**
* Get the current balance.
*
* @return the current balance
*/ | block_comment | en | false | 268 | 21 | 277 | 19 | 305 | 24 | 277 | 19 | 326 | 24 | false | false | false | false | false | true |
211080_2 | import java.util.*;
/**
* Main World Class
*
* @author Ezekiel Elin
* @author Unknown Author
* @version 11/02/2016
*/
public class World {
private List<List<Cell>> board;
private int lightEnergy;
private int steps;
public World(int width, int height, int light) {
lightEnergy = light;
steps = 0;
board = new ArrayList<List<Cell>>();
for(int i = 0; i < width; i++) {
board.add(new ArrayList<Cell>());
for(int j = 0; j < height; j++) {
board.get(i).add(new Cell(this));
board.get(i).get(j).setLocation(new Point(i, j));
}
}
}
public int getLightEnergy() {
return lightEnergy;
}
public Cell get(int x, int y) {
return this.board.get(x).get(y);
}
public int getWidth() {
return this.board.size();
}
public int getHeight() {
return this.board.get(0).size();
}
public int getSteps() {
return this.steps;
}
/**
* Goes through each cell and runs the activities for each species
* Also adds a new element to the birth and death lists so they can be tracker for the turn
*/
public void turn() {
int curSteps = this.getSteps();
if(Species.getDeaths().size() == curSteps) {
Species.getDeaths().add(new ArrayList<Integer>());
for(int i = 0; i < Species.getSpecies().size(); i++) {
Species.getDeaths().get(curSteps).add(0);
}
}
if(Species.getBirths().size() == curSteps) {
Species.getBirths().add(new ArrayList<Integer>());
for(int i = 0; i < Species.getSpecies().size(); i++) {
Species.getBirths().get(curSteps).add(0);
}
}
for(int i = 0; i < board.size(); i++) {
List<Cell> column = board.get(i);
for(int j = 0; j < column.size(); j++) {
Cell cell = column.get(j);
if(cell.getAnimal() != null) {
cell.getAnimal().activity();
}
if(cell.getPlant() != null) {
cell.getPlant().activity();
}
}
}
steps++;
}
/**
* Prints the board in an easy to view way
*/
public void print() {
for(int y = 0; y < this.getHeight(); y++) {
System.out.print("|");
for(int x = 0; x < this.getWidth(); x++) {
Cell cell = this.get(x, y);
String message = "";
if (cell.isMountain()) {
message += "MNT";
}
if (cell.flag) {
message += "!!!";
}
if(cell.getAnimal() != null) {
message += cell.getAnimal().getRepresentation();
}
if(message.length() > 0 && cell.getPlant() != null) {
message += "/";
}
if(cell.getPlant() != null) {
message += cell.getPlant().getRepresentation();
}
System.out.print(message + "\t|");
}
System.out.println();
System.out.println("-----------------------------------------------------------------------------------------------------");
}
}
/**
* Takes a species and generates random coordinates until it finds an empty cell for it
* @param Species s - the species that should be randomly added to the world
*/
public void randomAddToWorld(Species s) {
Random generator = new Random(Simulation.SEED);
boolean found = false;
int count = 0; //Prevents infinite loop in case more species are trying to be added than there are spaces for them
while(!found && count < 10000) {
count++;
int x = generator.nextInt(this.board.size());
int y = generator.nextInt(this.board.get(0).size());
Cell cell = this.board.get(x).get(y);
/* cannot use mountain spaces */
if (cell.isMountain()) {
continue;
}
if(s instanceof Animal) {
if(cell.getAnimal() == null) {
cell.setAnimal((Animal)s);
s.setCell(cell);
found = true;
}
} else if(s instanceof Plant) {
if(cell.getPlant() == null) {
cell.setPlant((Plant)s);
s.setCell(cell);
found = true;
}
}
}
}
}
| ezfe/Animal-Park-2 | World.java | 1,120 | /**
* Prints the board in an easy to view way
*/ | block_comment | en | false | 1,000 | 15 | 1,120 | 14 | 1,275 | 17 | 1,120 | 14 | 1,373 | 19 | false | false | false | false | false | true |
214058_18 | import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
public class ATSGui extends JFrame implements ActionListener {
private JComboBox<String> menuOptions;
private JPanel cardPanel;
private CardLayout cardLayout;
private JTextArea outputArea;
// Events attributes
private JTextField ageRestrictionField;
private JTextField startDateField;
private JTextField startTimeField;
private JTextField durationField;
private JTextField typeIdField;
private JButton addEventButton;
// RegisteredUsers attributes
private JTextField emailField;
private JTextField dobField;
private JTextField usernameField;
private JTextField passwordField;
private JTextField creditCardField;
private JTextField expiryDateField;
private JTextField locationField;
private JTextField preferredTypeField;
private JTextField preferredGenreField;
private JButton registerUserButton;
// Tickets attributes
private JTextField priceField;
private JTextField designatedEntranceField;
private JTextField userIDField;
private JTextField purchaseDateField;
private JTextField EIDField;
private JButton addTicketButton;
// Sponsor attributes
private JTextField sponsorNameField;
private JTextField sponsorTypeField;
private JButton addSponsorButton;
public ATSGui() {
setTitle("Arena Ticketing System (ATS)");
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setSize(400, 300);
JPanel panel = new JPanel();
panel.setLayout(new BorderLayout());
// Menu options
String[] options = {"Add a new event", "Register a new user", "Purchase a ticket",
"Add a new sponsor to an event", "Exit"};
menuOptions = new JComboBox<>(options);
menuOptions.addActionListener(this);
panel.add(menuOptions, BorderLayout.NORTH);
// Output area
outputArea = new JTextArea();
outputArea.setEditable(false);
JScrollPane scrollPane = new JScrollPane(outputArea);
panel.add(scrollPane, BorderLayout.CENTER);
// CardLayout for different card panels
cardLayout = new CardLayout();
cardPanel = new JPanel(cardLayout);
panel.add(cardPanel, BorderLayout.SOUTH);
// Components for adding a new event
JPanel addEventPanel = new JPanel(new GridLayout(6, 2));
addEventPanel.add(new JLabel("Age Restriction:"));
ageRestrictionField = new JTextField();
addEventPanel.add(ageRestrictionField);
addEventPanel.add(new JLabel("Start Date (YYYY-MM-DD):"));
startDateField = new JTextField();
addEventPanel.add(startDateField);
addEventPanel.add(new JLabel("Start Time (HH:mm:ss):"));
startTimeField = new JTextField();
addEventPanel.add(startTimeField);
addEventPanel.add(new JLabel("Duration (minutes):"));
durationField = new JTextField();
addEventPanel.add(durationField);
addEventPanel.add(new JLabel("Type ID (Layout):"));
typeIdField = new JTextField();
addEventPanel.add(typeIdField);
addEventButton = new JButton("Submit");
addEventButton.addActionListener(this);
addEventPanel.add(addEventButton);
cardPanel.add(addEventPanel, "AddEvent");
// Components for registering a new user
JPanel registerUserPanel = new JPanel(new GridLayout(10, 2));
registerUserPanel.add(new JLabel("Email Address:"));
emailField = new JTextField();
registerUserPanel.add(emailField);
registerUserPanel.add(new JLabel("Date of Birth (YYYY-MM-DD):"));
dobField = new JTextField();
registerUserPanel.add(dobField);
registerUserPanel.add(new JLabel("Username:"));
usernameField = new JTextField();
registerUserPanel.add(usernameField);
registerUserPanel.add(new JLabel("Password:"));
passwordField = new JTextField();
registerUserPanel.add(passwordField);
registerUserPanel.add(new JLabel("Credit Card Number:"));
creditCardField = new JTextField();
registerUserPanel.add(creditCardField);
registerUserPanel.add(new JLabel("Expiry Date (YYYY-MM-DD):"));
expiryDateField = new JTextField();
registerUserPanel.add(expiryDateField);
registerUserPanel.add(new JLabel("Location:"));
locationField = new JTextField();
registerUserPanel.add(locationField);
registerUserPanel.add(new JLabel("Preferred Type:"));
preferredTypeField = new JTextField();
registerUserPanel.add(preferredTypeField);
registerUserPanel.add(new JLabel("Preferred Genre:"));
preferredGenreField = new JTextField();
registerUserPanel.add(preferredGenreField);
registerUserButton = new JButton("Submit");
registerUserButton.addActionListener(this);
registerUserPanel.add(registerUserButton);
cardPanel.add(registerUserPanel, "RegisterUser");
// Components for purchasing a new ticket
JPanel addTicketPanel = new JPanel(new GridLayout(6, 2));
addTicketPanel.add(new JLabel("Price:"));
priceField = new JTextField();
addTicketPanel.add(priceField);
addTicketPanel.add(new JLabel("Designated Entrance:"));
designatedEntranceField = new JTextField();
addTicketPanel.add(designatedEntranceField);
addTicketPanel.add(new JLabel("User ID:"));
userIDField = new JTextField();
addTicketPanel.add(userIDField);
addTicketPanel.add(new JLabel("Purchase Date:"));
purchaseDateField = new JTextField();
addTicketPanel.add(purchaseDateField);
addTicketPanel.add(new JLabel("EID:"));
EIDField = new JTextField();
addTicketPanel.add(EIDField);
addTicketButton = new JButton("Submit");
addTicketButton.addActionListener(this);
addTicketPanel.add(addTicketButton);
cardPanel.add(addTicketPanel, "AddTicket");
// Components for adding a new sponsor
JPanel addSponsorPanel = new JPanel(new GridLayout(3, 2));
addSponsorPanel.add(new JLabel("Sponsor Name:"));
sponsorNameField = new JTextField();
addSponsorPanel.add(sponsorNameField);
addSponsorPanel.add(new JLabel("Sponsor Type:"));
sponsorTypeField = new JTextField();
addSponsorPanel.add(sponsorTypeField);
addSponsorButton = new JButton("Submit");
addSponsorButton.addActionListener(this);
addSponsorPanel.add(addSponsorButton);
cardPanel.add(addSponsorPanel, "AddSponsor");
// Add panel to frame
add(panel);
}
public void actionPerformed(ActionEvent e) {
String option = (String) menuOptions.getSelectedItem();
String output = "";
switch (option) {
case "Add a new event":
output = "Option 1: Add a new event - Please fill in the details below:";
cardLayout.show(cardPanel, "AddEvent");
break;
case "Register a new user":
output = "Option 2: Register a new user - Please fill in the details below:";
cardLayout.show(cardPanel, "RegisterUser");
break;
case "Purchase a ticket":
output = "Option 3: Purchase a ticket - Please fill in the details below:";
cardLayout.show(cardPanel, "AddTicket");
break;
case "Add a new sponsor to an event":
output = "Option 4: Add a new sponsor to an event - Please fill in the details below:";
cardLayout.show(cardPanel, "AddSponsor");
break;
case "Exit":
System.exit(0);
break;
case "Submit": // Submit button actions for Add Event and Register User
if (e.getSource() == addEventButton) {
// Submit action for Add Event
output = "Adding a new event...\n";
// Get values from fields and perform actions accordingly
String ageRestriction = ageRestrictionField.getText();
String startDate = startDateField.getText();
String startTime = startTimeField.getText();
String duration = durationField.getText();
String typeId = typeIdField.getText();
// Perform actions, e.g., call a method to add event to database
} else if (e.getSource() == registerUserButton) {
// Submit action for Register User
output = "Registering a new user...\n";
// Get values from fields and perform actions accordingly
String emailAddress = emailField.getText();
String dob = dobField.getText();
String username = usernameField.getText();
String password = passwordField.getText();
String creditCard = creditCardField.getText();
String expiryDate = expiryDateField.getText();
String location = locationField.getText();
String preferredType = preferredTypeField.getText();
String preferredGenre = preferredGenreField.getText();
// Perform actions, e.g., call a method to register user to database
}
break;
}
outputArea.setText(output + "\n");
}
public static void main(String[] args) {
SwingUtilities.invokeLater(() -> {
ATSGui gui = new ATSGui();
gui.setVisible(true);
});
}
}
| rambodazimi/Arena-Ticketing-System | src/ATSGui.java | 2,070 | // Perform actions, e.g., call a method to register user to database | line_comment | en | false | 1,873 | 15 | 2,070 | 16 | 2,197 | 16 | 2,070 | 16 | 2,576 | 16 | false | false | false | false | false | true |
214667_9 | import java.util.Observable;
import java.util.Observer;
/**
*
*/
/**
* @author chris
*
*/
public abstract class ALevel extends Observable implements I_Levels,
I_Enemies {
private BadGuyFactory _badgroupone;
private BadGuyFactory _badgrouptwo;
private BadGuyFactory _badgroupthree;
private BattleArena _battleArena;
private java.util.List<BadGuyFactory> _badGuysOnLevel;
private GoodGuyFactory _goodGuys;
private String _levelName;
/**
*
* @param levelName
* @param goodGuys
*/
public ALevel(String levelName, GoodGuyFactory goodGuys)
{
_levelName = levelName;
_goodGuys = goodGuys;
_badGuysOnLevel = new java.util.ArrayList<BadGuyFactory>();
_badgroupone = new BadGuyFactory(this);
_badgrouptwo = new BadGuyFactory(this);
_badgroupthree = new BadGuyFactory(this);
for(AGoodGuy gg : goodGuys.get_goodGuys())
{
accept(gg);
gg.set_level(this);
}
play_level(goodGuys);
}
/*
* (non-Javadoc)
* @see I_Enemies#addEnemies(BadGuyFactory, int, int)
*/
@Override
public void addEnemies(BadGuyFactory badGuys, int originX, int originY) {
// adds mobs at specific points on the level
_badGuysOnLevel.add(badGuys);
for(ABadGuy bg : badGuys.get_badGuys())
{
addObserver((Observer) bg);
bg.set_locx(originX);
bg.set_locy(originY);
}
}
/*
* (non-Javadoc)
* @see I_Levels#accept(AGoodGuy)
*/
@Override
public void accept(AGoodGuy goodGuy)
{
System.out.println(goodGuy.get_name() + " has entered " +
get_levelName() + " at location (0, 0)\n");
}
/**
*
* @return
*/
public GoodGuyFactory get_goodGuys() {
return _goodGuys;
}
/**
*
* @param _goodGuys
*/
public void set_goodGuys(GoodGuyFactory _goodGuys) {
this._goodGuys = _goodGuys;
}
/**
*
* @return
*/
public BadGuyFactory get_badgroupone() {
return _badgroupone;
}
/**
*
* @param _badgroupone
*/
public void set_badgroupone(BadGuyFactory _badgroupone) {
this._badgroupone = _badgroupone;
}
/**
*
* @return
*/
public BadGuyFactory get_badgrouptwo() {
return _badgrouptwo;
}
/**
*
* @param _badgrouptwo
*/
public void set_badgrouptwo(BadGuyFactory _badgrouptwo) {
this._badgrouptwo = _badgrouptwo;
}
/**
*
* @return
*/
public BadGuyFactory get_badgroupthree() {
return _badgroupthree;
}
/**
*
* @param _badgroupthree
*/
public void set_badgroupthree(BadGuyFactory _badgroupthree) {
this._badgroupthree = _badgroupthree;
}
/**
*
* @return
*/
public java.util.List<BadGuyFactory> get_badGuysOnLevel() {
return _badGuysOnLevel;
}
/**
*
* @param _badGuysOnLevel
*/
public void set_badGuysOnLevel(java.util.List<BadGuyFactory> _badGuysOnLevel) {
this._badGuysOnLevel = _badGuysOnLevel;
}
/*
* (non-Javadoc)
* @see I_Levels#move(GoodGuyFactory, int, int)
*/
@Override
public void move(GoodGuyFactory goodGuys, int dirx, int diry)
{
//notifies Observers local to level of GoodGuy presence,
//if GoodGuy comes to BadGuy location new BattleArena made
goodGuys.set_grouplocx(goodGuys.get_grouplocx() + dirx);
goodGuys.set_grouplocy(goodGuys.get_grouplocy() + diry);
for(BadGuyFactory badGuys : get_badGuysOnLevel())
{
if(goodGuys.get_grouplocx() == badGuys.get_grouplocx()
&& goodGuys.get_grouplocy() == badGuys.get_grouplocy())
{
for(ABadGuy abg : badGuys.get_badGuys())
{
abg.update();
}
set_battleArena(new BattleArena(goodGuys, badGuys));
get_battleArena().fight();
}
}
}
/**
*
* @return
*/
public BattleArena get_battleArena() {
return _battleArena;
}
/**
*
* @param _battleArena
*/
public void set_battleArena(BattleArena _battleArena) {
this._battleArena = _battleArena;
}
/*
* (non-Javadoc)
* @see I_Levels#play_level(GoodGuyFactory)
*/
@Override
public void play_level(GoodGuyFactory goodGuys) {
// group can move x and y the amount of their combined attack speed
// must wait num moves to attack, i.e combined attack speed 10, x = 3 y = 4
// group waits seven seconds to move again, has to clear entire level of mobs to
// advance, treasure for each group member at end of level based on chartype
// if move to enemy location, group must wait enemy group combined attack speed,
// less combined move, i.e combined move = 7 enemy attack speed = 10, must wait 3 seconds,
// pseudo enemy ambush, each enemy with attack speed <= numMoves - combinedEnemyAttackSpeed
// can attack random member of group, then turn based until goodguys or badguys win
for(AGoodGuy gg : goodGuys.get_goodGuys())
{
System.out.println(gg.get_name() + " has conquered " + get_levelName() + "\n");
}
}
/*
* (non-Javadoc)
* @see I_Levels#treasureDrop(AHeavyWarrior)
*/
@Override
public void treasureDrop(AHeavyWarrior hWarrior) {
}
/*
* (non-Javadoc)
* @see I_Levels#treasureDrop(AShadowWarrior)
*/
@Override
public void treasureDrop(AShadowWarrior sWarrior) {
}
/*
* (non-Javadoc)
* @see I_Levels#treasureDrop(AMage)
*/
@Override
public void treasureDrop(AMage mage) {
}
/*
* (non-Javadoc)
* @see I_Levels#treasureDrop(AWizard)
*/
@Override
public void treasureDrop(AWizard wizard) {
}
/**
*
* @return
*/
public String get_levelName() {
return _levelName;
}
/**
*
* @param _levelName
*/
public void set_levelName(String _levelName) {
this._levelName = _levelName;
}
}
| NTonani/DreamStreet | src/ALevel.java | 1,978 | /**
*
* @param _badgroupone
*/ | block_comment | en | false | 1,714 | 15 | 1,978 | 13 | 1,957 | 17 | 1,978 | 13 | 2,286 | 17 | false | false | false | false | false | true |
215230_3 | /*
* This file is part of TiPi (a Toolkit for Inverse Problems and Imaging)
* developed by the MitiV project.
*
* Copyright (c) 2014 the MiTiV project, http://mitiv.univ-lyon1.fr/
*
* 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.
*/
package mitiv.array;
import mitiv.base.Shaped;
import mitiv.base.Typed;
import mitiv.linalg.shaped.ShapedVector;
/**
* A ShapedArray is a shaped object with a primitive type.
*
* <p> A ShapedArray stores rectangular multi-dimensional arrays of elements of
* the same data type. Compared to a {@link ShapedVector}, the elements of a
* ShapedArray reside in conventional memory and may be stored in arbitrary
* order and in a non-contiguous way. </p>
*
* @author Éric Thiébaut.
*/
public interface ShapedArray extends Shaped, Typed {
/**
* Check whether a shaped array is stored as a flat Java array.
*
* @return True if the results of {@code this.flatten(false)} and
* {@code this.flatten()} are guaranteed to yield a direct
* reference (not a copy) to the contents of the array.
*/
public abstract boolean isFlat();
/**
* Flatten the elements of a shaped array in a simple generic array.
*
* <p> The contents of a shaped array can be stored in many different
* forms. This storage details are hidden to the end-user in favor of a
* unified and comprehensive interface. This method returns the contents
* of a shaped array as a simple <i>flat</i> array, <i>i.e.</i> successive
* elements are contiguous and the first element has {@code 0}-offset. If
* the shaped array is multi-dimensional, the storage of the returned
* result is column-major order. </p>
*
* @param forceCopy
* Set true to force a copy of the internal data even though it can
* already be in a flat form. Otherwise and if the shaped array is
* in flat form, see {@link #isFlat()}, the data storage of the
* array is directly returned (not a copy).
*
* @return An object which can be recast into a {@code type[]}
* array with {@code type} the generic Java type corresponding
* to the type of the elements of the shaped array: {@code byte},
* {@code short}, {@code int}, {@code long}, {@code float} or
* {@code double}.
*/
public abstract Object flatten(boolean forceCopy);
/**
* Flatten the elements of a shaped array in a simple generic array.
*
* <p> This method behaves as if argument {@code forceCopy} was set to
* false in {@link #flatten(boolean)}. Depending on the storage layout,
* the returned array may or may not share the same storage as the
* ${className} array. Call {@code flatten(true)} to make sure that the
* two storage areas are independent. </p>
*
* @return An object (see {@link #flatten(boolean)} for more explanations).
*/
public abstract Object flatten();
/**
* Get a direct access to the elements of a shaped array.
*
* <p> Calling this method should be equivalent to: </p>
*
* <pre>
* (this.isFlat() ? this.flatten() : null)
* </pre>
*
* @return An object which can be {@code null} if direct access is not
* possible (or allowed). If non-{@code null}, the returned value
* can be recast into a {@code type[]} array with {@code type} the
* generic Java type corresponding to the type of the elements of
* the shaped array: {@code byte}, {@code short}, {@code int},
* {@code long}, {@code float} or {@code double}.
*
* @see #flatten()
* @see #isFlat()
*/
public abstract Object getData();
/**
* Convert array elements to type {@code byte}.
*
* @return A {@link ByteArray} object which may be the object itself
* if it is already a ByteArray.
*/
public abstract ByteArray toByte();
/**
* Convert array elements to type {@code short}.
*
* @return A {@link ShortArray} object which may be the object itself
* if it is already a ShortArray.
*/
public abstract ShortArray toShort();
/**
* Convert array elements to type {@code int}.
*
* @return A {@link IntArray} object which may be the object itself
* if it is already an IntArray.
*/
public abstract IntArray toInt();
/**
* Convert array elements to type {@code long}.
*
* @return A {@link LongArray} object which may be the object itself
* if it is already a LongArray.
*/
public abstract LongArray toLong();
/**
* Convert array elements to type {@code float}.
*
* @return A {@link FloatArray} object which may be the object itself
* if it is already a FloatArray.
*/
public abstract FloatArray toFloat();
/**
* Convert array elements to type {@code double}.
*
* @return A {@link DoubleArray} object which may be the object itself
* if it is already a DoubleArray.
*/
public abstract DoubleArray toDouble();
/**
* Create a new array with same element type and shape.
*
* <p> This method yields a new shaped array which has the same element
* type and shape as the object but whose contents is not initialized.
* </p>
*
* @return A new shaped array.
*/
public abstract ShapedArray create();
/**
* Create a copy of the array with the dimension initpos at the position finalpos
* @param initpos
* @param finalpos
* @return the new array
*/
public abstract ShapedArray movedims( int initpos, int finalpos);
/**
* Copy the contents of the object as a new array.
*
* <p> This method yields a new shaped array which has the same shape, type
* and values as the object but whose contents is independent from that of
* the object. If the object is a <i>view</i>, then this method yields a
* compact array in a <i>flat</i> form. </p>
*
* @return A flat shaped array.
*/
public abstract ShapedArray copy();
/**
* Assign the values of the object from those of another shaped array.
*
* <p> The shape of the source and of the destination must match, type
* conversion (to the type of the elements of the destination) is
* automatically done if needed. </p>
*
* @param src
* The source object.
*/
public abstract void assign(ShapedArray src);
/**
* Assign the values of the object from those of a shaped vector.
*
* <p> This operation may be slow. </p>
*
* @param src
* The source object.
*
* @see #assign(ShapedArray) for a discussion of the rules that apply.
*/
public abstract void assign(ShapedVector src);
/**
* Get a view of the object as a 1D array.
*
* <p> The result is a 1D <i>view</i> of its parents, this means that they
* share the same contents. </p>
*
* @return A 1D view of the object.
*/
public abstract Array1D as1D();
/**
* Perform some sanity tests.
*
* <p> For performance reasons, not all errors are checked by TiPi code.
* This means that arguments may be simply trusted for being correct. This
* method can be used for debugging and tracking incorrect
* parameters/arguments. It throws runtime exception(s) if some errors or
* inconsistencies are discovered. </p>
*/
public abstract void checkSanity();
}
| emmt/TiPi | src/mitiv/array/ShapedArray.java | 2,112 | /**
* Flatten the elements of a shaped array in a simple generic array.
*
* <p> The contents of a shaped array can be stored in many different
* forms. This storage details are hidden to the end-user in favor of a
* unified and comprehensive interface. This method returns the contents
* of a shaped array as a simple <i>flat</i> array, <i>i.e.</i> successive
* elements are contiguous and the first element has {@code 0}-offset. If
* the shaped array is multi-dimensional, the storage of the returned
* result is column-major order. </p>
*
* @param forceCopy
* Set true to force a copy of the internal data even though it can
* already be in a flat form. Otherwise and if the shaped array is
* in flat form, see {@link #isFlat()}, the data storage of the
* array is directly returned (not a copy).
*
* @return An object which can be recast into a {@code type[]}
* array with {@code type} the generic Java type corresponding
* to the type of the elements of the shaped array: {@code byte},
* {@code short}, {@code int}, {@code long}, {@code float} or
* {@code double}.
*/ | block_comment | en | false | 2,065 | 304 | 2,112 | 304 | 2,225 | 312 | 2,112 | 304 | 2,452 | 333 | true | true | true | true | true | false |
215805_1 | /**
* Quad.java
*
* Represents quadrants for the Barnes-Hut algorithm.
*
* Dependencies: StdDraw.java
*
* @author chindesaurus
* @version 1.00
*/
public class Quad {
private double xmid;
private double ymid;
private double length;
/**
* Constructor: creates a new Quad with the given
* parameters (assume it is square).
*
* @param xmid x-coordinate of center of quadrant
* @param ymid y-coordinate of center of quadrant
* @param length the side length of the quadrant
*/
public Quad(double xmid, double ymid, double length) {
this.xmid = xmid;
this.ymid = ymid;
this.length = length;
}
/**
* Returns the length of one side of the square quadrant.
*
* @return side length of the quadrant
*/
public double length() {
return length;
}
/**
* Does this quadrant contain (x, y)?
*
* @param x x-coordinate of point to test
* @param y y-coordinate of point to test
* @return true if quadrant contains (x, y), else false
*/
public boolean contains(double x, double y) {
double halfLen = this.length / 2.0;
return (x <= this.xmid + halfLen &&
x >= this.xmid - halfLen &&
y <= this.ymid + halfLen &&
y >= this.ymid - halfLen);
}
/**
* Returns a new object that represents the northwest quadrant.
*
* @return the northwest quadrant of this Quad
*/
public Quad NW() {
double x = this.xmid - this.length / 4.0;
double y = this.ymid + this.length / 4.0;
double len = this.length / 2.0;
Quad NW = new Quad(x, y, len);
return NW;
}
/**
* Returns a new object that represents the northeast quadrant.
*
* @return the northeast quadrant of this Quad
*/
public Quad NE() {
double x = this.xmid + this.length / 4.0;
double y = this.ymid + this.length / 4.0;
double len = this.length / 2.0;
Quad NE = new Quad(x, y, len);
return NE;
}
/**
* Returns a new object that represents the southwest quadrant.
*
* @return the southwest quadrant of this Quad
*/
public Quad SW() {
double x = this.xmid - this.length / 4.0;
double y = this.ymid - this.length / 4.0;
double len = this.length / 2.0;
Quad SW = new Quad(x, y, len);
return SW;
}
/**
* Returns a new object that represents the southeast quadrant.
*
* @return the southeast quadrant of this Quad
*/
public Quad SE() {
double x = this.xmid + this.length / 4.0;
double y = this.ymid - this.length / 4.0;
double len = this.length / 2.0;
Quad SE = new Quad(x, y, len);
return SE;
}
/**
* Draws an unfilled rectangle that represents the quadrant.
*/
public void draw() {
StdDraw.rectangle(xmid, ymid, length / 2.0, length / 2.0);
}
/**
* Returns a string representation of this quadrant for debugging.
*
* @return string representation of this quadrant
*/
public String toString() {
String ret = "\n";
for (int row = 0; row < this.length; row++) {
for (int col = 0; col < this.length; col++) {
if (row == 0 || col == 0 || row == this.length - 1 || col == this.length - 1)
ret += "*";
else
ret += " ";
}
ret += "\n";
}
return ret;
}
}
| chindesaurus/BarnesHut-N-Body | Quad.java | 989 | /**
* Constructor: creates a new Quad with the given
* parameters (assume it is square).
*
* @param xmid x-coordinate of center of quadrant
* @param ymid y-coordinate of center of quadrant
* @param length the side length of the quadrant
*/ | block_comment | en | false | 922 | 66 | 989 | 67 | 1,067 | 72 | 989 | 67 | 1,141 | 78 | false | false | false | false | false | true |
216310_1 | /**
* This is in an interface class that has the method kmPerHour, numOfWheels, numOfSeats, renewLicensePlate
*
* @author Muhammad Hameez Iqbal, Shardul Bhardwaj, Brandon Nguyen
* @since jdk 14.02
* @version ide 4.16
*
*/
public interface roadVehicles {
/**
* This method is to print the vehicles max speed
*/
public String kmPerHour();
/**
* This method is to print the vehicles number of wheels
*/
public String numOfWheels();
/**
* This method is to print the vehicles number of seats
*/
public String numOfSeats();
/**
*This method is to print a statement saying license plate has been renewed
*/
public String renewLicensePlate();
}
| Hameez10/JavaClasses-ObjectsAssignment | roadVehicles.java | 199 | /**
* This method is to print the vehicles max speed
*/ | block_comment | en | false | 174 | 15 | 199 | 14 | 189 | 16 | 199 | 14 | 220 | 16 | false | false | false | false | false | true |