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 |
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
171648_5 | package me.jay;
import me.jay.interfaces.Logger;
import java.util.GregorianCalendar;
/**
* @Author Jay
*
* @see me.jay.interfaces.Logger
*
* Very simple for now, may upgrade.
*
* TODO: Check if withName is not used, if not then set to normal name: logger.
* TODO: Make more options for the user.
*
* Fucking Deprication
*/
public class LoggerFactory implements Logger {
/**
* Raw Variables
*/
private String name;
private boolean withParenthesis;
/**
* Time As Suggested by Stone_Warrior <3
*/
private GregorianCalendar cal = new GregorianCalendar();
/**
* <p>
* Determine's if the logger should have a name
* </p>
* @param name -> Name
* @return -> This class
*/
public LoggerFactory withName(String name) {
if(name == null || name.equals("")) {
name = "Logger";
}
this.name = name.toUpperCase();
return this;
}
/**
* <p>
* Determine's if the logger should use parenthesis
* </p>
* @param withParenthesis -> Parenthesis (bool)
* @return -> This class
*/
public LoggerFactory withParenthesis(boolean withParenthesis) {
this.withParenthesis = withParenthesis;
return this;
}
@Override
public void print(Object msg) {
System.out.println(msg);
}
@Override
public void info(Object msg) {
String prefix = withParenthesis ? "(" + name + ")(INFO)(" + cal.getTime().getHours() + ":" + cal.getTime().getMinutes() + ":" + cal.getTime().getSeconds() + ")" : "[" + name + "][INFO][" + + cal.getTime().getHours() + ":" + cal.getTime().getMinutes() + ":" + cal.getTime().getSeconds() + "]";
print(prefix + " " + msg);
}
@Override
public void log(Object msg, Level level) {
String prefix = withParenthesis ? "(" + name + ")(" + level.getName() + ")(" + + cal.getTime().getHours() + ":" + cal.getTime().getMinutes() + ":" + cal.getTime().getSeconds() + ")" : "[" + name + "][" + level.getName() + "][" + + cal.getTime().getHours() + ":" + cal.getTime().getMinutes() + ":" + cal.getTime().getSeconds() + "]";
switch(level) {
case FATAL:
print(prefix + " " + msg);
break;
case ERROR:
print(prefix + " " + msg);
break;
case DEBUG:
print(prefix + " " + msg);
break;
case INFO:
print(prefix + " " + msg);
break;
}
}
/**
* <p>
* Create's the new LoggerFactory instance using the specified arguments.
* (Made static, thanks Stone <3)
* </p>
* @return
*/
public static LoggerFactory create() {
return new LoggerFactory().withName(this.name).withParenthesis(this.withParenthesis);
}
}
| SyntheticJay/LoggingFramework | src/me/jay/LoggerFactory.java | 727 | /**
* <p>
* Create's the new LoggerFactory instance using the specified arguments.
* (Made static, thanks Stone <3)
* </p>
* @return
*/ | block_comment | en | false | 673 | 44 | 727 | 44 | 778 | 50 | 727 | 44 | 891 | 52 | false | false | false | false | false | true |
171860_28 | // This file is part of OpenTSDB.
// Copyright (C) 2010-2012 The OpenTSDB Authors.
//
// This program is free software: you can redistribute it and/or modify it
// under the terms of the GNU Lesser General Public License as published by
// the Free Software Foundation, either version 2.1 of the License, or (at your
// option) any later version. This program 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 Lesser
// General Public License for more details. You should have received a copy
// of the GNU Lesser General Public License along with this program. If not,
// see <http://www.gnu.org/licenses/>.
package net.opentsdb.tools;
import java.io.IOException;
import java.lang.reflect.Constructor;
import java.net.InetAddress;
import java.net.InetSocketAddress;
import java.util.concurrent.Executor;
import java.util.concurrent.Executors;
import java.util.HashMap;
import java.util.Map;
import org.jboss.netty.bootstrap.ServerBootstrap;
import org.jboss.netty.channel.socket.ServerSocketChannelFactory;
import org.jboss.netty.channel.socket.nio.NioServerBossPool;
import org.jboss.netty.channel.socket.nio.NioServerSocketChannelFactory;
import org.jboss.netty.channel.socket.nio.NioWorkerPool;
import org.jboss.netty.channel.socket.oio.OioServerSocketChannelFactory;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import net.opentsdb.tools.BuildData;
import net.opentsdb.core.TSDB;
import net.opentsdb.core.Const;
import net.opentsdb.tsd.PipelineFactory;
import net.opentsdb.tsd.RpcManager;
import net.opentsdb.utils.Config;
import net.opentsdb.utils.FileSystem;
import net.opentsdb.utils.Pair;
import net.opentsdb.utils.PluginLoader;
import net.opentsdb.utils.Threads;
/**
* Main class of the TSD, the Time Series Daemon.
*/
final class TSDMain {
/** Prints usage and exits with the given retval. */
static void usage(final ArgP argp, final String errmsg, final int retval) {
System.err.println(errmsg);
System.err.println("Usage: tsd --port=PORT"
+ " --staticroot=PATH --cachedir=PATH\n"
+ "Starts the TSD, the Time Series Daemon");
if (argp != null) {
System.err.print(argp.usage());
}
System.exit(retval);
}
/** A map of configured filters for use in querying */
private static Map<String, Pair<Class<?>, Constructor<? extends StartupPlugin>>>
startupPlugin_filter_map = new HashMap<String,
Pair<Class<?>, Constructor<? extends StartupPlugin>>>();
private static final short DEFAULT_FLUSH_INTERVAL = 1000;
private static TSDB tsdb = null;
public static void main(String[] args) throws IOException {
Logger log = LoggerFactory.getLogger(TSDMain.class);
log.info("Starting.");
log.info(BuildData.revisionString());
log.info(BuildData.buildString());
try {
System.in.close(); // Release a FD we don't need.
} catch (Exception e) {
log.warn("Failed to close stdin", e);
}
final ArgP argp = new ArgP();
CliOptions.addCommon(argp);
argp.addOption("--port", "NUM", "TCP port to listen on.");
argp.addOption("--bind", "ADDR", "Address to bind to (default: 0.0.0.0).");
argp.addOption("--staticroot", "PATH",
"Web root from which to serve static files (/s URLs).");
argp.addOption("--cachedir", "PATH",
"Directory under which to cache result of requests.");
argp.addOption("--worker-threads", "NUM",
"Number for async io workers (default: cpu * 2).");
argp.addOption("--async-io", "true|false",
"Use async NIO (default true) or traditional blocking io");
argp.addOption("--read-only", "true|false",
"Set tsd.mode to ro (default false)");
argp.addOption("--disable-ui", "true|false",
"Set tsd.core.enable_ui to false (default true)");
argp.addOption("--disable-api", "true|false",
"Set tsd.core.enable_api to false (default true)");
argp.addOption("--backlog", "NUM",
"Size of connection attempt queue (default: 3072 or kernel"
+ " somaxconn.");
argp.addOption("--max-connections", "NUM",
"Maximum number of connections to accept");
argp.addOption("--flush-interval", "MSEC",
"Maximum time for which a new data point can be buffered"
+ " (default: " + DEFAULT_FLUSH_INTERVAL + ").");
argp.addOption("--statswport", "Force all stats to include the port");
CliOptions.addAutoMetricFlag(argp);
args = CliOptions.parse(argp, args);
args = null; // free().
// get a config object
Config config = CliOptions.getConfig(argp);
// check for the required parameters
try {
if (config.getString("tsd.http.staticroot").isEmpty())
usage(argp, "Missing static root directory", 1);
} catch(NullPointerException npe) {
usage(argp, "Missing static root directory", 1);
}
try {
if (config.getString("tsd.http.cachedir").isEmpty())
usage(argp, "Missing cache directory", 1);
} catch(NullPointerException npe) {
usage(argp, "Missing cache directory", 1);
}
try {
if (!config.hasProperty("tsd.network.port"))
usage(argp, "Missing network port", 1);
config.getInt("tsd.network.port");
} catch (NumberFormatException nfe) {
usage(argp, "Invalid network port setting", 1);
}
// validate the cache and staticroot directories
try {
FileSystem.checkDirectory(config.getString("tsd.http.staticroot"),
!Const.MUST_BE_WRITEABLE, Const.DONT_CREATE);
FileSystem.checkDirectory(config.getString("tsd.http.cachedir"),
Const.MUST_BE_WRITEABLE, Const.CREATE_IF_NEEDED);
} catch (IllegalArgumentException e) {
usage(argp, e.getMessage(), 3);
}
final ServerSocketChannelFactory factory;
int connections_limit = 0;
try {
connections_limit = config.getInt("tsd.core.connections.limit");
} catch (NumberFormatException nfe) {
usage(argp, "Invalid connections limit", 1);
}
if (config.getBoolean("tsd.network.async_io")) {
int workers = Runtime.getRuntime().availableProcessors() * 2;
if (config.hasProperty("tsd.network.worker_threads")) {
try {
workers = config.getInt("tsd.network.worker_threads");
} catch (NumberFormatException nfe) {
usage(argp, "Invalid worker thread count", 1);
}
}
final Executor executor = Executors.newCachedThreadPool();
final NioServerBossPool boss_pool =
new NioServerBossPool(executor, 1, new Threads.BossThreadNamer());
final NioWorkerPool worker_pool = new NioWorkerPool(executor,
workers, new Threads.WorkerThreadNamer());
factory = new NioServerSocketChannelFactory(boss_pool, worker_pool);
} else {
factory = new OioServerSocketChannelFactory(
Executors.newCachedThreadPool(), Executors.newCachedThreadPool(),
new Threads.PrependThreadNamer());
}
StartupPlugin startup = null;
try {
startup = loadStartupPlugins(config);
} catch (IllegalArgumentException e) {
usage(argp, e.getMessage(), 3);
} catch (Exception e) {
throw new RuntimeException("Initialization failed", e);
}
try {
tsdb = new TSDB(config);
if (startup != null) {
tsdb.setStartupPlugin(startup);
}
tsdb.initializePlugins(true);
if (config.getBoolean("tsd.storage.hbase.prefetch_meta")) {
tsdb.preFetchHBaseMeta();
}
// Make sure we don't even start if we can't find our tables.
tsdb.checkNecessaryTablesExist().joinUninterruptibly();
registerShutdownHook();
final ServerBootstrap server = new ServerBootstrap(factory);
// This manager is capable of lazy init, but we force an init
// here to fail fast.
final RpcManager manager = RpcManager.instance(tsdb);
server.setPipelineFactory(new PipelineFactory(tsdb, manager, connections_limit));
if (config.hasProperty("tsd.network.backlog")) {
server.setOption("backlog", config.getInt("tsd.network.backlog"));
}
server.setOption("child.tcpNoDelay",
config.getBoolean("tsd.network.tcp_no_delay"));
server.setOption("child.keepAlive",
config.getBoolean("tsd.network.keep_alive"));
server.setOption("reuseAddress",
config.getBoolean("tsd.network.reuse_address"));
// null is interpreted as the wildcard address.
InetAddress bindAddress = null;
if (config.hasProperty("tsd.network.bind")) {
bindAddress = InetAddress.getByName(config.getString("tsd.network.bind"));
}
// we validated the network port config earlier
final InetSocketAddress addr = new InetSocketAddress(bindAddress,
config.getInt("tsd.network.port"));
server.bind(addr);
if (startup != null) {
startup.setReady(tsdb);
}
log.info("Ready to serve on " + addr);
} catch (Throwable e) {
factory.releaseExternalResources();
try {
if (tsdb != null)
tsdb.shutdown().joinUninterruptibly();
} catch (Exception e2) {
log.error("Failed to shutdown HBase client", e2);
}
throw new RuntimeException("Initialization failed", e);
}
// The server is now running in separate threads, we can exit main.
}
private static StartupPlugin loadStartupPlugins(Config config) {
Logger log = LoggerFactory.getLogger(TSDMain.class);
// load the startup plugin if enabled
StartupPlugin startup = null;
if (config.getBoolean("tsd.startup.enable")) {
log.debug("Startup Plugin is Enabled");
final String plugin_path = config.getString("tsd.core.plugin_path");
final String plugin_class = config.getString("tsd.startup.plugin");
log.debug("Plugin Path: " + plugin_path);
try {
TSDB.loadPluginPath(plugin_path);
} catch (Exception e) {
log.error("Error loading plugins from plugin path: " + plugin_path, e);
}
log.debug("Attempt to Load: " + plugin_class);
startup = PluginLoader.loadSpecificPlugin(plugin_class, StartupPlugin.class);
if (startup == null) {
throw new IllegalArgumentException("Unable to locate startup plugin: " +
config.getString("tsd.startup.plugin"));
}
try {
startup.initialize(config);
} catch (Exception e) {
throw new RuntimeException("Failed to initialize startup plugin", e);
}
log.info("Successfully initialized startup plugin [" +
startup.getClass().getCanonicalName() + "] version: "
+ startup.version());
} else {
startup = null;
}
return startup;
}
private static void registerShutdownHook() {
final class TSDBShutdown extends Thread {
public TSDBShutdown() {
super("TSDBShutdown");
}
public void run() {
try {
if (RpcManager.isInitialized()) {
// Check that its actually been initialized. We don't want to
// create a new instance only to shutdown!
RpcManager.instance(tsdb).shutdown().join();
}
if (tsdb != null) {
tsdb.shutdown().join();
}
} catch (Exception e) {
LoggerFactory.getLogger(TSDBShutdown.class)
.error("Uncaught exception during shutdown", e);
}
}
}
Runtime.getRuntime().addShutdownHook(new TSDBShutdown());
}
}
| OpenTSDB/opentsdb | src/tools/TSDMain.java | 2,944 | // create a new instance only to shutdown! | line_comment | en | false | 2,624 | 9 | 2,944 | 9 | 3,151 | 9 | 2,944 | 9 | 3,543 | 10 | false | false | false | false | false | true |
172270_16 | // Course.java - Chapter 14, Java 5 version.
// Copyright 2005 by Jacquie Barker - all rights reserved.
// A MODEL class.
import java.util.ArrayList;
import java.util.Collection;
public class Course {
//------------
// Attributes.
//------------
private String courseNo;
private String courseName;
private double credits;
private ArrayList<Section> offeredAsSection;
private ArrayList<Course> prerequisites;
//----------------
// Constructor(s).
//----------------
public Course(String cNo, String cName, double credits) {
setCourseNo(cNo);
setCourseName(cName);
setCredits(credits);
// Note that we're instantiating empty support Collection(s).
offeredAsSection = new ArrayList<Section>();
prerequisites = new ArrayList<Course>();
}
//------------------
// Accessor methods.
//------------------
public void setCourseNo(String cNo) {
courseNo = cNo;
}
public String getCourseNo() {
return courseNo;
}
public void setCourseName(String cName) {
courseName = cName;
}
public String getCourseName() {
return courseName;
}
public void setCredits(double c) {
credits = c;
}
public double getCredits() {
return credits;
}
//-----------------------------
// Miscellaneous other methods.
//-----------------------------
public void display() {
System.out.println("Course Information:");
System.out.println("\tCourse No.: " + getCourseNo());
System.out.println("\tCourse Name: " + getCourseName());
System.out.println("\tCredits: " + getCredits());
System.out.println("\tPrerequisite Courses:");
for (Course c : prerequisites) {
System.out.println("\t\t" + c.toString());
}
// Note use of print vs. println in next line of code.
System.out.print("\tOffered As Section(s): ");
for (Section s : offeredAsSection) {
System.out.print(s.getSectionNo() + " ");
}
// Finish with a blank line.
System.out.println();
}
public String toString() {
return getCourseNo() + ": " + getCourseName();
}
public void addPrerequisite(Course c) {
prerequisites.add(c);
}
public boolean hasPrerequisites() {
if (prerequisites.size() > 0) return true;
else return false;
}
public Collection<Course> getPrerequisites() {
return prerequisites;
}
public Section scheduleSection(char day, String time, String room,
int capacity) {
// Create a new Section (note the creative way in
// which we are assigning a section number) ...
Section s = new Section(offeredAsSection.size() + 1,
day, time, this, room, capacity);
// ... and then remember it!
addSection(s);
return s;
}
public void addSection(Section s) {
offeredAsSection.add(s);
}
}
| Apress/beg-java-objects | Ch15/SRS/Course.java | 809 | // Note use of print vs. println in next line of code. | line_comment | en | false | 665 | 14 | 809 | 14 | 816 | 14 | 809 | 14 | 973 | 14 | false | false | false | false | false | true |
172730_17 | package bank_system.users;
import bank_system.FinancialProduct.Funding;
import bank_system.*;
import bank_system.accounts.Account;
import bank_system.accounts.AssetAccount;
import bank_system.accounts.ChequingAccount;
import bank_system.accounts.DebtAccount;
import bank_system.atm_interface.UserInterface;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.FileWriter;
import java.io.IOException;
import java.util.*;
/**
Class user for bank clients, extend from Person
*/
public class User extends Person implements Observer {
/** bank_system.users.User class should be able to do these four things:
-see a summary of all of their account balances -> viewBalanceInterface()
-the most recent transaction on any account -> mostRecentTransaction
-the date of creation of one of their accounts -> BankManager.
-their net total -> getTotalBalance()
*/
private final ArrayList<Account> accountList = new ArrayList<>();
/**
* The primary account for any deposit and default transferIn.
*/
private final ArrayList<Account> primaryAccount;
/**
* The list of stock the user have.
*/
private final ArrayList<Object[]> stockArrayList = new ArrayList<>();
/**
* The list of funding the user joints.
*/
private final ArrayList<Funding> fundingArrayList = new ArrayList<>();
/**
* Constructor for User
*/
public User(String username, String password) {
super(username, password);
primaryAccount = new ArrayList<>();
}
public ArrayList<Account> getAccountList() {
return accountList;
}
/**
* @return The list of stocks the user bought.
*/
public ArrayList<Object[]> getStockArrayList(){
return stockArrayList;
}
/**
* Add a new funding to the list of funding that user joints.
* @param f new funding.
*/
public void addToFundingList(Funding f){
fundingArrayList.add(f);
}
/**
* Remove all occurrence of specific funding after that funding project finished.
* @param f one funding project.
*/
private void removeFromFundingList(Funding f){
if (fundingArrayList.contains(f)){
for (int i = 0; i < Collections.frequency(fundingArrayList, f); i++){
fundingArrayList.remove(f);
}
}
}
/**
* Get funding list that specific user joints.
* @return fundingArrayList.
*/
public ArrayList<Funding> getFundingArrayList() {
return fundingArrayList;
}
/**
* Get the total balance for a specific user.
* @return total balance.
*/
public double getTotalBalance() {
double total = 0;
for (Account currentAccount : accountList) { // loops over all accounts
if (currentAccount instanceof AssetAccount) {
total += currentAccount.getBalance(); // adds balance of each asset account
}
if (currentAccount instanceof DebtAccount) {
total -= currentAccount.getBalance(); // subtracts balance of each debt account
}
}
return total; // obtain total balance
}
/**
* Change the primary account to another chequing account
* @param account A chequing account
*/
public void setPrimaryAccount(Account account){
for(int i = 0; i < this.primaryAccount.size(); i++){
if(this.primaryAccount.get(i).getMoneyType().equals(account.getMoneyType())){
this.primaryAccount.remove(i);
break;
}
}
this.primaryAccount.add(account);
}
/**
* Get method for primaryAccount
* @return ArrayList of Account represents the primary accounts
*/
public ArrayList<Account> getPrimaryAccount() {
return this.primaryAccount;
}
/**
* Create a new account.
* A user must has a chequing account of the currency before having other account with that currency
* @param a account.
*/
public void addAccount(Account a) {
this.accountList.add(a);
// Check if this user already has a primary account of this currency type
if(this.findPrimaryType(a.getMoneyType()) != null){
return;
}
// If not, check if this is a Chequing Account
if(a instanceof ChequingAccount){
primaryAccount.add(a); //Add it to primary account
}
}
/**
* Make e transfer between one account of self to other's account.
* @param self my account
* @param other destination account
*/
public void interactE(String type, Account self, Account other, double amount){
if (self.accessOut()){
Transaction transaction = new Transaction(type, self, other, amount);
transaction.execute();
}
else{
System.out.println("!Invalid Account Selected! You Can't Transfer Out With This bank_system.accounts.Account!");
}
}
/**
* Find the primary account with corresponding currency name
* @param moneyType name of the currency in String
* @return primary account in Account if found, otherwise null
*/
public Account findPrimaryType(String moneyType){
for(Account a : primaryAccount){
if(a.getMoneyType().equals(moneyType)){
return a;
}
}
return null;
}
/**
* Deposit money into ATM machine
* @param amount the amount of money
* @param moneyType the type of currency
*/
public void deposit(double amount, String moneyType){
Account tempPrimary = this.findPrimaryType(moneyType);
// if the user does not have account that stores this type of currency
if(tempPrimary == null){
System.out.printf("Cannot deposit %s into this account!\n", moneyType);
return;
}
Transaction transaction = new Transaction("Deposit", "ATM", tempPrimary, amount);
transaction.execute();
try {
recordDeposit(amount, moneyType);
} catch (IOException e){
e.printStackTrace();
}
}
/**
* Method to record deposit in a .txt file.
* @param amount amount of money for the deposit
* @param moneyType type of currency for the deposit.
* @throws IOException handle in out exception
*/
private void recordDeposit(double amount, String moneyType) throws IOException{
final String depositFile = "phase2/data/deposit.txt";
FileWriter fw = new FileWriter(depositFile, true);
fw.write(String.format("%s deposit %.2f %s at %s.\n", this.getUsername(), amount, moneyType, ATM.getTime()));
fw.close();
}
public void payBill(String payee, Account account, double amount) {
Transaction transaction = new Transaction("bill-paying", account, payee, amount);
transaction.setToCantUndo();//bill-paying transaction can undo.
transaction.execute();
try {
saveToFile(payee, amount);
} catch (IOException e) {
e.printStackTrace();
}
}
/**
* Find account under user by ID
* @param accountID id of the account
* @return null if account not found
*/
public Account findAccount(String accountID){
for(Account i : accountList){
if(i.getId().equals(accountID)){
return i;
}
}
return null;
}
/**
* Withdraw money from an account
*
* @param amount The amount of money
* @param accountID The account ID
* @throws IOException for saving the file.
*/
public void withdraw(String moneyType, int amount, String accountID) throws IOException{
Account withdrawAccount = findAccount(accountID);
if(withdrawAccount == null) {
System.out.println("Account doesn't exist!");
return;
}
if(!withdrawAccount.accessOut()) {
System.out.println("This account cannot transfer money out");
return;
}
if(Bank.currentAC.handlingMoney(moneyType, amount)){
Transaction transaction = new Transaction("withdraw", withdrawAccount, "ATM", amount);
transaction.execute();
}
Bank.alertManager();
}
/**
* A user interface for the one using bank_system.ATM.
* @param br BufferedReader.
* @throws IOException console input
*/
public void userInterface(BufferedReader br) throws IOException {
UserInterface UI = new UserInterface(this);
String inputLine = null;
do {
if (inputLine != null) {
switch (inputLine) {
case "1":
UI.viewBalanceUI();
break;
case "2":
UI.transferMoneyUI();
break;
case "3":
UI.depositUI();
break;
case "4":
UI.withdrawUI();
break;
case "5":
UI.changePrimaryAccountUI();
break;
case "6":
UI.changePasswordUI();
break;
case "7":
UI.checkAccountsCreationTime();
break;
case "8":
UI.checkTransactionsUI();
break;
case "9":
UI.buyFundsUI();
break;
case "10":
UI.buyStockUI();
break;
case "11":
UI.sellStockUI();
break;
case "12":
UI.EMTUI();
break;
default:
System.out.println("INVALID INPUT.");
break;
}
}
System.out.println("\nMain menu:");
System.out.println("Type 1 to view the balance of each account.");
System.out.println("Type 2 to transfer money.");
System.out.println("Type 3 to deposit");
System.out.println("Type 4 to withdraw");
System.out.println("Type 5 to check or change primary accounts");
System.out.println("Type 6 to change password");
System.out.println("Type 7 to check account creation time");
System.out.println("Type 8 to check transactions");
System.out.println("Type 9 to manage funding projects");
System.out.println("Type 10 to purchase stock");
System.out.println("Type 11 to sell stock");
System.out.println("Type 12 to interact EMT");
System.out.println("Type LOGOUT to exit.");
} while (!(inputLine = br.readLine().toLowerCase()).equals("logout"));
System.out.println("Thank you! See you next time!");
}
/**
* Save completed payments.
*/
private void saveToFile(String payee, double amount) throws IOException {
BufferedWriter writer = new BufferedWriter(new FileWriter("phase2/data/outgoing.txt", true));
writer.write(getUsername() + " made a" + amount + " dollar(s) payment to " + payee + "\n");
writer.close();
}
/**
* Purchase a new stock, and add the information to the stock list
* @param stockID the id for the stock
* @param amount the amount of the stock
* @param price the price for the stock when purchase
* @param account the account pay the money
*/
public void purchaseStock(String stockID, int amount, double price, Account account){
Object[] newInfo = {stockID, amount};
stockArrayList.add(newInfo);
Transaction transaction = new Transaction("buy Stock", account, "Bank", amount*price);
transaction.setToCantUndo();
transaction.execute();
}
/**
* Get the name for this stock.
* @param index The index of the stock stored in the list.
* @return The name for the stock.
*/
public String getStockName(int index){
return (String) stockArrayList.get(index)[0];
}
/**
* Get the amount for this stock.
* @param index The index of the stock stored in the list.
* @return The amount for the stock.
*/
public int getStockAmount(int index){
return (int) stockArrayList.get(index)[1];
}
/**
* Purchase a new stock, and update the information to the stock list. If the
* amount of this stock is 0, delete the stock information.
* @param stockID the id for the stock
* @param amount the amount of the stock
* @param price the price for the stock when purchase
* @param account the account store the money
*/
public void sellStock(String stockID, int amount, double price, Account account){
int index = sellHelper(stockID);
stockArrayList.get(index)[1] = (int)stockArrayList.get(index)[1] - amount;
if ((int)stockArrayList.get(index)[1] == 0){
stockArrayList.remove(index);
}
Transaction transaction = new Transaction("sell Stock", "Bank", account, amount*price);
transaction.setToCantUndo();
transaction.execute();
}
/**
* @param id The String want to check
* @return the index of object in stock list who has the same id.
*/
private int sellHelper (String id){
ArrayList<String> temp = new ArrayList<>();
for (Object[] s: stockArrayList){
temp.add((String)s[0]);
}
return temp.indexOf(id);
}
/**
* Update Funding when completed.
* @param o a Funding
* @param obj money returned.
*/
public void update(Observable o, Object obj){
removeFromFundingList((Funding) o);
Transaction t = new Transaction("Join Funding Project", "Bank", this.findPrimaryType("CAD"),
Collections.frequency(fundingArrayList, o) * ((double) obj));
t.setToCantUndo();
t.execute();
}
/**
* Send a new EMT. The money will store in the bank until the receiver accept the money.
* @param senderA The account information about sender.
* @param receiverA The account information about receiver.
* @param amount The amount of money for this EMT.
* @param key The password for this EMT.
*/
public void sendEMT(Account senderA, Account receiverA, double amount, String key){
EMT newEMT = new EMT(senderA, receiverA, amount, key);
Bank.addNewEMT(newEMT);
Transaction transaction = new Transaction("send EMT", senderA, "Bank", amount);
transaction.setToCantUndo();
transaction.execute();
}
/**
* Accept the target EMT. And the EMT information will be deleted in bank.
* @param EMTid The if for the target EMT.
*/
public void acceptEMT(String EMTid){
Account receiver;
double amount;
for(EMT e: Bank.getEMTArrayList()){
if (EMTid.equals(e.getEMTid())){
receiver = e.getReceiver();
amount = e.getAmount();
Transaction transaction = new Transaction("receive EMT", "Bank", receiver, amount);
transaction.setToCantUndo();
transaction.execute();
Bank.removeEMT(e);
break;
}
}
}
@Override
public String fileOutputFormat(){
return String.format("user,%s,%s", getUsername(), getPassword());
}
}
| Andy8647/Bank_System | bank_system/users/User.java | 3,456 | /**
* Create a new account.
* A user must has a chequing account of the currency before having other account with that currency
* @param a account.
*/ | block_comment | en | false | 3,217 | 39 | 3,456 | 38 | 3,763 | 41 | 3,456 | 38 | 4,119 | 42 | false | false | false | false | false | true |
172792_19 | // Logging utility class. Sets a custom logging handler to write log messages to a file on the
// controller phone "disk". You can then pull the file back to your PC with an adb command in the
// Android Studio terminal window.
//
// You normally only need to call the logger.setup function in your class before any logging.
// You can use LogPrintStream to send streams to the log file.
//
// Use the logger object in your code to write log messages or use the simpler methods
// in this class. The methods in this class record the location in your program where
// you call them.
package org.firstinspires.ftc.teamcode;
import com.qualcomm.robotcore.hardware.HardwareDevice;
import com.qualcomm.robotcore.hardware.HardwareMap;
import java.io.IOException;
import java.io.OutputStream;
import java.io.PrintStream;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Map;
import java.util.Set;
import java.util.TimeZone;
import java.util.logging.ConsoleHandler;
import java.util.logging.FileHandler;
import java.util.logging.Formatter;
import java.util.logging.Handler;
import java.util.logging.Level;
import java.util.logging.LogRecord;
import java.util.logging.Logger;
/**
* Custom logging class. Configures log system (not console) to write to a disk file.
* Customize the setup() method for the controller phone you are using.
*/
public class Logging
{
/**
* PrintStream that writes to out custom logging location.
*/
public static final PrintStream logPrintStream = new PrintStream(new LoggingOutputStream());
/**
* Used by other classes to implement logging. Other classes should log with methods on this
* object or the simpler methods included in this class. The methods in class record the
* location in your program where you call them.
*/
public final static Logger logger = Logger.getGlobal();
// The log file can be copied from the ZTE robot controller to your PC for review by using the
// following AndroidDeBugger command in the Android Studio Terminal window:
//
// ZTE: adb pull //storage/sdcard0/Logging.txt c:\temp\robot_logging.txt
// MOTO G: adb pull sdcard/Logging.txt c:\temp\robot_logging.txt
// Control Hub: adb pull sdcard/Logging.txt c:\temp\robot_Logging.txt
/**
* Indicates if logging is turned on or off.
*/
public static boolean enabled = true;
private static FileHandler fileTxt;
//static private SimpleFormatter formatterTxt;
private static LogFormatter logFormatter;
private static boolean isSetup;
/**
* Configures our custom logging. If you don't use this custom logging, logging will go to
* the default logging location, typically the console. Call setup to turn on custom logging.
* With custom logging turned on logging goes to the console and also to the file opened in
* setup().
*/
/**
* Call to initialize our custom logging system.
* @throws IOException
*/
static public void setup() throws IOException
{
if (isSetup)
{
logger.info("========================================================================");
return;
}
// get the global logger to configure it and add a file handler.
Logger logger = Logger.getGlobal();
logger.setLevel(Level.ALL);
// If we decide to redirect system.out to our log handler, then following
// code will delete the default log handler for the console to prevent
// a recursive loop. We would only redirect system.out if we only want to
// log to the file. If we delete the console handler we can skip setting
// the formatter...otherwise we set our formatter on the console logger.
Logger rootLogger = Logger.getLogger("");
Handler[] handlers = rootLogger.getHandlers();
// if (handlers[0] instanceof ConsoleHandler)
// {
// rootLogger.removeHandler(handlers[0]);
// return;
// }
logFormatter = new LogFormatter();
// Set our formatter on the console log handler.
if (handlers[0] instanceof ConsoleHandler) handlers[0].setFormatter(logFormatter);
// Now create a handler to log to a file on controller phone "disk".
// For ZTE:
//fileTxt = new FileHandler("storage/sdcard0/Logging.txt", 0 , 1);
// For MOTO G:
fileTxt = new FileHandler("sdcard/Logging.txt", 0 , 1);
fileTxt.setFormatter(logFormatter);
logger.addHandler(fileTxt);
isSetup = true;
}
/**
* Flush logged data to disk file. Not normally needed.
*/
public static void flushlog()
{
fileTxt.flush();
}
// Our custom formatter for logging output.
private static class LogFormatter extends Formatter
{
public String format(LogRecord rec)
{
StringBuffer buf = new StringBuffer(1024);
buf.append(String.format("<%d>", rec.getThreadID())); //Thread.currentThread().getId()));
buf.append(formatDate(rec.getMillis()));
buf.append(" ");
buf.append(formatMessage(rec));
buf.append("\r\n");
return buf.toString();
}
private String formatDate(long milliseconds)
{
SimpleDateFormat dateFormat = new SimpleDateFormat("hh:mm:ss:SSS");
dateFormat.setTimeZone(TimeZone.getTimeZone("America/Los_Angeles"));
Date resultDate = new Date(milliseconds);
return dateFormat.format(resultDate);
}
}
/**
* Log blank line with program location.
*/
public static void log()
{
if (!enabled) return;
logger.log(Level.INFO, currentMethod(2));
}
/**
* Log message with optional formatting and program location.
* @param message message with optional format specifiers for listed parameters
* @param parms parameter list matching format specifiers
*/
public static void log(String message, Object... parms)
{
if (!enabled) return;
logger.log(Level.INFO, String.format("%s: %s", currentMethod(2), String.format(message, parms)));
}
/**
* Log message with optional formatting and no program location.
* @param message message with optional format specifiers for listed parameters
* @param parms parameter list matching format specifiers
*/
public static void logNoMethod(String message, Object... parms)
{
if (!enabled) return;
logger.log(Level.INFO, String.format(message, parms));
}
/**
* Log message with no formatting and program location.
* @param message message with optional format specifiers for listed parameters
*/
public static void logNoFormat(String message)
{
if (!enabled) return;
logger.log(Level.INFO, String.format("%s: %s", currentMethod(2), message));
}
/**
* Log message with no formatting and no program location.
* @param message message with optional format specifiers for listed parameters
*/
public static void logNoFormatNoMethod(String message)
{
if (!enabled) return;
logger.log(Level.INFO, message);
}
/**
* Returns program location where call to this method is located.
*/
public static String currentMethod()
{
return currentMethod(2);
}
private static String currentMethod(Integer level)
{
StackTraceElement stackTrace[];
stackTrace = new Throwable().getStackTrace();
try
{
return stackTrace[level].toString().split("teamcode.")[1];
}
catch (Exception e)
{
try
{
return stackTrace[level].toString().split("lib.")[1];
}
catch (Exception e1)
{
try
{
return stackTrace[level].toString().split("activities.")[1];
}
catch (Exception e2) {e2.printStackTrace(); return "";}
}
}
}
/**
* Write a list of configured hardware devices to the log file. Can be called in init()
* function or later.
* @param map hardwareMap object.
*/
public static void logHardwareDevices(HardwareMap map)
{
log();
// This list must be manually updated when First releases support for new devices.
logDevices(map.dcMotorController);
logDevices(map.dcMotor);
logDevices(map.servoController);
logDevices(map.servo);
logDevices(map.deviceInterfaceModule);
logDevices(map.analogInput);
logDevices(map.analogOutput);
logDevices(map.digitalChannel);
logDevices(map.pwmOutput);
logDevices(map.accelerationSensor);
logDevices(map.colorSensor);
logDevices(map.compassSensor);
logDevices(map.gyroSensor);
logDevices(map.irSeekerSensor);
logDevices(map.i2cDevice);
logDevices(map.led);
logDevices(map.lightSensor);
logDevices(map.opticalDistanceSensor);
logDevices(map.touchSensor);
logDevices(map.ultrasonicSensor);
logDevices(map.legacyModule);
}
@SuppressWarnings("unchecked")
private static void logDevices(HardwareMap.DeviceMapping deviceMap)
{
for (Map.Entry<String, HardwareDevice> entry :(Set<Map.Entry<String,HardwareDevice>>) deviceMap.entrySet())
{
HardwareDevice device = entry.getValue();
log("%s;%s;%s", entry.getKey(), device.getDeviceName(), device.getConnectionInfo());
}
}
/**
* Get the user assigned name for a hardware device.
* @param deviceMap The DEVICE_TYPE map, such as hardwareDevice.dcMotor, that the dev belongs to.
* @param dev Instance of a device of DEVICE_TYPE.
* @return User assigned name or empty string if not found.
*/
@SuppressWarnings("unchecked")
public static String getDeviceUserName(HardwareMap.DeviceMapping deviceMap, HardwareDevice dev)
{
for (Map.Entry<String, HardwareDevice> entry : (Set<Map.Entry<String,HardwareDevice>>) deviceMap.entrySet())
{
HardwareDevice device = entry.getValue();
if (dev == device) return entry.getKey();
}
return "";
}
// An output stream that writes to our logging system. Writes data with flush on
// flush call or on a newline character in the stream.
private static class LoggingOutputStream extends OutputStream
{
private static final int DEFAULT_BUFFER_LENGTH = 2048;
private boolean hasBeenClosed = false;
private byte[] buf;
private int count, curBufLength;
public LoggingOutputStream()
{
curBufLength = DEFAULT_BUFFER_LENGTH;
buf = new byte[curBufLength];
count = 0;
}
public void write(final int b) throws IOException
{
if (!enabled) return;
if (hasBeenClosed) {throw new IOException("The stream has been closed.");}
// don't log nulls
if (b == 0) return;
// force flush on newline character, dropping the newline.
if ((byte) b == '\n')
{
flush();
return;
}
// would this be writing past the buffer?
if (count == curBufLength)
{
// grow the buffer
final int newBufLength = curBufLength + DEFAULT_BUFFER_LENGTH;
final byte[] newBuf = new byte[newBufLength];
System.arraycopy(buf, 0, newBuf, 0, curBufLength);
buf = newBuf;
curBufLength = newBufLength;
}
buf[count] = (byte) b;
count++;
}
public void flush()
{
if (count == 0) return;
final byte[] bytes = new byte[count];
System.arraycopy(buf, 0, bytes, 0, count);
String str = new String(bytes);
logNoFormatNoMethod(str);
count = 0;
}
public void close()
{
flush();
hasBeenClosed = true;
}
}
}
| stemrobotics/Tetrix-Exercises | Logging.java | 2,765 | /**
* Indicates if logging is turned on or off.
*/ | block_comment | en | false | 2,534 | 14 | 2,765 | 14 | 3,021 | 16 | 2,765 | 14 | 3,320 | 18 | false | false | false | false | false | true |
173168_9 | import java.security.AlgorithmParameters;
import java.security.KeyFactory;
import java.security.KeyPair;
import java.security.KeyPairGenerator;
import java.security.PrivateKey;
import java.security.PublicKey;
import java.security.spec.PKCS8EncodedKeySpec;
import java.security.spec.X509EncodedKeySpec;
import java.security.MessageDigest;
import javax.crypto.Cipher;
import javax.crypto.KeyAgreement;
import javax.crypto.interfaces.DHPublicKey;
import javax.crypto.spec.DHParameterSpec;
import javax.crypto.spec.SecretKeySpec;
import java.nio.ByteBuffer;
import java.util.Arrays;
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Paths;
/**
* Handles security related tasks on behalf of Messenger, interacts with the javax.crypto and java.security libraries
*/
class Security{
/**
* Shared key for encryption
*/
private Cipher enCipher;
/**
* Shared key for decryption
*/
private Cipher deCipher;
/**
* Object for access in multiple methods
*/
private KeyAgreement keyAgree;
/**
* Instance key for creating ciphers
*/
private SecretKeySpec aesKey;
/**
* Messenger that we are communicating with
*/
private CommunicationInterface other;
/*
* Our Messenger parent
*/
private CommunicationInterface self;
/*
* Id of our Messenger parent
*/
private String id;
/*
* Private key (not diffie-hellman)
*/
private PrivateKey priv;
/*
* Public key (not diffie-hellman)
*/
PublicKey myPub;
/*
* Stores the 3 security flags in the following order: confidentiality, integrity, authentication
*/
private static Boolean[] flags;
/*
* Stores the boolean of whether the user has authenticated successfully as the id of our messenger parent.
*/
private Boolean authenticated = false;
/**
* Initialize Security
* @param parent object of caller
* @param parentID id of caller
*/
public Security(CommunicationInterface parent, String parentID) throws Exception{
self = parent; //set instance variables
id = parentID;
flags = new Boolean[]{false,false, false};
try{
priv = getPrivate(); //get from file
myPub = getPublic(id); //get from file
}catch(Exception e){
System.out.println("public/private key read error, maybe user does not exist");
}
}
/**
* First step in diffie-hellman protocol, generate public key and send to other party
* @param obj party to send to
*/
public void createSharedSecret(CommunicationInterface obj) throws Exception{
other = obj; //set instance var for use by other functions
KeyPairGenerator kPairGen = KeyPairGenerator.getInstance("DH");
kPairGen.initialize(2048);
KeyPair kPair = kPairGen.generateKeyPair(); //generate diffie-hellman public/private pair
keyAgree = KeyAgreement.getInstance("DH"); //init KeyAgreement instance for use in generating secret
keyAgree.init(kPair.getPrivate());
other.createPub(kPair.getPublic().getEncoded(), self); //send encoded public key to other party
}
/**
* Second step in diffie-hellman protocol, take a public key and generate our own, send to the other party to create a shared secret
* @param otherPubEnc other party's public key
* @param other object of other party
*/
public void createPub(byte[] otherPubEnc, CommunicationInterface other) throws Exception{
KeyFactory keyFac = KeyFactory.getInstance("DH");
X509EncodedKeySpec x509KeySpec = new X509EncodedKeySpec(otherPubEnc); //create a spec to determine other public key
PublicKey otherPub = keyFac.generatePublic(x509KeySpec); //get other public key
DHParameterSpec dhParam = ((DHPublicKey)otherPub).getParams(); //create spec to create a similar key
KeyPairGenerator kPairGen = KeyPairGenerator.getInstance("DH");
kPairGen.initialize(dhParam);
KeyPair kPair = kPairGen.generateKeyPair(); //generate keypair based on spec
KeyAgreement keyAgree = KeyAgreement.getInstance("DH"); //does not need to be externally defined as this step is self-contained
keyAgree.init(kPair.getPrivate());
keyAgree.doPhase(otherPub, true);
byte[] sharedSecret = keyAgree.generateSecret(); //create diffie-hellman secret
aesKey = new SecretKeySpec(sharedSecret, 0, 16, "AES");
enCipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
enCipher.init(Cipher.ENCRYPT_MODE, aesKey); //create cipher for encoding
byte[] params = enCipher.getParameters().getEncoded();
other.share(kPair.getPublic().getEncoded(), params); //send required information to other party
}
/**
* Third step in diffie-hellman protocol, take a public key and create a shared secret, take cipher params and use secret to create a cipher
* @param otherPubEnc other party's public key
* @param otherParams other party's cypher paremeters
*/
public void share(byte[] otherPubEnc, byte[] otherParams) throws Exception{
KeyFactory keyFac = KeyFactory.getInstance("DH");
X509EncodedKeySpec x509KeySpec = new X509EncodedKeySpec(otherPubEnc); //create a spec to determine other public key
PublicKey otherPub = keyFac.generatePublic(x509KeySpec); //get other public key
keyAgree.doPhase(otherPub, true);
byte[] sharedSecret = keyAgree.generateSecret(); //create diffie-hellman secret
aesKey = new SecretKeySpec(sharedSecret, 0, 16, "AES");
enCipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
enCipher.init(Cipher.ENCRYPT_MODE, aesKey); //create cipher for encoding
byte[] selfParams = enCipher.getParameters().getEncoded();
other.createDecoder(selfParams); //create decoder for this key
self.createDecoder(otherParams); //create decoder for other party's key (we do it here to avoid race condition)
}
/**
* Last step in diffie-hellman protocol, take cipher params to create a decoder
* @param params cipher parameters
*/
public void createDecoder(byte[] params) throws Exception{
AlgorithmParameters aesParams = AlgorithmParameters.getInstance("AES");
aesParams.init(params);
deCipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
deCipher.init(Cipher.DECRYPT_MODE, aesKey, aesParams); //create cipher for decoding
}
/**
* Encrypt text using the cipher
* @param plaintext readable version of message
* @return unreadable version of message
*/
private byte[] encrypt(String plaintext) throws Exception{
return enCipher.doFinal(plaintext.getBytes());
}
/**
* Utilize flags to create a sendable message
* @param msg message to make sendable
* @return sendable message
*/
public byte[][] send(String msg, String receiver) throws Exception{
byte[] msg_ret = msg.getBytes();
byte[] checksum_ret = new byte[0];
if(flags[0]){
msg_ret = encrypt(msg);
}
if(flags[1]){
checksum_ret = encryptCheckSum(receiver, generateCheckSum(msg));
}
if(flags[2]){
if(!authenticated){
System.out.println(id+" attempted to send a message while unauthenticated.");
return null;
}
}
byte[][] ret = new byte[2][];
ret[0] = msg_ret;
ret[1] = checksum_ret;
return ret;
}
/**
* Decrypt text using the cipher
* @param ciphertext unreadable version of message
* @return readable version of message
*/
private String decrypt(byte[] ciphertext) throws Exception{
return new String(deCipher.doFinal(ciphertext));
}
/**
* Utilize flags to create a sendable message
* @param msg message to make readable
* @return readable message
*/
public String receive(byte[] msg, byte[] checksum) throws Exception{
String ret;
if(flags[0]){
ret = decrypt(msg);
}else{
ret = new String(msg);
}
if(flags[1]){
byte[] decrypted_cs = decryptCheckSum(checksum);
if(compareCheckSum(decrypted_cs, ret)){
return ret;
}else{
return "Checksum does not match";
}
}
if(flags[2]){
if(!authenticated){
System.out.println(id+" did not receive message due to not being authenticated.");
return null;
}
}
return ret;
}
/**
* Set security flags from Messenger
* @param newFlags security flags to set
*/
public void setFlags(Boolean[] newFlags){
flags = newFlags;
}
/**
* Get security flags and return them
* @return current security flags
*/
public Boolean[] getFlags(){
return flags;
}
/**
* Get private key for the current messenger from a file
* @return our private key
*/
private PrivateKey getPrivate() throws Exception{
byte[] key = Files.readAllBytes(Paths.get("keys/private-" + id + "/private.der"));
PKCS8EncodedKeySpec PKCS8KeySpec = new PKCS8EncodedKeySpec(key);
KeyFactory keyFac = KeyFactory.getInstance("RSA");
return keyFac.generatePrivate(PKCS8KeySpec);
}
/**
* Get public key for the specified messenger from a file
* @param messenger id of messenger to get public key for
* @return public key of the messenger
*/
private PublicKey getPublic(String messenger) throws Exception{
byte[] key = Files.readAllBytes(Paths.get("keys/public/" + messenger + ".der"));
X509EncodedKeySpec x509KeySpec = new X509EncodedKeySpec(key);
KeyFactory keyFac = KeyFactory.getInstance("RSA");
return keyFac.generatePublic(x509KeySpec);
}
/**
* Create a checksum for a specific message
* @param message message to generate a checksum for
* @return created checksum
*/
private byte[] generateCheckSum(String message){
int m = message.hashCode();
ByteBuffer bb = ByteBuffer.allocate(4);
bb.putInt(m);
System.out.println("Generated checksum: "+toHexString(bb.array()));
return bb.array();
}
/**
* Encrypt a given checksum
* @param receiver id of Messenger to receive
* @param inputData data to encrypt
* @return encrypted checksum
*/
private byte[] encryptCheckSum(String receiver, byte[] inputData) throws Exception {
PublicKey key = getPublic(receiver);
Cipher cipher = Cipher.getInstance("RSA");
cipher.init(Cipher.PUBLIC_KEY, key);
byte[] encryptedBytes = cipher.doFinal(inputData);
return encryptedBytes;
}
/**
* Decrypt a given checksum
* @param checksum checksum to decrypt
* @return decrypted checksum
*/
private byte[] decryptCheckSum(byte[] checksum) throws Exception {
PrivateKey key = getPrivate();
Cipher cipher = Cipher.getInstance("RSA");
cipher.init(Cipher.PRIVATE_KEY, key);
byte[] decryptedBytes = cipher.doFinal(checksum);
return decryptedBytes;
}
/**
* Compare two checksums
* @param checksum checksum to check
* @param message message to confirm same as checksum
* @return true if same, false otherwise
*/
private boolean compareCheckSum(byte[] checksum, String message){
byte[] temp_checksum = generateCheckSum(message);
if(Arrays.equals(temp_checksum, checksum)){
System.out.println("Checksum matches: "+toHexString(temp_checksum));
return true;
}
return false;
}
/**
* Attempts to authenticate a user
* @param id id of user to authenticate
* @param pass attempted password to authenticate
* @return true if successful, false if not
*/
public boolean authenticate(String id, String pass)throws Exception{
byte[] bom = pass.getBytes("UTF-8");
MessageDigest md = MessageDigest.getInstance("MD5");
byte[] hash = md.digest(bom);
String attempted_hash = toHexString(hash);
String stored_hash = getStoredHash(id);
if(attempted_hash.equals(stored_hash)){
authenticated = true;
System.out.println(id+" authenticated successfully.");
return true;
}else{
System.out.println("Attempted password hash: "+attempted_hash);
System.out.println("Stored password hash: "+stored_hash);
System.out.println(id+" failed to authenticate.");
return false;
}
}
/**
* Gets the stored password hash for id
* @param id id of user to get password hash of
* @return password hash if found, "" if not
*/
private String getStoredHash(String id){
String line;
try {
BufferedReader bufferreader = new BufferedReader(new FileReader("users"));
line = bufferreader.readLine();
while (line != null) {
String[] el = line.split(":");
if(el[0].equals(id)){
return el[1];
}
line = bufferreader.readLine();
}
} catch (FileNotFoundException ex) {
ex.printStackTrace();
} catch (IOException ex) {
ex.printStackTrace();
}
return "";
}
/**
* Converts MD5 byte array to a string
* @param bytes byte array to convert
* @return Base 16 string
*/
private String toHexString(byte[] bytes) {
StringBuilder hexString = new StringBuilder();
for (int i = 0; i < bytes.length; i++) {
String hex = Integer.toHexString(0xFF & bytes[i]);
if (hex.length() == 1) {
hexString.append('0');
}
hexString.append(hex);
}
return hexString.toString();
}
/**
* Deauthorizes id
*/
public void deAuth(){
authenticated = false;
}
/**
* Checks to see if id is authenticated
* @return true or false
*/
public boolean getAuth(){
return authenticated;
}
}
| danielfrankcom/securemessenger | Security.java | 3,305 | /*
* Public key (not diffie-hellman)
*/ | block_comment | en | false | 3,123 | 15 | 3,305 | 15 | 3,617 | 17 | 3,305 | 15 | 4,092 | 17 | false | false | false | false | false | true |
173234_23 | public class FFT {
// compute the FFT of x[], assuming its length is a power of 2
public static Complex[] fft(Complex[] x) {
int N = x.length;
// base case
if (N == 1) return new Complex[] { x[0] };
// radix 2 Cooley-Tukey FFT
if (N % 2 != 0) { throw new RuntimeException("N is not a power of 2"); }
// fft of even terms
Complex[] even = new Complex[N/2];
for (int k = 0; k < N/2; k++) {
even[k] = x[2*k];
}
Complex[] q = fft(even);
// fft of odd terms
Complex[] odd = even; // reuse the array
for (int k = 0; k < N/2; k++) {
odd[k] = x[2*k + 1];
}
Complex[] r = fft(odd);
// combine
Complex[] y = new Complex[N];
for (int k = 0; k < N/2; k++) {
double kth = -2 * k * Math.PI / N;
Complex wk = new Complex(Math.cos(kth), Math.sin(kth));
y[k] = q[k].plus(wk.times(r[k]));
y[k + N/2] = q[k].minus(wk.times(r[k]));
}
return y;
}
// compute the inverse FFT of x[], assuming its length is a power of 2
public static Complex[] ifft(Complex[] x) {
int N = x.length;
Complex[] y = new Complex[N];
// take conjugate
for (int i = 0; i < N; i++) {
y[i] = x[i].conjugate();
}
// compute forward FFT
y = fft(y);
// take conjugate again
for (int i = 0; i < N; i++) {
y[i] = y[i].conjugate();
}
// divide by N
for (int i = 0; i < N; i++) {
y[i] = y[i].times(1.0 / N);
}
return y;
}
// compute the circular convolution of x and y
public static Complex[] cconvolve(Complex[] x, Complex[] y) {
// should probably pad x and y with 0s so that they have same length
// and are powers of 2
if (x.length != y.length) { throw new RuntimeException("Dimensions don't agree"); }
int N = x.length;
// compute FFT of each sequence
Complex[] a = fft(x);
Complex[] b = fft(y);
// point-wise multiply
Complex[] c = new Complex[N];
for (int i = 0; i < N; i++) {
c[i] = a[i].times(b[i]);
}
// compute inverse FFT
return ifft(c);
}
// compute the linear convolution of x and y
public static Complex[] convolve(Complex[] x, Complex[] y) {
Complex ZERO = new Complex(0, 0);
Complex[] a = new Complex[2*x.length];
for (int i = 0; i < x.length; i++) a[i] = x[i];
for (int i = x.length; i < 2*x.length; i++) a[i] = ZERO;
Complex[] b = new Complex[2*y.length];
for (int i = 0; i < y.length; i++) b[i] = y[i];
for (int i = y.length; i < 2*y.length; i++) b[i] = ZERO;
return cconvolve(a, b);
}
// display an array of Complex numbers to standard output
public static void show(Complex[] x, String title) {
System.out.println(title);
System.out.println("-------------------");
for (int i = 0; i < x.length; i++) {
System.out.println(x[i]);
}
System.out.println();
}
public static void main(String[] args) {
int N = Integer.parseInt(args[0]);
Complex[] x = new Complex[N];
// original data
for (int i = 0; i < N; i++) {
x[i] = new Complex(i, 0);
x[i] = new Complex(-2*Math.random() + 1, 0);
}
show(x, "x");
// FFT of original data
Complex[] y = fft(x);
show(y, "y = fft(x)");
// take inverse FFT
Complex[] z = ifft(y);
show(z, "z = ifft(y)");
// circular convolution of x with itself
Complex[] c = cconvolve(x, x);
show(c, "c = cconvolve(x, x)");
// linear convolution of x with itself
Complex[] d = convolve(x, x);
show(d, "d = convolve(x, x)");
}
} | yifan-guo/KimiWoNosete | FFT.java | 1,208 | // circular convolution of x with itself | line_comment | en | false | 1,132 | 7 | 1,209 | 7 | 1,313 | 7 | 1,208 | 7 | 1,403 | 7 | false | false | false | false | false | true |
173788_17 | import java.awt.*;
import java.awt.image.BufferedImage;
import java.util.stream.*;
/**
* Main renderer
*/
public class Tracer{
public static final int MAX_DEPTH = 5; //maximum recursion depth
public static final int nx = 600; //output resolution
public static final int ny = 400;
public static final int ns = 150; //samples per pixel
public static void main(String[] args){
DrawingPanel d = new DrawingPanel(nx,ny);
Graphics gr = d.getGraphics();
BufferedImage img = new BufferedImage(nx,ny,BufferedImage.TYPE_INT_ARGB);
HittableList world = Scenes.poke(true);
Camera cam = Scenes.pokeCam(nx,ny);
for(int j = 0; j<ny; j++){
System.out.println("Row: " + j);
final int jj = j;
IntStream.range(0, nx).parallel().forEach(i->{ //parallelize
Vec3 col = new Vec3(0,0,0);
//Latin hypercube sampling to get more evenly distributed samples
//See pbrt Chapter 7 available free online
//Is this implementation inefficient/necessary?
double delta = 1.0/ns; //width of each cell
double[] hs = new double[ns];
double[] vs = new double[ns];
for(int s = 0; s<ns; s++){ //generate random positions
hs[s] = (s+Math.random())*delta;
vs[s] = (s+Math.random())*delta;
}
Utilities.permute(hs);
Utilities.permute(vs);
for(int s = 0; s<ns; s++){ //multisampling and free anti-aliasing
double u = (i+hs[s])/nx;
double v = (jj+vs[s])/ny;
Ray r = cam.get_ray(u,v);
col = col.add(color(r,world,0));
}
col = col.div(ns);
if(col.r() > 1) col.e[0] = 1; //clamp outputs due to light sources
if(col.g() > 1) col.e[1] = 1;
if(col.b() > 1) col.e[2] = 1;
col = new Vec3(Math.sqrt(col.e[0]),Math.sqrt(col.e[1]),Math.sqrt(col.e[2])); //gamma
Color c = new Color((int)(255*col.r()),(int)(255*col.g()),(int)(255*col.b()));
img.setRGB(i,ny-jj-1,c.getRGB());
});
gr.drawImage(img,0,0,null);
}
gr.drawImage(img,0,0,null);
}
/**
* Calculates the color of a pixel
* @param r the ray that needs to hit the materials in the world
* @param world the list of objects to hit
* @param depth the current recursion depth
*/
static Vec3 color(Ray r, HittableList world, int depth){
HitRecord rec = new HitRecord();
if(world.hit(r,0.001,Double.MAX_VALUE,rec)){ //intersect with list of objects
Ray scattered = new Ray();
Vec3 attenuation = new Vec3();
Vec3 emitted = rec.mat.emitted(rec.u, rec.v, rec.p);
if(depth < MAX_DEPTH && rec.mat.scatter(r,rec,attenuation,scattered)){ //if we haven't recursed beyond max depth and there is an impact
return color(scattered,world,depth+1).mul(attenuation).add(emitted); //rendering equation
} else {
return emitted;
}
} else {
//background acts a large light source
//Vec3 unit_dir = Vec3.unit_vector(r.direction());
//double t = 0.5*(unit_dir.y() + 1.0);
//return new Vec3(1.0,1.0,1.0).mul(1.0-t).add(new Vec3(0.5,0.7,1.0).mul(t)); //create a gradient
//or all black
return new Vec3(0,0,0);
}
}
} | njeff/raytracer0 | week/Tracer.java | 1,099 | //background acts a large light source | line_comment | en | false | 956 | 7 | 1,099 | 7 | 1,086 | 7 | 1,099 | 7 | 1,289 | 7 | false | false | false | false | false | true |
175098_3 | public interface IntSet{
//adds a new int to the set; if it is there already, nothing happens.
void add(int newNumber);
//returns true if the number is in the set, false otherwise.
boolean contains(int newNumber);
/**returns the same values as the former method, but for every element that is checked print
*its value on screen.
*/
boolean containsVerbose(int newNumber);
//returns a string with the values of the elements in the set separated by commas.
String toString();
} | PhilHannant/Day9 | IntSet.java | 127 | //returns a string with the values of the elements in the set separated by commas. | line_comment | en | false | 111 | 17 | 127 | 17 | 131 | 17 | 127 | 17 | 137 | 18 | false | false | false | false | false | true |
176810_0 | import java.awt.*;
public class vertex {
private int redValue;
private int blueValue;
private int greenValue;
private int rgbValue;
private int xValue;
private int yValue;
//get the coordinates of the pixel to refer to later, get the color to derive rgb values from
public vertex(int xValue, int yValue, Color color){
this.xValue=xValue;
this.yValue=yValue;
redValue=color.getRed();
greenValue=color.getGreen();
blueValue=color.getBlue();
rgbValue=color.getRGB();
}
//methods return references to the variables. the x and y will be used to change the color of the
//pixel after they're segmented into their respective components.
public int getRedValue(){
return redValue;
}
public int getBlueValue(){
return blueValue;
}
public int getGreenValue(){
return greenValue;
}
public int getRgbValue(){
return rgbValue;
}
public int getxValue(){
return xValue;
}
public int getyValue(){
return yValue;
}
}
| daltamur/imageSegmentation | vertex.java | 262 | //get the coordinates of the pixel to refer to later, get the color to derive rgb values from
| line_comment | en | false | 244 | 21 | 262 | 21 | 319 | 21 | 262 | 21 | 334 | 22 | false | false | false | false | false | true |
176969_0 | package state;
import java.util.ArrayList;
/**
* Represents the Spanish state in the BabyBook application.
*/
class SpanishState extends State {
/**
* Constructor for the SpanishState class.
*
* @param book The BabyBook instance associated with this state.
*/
public SpanishState(BabyBook book) {
super(book);
// Initialize Spanish animal sounds
animalSounds.put("Pájaro", "pío");
animalSounds.put("Gato", "miau");
animalSounds.put("Gallina", "coc co co coc");
animalSounds.put("Perro", "Guau");
animalSounds.put("Caballo", "relinchar");
animalSounds.put("Ratón", "cui-cui");
animalSounds.put("Oveja", "bee, mee");
}
/**
* Gets the list of animals in the Spanish language.
*
* @return An ArrayList containing the names of animals in Spanish.
*/
@Override
public ArrayList<String> getAnimalList() {
return new ArrayList<>(animalSounds.keySet());
}
/**
* Presses the button associated with a specific animal in the Spanish state,
* producing the corresponding animal sound.
*
* @param animal The name of the animal whose button is pressed.
*/
@Override
public void pressAnimalButton(String animal) {
System.out.println(animalSounds.get(animal));
}
/**
* Switches the BabyBook application to the English state.
*/
@Override
public void pressEnglishButton() {
// Switch to English state
book.setState(book.getEnglishState());
}
/**
* Displays a message indicating that the application is already in the Spanish state.
*/
@Override
public void pressSpanishButton() {
// Already in Spanish state
System.out.println("Already in Spanish state");
}
/**
* Switches the BabyBook application to the French state.
*/
@Override
public void pressFrenchButton() {
// Switch to French state
book.setState(book.getFrenchState());
}
}
| sattiabicsce/design-patterns-todelete | state/SpanishState.java | 498 | /**
* Represents the Spanish state in the BabyBook application.
*/ | block_comment | en | false | 447 | 13 | 498 | 17 | 520 | 15 | 498 | 17 | 570 | 17 | false | false | false | false | false | true |
177021_0 | package helper;
import java.math.BigDecimal;
import java.math.RoundingMode;
import play.i18n.Lang;
public final class UtilsHelper {
/**
Truncate a String to the given length with no warnings
or error raised if it is bigger.
@param value String to be truncated
@param length Maximum length of string
@return Returns value if value is null or value.length() is less or equal to than length, otherwise a String representing
value truncated to length.
*/
public static String truncate(String value, int length)
{
if (value != null && value.length() > length)
value = value.substring(0, length);
return value;
}
public static Integer roundPrice(Float price){
BigDecimal priceRounded = new BigDecimal(price);
priceRounded = priceRounded.setScale(0, RoundingMode.DOWN);
return price.intValue();
}
public static Boolean langIsFrench(String lang){
if (lang != null && (lang.equalsIgnoreCase("fr")||lang.equals(Lang.getLocale().FRENCH.getLanguage()))){
return Boolean.TRUE;
}
return Boolean.FALSE;
}
public static Boolean langIsSpanish(String lang){
if (lang != null && (lang.equalsIgnoreCase("es") || lang.equalsIgnoreCase("es_ES"))){
return Boolean.TRUE;
}
return Boolean.FALSE;
}
}
| robertogds/ReallyLateBooking | app/helper/UtilsHelper.java | 343 | /**
Truncate a String to the given length with no warnings
or error raised if it is bigger.
@param value String to be truncated
@param length Maximum length of string
@return Returns value if value is null or value.length() is less or equal to than length, otherwise a String representing
value truncated to length.
*/ | block_comment | en | false | 295 | 78 | 343 | 76 | 365 | 88 | 343 | 76 | 411 | 94 | false | false | false | false | false | true |
177202_3 | package psl.xues.ep.store;
import java.util.HashMap;
import java.util.TreeMap;
import org.w3c.dom.Element;
import psl.xues.ep.event.EPEvent;
/**
* Simple implementation of an EP store to store events in memory.
* Fast, and useful for testing.
* <p>
* Usage: <em>([] implies an optional parameter)</em></p>
* <p><tt>
* <Stores><br>
* <blockquote><Store Name="<em>instance name</em>"
* Type="psl.xues.ep.store.MemoryStore"/><br></blockquote>
* </Stores>
* </tt></p>
* <p>
* Note that there are no configurable parameters for this store.
* <p>
* Copyright (c) 2002: The Trustees of Columbia University in the
* City of New York. All Rights Reserved.
*
* <!--
* TODO:
* - Support store-to-file (is it possible, actually, to support generalized
* serialization?)
* - Make sure we return a copy, not a reference, of the event.
* -->
*
* @author Janak J Parekh ([email protected])
* @version $Revision$
*/
public class MemoryStore extends EPStore {
/**
* TreeMap of the events sorted by time.
*/
private TreeMap eventsByTime = new TreeMap();
/**
* HashMap of the events by source. Each entry associated with an owner
* is actually a TreeMap of events mapped by time.
*/
private HashMap eventsBySource = new HashMap();
/**
* File to write out data structures to.
*/
private String storeFile = null;
/**
* CTOR.
*/
public MemoryStore(EPStoreInterface ep, Element el)
throws InstantiationException {
super(ep,el);
// Saved file?
//storeFile = el.getAttribute("StoreFile");
//if(storeFile != null) {
// Try to restore it
}
/**
* Request an individual event given its (opaque) reference.
*
* @param ref The event reference.
* @return The event in EPEvent form, or null if it doesn't exist.
*/
public EPEvent requestEvent(Object ref) {
if(!(ref instanceof EPEvent)) { // BAD!
debug.warn("Was handed invalid reference");
return null;
}
return (EPEvent)ref;
}
/**
* Request event(s). Return a set of references to this event.
*
* @param t1 The lower timebound (inclusive).
* @param t2 The upper timebound (inclusive).
* @return An array of (possibly opaque) object references, null if error.
*/
public Object[] requestEvents(long t1, long t2) {
// Here's a particularly nifty piece of code
return eventsByTime.subMap(new Long(t1), new Long(t2)).values().toArray();
}
/**
* Store the supplied event.
*
* @param e The event to be stored.
* @return An object reference indicating success, or null.
*/
public Object storeEvent(EPEvent e) {
// Put it in the time map
eventsByTime.put(new Long(e.getTimestamp()), e);
// Put it in the owner map
TreeMap t = (TreeMap)eventsBySource.get(e.getSource());
if(t == null) { // No such map, create one
t = new TreeMap();
eventsBySource.put(e.getSource(), t);
}
t.put(new Long(e.getTimestamp()), e); // Actually put it in the tree
return e;
}
/**
* Request all events from a given source.
*
* @param source The source of this event - matches the source in
* the EPEvent.
* @return An array of (possibly opaque) object references, empty array if
* no match, and null if error.
*/
public Object[] requestEvents(String source) {
// Grab the TreeMap from the sourceMap
TreeMap t = (TreeMap)eventsBySource.get(source);
if(t == null) return null;
else return t.values().toArray();
}
/**
* Request events from a given source between the two timestamps.
*
* @param source The source of this event - matches the source in
* the EPEvent.
* @param t1 The lower timebound (inclusive).
* @param t2 The upper timebound (inclusive).
* @return An array of (possibly opaque) object references, empty array if
* no match, and null if error.
*/
public Object[] requestEvents(String source, long t1, long t2) {
// Grab the TreeMap from the sourceMap
TreeMap t = (TreeMap)eventsBySource.get(source);
if(t == null) return null;
else return t.subMap(new Long(t1), new Long(t2)).values().toArray();
}
/**
* Get the type.
*/
public String getType() {
return "MemoryStore";
}
}
| Programming-Systems-Lab/archived-xues | ep/store/MemoryStore.java | 1,190 | /**
* File to write out data structures to.
*/ | block_comment | en | false | 1,120 | 13 | 1,190 | 13 | 1,303 | 15 | 1,190 | 13 | 1,375 | 15 | false | false | false | false | false | true |
177241_12 | /*
* @(#)WVM_Registry.java
*
* Copyright (c) 2002: The Trustees of Columbia University in the City of New York. All Rights Reserved
*
* Copyright (c) 2002: @author Dan Phung ([email protected])
*
* CVS version control block - do not edit manually
* $RCSfile$
* $Revision$
* $Date$
* $Source$
*/
package psl.worklets;
import java.rmi.server.*;
import java.rmi.registry.*;
import java.rmi.*;
import java.util.*;
/**
* The Worklets implemented RMI <code>Registry</code>
*
* We subclass the Sun implementation of the registry to add
* registration features to the bind, rebind, and unbind methods, and
* so that we can restrict who can rebind the names.
*/
class WVM_Registry extends sun.rmi.registry.RegistryImpl{
/** Collection of WVM_URL/registrationKey values */
private Map _regKeys;
/** Collection of name/WVM_URL values */
// we need to keep a name/WVM_URL association list
// so that when a server unbinds, we can remove the
// value up from the name
private Map _names;
/**
* Creates a WVM_Registry on the given port
*
* @param port: Socket number to create the registry on
* @throws RemoteException if the WVM_Registry could not be created
*/
WVM_Registry(int port) throws RemoteException {
super(port);
_regKeys = Collections.synchronizedMap(new HashMap());
_names = Collections.synchronizedMap(new HashMap());
WVM.out.println("WVM RMI Registry running on port: " + port);
}
/**
* Gets the available registration keys
*
* @return the collection of WVM_URL/registrationKey values.
*/
Map getRegistrationKeys(){
return _regKeys;
}
/**
* Register an object with the RMI bound name
*
* @param name: RMI name that the object is binding with
* @param obj: <code>Remote</code> object to register
* @throws RemoteException if the name/obj cannot be bound
*/
private void _registerHost(String name, Remote obj) throws RemoteException{
_regKeys.put( ((RTU_Registrar) obj).getWVM_URL(),
((RTU_Registrar) obj).getRegistrationKey());
_names.put(name, ((RTU_Registrar) obj).getWVM_URL());
}
/**
* Remove the RMI bound name from the registration.
*
* @param name: RMI name to remove
*/
private void _removeHost(String name) {
_regKeys.remove(name);
_regKeys.remove(_names.get(name));
}
/**
* Binds the <code>Remote</code> object to the given name
*
* @param name: name to bind with
* @param obj: <code>Remote</code> object associated with the name
* @throws AlreadyBoundException if the name is already used
* @throws RemoteException if the object cannot be bound
*/
public void bind(String name, Remote obj) throws AlreadyBoundException, RemoteException
{
try {
Remote server = ((RTU_Registrar) obj).getServer();
super.bind(name, server);
_registerHost(name, obj);
} catch (ClassCastException e) {
super.bind(name, obj);
}
}
/**
* Rebinds the <code>Remote</code> object to the given name if the binding object is
* a {@link WVM_RMI_Transporter}
*
* @param name: the name to rebind with
* @param obj: the <code>Remote</code> object associated with the name
* @throws RemoteException if the object cannot be bound
* @throws AccessException if the object does not have permission to rebind with the name
*/
public void rebind(String name, Remote obj) throws RemoteException, AccessException
{
String objName = "" + obj.getClass();
Remote server = obj;
if (objName.matches(".*RTU_Registrar.*")) {
server = ((RTU_Registrar) obj).getServer();
objName = "" + server.getClass();
}
if (objName.matches(".*psl[.]worklets[.]WVM_RMI_Transporter.*")) {
try {
super.rebind(name, server);
_registerHost(name, obj);
} catch (ClassCastException e) {
super.rebind(name, obj);
}
}
else
throw new AccessException("WVM_Registry Error: You do not have access to rebind to this name: " + name);
}
/**
* Unbinds the name from the registry.
*
* @param name: name to unbind
* @throws RemoteException if the name could not be unbound
* @throws NotBoundException if the name is not bound in the registry
*/
public void unbind(String name) throws RemoteException, NotBoundException
{
super.unbind(name);
_removeHost(name);
}
/**
* Creates an external registry from a command line
*
* @param args[0]: the port to create the {@link WVM_Registry} on
*/
public static void main (String args[]){
int port = WVM_Host.PORT;
if (args.length > 0)
port = Integer.parseInt(args[0]);
try {
new WVM_Registry(port);
new Thread() {
public void run() {
while (true){
try {
sleep(1000);
} catch (InterruptedException e) { }
}
}
}.start();
} catch (Exception e){
}
}
}
| Programming-Systems-Lab/archived-worklets | WVM_Registry.java | 1,349 | /**
* Rebinds the <code>Remote</code> object to the given name if the binding object is
* a {@link WVM_RMI_Transporter}
*
* @param name: the name to rebind with
* @param obj: the <code>Remote</code> object associated with the name
* @throws RemoteException if the object cannot be bound
* @throws AccessException if the object does not have permission to rebind with the name
*/ | block_comment | en | false | 1,276 | 106 | 1,349 | 103 | 1,449 | 105 | 1,349 | 103 | 1,573 | 114 | false | false | false | false | false | true |
178261_13 | /*
* This is the main class. It creates the program window, adds all the
* required Swing components, registers the needed listeners, etc. A Piano
* object is created and added to the window, and messages are sent to the
* Piano as appropriate. This class also listens for changes in the Piano's
* state (e.g., to disable most of the components when a melody is being
* automatically played.
*/
import java.awt.*;
import java.awt.event.*;
import java.beans.*;
import javax.swing.*;
import javax.swing.event.*;
@SuppressWarnings("serial")
public class MusicalEarTrainer extends JFrame implements ActionListener,
ItemListener, ChangeListener, PropertyChangeListener {
JCheckBox showBox;
JButton playButton;
Piano piano;
String[] keyArray = {"Low C", "C#", "D", "D#", "E", "F", "F#",
"G", "G#", "A", "A#", "B", "Mid C"};
JComboBox<String> keyList = new JComboBox<String>(keyArray);
String[] tonalityArray = {"Major", "Minor", "Chromatic"};
JComboBox<String> tonalityList = new JComboBox<String>(tonalityArray);
JSpinner lengthSpinner = new JSpinner(new SpinnerNumberModel(3, 2, 20, 1));
JSpinner tempoSpinner = new JSpinner(new SpinnerNumberModel(160, 60, 480, 1));
// Initialize window and add keyboard
private MusicalEarTrainer() {
setTitle("Musical Ear Trainer");
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setResizable(false);
JPanel pane = new JPanel(new GridBagLayout());
// create group box and add components
JPanel melodyGroup = new JPanel();
melodyGroup.setBorder(BorderFactory.createTitledBorder("Melody Properties"));
keyList.setSelectedItem(keyArray[0]);
melodyGroup.add(new JLabel("Key: "));
melodyGroup.add(keyList);
Dimension dim = new Dimension(15, 0);
melodyGroup.add(new Box.Filler(dim, dim, dim));
melodyGroup.add(new JLabel("Scale: "));
melodyGroup.add(tonalityList);
melodyGroup.add(new Box.Filler(dim, dim, dim));
melodyGroup.add(new JLabel("Length: "));
melodyGroup.add(lengthSpinner);
melodyGroup.add(new Box.Filler(dim, dim, dim));
melodyGroup.add(new JLabel("Tempo (bpm): "));
melodyGroup.add(tempoSpinner);
// add group box to pane
GridBagConstraints c = new GridBagConstraints();
c.gridx = 0;
c.gridy = 0;
c.gridwidth = 2;
c.weightx = 0.5;
c.fill = GridBagConstraints.HORIZONTAL;
c.insets = new Insets(5, 5, 5, 5);
pane.add(melodyGroup, c);
// add check box
showBox = new JCheckBox("Show first note only");
c = new GridBagConstraints();
c.gridx = 0;
c.gridy = 1;
c.weightx = 1;
c.anchor = GridBagConstraints.LINE_END;
c.insets = new Insets(0, 0, 0, 10);
showBox.setSelected(false);
pane.add(showBox, c);
// add button
playButton = new JButton("Play New");
playButton.setMnemonic(KeyEvent.VK_P);
c = new GridBagConstraints();
c.gridx = 1;
c.gridy = 1;
c.weightx = 0;
c.anchor = GridBagConstraints.LINE_END;
c.insets = new Insets(0, 0, 0, 7);
pane.add(playButton, c);
// add piano
piano = new Piano();
c = new GridBagConstraints();
c.gridx = 0;
c.gridy = 2;
c.gridwidth = 2;
c.weightx = 0.5;
c.weighty = 0.5;
c.fill = GridBagConstraints.HORIZONTAL;
c.anchor = GridBagConstraints.PAGE_END;
c.insets = new Insets(7, 7, 7, 7);
pane.add(piano, c);
// add interactions
piano.addPropertyChangeListener(this);
playButton.addActionListener(this);
keyList.addActionListener(this);
tonalityList.addActionListener(this);
tempoSpinner.addChangeListener(this);
lengthSpinner.addChangeListener(this);
showBox.addItemListener(this);
getContentPane().add(pane);
}
// enable/disable all controls except for the button
private void setEnabledControls(boolean isEnabled) {
tonalityList.setEnabled(isEnabled);
keyList.setEnabled(isEnabled);
showBox.setEnabled(isEnabled);
tempoSpinner.setEnabled(isEnabled);
lengthSpinner.setEnabled(isEnabled);
}
// listen to the button and drop-down lists
@Override
public void actionPerformed (ActionEvent e) {
if (e.getSource() == playButton) {
if (piano.getMode() == Modes.AUTOPLAY ) {
piano.stopMelody();
} else {
piano.playMelody();
}
} else {
if (e.getSource() == keyList)
piano.getMelodyMaker().setKey(keyList.getSelectedIndex());
else if (e.getSource() == tonalityList)
piano.getMelodyMaker().setTonality(tonalityList.getSelectedIndex());
piano.setRepeatMelody(false);
piano.getMelodyMaker().createMelody();
playButton.setText("Play New");
}
}
// listen to the check box
@Override
public void itemStateChanged(ItemEvent e) {
if (e.getStateChange() == ItemEvent.SELECTED) {
piano.setFirstNoteOnly(true);
} else {
piano.setFirstNoteOnly(false);
}
}
// listen to the spinners
@Override
public void stateChanged(ChangeEvent e) {
JSpinner source = (JSpinner)e.getSource();
if (source == lengthSpinner) {
piano.getMelodyMaker().setLength((int)source.getValue());
} else if (source == tempoSpinner) {
piano.setTempo((int)source.getValue());
}
piano.setRepeatMelody(false);
piano.getMelodyMaker().createMelody();
playButton.setText("Play New");
}
// listen for property changes in the Piano object
public void propertyChange(PropertyChangeEvent e) {
if (e.getNewValue() == Modes.AUTOPLAY) {
setEnabledControls(false);
playButton.setText("Stop");
} else if (e.getNewValue() == Modes.RECITE) {
setEnabledControls(true);
playButton.setText("Repeat");
} else {
setEnabledControls(true);
playButton.setText("Play New");
}
}
// Create and show application window
public static void main(String[] args) {
// Code is run on an event-dispatching thread
SwingUtilities.invokeLater(new Runnable() {
@Override
public void run() {
MusicalEarTrainer window = new MusicalEarTrainer();
window.pack();
window.setVisible(true);
}
});
}
} | ckahn/musical-ear-trainer | MusicalEarTrainer.java | 1,769 | // Create and show application window | line_comment | en | false | 1,513 | 6 | 1,769 | 6 | 1,808 | 6 | 1,769 | 6 | 2,076 | 6 | false | false | false | false | false | true |
179837_2 | /*
* CSE 12 Homework 8
* Francisco Arredondo, Michelle Arteaga
* A07614106, A11468765
* A00, A00
* May 23, 2014
*/
// file: Tokenizer.java
// purpose: Input Tokenizer
// author: Zach Dodds, Christine Alvarado
// date: Sometime in 2008 or so
// comments:
import java.util.*;
import java.io.InputStream;
import java.io.FileInputStream;
import java.util.regex.Pattern;
import java.util.regex.Matcher;
/** class: Tokenizer
* purpose: to provide an array of Strings (tokens) as desired
* can use System.in or a filename to get its tokens
*/
public class Tokenizer
{
/** method: nextTokens
* inputs: none
* outputs: an array of Strings - the next array of tokens from
* this Tokenizer's input stream...
*/
public static List<String> tokenize( String line )
{
List<String> tokens = new LinkedList<String>();
Pattern pat = Pattern.compile( "[a-zA-Z]+|[0-9]*\\.[0-9]+|[0-9]+|[\\+\\-\\^\\*/#\\(\\)]" );
Matcher match = pat.matcher( line );
while ( match.find() ) {
tokens.add( line.substring( match.start(), match.end() ) );
}
if ( tokens.size() > 0 ) {
return tokens;
}
else return null;
}
/** method: main
* inputs: usual
* outputs: none - just tests the Tokenizer...
*/
public static void main(String[] args)
{
Tokenizer tokenizer = new Tokenizer();
//tokenizer = new Tokenizer("testfile.txt");
Scanner s = new Scanner( System.in );
while (true)
{
String line = s.nextLine();
List<String> tokens = Tokenizer.tokenize( line );
if (tokens == null)
break;
System.out.println("The tokens are " + tokens );
System.out.println();
}
}
}
| FranciscoArredondo/HW8 | Tokenizer.java | 536 | // purpose: Input Tokenizer
| line_comment | en | false | 473 | 7 | 536 | 7 | 595 | 7 | 536 | 7 | 639 | 7 | false | false | false | false | false | true |
180563_0 | /**
* The type Giant.
*/
public class Giant extends Troop {
private static int[] damageArray = new int[]{126, 138, 152, 167, 183};
private static int[] hpArray = new int[]{2000, 2200, 2420, 2660, 2920};
private static String imageBluePath = "sprites/GiantBlue.gif";
private static String imageRedPath = "sprites/GiantRed.gif";
private static boolean isRoyal = false;
/**
* Instantiates a new Giant.
*
* @param user the user
* @param x the x
* @param y the y
*/
public Giant(User user, int x, int y) {
this.arrayX = x;
this.arrayY = y;
switch (user.getLevel()) {
case 1:
hp = hpArray[0];
damage = damageArray[0];
break;
case 2:
hp = hpArray[1];
damage = damageArray[1];
break;
case 3:
hp = hpArray[2];
damage = damageArray[2];
break;
case 4:
hp = hpArray[3];
damage = damageArray[3];
break;
case 5:
hp = hpArray[4];
damage = damageArray[4];
}
hitSpeed = 1.5;
speed = 2;
target = 3;
range = 0;
areaSplash = false;
count = 1;
zone = 0;
imageBlue = imageBluePath;
imageRed = imageRedPath;
imageWidth = 120;
imageHeight = 120;
}
/**
* Upgrade.
*/
public static void upgrade() {
damageArray = new int[]{252, 276, 304, 334, 366};
hpArray = new int[]{3000, 3300, 3630, 3990, 4380};
imageBluePath = "sprites/RoyalGiantBlue.gif";
imageRedPath = "sprites/RoyalGiantRed.gif";
isRoyal = true;
}
/**
* Is royal boolean.
*
* @return the boolean
*/
public static boolean isRoyal() {
return isRoyal;
}
@Override
public String toString() {
return "Giant";
}
@Override
public void buildImageView(String color) {
super.buildImageView(color);
imageView.setX(mapX - 15);
imageView.setY(mapY - 20);
}
}
| AshkanShakiba/Clash-Royale | src/Giant.java | 644 | /**
* The type Giant.
*/ | block_comment | en | false | 615 | 7 | 644 | 10 | 701 | 9 | 644 | 10 | 749 | 10 | false | false | false | false | false | true |
181098_0 |
import java.util.Calendar;
import java.util.Random;
public class Main {
public static void main(String[] args) {
String idNumber = generateRandomSouthAfricanId();
System.out.println("Generated South African ID: " + idNumber);
}
private static String generateRandomSouthAfricanId() {
String year = generateRandomYear();
String month = generateRandomMonth();
String day = generateRandomDay();
String sequence = generateRandomSequence();
String citizenship = generateRandomCitizenshipStatus();
String withoutCheckDigit = year + month + day + sequence + citizenship + "8";
String idNumber = withoutCheckDigit + findValidCheckDigit(withoutCheckDigit);
return idNumber;
}
private static String generateRandomYear() {
int currentYear = Calendar.getInstance().get(Calendar.YEAR);
int randomYear = currentYear - new Random().nextInt(42) - 18; // Generate between 18 and 59 years old
return String.format("%02d", randomYear % 100);
}
private static String generateRandomMonth() {
int randomMonth = new Random().nextInt(12) + 1;
return String.format("%02d", randomMonth);
}
private static String generateRandomDay() {
int randomDay = new Random().nextInt(31) + 1;
return String.format("%02d", randomDay);
}
private static String generateRandomSequence() {
int sequenceValue = new Random().nextInt(5000);
return String.format("%04d", sequenceValue);
}
private static String generateRandomCitizenshipStatus() {
return "0";
}
public static int findValidCheckDigit(String number) {
int candidate = 0;
do {
if (calculateCheckDigit(number + candidate)) {
return candidate;
}
candidate++;
} while (true);
}
public static boolean calculateCheckDigit(String number) {
int checksum = Character.getNumericValue(number.charAt(number.length() - 1));
int total = 0;
for (int i = number.length() - 2; i >= 0; i--) {
int sum = 0;
int digit = Character.getNumericValue(number.charAt(i));
if (i % 2 == number.length() % 2) {
digit = digit * 2;
if (digit > 9) {
digit -= 9;
}
}
sum = digit / 10 + digit % 10;
total += sum;
}
return total % 10 != 0 ? 10 - total % 10 == checksum : checksum == 0;
}
}
| ndivhomakhuvha/South-african-id-generator-java | src/Main.java | 628 | // Generate between 18 and 59 years old | line_comment | en | false | 585 | 12 | 628 | 12 | 672 | 12 | 628 | 12 | 731 | 13 | false | false | false | false | false | true |
181382_1 | /**
* This class is the super class of all RPG games.
* It also inherits from the Game class, which is the top super class of all games.
*/
public abstract class RPGGame extends Game {
public RPGGame() {}
/*
Display welcome messages and relevant game instructions.
Get the necessary information from the players.
*/
public abstract void prepare();
/*
Print the stats of all the heroes in the team ArrayList.
*/
public abstract void printTeamMembers();
}
| Superkakayong/Legends_OO_Design-pattern | RPGGame.java | 111 | /*
Display welcome messages and relevant game instructions.
Get the necessary information from the players.
*/ | block_comment | en | false | 101 | 21 | 111 | 21 | 117 | 24 | 111 | 21 | 125 | 24 | false | false | false | false | false | true |
181453_3 | import static org.junit.Assert.*;
import org.junit.*;
import org.openqa.selenium.By;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;
public class Guidelines {
private static ChromeDriver driver;
@Before
public void beforeAll() throws InterruptedException {
System.setProperty("webdriver.chrome.driver", "/Users/rajnish/Documents/Codes/test/chromedriver102");
driver= new ChromeDriver();
driver.manage().window().maximize();
driver.get("https://travel-advisor-self.vercel.app/guidelines");
Thread.sleep(3000);
}
@Test
// Validate if country card shows
public void test1() {
WebElement card = driver.findElement(By.xpath("//*[@id=\"__next\"]/div/div/div[2]/div[1]/div"));
Assert.assertTrue(card.isDisplayed());
}
@Test
// Validate if show detail button is clickable
public void test2() throws InterruptedException {
WebElement showDetail = driver.findElement(By.xpath("//*[@id=\"__next\"]/div/div/div[2]/div[1]/div/button"));
showDetail.click();
Assert.assertEquals(showDetail.getText(), "Loading....");
}
@Test
// Validate if details populated
public void test3() throws InterruptedException {
WebElement showDetail = driver.findElement(By.xpath("//*[@id=\"__next\"]/div/div/div[2]/div[1]/div/button"));
showDetail.click();
Thread.sleep(10000);
Assert.assertTrue(driver.findElement(By.xpath("//*[@id=\"__next\"]/div/div/div[2]/div[1]/div[2]/div/div/div/h2")).isDisplayed());
}
@Test
// Validate if close button clickable
public void test4() throws InterruptedException {
WebElement showDetail = driver.findElement(By.xpath("//*[@id=\"__next\"]/div/div/div[2]/div[1]/div/button"));
showDetail.click();
Thread.sleep(10000);
showDetail.click();
Assert.assertEquals(driver.findElements(By.xpath("//*[@id=\"__next\"]/div/div/div[2]/div[1]/div[2]/div/div/div/h2")).size(), 0);
}
@After
public void afterClass() {
driver.close();
}
}
| dhruvradadiya7/travel-advisor | testcases/Guidelines.java | 620 | // Validate if show detail button is clickable | line_comment | en | false | 476 | 8 | 620 | 9 | 629 | 8 | 620 | 9 | 722 | 10 | false | false | false | false | false | true |
181475_5 | import java.net.InetAddress;
import java.net.UnknownHostException;
/**
* @author Suchith Chandrashekhara Arodi
* @version 1.0
*
*/
/*
* Main class
*/
public class fcntcp {
// variables to hold the input details.
private static boolean client = false;
private static boolean server = false;
private static String filename;
private static long time_out = 1000;
private static Boolean quiet = false;
// Main method
public static void main(String[] args) throws UnknownHostException {
int argu_length = args.length;
int port = 0;
String address = null;
int next;
// parsing the input
for (int i = 0; i < argu_length; i++) {
if (args[i].equals("-s")) {
server = true;
}
if (args[i].equals("-f")) {
int pos = i + 1;
filename = args[pos];
i++;
}
if (args[i].equals("-c")) {
client = true;
}
if (args[i].equals("-t")) {
next = i + 1;
time_out = Long.parseLong(args[next]);
i++;
}
if (args[i].equals("-q")) {
quiet = true;
}
}
port = Integer.parseInt(args[argu_length - 1]);
address = args[argu_length - 2];
// Call out the specific functionality
if (client) {
(new Thread(new Sender(port, InetAddress.getByName(address), time_out, quiet, filename))).start();
} else if (server) {
(new Thread(new Receiver(port, quiet))).start();
} else {
System.out.println("Invalid Command Line!\nPlease follow the CLI guidelines.");
}
}
}
| SuchithArodi/RDTPusingUDP | fcntcp.java | 489 | // Call out the specific functionality
| line_comment | en | false | 404 | 8 | 489 | 7 | 500 | 7 | 489 | 7 | 604 | 7 | false | false | false | false | false | true |
182246_1 | /**
* @author Duncan Grubbs
* @date 2020-01-30
* @license MIT
*/
public class Rule {
private String a;
private String b;
private double p;
/**
* a -> b
* @param a Initially character
* @param b Transformed character (could be a string)
*/
public Rule(String a, String b) {
this.a = a;
this.b = b;
}
/**
* a -> b with probability p
* @param a Initially character
* @param b Transformed character (could be a string)
* @param p Probability that the rule will be applied
*/
public Rule(String a, String b, double p) {
this.a = a;
this.b = b;
this.p = p;
}
/**
* Does this rule apply to the current character.
* @param c Character to test.
* @return If the rules applies or not.
*/
public boolean applies(Character c) {
return (Character.toString(c).equals(this.a));
}
public String getB() {
return b;
}
public double getP() {
return p;
}
}
| duncangrubbs/L-system | src/Rule.java | 286 | /**
* a -> b
* @param a Initially character
* @param b Transformed character (could be a string)
*/ | block_comment | en | false | 268 | 31 | 286 | 30 | 314 | 33 | 286 | 30 | 330 | 34 | false | false | false | false | false | true |
182325_7 |
public class Employee {
public String eFullName; //Employee Full Name
public double eHSalary; //Employee Hourly Salary
public int hourWeekly; //Max hours worked a week
public int yearService; //Years working
public boolean workStatus; //Permanent [True] Temporary [False]
public int warnings; //Number of warnings given
public Employee(String fullName, double hSalary, int hWeekly, int years, boolean status, int warnings) {
eFullName = fullName;
eHSalary = hSalary;
hourWeekly = hWeekly;
yearService = years;
workStatus = status;
this.warnings = warnings;
}
public String getFullName() {
return eFullName;
}
public double getHourlySalary() {
return eHSalary;
}
public int getHoursPerWeek() {
return hourWeekly;
}
public int getYearsOfService() {
return yearService;
}
public boolean getStatus() {
return workStatus;
}
public int getWarnings() {
return warnings;
}
public double getYearlySalary() {
return eHSalary*hourWeekly*4.5*12;
}
public void setFullName(String fullName) {
eFullName = fullName;
}
public void setHourlySalary(double hSalary) {
eHSalary = hSalary;
}
public void setHoursPerWeek(int hours) {
hourWeekly = hours;
}
public void setYearsOfService(int years) {
yearService = years;
}
public void setStatus(boolean status) {
workStatus = status;
}
public void setWarnings(int warnings) {
this.warnings = warnings;
}
/**
* A method that returns the level of seniority of an employee. (Levels 0 to 3)
* 1. The level of seniority is determined by years of service:
* a) For a level 3 seniority the employee needs at least 10 years of service.
* b) For a level 2 seniority the employee needs at least 5 years of service.
* c) For a level 1 seniority the employee needs at least 1 years of service.
* d) For a level 0 the employee needs less than 1 year of service.
* @return
*/
public int seniorityLevel() {
//Add Code Here [You have to use If/Else to get graded]
if(this.yearService >= 10){
return 3;
}else if(this.yearService < 10 && this.yearService >= 5){
return 2;
}else if(this.yearService < 5 && this.yearService >= 1){
return 1;
}else{
return 0;// Temporal Return
}
}
}
| UPRM-CIIC4010-F18/using-git-github-with-eclipse-the-infamous-arvahk | src/Employee.java | 708 | //Add Code Here [You have to use If/Else to get graded] | line_comment | en | false | 615 | 16 | 708 | 18 | 728 | 16 | 708 | 18 | 821 | 17 | false | false | false | false | false | true |
182880_2 | package com.ars;
import junit.framework.Test;
import junit.framework.TestCase;
import junit.framework.TestSuite;
/**
* Unit test for simple App.
*/
public class AppTest
extends TestCase
{
/**
* Create the test case
*
* @param testName name of the test case
*/
public AppTest( String testName )
{
super( testName );
}
/**
* @return the suite of tests being tested
*/
public static Test suite()
{
return new TestSuite( AppTest.class );
}
/**
* Rigourous Test :-)
*/
public void testApp()
{
assertTrue( true );
}
}
| Ranjan121099/Sprint1 | AppTest.java | 166 | /**
* @return the suite of tests being tested
*/ | block_comment | en | false | 144 | 14 | 166 | 13 | 195 | 16 | 166 | 13 | 214 | 17 | false | false | false | false | false | true |
183018_0 | package mekanism.common;
import java.util.Map;
import mekanism.api.AdvancedInput;
import mekanism.api.gas.Gas;
import mekanism.api.gas.GasStack;
import mekanism.common.block.BlockMachine.MachineType;
import mekanism.common.recipe.RecipeHandler;
import mekanism.common.recipe.RecipeHandler.Recipe;
import mekanism.common.tile.TileEntityAdvancedElectricMachine;
import mekanism.common.util.MekanismUtils;
import mekanism.common.util.StackUtils;
import net.minecraft.item.ItemStack;
import net.minecraft.item.crafting.FurnaceRecipes;
import net.minecraftforge.common.ForgeDirection;
/**
* Internal interface for managing various Factory types.
* @author AidanBrady
*
*/
public interface IFactory
{
/**
* Gets the recipe type this Smelting Factory currently has.
* @param itemStack - stack to check
* @return RecipeType ordinal
*/
public int getRecipeType(ItemStack itemStack);
/**
* Sets the recipe type of this Smelting Factory to a new value.
* @param type - RecipeType ordinal
* @param itemStack - stack to set
*/
public void setRecipeType(int type, ItemStack itemStack);
public static enum RecipeType
{
SMELTING("smelting", "Smelter.ogg", MachineType.ENERGIZED_SMELTER.getStack(), false, null),
ENRICHING("enriching", "Chamber.ogg", MachineType.ENRICHMENT_CHAMBER.getStack(), false, Recipe.ENRICHMENT_CHAMBER),
CRUSHING("crushing", "Crusher.ogg", MachineType.CRUSHER.getStack(), false, Recipe.CRUSHER),
COMPRESSING("compressing", "Compressor.ogg", MachineType.OSMIUM_COMPRESSOR.getStack(), true, Recipe.OSMIUM_COMPRESSOR),
COMBINING("combining", "Combiner.ogg", MachineType.COMBINER.getStack(), true, Recipe.COMBINER),
PURIFYING("purifying", "PurificationChamber.ogg", MachineType.PURIFICATION_CHAMBER.getStack(), true, Recipe.PURIFICATION_CHAMBER),
INJECTING("injecting", "ChemicalInjectionChamber.ogg", MachineType.CHEMICAL_INJECTION_CHAMBER.getStack(), true, Recipe.CHEMICAL_INJECTION_CHAMBER);
private String name;
private String sound;
private ItemStack stack;
private boolean usesFuel;
private Recipe recipe;
private TileEntityAdvancedElectricMachine cacheTile;
public ItemStack getCopiedOutput(ItemStack input, Gas gas, boolean stackDecrease)
{
if(input == null)
{
return null;
}
if(this == SMELTING)
{
if(FurnaceRecipes.smelting().getSmeltingResult(input) != null)
{
ItemStack toReturn = FurnaceRecipes.smelting().getSmeltingResult(input).copy();
if(stackDecrease)
{
input.stackSize--;
}
return toReturn;
}
return null;
}
if(usesFuel())
{
return RecipeHandler.getOutput(new AdvancedInput(input, gas), stackDecrease, recipe.get());
}
else {
return RecipeHandler.getOutput(input, stackDecrease, recipe.get());
}
}
public GasStack getItemGas(ItemStack itemstack)
{
if(usesFuel)
{
return getTile().getItemGas(itemstack);
}
return null;
}
public int getSecondaryEnergyPerTick()
{
if(usesFuel)
{
return getTile().SECONDARY_ENERGY_PER_TICK;
}
return 0;
}
public boolean canReceiveGas(ForgeDirection side, Gas type)
{
if(usesFuel)
{
return getTile().canReceiveGas(side, type);
}
return false;
}
public boolean canTubeConnect(ForgeDirection side)
{
if(usesFuel)
{
return getTile().canTubeConnect(side);
}
return false;
}
public boolean isValidGas(Gas gas)
{
if(usesFuel)
{
return getTile().isValidGas(gas);
}
return false;
}
public boolean hasRecipe(ItemStack itemStack)
{
if(itemStack == null)
{
return false;
}
for(Object obj : recipe.get().entrySet())
{
if(((Map.Entry)obj).getKey() instanceof AdvancedInput)
{
Map.Entry entry = (Map.Entry)obj;
ItemStack stack = ((AdvancedInput)entry.getKey()).itemStack;
if(StackUtils.equalsWildcard(stack, itemStack))
{
return true;
}
}
}
return false;
}
public TileEntityAdvancedElectricMachine getTile()
{
if(cacheTile == null)
{
MachineType type = MachineType.get(getStack().itemID, getStack().getItemDamage());
cacheTile = (TileEntityAdvancedElectricMachine)type.create();
}
return cacheTile;
}
public int getMaxSecondaryEnergy()
{
return 200;
}
public ItemStack getStack()
{
return stack;
}
public String getName()
{
return MekanismUtils.localize("gui.factory." + name);
}
public String getSound()
{
return sound;
}
public boolean usesFuel()
{
return usesFuel;
}
private RecipeType(String s, String s1, ItemStack is, boolean b, Recipe r)
{
name = s;
sound = s1;
stack = is;
usesFuel = b;
recipe = r;
}
}
}
| vmrob/Mekanism | common/mekanism/common/IFactory.java | 1,492 | /**
* Internal interface for managing various Factory types.
* @author AidanBrady
*
*/ | block_comment | en | false | 1,322 | 20 | 1,492 | 25 | 1,528 | 21 | 1,492 | 25 | 2,066 | 26 | false | false | false | false | false | true |
183339_4 | package asteroids;
/**
Name: Chris Drury
Class: CSc 2310: Introduction to programming
Filename: Bullets.java
Date written: April, 19, 2011
Description:
This class controls how a bullet should act.
*/
import processing.core.PApplet;
public class Bullets {
double bulletx, bullety, crosshairx, crosshairy;
double speedx, speedy;
PApplet parent;
//Default constructor
public Bullets(PApplet papp, int x, int y, int crosshairx, int crosshairy, int speed)
{
parent = papp;
bulletx = x;
bullety = y;
//finds missing sides and angles
//This will auto find the direction the bullet
//needs to travel.
double xdis = crosshairx - x;
double ydis = crosshairy - y;
double angleAradians = Math.atan2(ydis,xdis);
double rotation = Math.toDegrees(angleAradians);
//creates the points to add to next frame
//This is a way of presetting our increments
//That way we dont have to do more math fucntions
//Each cycle.
speedx = (float)(speed * 60 * Math.cos(Math.toRadians(rotation)));
speedy = (float)(speed * 60 * Math.sin(Math.toRadians(rotation)));
}
public void update(double aDelta)
{
//Increment our location times delta
//To make smooth transitions
bulletx += speedx * aDelta;
bullety += speedy * aDelta;
}
public void draw()
{
//Fill the rect with a greyish white.
parent.fill(155);
//render rect in the center of the pisition.
parent.rectMode(parent.CENTER);
//draw rect
parent.rect((float)bulletx, (float)bullety, 3, 3);
//reset rect mode to default
parent.rectMode(0);
}
}
| gamepro65/Asteroids | Bullets.java | 530 | //needs to travel.
| line_comment | en | false | 463 | 6 | 530 | 6 | 543 | 5 | 530 | 6 | 624 | 6 | false | false | false | false | false | true |
183704_0 | package dice;
import org.junit.jupiter.api.Test;
import static org.junit.jupiter.api.Assertions.*;
public class DieTests {
// Testing that the upface of a Die is a letter in the alphabet when no string is given in the Die constructor
@Test
void rollDie() {
Die defaultDie = new Die();
for(int i = 0; i < 100; i++){
defaultDie.roll();
assertTrue("ABCDEFGHIJKLMNOPQRSTUVWXYZ".contains(defaultDie.toString().toUpperCase()));
}
}
// Testing that the upface of a Die is a letter in the string that is given in the Die constructor
@Test
void rollDieGivenLetters() {
Die specialDie = new Die("LMAO");
for(int i = 0; i < 100; i++){
specialDie.roll();
assertTrue("LMAO".contains(specialDie.toString().toUpperCase()));
}
}
// Testing that the upface of a HardDie is a hard letter to make words out of (ZJKXQV)
@Test
void rollHardDie() {
HardDie hd = new HardDie();
for(int i = 0; i < 100; i++){
hd.roll();
assertTrue("ZJKXQV".contains(hd.toString().toUpperCase()));
}
}
// Testing that the upface of a VowelDie is a vowel (AEIOUY)
@Test
void rollVowelDie() {
VowelDie vd = new VowelDie();
for(int i = 0; i < 100; i++){
vd.roll();
assertTrue("AEIOUY".contains(vd.toString().toUpperCase()));
}
}
// Testing that the upface of a VowelDie is an S
@Test
void rollSDie() {
SDie sd = new SDie();
for(int i = 0; i < 100; i++){
sd.roll();
assertTrue("S".contains(sd.toString().toUpperCase()));
}
}
}
| guninkakar03/BoggleGame | dice/DieTests.java | 471 | // Testing that the upface of a Die is a letter in the alphabet when no string is given in the Die constructor | line_comment | en | false | 437 | 24 | 471 | 24 | 501 | 24 | 471 | 24 | 566 | 25 | false | false | false | false | false | true |
184423_9 | import java.io.*;
import java.net.*;
import java.util.*;
import java.nio.*;
/** Class for working with studio3 packets. */
public class Packet {
// packet fields - note: all are public
public byte type; // packet type
public short seqNum; // sequence number in
// [0,2^15)
public String payload; // application payload
public static final byte DATA_TYPE = 0;
/** Constructor, initializes fields to default values. */
public Packet() {
clear();
}
/** Initialize all packet fields.
* Initializes all fields to an undefined value.
*/
public void clear() {
type = 0;
seqNum = 0;
payload = "";
}
/** Pack attributes defining packet fields into buffer.
* Fails if the packet type is undefined or if the resulting
* buffer exceeds the allowed length of 1400 bytes.
* @return null on failure, otherwise a byte array
* containing the packet payload.
*/
public byte[] pack() {
byte[] pbuf;
try {
pbuf = payload.getBytes("US-ASCII");
} catch (Exception e) {
return null;
}
if (pbuf.length > 1400 - 3)
return null;
ByteBuffer bbuf = ByteBuffer.allocate(3 + pbuf.length);
bbuf.order(ByteOrder.BIG_ENDIAN);
bbuf.put(type);
bbuf.putShort(seqNum);
bbuf.put(pbuf);
return bbuf.array();
}
/** Unpack attributes defining packet fields from buffer.
* @param buf is a byte array containing the packet
* (or if you like, the payload of a UDP packet).
* @param bufLen is the number of valid bytes in buf
*/
public boolean unpack(byte[] buf, int bufLen) {
if (bufLen < 3)
return false;
ByteBuffer bbuf = ByteBuffer.wrap(buf);
bbuf.order(ByteOrder.BIG_ENDIAN);
type = bbuf.get();
seqNum = bbuf.getShort();
try {
payload = new String(buf, 3, bufLen - 3, "US-ASCII");
} catch (Exception e) {
return false;
}
return true;
}
/** Create String representation of packet.
* The resulting String is produced using the defined
* attributes and is formatted with one field per line,
* allowing it to be used as the actual buffer contents.
*/
public String toString() {
if (type == DATA_TYPE)
return "data[" + seqNum + "] " + payload;
else
return "ack[" + seqNum + "]";
}
}
| pedrettin/Reliable-Data-Transfer-Protocol-Implementation | Packet.java | 690 | /** Unpack attributes defining packet fields from buffer.
* @param buf is a byte array containing the packet
* (or if you like, the payload of a UDP packet).
* @param bufLen is the number of valid bytes in buf
*/ | block_comment | en | false | 603 | 58 | 690 | 56 | 698 | 60 | 690 | 56 | 802 | 61 | false | false | false | false | false | true |
184914_6 | public class Board implements BoardAPI {
// Board hold the details for the current board positions, performs moves and returns the list of legal moves
private static final int[] RESET = {0,0,0,0,0,0,5,0,3,0,0,0,0,5,0,0,0,0,0,0,0,0,0,0,2,0};
private static final int[][] CHEAT = {
{13,2,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0}, // Bear in & Bear off test
{13,2,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0},
};
public static final int BAR = 25; // index of the BAR
public static final int BEAR_OFF = 0; // index of the BEAR OFF
private static final int INNER_END = 6; // index for the end of the inner board
private static final int OUTER_END = 18;
public static final int NUM_PIPS = 24; // excluding BAR and BEAR OFF
public static final int NUM_SLOTS = 26; // including BAR and BEAR OFF
private static final int NUM_CHECKERS = 15;
private int[][] checkers;
private Players players;
// 2D array of checkers
// 1st index: is the player id
// 2nd index is number pip number, 0 to 25
// pip 0 is bear off, pip 25 is the bar, pips 1-24 are on the main board
// the value in checkers is the number of checkers that the player has on the point
Board(Players players) {
this.players = players;
checkers = new int[Backgammon.NUM_PLAYERS][NUM_SLOTS];
for (int player=0; player<Backgammon.NUM_PLAYERS; player++) {
for (int pip=0; pip<NUM_SLOTS; pip++) {
checkers[player][pip] = RESET[pip];
}
}
}
Board(Players players, Board board) {
this.players = players;
this.checkers = new int[Backgammon.NUM_PLAYERS][NUM_SLOTS];
for (int player=0; player<Backgammon.NUM_PLAYERS; player++) {
for (int pip=0; pip<NUM_SLOTS; pip++) {
this.checkers[player][pip] = board.checkers[player][pip];
}
}
}
@Override
public int[][] get() {
// duplicate prevents the Bot moving the checkers
int[][] duplicateCheckers = new int[Backgammon.NUM_PLAYERS][NUM_SLOTS];
for (int i=0; i<checkers.length; i++) {
for (int j=0; j<checkers[i].length; j++) {
duplicateCheckers[i][j] = checkers[i][j];
}
}
return duplicateCheckers;
}
private int calculateOpposingPip(int pip) {
return NUM_PIPS-pip+1;
}
public void move(Player player, Move move) {
checkers[player.getId()][move.getFromPip()]--;
checkers[player.getId()][move.getToPip()]++;
int opposingPlayerId = players.getOpposingPlayer(player).getId();
if (move.getToPip()<BAR && move.getToPip()>BEAR_OFF &&
checkers[opposingPlayerId][calculateOpposingPip(move.getToPip())] == 1) {
checkers[opposingPlayerId][calculateOpposingPip(move.getToPip())]--;
checkers[opposingPlayerId][BAR]++;
}
}
public void move(Player player, Play play) {
for (Move move : play) {
move(player,move);
}
}
@Override
public int getNumCheckers(int playerId, int pip) {
return checkers[playerId][pip];
}
private boolean bearOffIsLegal(Player player) {
int numberCheckersInInnerBoard=0;
for (int pip=BEAR_OFF; pip<=INNER_END; pip++) {
numberCheckersInInnerBoard = numberCheckersInInnerBoard + checkers[player.getId()][pip];
}
if (numberCheckersInInnerBoard==NUM_CHECKERS) {
return true;
} else {
return false;
}
}
private int findLastChecker(Player player) {
int pip;
for (pip=BAR; pip>=BEAR_OFF; pip--) {
if (checkers[player.getId()][pip]>0) {
break;
}
}
return pip;
}
private Plays findAllPlays(Board board, Player player, Movements movements) {
// Search recursively for the plays that are possible with a given sequence of movements
Plays plays = new Plays();
int fromPipLimit;
// must take checkers from the bar first
if (board.checkers[player.getId()][BAR] > 0) {
fromPipLimit = BAR-1;
} else {
fromPipLimit = BEAR_OFF-1;
}
// search over the board for valid moves
for (int fromPip=BAR; fromPip>fromPipLimit; fromPip--) {
if (board.checkers[player.getId()][fromPip]>0) {
int toPip = fromPip-movements.getFirst();
Move newMove = new Move();
Boolean isNewMove = false;
if (toPip>BEAR_OFF) {
// check for valid moves with and without a hit
int opposingPlayerId = players.getOpposingPlayer(player).getId();
if (board.checkers[opposingPlayerId][calculateOpposingPip(toPip)]==0) {
newMove = new Move(fromPip,toPip,false);
isNewMove = true;
} else if (board.checkers[opposingPlayerId][calculateOpposingPip(toPip)]==1) {
newMove = new Move(fromPip,toPip,true);
isNewMove = true;
}
} else {
// check for valid bear off
if (board.bearOffIsLegal(player) && (toPip==0 || (toPip<0 && board.findLastChecker(player)==fromPip))) {
newMove = new Move(fromPip,BEAR_OFF, false);
isNewMove = true;
}
}
// apply the move to the board and search for a follow on move
if (isNewMove) {
if (movements.number()>1) {
Board childBoard = new Board(players,board);
childBoard.move(player,newMove);
Movements childMovements = new Movements(movements);
childMovements.removeFirst();
Plays childPlays = findAllPlays(childBoard, player, childMovements);
if (childPlays.number()>0) {
childPlays.prependAll(newMove);
plays.add(childPlays);
} else {
plays.add(new Play(newMove));
}
} else {
plays.add(new Play(newMove));
}
}
}
}
return plays;
}
@Override
public Plays getPossiblePlays(Player player, Dice dice) {
// Search for the plays that are possible with all of the movements that can be made based on the dice
Plays possiblePlays;
Movements movements = new Movements(dice);
if (player.getDice().isDouble()) {
possiblePlays = findAllPlays(this,player,movements);
} else {
possiblePlays = findAllPlays(this,player,movements);
movements.reverse();
possiblePlays.add(findAllPlays(this,player,movements));
}
possiblePlays.removeIncompletePlays();
possiblePlays.removeDuplicatePlays();
return possiblePlays;
}
public void cheat() {
for (int player=0; player<Backgammon.NUM_PLAYERS; player++) {
for (int pip=0; pip<NUM_SLOTS; pip++) {
checkers[player][pip] = CHEAT[player][pip];
}
}
}
public boolean allCheckersOff(Player player) {
return checkers[player.getId()][BEAR_OFF] == NUM_CHECKERS;
}
public boolean hasCheckerOff(Player player) {
return checkers[player.getId()][BEAR_OFF] > 0;
}
public boolean lastCheckerInInnerBoard(Player player) {
return findLastChecker(player)<=INNER_END;
}
public boolean lastCheckerInOpponentsInnerBoard(Player player) {
return findLastChecker(player)>OUTER_END;
}
public void reset() {
for (int player=0; player<Backgammon.NUM_PLAYERS; player++) {
for (int pip=0; pip<NUM_SLOTS; pip++) {
checkers[player][pip] = RESET[pip];
}
}
}
public Plays getPossiblePlays(int playerId, Dice dice) {
return getPossiblePlays(players.get(playerId),dice);
}
public boolean lastCheckerInInnerBoard(int playerId) {
return lastCheckerInInnerBoard(players.get(playerId));
}
public boolean lastCheckerInOpponentsInnerBoard(int playerId) {
return lastCheckerInOpponentsInnerBoard(players.get(playerId));
}
public boolean allCheckersOff(int playerId) {
return allCheckersOff(players.get(playerId));
}
public boolean hasCheckerOff(int playerId) {
return hasCheckerOff(players.get(playerId));
}
} | ConorDunne/DeepBlue2 | Board.java | 2,330 | // including BAR and BEAR OFF | line_comment | en | false | 2,173 | 7 | 2,330 | 7 | 2,436 | 6 | 2,330 | 7 | 2,752 | 9 | false | false | false | false | false | true |
185057_1 | import greenfoot.*; // (World, Actor, GreenfootImage, Greenfoot and MouseInfo)
/**
* Base class for all game entities
*
* @author (your name)
* @version (a version number or a date)
*/
public abstract class Entity extends Actor
{
/**
* Initial entity location
*/
private Location initialLocation;
/**
* Sprite sheet file
*/
private String spriteSheet = "sprites.png";
/**
* Sprite block size.
*/
private int blockSize = 32;
private String name;
private String scriptObject;
/**
* Set if this entity is visible on the current world.
*/
private boolean visible;
private int x;
private int y;
public abstract void reset();
public void act() {
if(getInitialLocation() == null) {
setInitialLocation(getLocation());
}
}
public void setName(String name) {
this.name = name;
}
public String getName() {
return this.name;
}
public void setVisible(boolean visible) {
this.visible = visible;
}
public boolean isVisible() {
return this.visible;
}
public void show() {
this.visible = true;
}
public void hide() {
this.visible = false;
}
public void setScriptObject(String scriptObject) {
this.scriptObject = scriptObject;
}
public String getScriptObject() {
if (scriptObject == null) return name;
return scriptObject;
}
public void setSpriteSheet(String spriteSheet) {
this.spriteSheet = spriteSheet;
}
public String getSpriteSheet() {
return this.spriteSheet;
}
public void setBlockSize(int blockSize) {
this.blockSize = blockSize;
}
public int getBlockSize() {
return this.blockSize;
}
public void setSprite(int id) {
setImage(SpriteSheetManager.getSprite(spriteSheet, id, blockSize));
}
public void setSprite(String spriteSheet, int id, int blockSize) {
setImage(SpriteSheetManager.getSprite(spriteSheet, id, blockSize));
}
public int getX() {
if(getWorld() == null) {
return x;
}
return super.getX();
}
public int getY() {
if(getWorld() == null) {
return y;
}
return super.getY();
}
public void setX(int x) {
super.setLocation(x, getY());
this.x = x;
}
public void setY(int y) {
super.setLocation(getX(), y);
this.y = y;
}
public void setLocation(int x, int y) {
this.x = x;
this.y = y;
super.setLocation(x, y);
}
public Location getLocation() {
return new Location(getX(), getY());
}
public Location getInitialLocation() {
return this.initialLocation;
}
public void setInitialLocation(Location initialLocation) {
this.initialLocation = initialLocation;
setX(initialLocation.getX());
setY(initialLocation.getY());
}
}
| thild/wizardsdoom | Entity.java | 721 | /**
* Base class for all game entities
*
* @author (your name)
* @version (a version number or a date)
*/ | block_comment | en | false | 683 | 31 | 721 | 33 | 863 | 36 | 721 | 33 | 931 | 36 | false | false | false | false | false | true |
185382_6 | /**
* Class Item - an item in the adventure game world.
*
* This class is part of the "World of KROZ" application.
* "World of KROZ" is a very simple, text based adventure game. Users should
* try to find a lucia bun before they starve
*
* An "Item" class handles the items in the world. They extend the GameObject class and works similarly.
* Items are meant to be picked up and dropped by players.
*
* @version 2012.12.01
*/
public class Item extends GameObject{
private Player holder; // The player that holds this item.
/**
* Creates an item with a specific name and description.
*
* @param name the item's name
* @param desc the item's description
*/
public Item(String name, String desc){
super(name, desc);
this.holder = null;
}
/**
* Creates an item like normal but also specifies the holder
*
* @param name the item's name
* @param desc the item's description
* @param holder the item's holder
*/
public Item(String name, String desc, Player holder){
super(name,desc);
this.holder = holder;
}
/**
* A command method to take an item. It checks if you already have the item
*
* @param p a reference to player is sent to all commands to refer to the player who used the command
*/
@Command
public void take(Player p){
if(this.holder != p){
p.getInventory().addItem(this);
p.getCurrentRoom().getInventory().removeItem(this); //TODO: Bug if the item is inside an inventory that is not the room inventory, it is still left in the inventory.
this.holder = p;
System.out.println("You took the "+this.getName().toLowerCase());
} else {
System.out.println("You're already carrying the "+this.getName().toLowerCase());
}
}
/**
* A command method to drop an item. The item is then switched from
* the player's inventory to the room's inventory.
*
* @param p a reference to player is sent to all commands to refer to the player who used the command
*/
@Command
public void drop(Player p){
if(this.holder == p){
p.getInventory().removeItem(this);
p.getCurrentRoom().getInventory().addItem(this);
this.holder = null;
System.out.println("You dropped the "+this.getName().toLowerCase());
} else {
System.out.println("You're not holding the "+this.getName().toLowerCase());
}
}
/**
* A command method to eat an item. If a lucia bun is eaten, the player wins the game.
*
* @param p a reference to player is sent to all commands to refer to the player who used the command
*/
@Command
public void eat(Player p){
if(p.getContents().contains(this)){
System.out.println("Eating");
if(this.getName().equals("lunch") || this.getName().equals("clove of garlic")){
System.out.println("You eat the " + this.getName() + " but your hunger for lucia buns remain.");
this.holder = null;
p.getInventory().removeItem(this);
} else if(this.getName().toLowerCase().equals("luciabun") || this.getName().equals("lucia bun")){
System.out.println("You finally taste the incredible lucia bun that you've been hungering for for a long time.\n\n *** You won the game ****\n\n");
System.exit(0);
}
} else {
System.out.println("You're not holding the " + this.getName());
}
}
}
| Siretu/Zuul-game | Item.java | 952 | /**
* A command method to drop an item. The item is then switched from
* the player's inventory to the room's inventory.
*
* @param p a reference to player is sent to all commands to refer to the player who used the command
*/ | block_comment | en | false | 843 | 60 | 952 | 58 | 1,004 | 67 | 952 | 58 | 1,148 | 71 | false | false | false | false | false | true |
186589_8 | package com.red.dao;
import com.red.AppController;
import com.red.entity.DVDLibrary;
import java.io.*;
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.List;
import java.util.logging.Logger;
/**
* DVD Library data access object class
*/
public class DVDLibraryDAO implements DVDLibraryDAOI {
private static DateTimeFormatter format = DateTimeFormatter.ofPattern("dd/MM/yyyy");
private static Logger logger;
// It's a static variable that stores the list of DVDLibrary objects.
private static List<DVDLibrary> dvds;
static {
dvds = new ArrayList<>();
logger = Logger.getLogger(DVDLibraryDAO.class.getName());
}
/**
* The function takes in a title, date, MPAARating, director, studio, and userRating and adds it to the list of DVD Library
*
* @param title The title of the DVD
* @param date The date the DVD was released.
* @param MPAARating The MPAA rating of the DVD. This is a double value between 0 and 10.
* @param director The director of the movie
* @param studio The studio that produced the movie
* @param userRating The user's rating of the DVD
*/
@Override
public void addDVD(String title, String date, Double MPAARating, String director, String studio, Double userRating) {
LocalDate dt = null;
if (null != date && date.trim().length() > 0) dt = LocalDate.parse(date, format);
MPAARating = MPAARating > 10 ? 10 : MPAARating < 0 ? 0 : MPAARating;
userRating = userRating > 10 ? 10 : userRating < 0 ? 0 : userRating;
dvds.add(new DVDLibrary(id(), title, dt, MPAARating, director, studio, userRating));
logger.info("The DVD was added");
}
/**
* The function takes an id as a parameter and searches for a DVD with that id. If it finds one, it removes it from the
* list. If it doesn't find one, it logs a warning
*
* @param id the id of the DVD to be deleted
*/
@Override
public void deleteDVD(int id) {
DVDLibrary dvdLibrary = findById(id);
if (!dvdLibrary.equals(null)) {
dvds.remove(dvdLibrary);
logger.info("The DVD was successfully deleted");
} else logger.warning("There's no such DVD");
}
/**
* If the DVD exists, update it with the new values
*
* @param id the id of the DVD to be edited
* @param title The title of the DVD
* @param date The date the DVD was released
* @param MPAARating The MPAA rating of the movie.
* @param director The director of the movie
* @param studio The studio that produced the movie
* @param userRating The user's rating of the movie
*/
@Override
public void editDVD(int id, String title, String date, Double MPAARating, String director, String studio, Double userRating) {
DVDLibrary dvdLibrary = findById(id);
if (!dvdLibrary.equals(null)) {
LocalDate dt = null;
if (null != date && date.trim().length() > 0) dt = LocalDate.parse(date, format);
MPAARating = MPAARating > 10 ? 10 : MPAARating < 0 ? 0 : MPAARating;
userRating = userRating > 10 ? 10 : userRating < 0 ? 0 : userRating;
dvds.set(id, new DVDLibrary(id, title, dt, MPAARating, director, studio, userRating));
logger.info("The DVD was successfully updated");
} else logger.warning("There's no such DVD");
}
/**
* If the library is empty, print a warning message. Otherwise, print all the DVDs in the library
*/
@Override
public void showAll() {
if (dvds.isEmpty()) logger.warning("The library is empty");
else for (DVDLibrary dvdLibrary : dvds) logger.info(dvdLibrary.toString());
}
/**
* If the DVD exists, print it out. If it doesn't, print out a warning message
*
* @param title The title of the DVD to be shown.
*/
@Override
public void showDVD(String title) {
DVDLibrary dvdLibrary = findByTitle(title);
if (dvdLibrary != null) logger.info(dvdLibrary.toString());
else logger.warning("There's no such DVD");
}
/**
* > This function returns the next available id for a new DVD
*
* @return The id of the next DVD.
*/
protected int id() {
if (dvds.isEmpty()) return 0;
else return dvds.get(dvds.size() - 1).getId() + 1;
}
/**
* The function takes in an integer, and returns a DVDLibrary object
*
* @param id the id of the DVD you want to find
* @return The DVDLibrary object with the matching id.
*/
@Override
public DVDLibrary findById(int id) {
DVDLibrary dvdLibrary = dvds.stream().filter(dvd -> (id == dvd.getId())).findAny().orElse(null);
return dvdLibrary;
}
/**
* It saves the library to a file.
*/
@Override
public void toFile() {
try (ObjectOutputStream out = new ObjectOutputStream(new FileOutputStream("src/main/resources/DVDLibrary.lbb"))) {
out.writeObject(dvds);
logger.info("The library was successfully saved");
} catch (IOException exception) {
throw new RuntimeException(exception);
}
}
/**
* It reads the file and loads the data into the program.
*/
@Override
public void fromFile() {
try (ObjectInputStream in = new ObjectInputStream(new FileInputStream("src/main/resources/DVDLibrary.lbb"))) {
dvds.clear();
dvds = (ArrayList) in.readObject();
logger.info("The library was successfully loaded");
} catch (IOException e) {
throw new RuntimeException(e);
} catch (ClassNotFoundException e) {
throw new RuntimeException(e);
}
}
/**
* The function takes in a title as a string, and returns a DVDLibrary object that matches the title, or null if no
* match is found.
*
* @param title The title of the DVD you want to find.
* @return The DVDLibrary object is being returned.
*/
@Override
public DVDLibrary findByTitle(String title) {
DVDLibrary dvdLibrary = dvds.stream().filter(dvd -> (title.equals(dvd.getTitle()))).findAny().orElse(null);
return dvdLibrary;
}
/**
* This function clears the list of dvds
*/
@Override
public void clear() {
dvds.clear();
}
}
| The-Software-Guild/java-classes-objects-jjsasha63 | src/main/java/com/red/dao/DVDLibraryDAO.java | 1,694 | /**
* The function takes in an integer, and returns a DVDLibrary object
*
* @param id the id of the DVD you want to find
* @return The DVDLibrary object with the matching id.
*/ | block_comment | en | false | 1,556 | 49 | 1,694 | 50 | 1,771 | 52 | 1,694 | 50 | 1,881 | 52 | false | false | false | false | false | true |
186957_9 | package Breccia.Web.imager;
import java.net.URI;
import java.net.URISyntaxException;
import java.nio.file.Path;
import Java.Unhandled;
import java.util.logging.Logger;
import static java.lang.Math.max;
import static java.lang.System.getProperty;
import static Java.Paths.hasExtension;
import static Java.URI_References.hasExtension;
/** The present project. Included is a medley of resources,
* residual odds and ends that properly fit nowhere else.
*/
public final class Project {
private Project() {}
/** Returns for the given source path its image sibling: a namesake with a `.xht` extension.
* Assuming a path {@linkplain java.nio.file.FileSystem#getSeparator name separator} of ‘/’,
* the image sibling of `dir/foo.brec`, for example, is `dir/foo.brec.xht`.
*
* @param s A path to a source file.
*/
public static Path imageSibling( final Path s ) {
return s.resolveSibling( imageSibling( s.getFileName().toString() )); }
/** Returns for the given source reference its image sibling: a namesake with a `.xht` extension.
* The image sibling of `dir/foo.brec`, for example, is `dir/foo.brec.xht`.
*
* @param s A URI reference to a source file.
*/
public static URI imageSibling( final URI s ) { return repath( s, imageSibling( s.getPath() )); }
/** The output directory of the present project.
*/
public static final Path outputDirectory = Path.of( getProperty("java.io.tmpdir"),
"Breccia.Web.imager_" + getProperty("user.name") );
/** Returns for the given image path its source sibling: a namesake without a `.xht` extension.
* Assuming a path {@linkplain java.nio.file.FileSystem#getSeparator name separator} of ‘/’,
* the source sibling of `dir/foo.brec.xht`, for example, is `dir/foo.brec`.
*
* @param i A path to an image file.
* @throws IllegalArgumentException If the image path itself has no `.xht` extension.
*/
public static Path sourceSibling( final Path i ) {
return i.resolveSibling( sourceSibling( i.getFileName().toString() )); }
/** Returns for the given image reference its source sibling: a namesake without a `.xht` extension.
* The source sibling of `dir/foo.brec.xht`, for example, is `dir/foo.brec`.
*
* @param i A URI reference to an image file.
* @throws IllegalArgumentException If the image reference itself has no `.xht` extension.
*/
public static URI sourceSibling( final URI i ) { return repath( i, sourceSibling( i.getPath() )); }
//// P r i v a t e ////////////////////////////////////////////////////////////////////////////////////
/** Returns the image sibling of `s`, a namesake with a `.xht` extension.
* The image sibling of `dir/foo.brec`, for example, is `dir/foo.brec.xht`.
*
* @param s A URI reference or local file path to a source file. *//*
*
* Unreliable for general exposure because `s` might be given in the form of a URI reference
* that has a query or fragment component.
*/
private static String imageSibling( final String s ) { return s + ".xht"; }
/** Whether character `ch` is a mathematics delimiter.
*/
static boolean isMathDelimiter( final char ch ) {
return ch == mathInLineDelimiter || ch == mathBlockDelimiter; }
/** Whether code point `ch` is a mathematics delimiter.
*/
static boolean isMathDelimiter( final int ch ) {
return ch == mathInLineDelimiter || ch == mathBlockDelimiter; }
/** The logger proper to the present project.
*/
static final Logger logger = Logger.getLogger( "Breccia.Web.imager" );
/** Whether the given file path appears to refer to a Breccian source file.
*
* @param file The path of a file.
* @throws AssertionError If assertions are enabled and `f` is a directory.
*/
static boolean looksBrecciaLike( final Path file ) {
// assert !isDirectory( file );
//// invalid: path `file` may be relative
return hasExtension( ".brec", file ); }
/** Whether the given URI reference appears to refer to a Breccian source file.
*
* @see <a href='https://www.rfc-editor.org/rfc/rfc3986#section-4.1'>
* URI generic syntax §4.1, URI reference</a>
*/
static boolean looksBrecciaLike( final URI ref ) { return hasExtension( ".brec", ref ); }
/** Whether the given file path appears to refer to a Breccian Web image file.
*
* @param file The path of a file.
* @throws AssertionError If assertions are enabled and `file` is a directory.
*/
static boolean looksImageLike( final Path file ) {
// assert !isDirectory( file );
//// invalid: path `file` may be relative
return hasExtension( ".brec.xht", file ); }
/** Whether the given URI reference appears to refer to a Breccian Web image file.
*
* @see <a href='https://www.rfc-editor.org/rfc/rfc3986#section-4.1'>
* URI generic syntax §4.1, URI reference</a>
*/
static boolean looksImageLike( final URI ref ) { return hasExtension( ".brec.xht", ref ); }
/** The delimiter for mathematics to be rendered in block (aka display) form.
*/
final static int mathBlockDelimiter = '・'; // Halfwidth katakana middle dot (FF65).
// Changing? Sync → `MathJax_configuration.js`.
/** The delimiter for mathematics to be rendered in-line.
*/
final static int mathInLineDelimiter = '\u2060'; // Word joiner.
// Changing? Sync → `MathJax_configuration.js`.
/** Returns the source sibling of `i`, a namesake without a `.xht` extension.
* The source sibling of `dir/foo.brec.xht`, for example, is `dir/foo.brec`.
*
* @param i A URI reference or local file path to an image file. *//*
* @throws IllegalArgumentException If `i` itself has no `.xht` extension.
*
* Unreliable for general exposure because `i` might be given in the form of a URI reference
* that has a query or fragment component.
*/
private static String sourceSibling( final String i ) {
if( !i.endsWith( ".xht" )) throw new IllegalArgumentException();
return i.substring( 0, i.length() - ".xht".length() ); }
/** Swaps into `u` the given path and returns the result.
*/
private static URI repath( final URI u, final String path ) {
try {
return new URI( u.getScheme(), u.getAuthority(), path, u.getQuery(), u.getFragment() ); } /*
With decoding (as opposed to raw) getters, as stipulated in (and above) § Identities:
`https://docs.oracle.com/en/java/javase/18/docs/api/java.base/java/net/URI.html` */
catch( URISyntaxException x ) { throw new Unhandled( x ); }}
// Unexpected with a reconstruction of this sort.
/** Returns `max( index, 0 )`, so translating to zero any index of -1.
*/
static int zeroBased( final int index ) { return max( index, 0 ); }}
// Copyright © 2020, 2022, 2024 Michael Allan. Licence MIT.
| Michael-Allan/Breccia.Web.imager | Project.java | 1,853 | /** Whether character `ch` is a mathematics delimiter.
*/ | block_comment | en | false | 1,729 | 13 | 1,853 | 14 | 1,951 | 14 | 1,853 | 14 | 2,163 | 14 | false | false | false | false | false | true |
189576_35 | import java.util.Scanner;
import java.util.ArrayList;
/** The class VM_Slot represents an abstract slot of the VM
*
* @author Paul Josef P. Agbuya
* @author Vince Kenneth D. Rojo
* @version 1.0
*/
public abstract class VM_Slot {
/**
* This instructor Initializes a slot's item and capacity based on the given parameters.
* Every slot can contain only one actual copy of the item it is set to hold
*
* @param capacity the maximum no. of items that this slot can hold
*/
public VM_Slot(int capacity){
storedProfit = 0.0;
slotItemName = null;
items = null;
copy_stockCount = 0;
price = 0.0;
slotItemSold = 0;
if(capacity >= 10)
MAX = capacity;
else
MAX = 10;
}
/**
* This copy constructor initializes itself with another VM_Slot and inherit
* its attributes and data.
*
* @param copy another VM_Slot object
*
*/
public VM_Slot(VM_Slot copy)
{
slotItemSold = copy.getSlotItemSold();
storedProfit = copy.getStoredProfit();
// Sets the item as a new item copy to be assigned as the attribute of this slot
if( copy.getSlotItemStock() > 0 )
{
slotItemName = new String( copy.getSlotItemName() );
price = copy.getPrice();
}
else
{
slotItemName = new String( "N/A" );
price = 0.0;
}
copy_stockCount = copy.getSlotItemStock();
// Slot should have at least 10 capacity for items
if(copy.getMAX() >= 10)
MAX = copy.getMAX();
else
MAX = 10;
}
/**
* Instructs slot to hold a different item, or even another of the same item
*
* @param givenItem the new item replacing the slot's original item
* @param qty the initial stock count of the new item
*/
public void replaceStock(VM_Item givenItem)
{
if(givenItem != null)
{
items = new ArrayList<VM_Item>();
items.add( givenItem );
slotItemName = new String(givenItem.getItemName());
}
repriceItem( givenItem.getItemPrice() );
}
/**
* Checks whether this slot contains the desired number of its item or more
*
* @param qty the desired number of pieces of the item
* @return true if slot contain the desired quantity of items, false otherwise
*/
public boolean hasEnoughStock(int qty) {
if( items != null &&
getSlotItemStock() >= 0 &&
qty >= 0 &&
qty <= getSlotItemStock() )
return true;
return false;
}
/**
* Computes for that fraction of the total cost
* contributed by the desired number of items from this slot
*
* @param qty the desired quantity of items
* @return the total cost of desired number of items from this slot
*/
public double computePartialCost(int qty)
{
double sum = 0.0;
sum = getPrice() * qty;
return sum;
}
/**
* Tells slot to "release" a certain quantity of its item,
* which in the current design of this program
* simply means increasing or decreasing the stock counter
*
* @param qty the number of items to be released from this slot
*/
public void releaseStock(int qty)
{
int i;
/* Only release stock if there is enough of it to release */
if( items != null && hasEnoughStock(qty) )
{
for(i = 0; i < qty; i++)
items.remove(0);
storedProfit += getPrice() * qty;
slotItemSold += qty;
}
}
/**
* Gets the name of this slot
*
* @return the String name of the slot
*/
public String getSlotItemName()
{
return slotItemName;
}
/**
* Gets the stock count of items in the slot
*
* @return the number of items currently in this slot
*/
public int getSlotItemStock()
{
if( items != null )
return items.size();
return 0;
}
/**
* Gets the maximum number of items that this slot can hold
*
* @return the maximum capacity of this slot
*/
public int getMAX()
{
return MAX;
}
/**
* Displays the information of the item currently held by this slot,
* as well as the stock count.
*
*/
public void displayAllItems()
{
if (getSlotItemStock() > 0)
{
System.out.println("Qty: " + getSlotItemStock());
System.out.println(items.get(0) + "\n");
}
else
System.out.println(slotItemName + " slot is empty.\n");
}
/**
* Adds to the stock count of this slot if givenItem
* has the the same name as the currently held item,
* but sets the stock count and replaces the currently held item
* with givenItem if the two items have different names.
*
* @param givenItem the given type of item to be added
* @param qty the quantity of objects
*/
public void addItemStock( VM_Item givenItem )
{
Scanner sc = new Scanner(System.in);
// Error that there was no stock added
if( givenItem == null )
System.out.println("\033[1;38;5;202mERROR! no stocks/item is detected\033[0m");
// State and excess and return it
else if( 1 + getSlotItemStock() > MAX && givenItem.getItemName().equalsIgnoreCase(slotItemName) ) {
System.out.println("You had an excess of " + 1 + " " +givenItem.getItemName() + " while we were stocking. Returning...");
System.out.println("\033[1;33m" + "Press and Enter Any Key To Continue..." + "\033[0m");
sc.nextLine();
}
// If slot was initialized empty, proceed to put in stock
if( items == null || getSlotItemStock() == 0 )
replaceStock( givenItem );
// Skips conditional construct if restocker is empty
else if( givenItem == null );
// If the slot is not empty, then proceed to add the stock
else if( givenItem.getItemName().equalsIgnoreCase(slotItemName) && (getSlotItemStock()+1) <= MAX )
{
givenItem.setPrice( getPrice() );
items.add( givenItem );
}
// if this slot already has an item, but has a different name
else
warnReplace( givenItem );
sc = null;
}
/**
* Adds to the stock count of this slot, if not yet at maximum capacity
*
* @param qty the number to add to stock counter attribute
* @return true if qty is 1 or greater, false otherwise
*/
/*
public boolean addItemStock(int qty)
{
Scanner sc = new Scanner(System.in);
// Add item only if this slot contains no item
if(item == null)
{
System.out.println("\033[1;38;5;202mERROR! no stocks/item is detected\033[0m");
sc = null;
return false;
}
// Set stock to max if there was an excess
else if(qty + slotItemStock > MAX)
{
System.out.println("You have an excess of " + (qty+slotItemStock- MAX) + " " + slotItemName + " while we were stocking. Returning...");
System.out.println("\033[1;33m" + "Press and Enter Any Key To Continue..." + "\033[0m");
sc.nextLine();
slotItemStock = MAX;
}
// Add item
else
slotItemStock += qty;
sc = null;
return true;
}
*/
/**
* This method Sets the price of the item object held by this slot
*
* @param amt the new price of the item
*/
public void repriceItem(double amt)
{
int i;
if(amt < 0.5) // minimum price of an item is 50 Cents
amt = 0.5;
for(i = 0; i < items.size(); i++)
items.get(i).setPrice(amt);
price = amt;
}
/**
* Gets how many items have been sold
* by this slot since last restocking
*
* @return the number of items sold by this slot since last restocking
*/
public int getSlotItemSold() {
return slotItemSold;
}
/**
* Sets the number of items sold
* by this slot since the last restocking
*
* @param slotItemSold the new number of items sold by this slot since last restocking
*/
public void setSlotItemSold(int slotItemSold)
{
this.slotItemSold = slotItemSold;
}
/**
* Gets the amount of profit generated
* by this slot since last restocking
*
* @return the profit made by the slot thus far
*/
public double getStoredProfit()
{
return storedProfit;
}
/**
* This method resets the stored profit back to 0.0
*
*
*/
public void clearStoredProfit()
{
storedProfit = 0.0;
}
/**
* Informs user of restocking conflict,
* asks user to choose whether or not to replace currently stocked item(s)
* with the new givenItem
*
* @param givenItem the new item to be held by this slot
* @param stock the initial stock count of the new item
*/
private void warnReplace( VM_Item givenItem )
{
Scanner sc = new Scanner(System.in);
System.out.println("\033[1;33mConflict with another type of item\033[0m, will you be replacing this stock of " + slotItemName +
" with " + givenItem.getItemName() + ". (Y/N)");
// Only proceed to replace when user agrees
if(sc.nextLine().equalsIgnoreCase("Y"))
{
System.out.println("Replaced " + slotItemName + " with " + givenItem.getItemName());
replaceStock( givenItem );
}
sc = null;
}
public double getPrice() { return price; }
public ArrayList<VM_Item> getItems() { return items; }
/** the item held by this slot */
private VM_Item item;
/** the number of items sold by this slot since last restocking or repricing */
private int slotItemSold;
/** the slot's item name */
private String slotItemName;
/** the stock count of the slot from which this slot was copied */
private int copy_stockCount;
/** profit that this slot has collected */
private double storedProfit;
/** max capacity of this slot */
private final int MAX;
/** the per piece price of the items */
private double price;
/** the items in this slot */
private ArrayList<VM_Item> items;
} | pjagbuya/CCPROG3-MCO2 | VM_Slot.java | 2,716 | /** profit that this slot has collected */ | block_comment | en | false | 2,605 | 8 | 2,716 | 8 | 3,137 | 8 | 2,716 | 8 | 3,469 | 8 | false | false | false | false | false | true |
190786_6 | package a4.domain;
public class Street extends Property {
private int houseCount = 0;
private int hotelCount = 0;
private int[] rent;
private Neighborhood neighborhood;
private String color;
public Street(String name, int value, int[] rent, String color) {
super(name, value, PropertyType.STREET);
this.color = color;
this.rent = rent;
}
public int getHouseCount() {
return houseCount;
}
public void setHouseCount(int houseCount) {
this.houseCount = houseCount;
}
public int getHotelCount() {
return hotelCount;
}
public void setHotelCount(int hotelCount) {
this.hotelCount = hotelCount;
}
public Neighborhood getNeighborhood() {
return neighborhood;
}
public String getColor() {
return color;
}
public void addHouse() {
if (hotelCount >= 1) {
} else if (houseCount < 4)
houseCount++;
else if (hotelCount == 0) {
houseCount = 0;
hotelCount = 1;
}
}
// returns rent based on total house and hotel count
@Override
public int getRent(int diceRoll) {
if (houseCount > 0)
return rent[houseCount];
else if (hotelCount > 0)
return rent[hotelCount * 5];
else if (houseCount == 0 && hotelCount == 0 && neighborhood.getOwner() != null
&& neighborhood.getOwner().equals(owner))
return rent[0] * 2;
else
return rent[0];
}
// removes house from street
public void removeHouse() {
if (houseCount > 0)
houseCount--;
else if (hotelCount > 0 && houseCount == 0) {
hotelCount = 0;
houseCount = 4;
}
}
// sets n as street's neighborhood
public void addToNeighborhood(Neighborhood n) {
neighborhood = n;
}
// returns 1 if street is developable, 0 otherwise
@Override
public int isDevelopable() {
if (isMortgaged) {
return 1;
} else if (hotelCount == 1) {
return -1;
} else if (neighborhood.hasOwner()) {
if (neighborhood.streetNeedsUnmortgaged()) {
return -1;
} else if (houseCount < neighborhood.getMaxNumHouses()) {
return 1;
} else {
return -1;
}
} else {
return -1;
}
}
// returns 1 if street was unMortgaged, 2 if a house was bought, and -1 if
// developing failed.
@Override
public int develop(Bank bank) {
if (isMortgaged) {
if (unmortgage(bank) == 1) {
return 1;
} else {
return -1;
}
} else if (houseCount < 4 && bank.canRemoveHouse()) {
if (neighborhood.addHouse(this)) {
owner.transferMoney(bank, neighborhood.getHouseValue());
bank.removeHouse();
return 2;
} else {
return -1;
}
} else if (houseCount == 4 && bank.canRemoveHotel()) {
if (neighborhood.addHouse(this)) {
owner.transferMoney(bank, neighborhood.getHouseValue());
bank.removeHotel();
return 2;
} else {
return -1;
}
} else {
return -1;
}
}
// sells house or mortgages house if street can be undeveloped, -1 otherwise
public int undevelop(Bank bank) {
int undevelopingValue = -1;
if (isMortgaged) {
return undevelopingValue;
} else if (hotelCount == 1 && bank.canAddHotel()) {
if (neighborhood.removeHouse(this)) {
undevelopingValue = sellHouse(bank);
bank.addHotel();
return undevelopingValue;
} else {
return undevelopingValue;
}
} else if (houseCount > 0) {
if (neighborhood.removeHouse(this)) {
undevelopingValue = sellHouse(bank);
bank.addHouse();
return undevelopingValue;
} else {
return undevelopingValue;
}
} else if (neighborhood.numHousesEqual() && houseCount == 0 && hotelCount == 0) {
return mortgage(bank);
} else {
return -1;
}
}
// returns half the value of the street if bank has enough funds, balance of
// bank otherwise
private int sellHouse(Bank bank) {
return bank.transferMoney(owner, neighborhood.getHouseValue() / 2);
}
public String toString() {
return super.toString() + " \nRent: " + getRent(0) + " Number of Houses: " + houseCount + " Number of Hotels: "
+ hotelCount;
}
}
| sadielise/CS414Project | src/a4/domain/Street.java | 1,314 | // sells house or mortgages house if street can be undeveloped, -1 otherwise | line_comment | en | false | 1,149 | 17 | 1,314 | 20 | 1,280 | 15 | 1,314 | 20 | 1,603 | 21 | false | false | false | false | false | true |
190862_3 | import greenfoot.*; // (World, Actor, GreenfootImage, Greenfoot and MouseInfo)
/**
* Write a description of class Lives here.
*
* @author (your name)
* @version (a version number or a date)
*/
public class Lives extends Actor
{
/**
* Act - do whatever the Lives wants to do. This method is called whenever
* the 'Act' or 'Run' button gets pressed in the environment.
*/
public void act()
{
// Add your action code here.
}
private String text;
private int points;
//sets the value of points to zero
//sets the images colour to white
//displays the image
public Lives()
{
points =3;
GreenfootImage img = new GreenfootImage(100,30);
img.setColor(Color.WHITE);
img.drawString("Lives: " + points, 5,25);
setImage(img);
}
//add to the value of the integer points
// if the value of points is greater than 0, the value of points increses
// if the value of points is 0 "you Lose' is displayed and the game ends.
public void addToLives()
{
points++;
GreenfootImage img = getImage();
img.clear();
// if(points >0) {
img.drawString("Lives: " + points, 5,25);
/*else {
//Greenfoot.playSound("fanfare.wav");
img.drawString("You Lose!!!", 5,25);
Greenfoot.stop();
//getWorld().addObject( Won(), 600,325);
} */
}
// subtracts from the value of lives
//displays updated value.
public void removeLives()
{
points --;
GreenfootImage img = getImage();
img.clear();
img.drawString("Lives: " + points, 5,25);
if(points >0) {
img.drawString("Lives: " + points, 5,25);
} else {
//Greenfoot.playSound("fanfare.wav");
img.drawString("You Lose!!!", 5,25);
Greenfoot.stop();
//getWorld().addObject( Won(), 600,325);
}
}
}
| sophiaabolore/Marvel-Galaxy-Battle | Lives.java | 560 | // Add your action code here.
| line_comment | en | false | 527 | 8 | 560 | 8 | 612 | 7 | 560 | 8 | 654 | 7 | false | false | false | false | false | true |
190913_5 | import greenfoot.*; // (World, Actor, GreenfootImage, Greenfoot and MouseInfo)
/**
* Score bar to keep track of all the variables such as; rocks, food, wood, gold,
* population, day, status, and average age.
*
* @author Mr.Cohen
* @version 2018-10-24
*/
public class Scorebar extends Actor
{
private GreenfootImage bg;
private int timer;
private int money, round, lives;
private String level;
/**
* Constructs a score bar that fits at the top of the screen
*/
public Scorebar()
{
//set the image size
bg = new GreenfootImage(130,100);
}
/**
* Updates values when added to the world
* @param w The world it is being added to
*/
public void addedToWorld(World w)
{
//display the bars
displayStats();
}
/**
* Updates the top bar with all the resources and statistics from the world
*/
public void displayStats()
{
bg.clear();
String display = "";
money = ((MyWorld)getWorld()).getMoney();//get world statistics
round = ((MyWorld)getWorld()).getRound();
lives = ((MyWorld)getWorld()).getLives();
if(((MyWorld)getWorld()).getMaxRounds() != -1)
display = "\u2665" + lives + "\n"+"$" + money + "\n"+"Round: " + round + "/" + ((MyWorld)getWorld()).getMaxRounds();
else
display = "\u2665" + lives + "\n"+"$" + money + "\n"+"Round: " + round;
GreenfootImage text = new GreenfootImage(display, 22 , Color.BLACK, null);
bg.drawImage(text, 10 , 0);
bg.setTransparency(180);
setImage(bg);
}
/**
* Updates scorebar every 8 acts to reduce lag.
*/
public void act()
{
//timer increase
timer++;
//update every 8 frames
if(timer %10==0)
displayStats();
}
} | kevinbiro99/Tower-Defence | Scorebar.java | 504 | //display the bars | line_comment | en | false | 491 | 4 | 504 | 4 | 545 | 4 | 504 | 4 | 587 | 4 | false | false | false | false | false | true |
191019_5 | /**
*
* Class was designed to build a Currency containing three basic details
*
* @author Ethan Moistner
*
*
*/
public class Currency {
private String Name;
private Double Ratio;
private String CurrencyCode;
/**
* Class Constructor specifying Name, ratio, and code.
*
* @param Name
* Name of the Currency
* @param Ratio
* Exchange rate of the Currency compared to the US Dollar
* @param CurrencyCode
* Three letter Code that refers to the Currency
*/
public Currency(String Name, Double Ratio, String CurrencyCode) {
this.Name = Name;
this.Ratio = Ratio;
this.CurrencyCode = CurrencyCode;
}
/**
* Getter for Ratio
*
* @return the ratio of the specified Currency
*/
public Double getRatio() {
return Ratio;
}
/**
* Setter for Ratio
*
* @param newRatio
* New Ratio for the specified Currency
*/
public void setRatio(Double newRatio) {
Ratio = newRatio;
}
/**
* Getter for Name of the specified Currency
*
* @return the name for the specified Currency
*/
public String getName() {
return Name;
}
/**
* Setter for name of the specified Currency
*
* @param newName
* replaces the current name with NewName
*/
public void setName(String newName) {
Name = newName;
}
public String getCurrencyCode() {
return CurrencyCode;
}
public void setCurrencyCode(String newCurrencyCode) {
CurrencyCode = newCurrencyCode;
}
public String toString() {
return Name;
}
}
| emmoistner/CurrencyConverter | Currency.java | 419 | /**
* Setter for name of the specified Currency
*
* @param newName
* replaces the current name with NewName
*/ | block_comment | en | false | 374 | 33 | 419 | 29 | 443 | 36 | 419 | 29 | 516 | 39 | false | false | false | false | false | true |
191295_8 | package org.androiddaisyreader.model;
import java.io.IOException;
import java.util.ArrayList;
public class DaisySection extends Section {
public DaisySection() {
// Use the Builder... not me...
}
public String getSmilFilename() {
String[] values = splitHref(href);
String smilFilename = values[0];
return isSmilFilenameValid(smilFilename) ? smilFilename : null;
}
/**
* Splits a Smil href. The href should be into 2 parts, the filename and the
* id used to locate elements.
*
* @return an array of string values split on the separator "#"
*/
private String[] splitHref(String href) {
return href.split("#");
}
/**
* Gets the parts.
*
* @param isDaisyFormat202 the is daisy format202 otherwise is daisy format
* @return the parts
*/
public Part[] getParts(boolean isDaisyFormat202) {
try {
if (isDaisyFormat202) {
return Smil10Specification.getParts(bookContext,
bookContext.getResource(getSmilFilename()));
} else {
return Smil30Specification.getParts(bookContext,
bookContext.getResource(getSmilFilename()));
}
} catch (IOException e) {
// TODO 20120301 jharty: refactor once I've sorted out the custom
// exceptions
throw new RuntimeException(e);
}
}
public boolean hasParts() {
return false;
}
/**
* Checks if the SmilHref seems Valid
*
* @param href in the format filename.smil#id
* @return true if the SmilHref seems valid, else false.
*/
private boolean isSmilHrefValid(String href) {
String[] values = splitHref(href);
if (values.length != 2) {
return false;
}
if (!isSmilFilenameValid(values[0])) {
return false;
}
// We can add more checks here. For now declare victory.
return true;
}
/**
* Simple helper method to validate the smil filename.
*
* We can enhance this to suit our needs.
*
* @param smilFilename
* @return true if the filename seems to represent a smil file, else false.
*/
public boolean isSmilFilenameValid(String smilFilename) {
if (smilFilename.endsWith(".smil")) {
return true;
}
return false;
}
public static class Builder {
private DaisySection newInstance = new DaisySection();
public Builder() {
newInstance.navigables = new ArrayList<Navigable>();
}
public Builder addSection(Section section) {
newInstance.navigables.add(section);
return this;
}
public Builder setLevel(int level) {
// Consider adding logic to protect the integrity of this Section
newInstance.level = level;
return this;
}
public Builder setParent(Navigable parent) {
newInstance.parent = parent;
return this;
}
public Builder setContext(BookContext context) {
newInstance.bookContext = context;
return this;
}
public Builder setTitle(String title) {
newInstance.title = title;
return this;
}
public DaisySection build() {
return newInstance;
}
public int getLevel() {
return newInstance.level;
}
public Builder setId(String id) {
newInstance.id = id;
return this;
}
public Builder setHref(String href) {
if (newInstance.isSmilHrefValid(href)) {
newInstance.href = href;
return this;
} else {
throw new IllegalArgumentException(String.format(
"Smil Filename [%s] seems invalid", href));
}
}
}
}
| julianharty/new-android-daisy-reader | daisy-engine/src/org/androiddaisyreader/model/DaisySection.java | 898 | // Consider adding logic to protect the integrity of this Section | line_comment | en | false | 835 | 11 | 898 | 11 | 990 | 11 | 898 | 11 | 1,099 | 11 | false | false | false | false | false | true |
192500_18 | package HW6;
/**
* @author Scotty
*/
import java.lang.reflect.Array;
import java.util.Random;
import java.util.Vector;
public class Driver{
//stuff to calculate TIME,AVG, and SD
public static long [] nums;
//create random to be used for creation of contacts
static Random rand = new Random();
//Make an empty vector, empty binary search tree of Person objects, and a tree iterator
//with my binary search tree passed into it
public static Vector<Person> myVector = new Vector<Person>();
public static BinarySearchTree<Person, ?> myTree = new BinarySearchTree();
public static TreeIterator<Person> bst = new TreeIterator<Person>(myTree);
private static int size = 0;
public static int size() {
return size;
}
public static String randomName() {
String[] alphabet = { "a", "b", "c", "d", "e", "f", "g", "h", "i", "j",
"k", "l", "m", "n", "o", "p", "q", "r", "s", "t", "u", "w",
"x", "y", "z" };
String name = "";
for (int i = 0; i < 6; i++) {
name += alphabet[rand.nextInt(25)];
}
return name;
}
// generate random numbers in form xxx-xxx-xxxx
public static String randomPhone() {
String phone = "";
while (phone.length() < 12) {
if (phone.length() == 3 || phone.length() == 7) {
phone += "-";
}
phone += rand.nextInt(9);
}
return phone;
}
public static void generatePersons(int amount) {
String name;
String phone;
Person person;
for (int i = 0; i < amount; i++) {
name = randomName();
phone = randomPhone();
person = new Person(name, phone);
myVector.add(person);
size++;
}
}
public static void display(Vector myVector) {
for (int i = 0; i < myVector.size(); i++) {
System.out.println("The value: " + myVector.get(i));
}
}
/**
* Method which balances the tree by using an iterator to iterate properly the passed in BinaryTree.
* Takes binary tree and creates a new organized tree with use of a Vector
* @param swag
*/
public static void balanceTree(BinarySearchTree<Person, ?> swag){
// This method should balance the tree if necessary.
BinarySearchTree<Person, ?> balance = new BinarySearchTree();
TreeIterator<Person> myIter = new TreeIterator<Person>(balance);
Vector<Person> newVector = new Vector<Person>();
TreeIterator<Person> bst = new TreeIterator<Person>(myTree);
TreeNode<Person> node;
//reorganize the vector in a new vector
bst.setInorder();
while (bst.hasNext()) {
newVector.add(bst.next());
}
int first = 0;
int last = newVector.size();
node = swag.balanceTree(newVector, first, last);
balance.root = node;
TreeIterator<Person> prac = new TreeIterator<Person>(balance);
while(prac.hasNext()){
System.out.println("The new tree: " + prac.next());
}
System.out.println("success!");
//find middle value and make root of tree then insert all values
}
public static void search(){
Person temp = null;
for(int i =0; i<myVector.size();i++){
while(bst.hasNext()){
temp = bst.next();
if(temp.getName() == myVector.get(i).getName()){
System.out.println("Found element: " + temp);
}
}
}
}
public static long timeStuff(long start, long finish){
long time;
time = finish - start;
return time;
}
public static void main(String[] args) {
long start;
long finish;
//create 131,071 contacts
System.out.println("TestCase 1: create 131,071 contacts");
generatePersons(3);
System.out.println();
//displayed my vector to check to see if it worked
System.out.println("TestCase 2:");
display(myVector);
System.out.println();
//created a bst and pass everything in myVector into it
// insert entries into BST
System.out.println("TestCase 3: Insert into BST");
start = System.nanoTime();
for (int i = 0; i < myVector.size(); i++) {
myTree.insert(myVector.get(i));
}
finish = System.nanoTime();
System.out.println();
//use iterator to display 1st 1000 using inorder traversal
System.out.println("TestCase 4:");
start = System.nanoTime();
bst.setInorder();
int number = 0;
while (bst.hasNext()) {
System.out.println("In tree " + number + ": " + bst.next());
number++;
}
finish = System.nanoTime();
System.out.println();
//measure and display height of tree
System.out.println("TestCase 5:");
start = System.nanoTime();
System.out.println("The height is: " + myTree.treeHeight());
finish = System.nanoTime();
System.out.println();
//Balance the BinarySearchTree<Person>.
System.out.println("TestCase 6:");
boolean isBalanced = myTree.isBalanced();
System.out.println("Balance: " + isBalanced);
start = System.nanoTime();
balanceTree(myTree);
finish = System.nanoTime();
isBalanced = myTree.isBalanced();
System.out.println("After balance method: " + myTree.treeHeight());
System.out.println();
//Search your BinarySearchTree<Person> for all the Person entries in your Vector<Person>.
System.out.println("TestCase 7:");
start = System.nanoTime();
search();
finish = System.nanoTime();
System.out.println();
//Use the TreeIterator<Person> to display the first 1000 entries using inOrder traversal
System.out.println("TestCase 8:");
start = System.nanoTime();
bst.setInorder();
int count = 0;
while(bst.hasNext() && count<1000){
System.out.println(bst.next());
count++;
}
finish = System.nanoTime();
System.out.println();
//Measure and display the height of the BinarySearchTree<Person>.
System.out.println("TestCase 9:");
start = System.nanoTime();
System.out.println("The height is: " + myTree.treeHeight());
finish = System.nanoTime();
System.out.println();
}
}
| Hitscotty/Binary-Search-Tree | Driver.java | 1,825 | //Use the TreeIterator<Person> to display the first 1000 entries using inOrder traversal
| line_comment | en | false | 1,528 | 22 | 1,825 | 23 | 1,912 | 23 | 1,825 | 23 | 2,244 | 24 | false | false | false | false | false | true |
192758_8 | import java.awt.*;
/**
* Created by chales on 11/6/2017.
*/
public class Satellite {
//VARIABLE DECLARATION SECTION
//Here's where you state which variables you are going to use.
public int xpos; //the x position
public int ypos; //the y position
public boolean isAlive; //a boolean to denote if the hero is alive or dead.
public int dx; //the speed of the hero in the x direction
public int dy; //the speed of the hero in the y direction
public int width;
public int height;
public Image pic;
public Rectangle rec; //declare a rectangle variable
// METHOD DEFINITION SECTION
// Constructor Definition
// A constructor builds the object when called and sets variable values.
public Satellite(int xParameter, int yParameter)
{
xpos = xParameter;
ypos = yParameter;
dx=-1;
dy=2;
isAlive=true;
width = 40;
height=40;
rec= new Rectangle (xpos,ypos,width,height); //construct a rectangle
} // constructor
public Satellite(int xParameter, int yParameter, Image picParameter)
{
xpos = xParameter;
ypos = yParameter;
dx=-1;
dy=2;
isAlive=true;
width = 40;
height=40;
pic = picParameter;
rec= new Rectangle (xpos,ypos,width,height); //construct a rectangle
} // constructor
//The move method. Everytime this is run (or "called") the hero's x position and y position change by dx and dy
public void move()
{
xpos = xpos + dx;
ypos = ypos + dy;
if(xpos>1000)
{
dx= -dx;
}
if(xpos<0)
{
dx= -dx;
}
if(ypos>700)
{
dy=-dy;
}
if(ypos<0)
{
dy=-dy;
}
//always rebuild or update the rectangle after you've changed an object's position, height or width
rec= new Rectangle (xpos,ypos,width,height); //construct a rectangle
}
}
| killiam-cs/4.1_Sound_Version_2 | src/Satellite.java | 544 | //declare a rectangle variable | line_comment | en | false | 523 | 5 | 544 | 5 | 586 | 5 | 544 | 5 | 670 | 6 | false | false | false | false | false | true |
192811_0 | import javax.imageio.ImageIO;
import javax.swing.*;
import java.awt.*;
import java.io.IOException;
class MenuScreen extends Screen {
private JLabel whereTo = new JLabel();
private JLabel tripComputer = new JLabel();
private JLabel map = new JLabel();
private JLabel speech = new JLabel();
private JLabel satellite = new JLabel();
private JLabel about = new JLabel();
private String selectedItem;
MenuScreen(ScreenManager sm) {
super(sm);
setLayout(null);
setBackground(Color.BLACK);
//Creates the whereTo image (Default Selected)
whereTo.setIcon(new ImageIcon(this.getClass().getResource("images/whereTo_selected.png")));
whereTo.setBounds(87, 224, 100, 72);
add(whereTo);
selectedItem = "whereTo";
//Creates the tripComputer image
tripComputer.setIcon(new ImageIcon(this.getClass().getResource("images/tripComputer.png")));
tripComputer.setBounds(182, 224, 90, 72);
add(tripComputer);
//Creates the map image
map.setIcon(new ImageIcon(this.getClass().getResource("images/map.png")));
map.setBounds(87, 301, 90, 72);
add(map);
//Creates the speech image
speech.setIcon(new ImageIcon(this.getClass().getResource("images/speech.png")));
speech.setBounds(182, 301, 90, 72);
add(speech);
//Creates the satellite image
satellite.setIcon(new ImageIcon(this.getClass().getResource("images/satellite.png")));
satellite.setBounds(87, 378, 90, 72);
add(satellite);
//Creates the about image
about.setIcon(new ImageIcon(this.getClass().getResource("images/about.png")));
about.setBounds(182, 378, 90, 72);
add(about);
}
@Override
void showScreen() {
}
@Override
void plus() {
try {
switch (selectedItem) {
case "whereTo": {
whereTo.setIcon(new ImageIcon(ImageIO.read(this.getClass().getResource("images/whereTo.png"))));
tripComputer.setIcon(new ImageIcon(ImageIO.read(this.getClass().getResource("images/tripComputer_selected.png"))));
selectedItem = "tripComputer";
break;
}
case "tripComputer": {
tripComputer.setIcon(new ImageIcon(ImageIO.read(this.getClass().getResource("images/tripComputer.png"))));
map.setIcon(new ImageIcon(ImageIO.read(this.getClass().getResource("images/map_selected.png"))));
selectedItem = "map";
break;
}
case "map": {
map.setIcon(new ImageIcon(ImageIO.read(this.getClass().getResource("images/map.png"))));
speech.setIcon(new ImageIcon(ImageIO.read(this.getClass().getResource("images/speech_selected.png"))));
selectedItem = "speech";
break;
}
case "speech": {
speech.setIcon(new ImageIcon(ImageIO.read(this.getClass().getResource("images/speech.png"))));
satellite.setIcon(new ImageIcon(ImageIO.read(this.getClass().getResource("images/satellite_selected.png"))));
selectedItem = "satellite";
break;
}
case "satellite": {
satellite.setIcon(new ImageIcon(ImageIO.read(this.getClass().getResource("images/satellite.png"))));
about.setIcon(new ImageIcon(ImageIO.read(this.getClass().getResource("images/about_selected.png"))));
selectedItem = "about";
break;
}
case "about": {
about.setIcon(new ImageIcon(ImageIO.read(this.getClass().getResource("images/about.png"))));
whereTo.setIcon(new ImageIcon(ImageIO.read(this.getClass().getResource("images/whereTo_selected.png"))));
selectedItem = "whereTo";
break;
}
}
} catch (IOException e) {
e.printStackTrace();
}
}
@Override
void minus() {
try {
switch (selectedItem) {
case "about": {
about.setIcon(new ImageIcon(ImageIO.read(this.getClass().getResource("images/about.png"))));
satellite.setIcon(new ImageIcon(ImageIO.read(this.getClass().getResource("images/satellite_selected.png"))));
selectedItem = "satellite";
break;
}
case "satellite": {
satellite.setIcon(new ImageIcon(ImageIO.read(this.getClass().getResource("images/satellite.png"))));
speech.setIcon(new ImageIcon(ImageIO.read(this.getClass().getResource("images/speech_selected.png"))));
selectedItem = "speech";
break;
}
case "speech": {
speech.setIcon(new ImageIcon(ImageIO.read(this.getClass().getResource("images/speech.png"))));
map.setIcon(new ImageIcon(ImageIO.read(this.getClass().getResource("images/map_selected.png"))));
selectedItem = "map";
break;
}
case "map": {
map.setIcon(new ImageIcon(ImageIO.read(this.getClass().getResource("images/map.png"))));
tripComputer.setIcon(new ImageIcon(ImageIO.read(this.getClass().getResource("images/tripComputer_selected.png"))));
selectedItem = "tripComputer";
break;
}
case "tripComputer": {
tripComputer.setIcon(new ImageIcon(ImageIO.read(this.getClass().getResource("images/tripComputer.png"))));
whereTo.setIcon(new ImageIcon(ImageIO.read(this.getClass().getResource("images/whereTo_selected.png"))));
selectedItem = "whereTo";
break;
}
case "whereTo": {
whereTo.setIcon(new ImageIcon(ImageIO.read(this.getClass().getResource("images/whereTo.png"))));
about.setIcon(new ImageIcon(ImageIO.read(this.getClass().getResource("images/about_selected.png"))));
selectedItem = "about";
break;
}
}
} catch (IOException e) {
e.printStackTrace();
}
}
@Override
void menu() {
//Do nothing, Disabled
}
@Override
void select() {
switch (selectedItem) {
case "whereTo": {
System.out.println("Where To clicked");
break;
}
case "tripComputer": {
System.out.println("Trip Computer clicked");
break;
}
case "map": {
System.out.println("Map clicked");
sm.changeCurrentScreen(sm.map);
break;
}
case "speech": {
System.out.println("Speech clicked");
break;
}
case "satellite": {
System.out.println("Satellite clicked");
break;
}
case "about": {
System.out.println("About clicked");
break;
}
}
}
}
| philipperoubert/Coursework | XTrek/src/MenuScreen.java | 1,665 | //Creates the whereTo image (Default Selected) | line_comment | en | false | 1,359 | 10 | 1,665 | 10 | 1,734 | 10 | 1,665 | 10 | 2,060 | 11 | false | false | false | false | false | true |
193191_1 |
import java.util.Scanner;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.util.InputMismatchException;
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
/** Server class
*
* @author Kerly Titus
*/
public class Server extends Thread{
int numberOfTransactions; /* Number of transactions handled by the server */
int numberOfAccounts; /* Number of accounts stored in the server */
int maxNbAccounts; /* maximum number of transactions */
Transactions transaction; /* Transaction being processed */
Network objNetwork; /* Server object to handle network operations */
Accounts [] account; /* Accounts to be accessed or updated */
/**
* Constructor method of Client class
*
* @return
* @param
*/
Server()
{
System.out.println("\n Initializing the server ...");
numberOfTransactions = 0;
numberOfAccounts = 0;
maxNbAccounts = 100;
transaction = new Transactions();
account = new Accounts[maxNbAccounts];
objNetwork = new Network("server");
System.out.println("\n Inializing the Accounts database ...");
initializeAccounts( );
System.out.println("\n Connecting server to network ...");
if (!(objNetwork.connect(objNetwork.getServerIP())))
{
System.out.println("\n Terminating server application, network unavailable");
System.exit(0);
}
}
/**
* Accessor method of Server class
*
* @return numberOfTransactions
* @param
*/
public int getNumberOfTransactions()
{
return numberOfTransactions;
}
/**
* Mutator method of Server class
*
* @return
* @param nbOfTrans
*/
public void setNumberOfTransactions(int nbOfTrans)
{
numberOfTransactions = nbOfTrans;
}
/**
* Accessor method of Server class
*
* @return numberOfAccounts
* @param
*/
public int getNumberOfAccounts()
{
return numberOfAccounts;
}
/**
* Mutator method of Server class
*
* @return
* @param nbOfAcc
*/
public void setNumberOfAccounts(int nbOfAcc)
{
numberOfAccounts = nbOfAcc;
}
/**
* Accessor method of Server class
*
* @return maxNbAccounts
* @param
*/
public int getmMxNbAccounts()
{
return maxNbAccounts;
}
/**
* Mutator method of Server class
*
* @return
* @param nbOfAcc
*/
public void setMaxNbAccounts(int nbOfAcc)
{
maxNbAccounts = nbOfAcc;
}
/**
* Initialization of the accounts from an input file
*
* @return
* @param
*/
public void initializeAccounts()
{
Scanner inputStream = null; /* accounts input file stream */
int i = 0; /* index of accounts array */
try
{
inputStream = new Scanner(new FileInputStream("account.txt"));
}
catch(FileNotFoundException e)
{
System.out.println("File account.txt was not found");
System.out.println("or could not be opened.");
System.exit(0);
}
while (inputStream.hasNextLine())
{
try
{ account[i] = new Accounts();
account[i].setAccountNumber(inputStream.next()); /* Read account number */
account[i].setAccountType(inputStream.next()); /* Read account type */
account[i].setFirstName(inputStream.next()); /* Read first name */
account[i].setLastName(inputStream.next()); /* Read last name */
account[i].setBalance(inputStream.nextDouble()); /* Read account balance */
}
catch(InputMismatchException e)
{
System.out.println("Line " + i + "file account.txt invalid input");
System.exit(0);
}
i++;
}
setNumberOfAccounts(i); /* Record the number of accounts processed */
//System.out.println("\n DEBUG : Server.initializeAccounts() " + getNumberOfAccounts() + " accounts processed");
inputStream.close( );
}
/**
* Find and return the index position of an account
*
* @return account index position or -1
* @param accNumber
*/
public int findAccount(String accNumber)
{
int i = 0;
/* Find account */
while ( !(account[i].getAccountNumber().equals(accNumber)))
i++;
if (i == getNumberOfAccounts())
return -1;
else
return i;
}
/**
* Processing of the transactions
*
* @return
* @param trans
*/
public boolean processTransactions(Transactions trans)
{ int accIndex; /* Index position of account to update */
double newBalance; /* Updated account balance */
/* Process the accounts until the client disconnects */
while ((!objNetwork.getClientConnectionStatus().equals("disconnected")))
{
while((objNetwork.getInBufferStatus().equals("empty"))) {
Thread.yield();
if(objNetwork.getClientConnectionStatus().equals("disconnected"))
break;
} /* Alternatively, busy-wait until the network input buffer is available */
if (!objNetwork.getInBufferStatus().equals("empty"))
{
//System.out.println("\n DEBUG : Server.processTransactions() - transferring in account " + trans.getAccountNumber());
objNetwork.transferIn(trans); /* Transfer a transaction from the network input buffer */
accIndex = findAccount(trans.getAccountNumber());
/* Process deposit operation */
if (trans.getOperationType().equals("DEPOSIT"))
{
newBalance = deposit(accIndex, trans.getTransactionAmount());
trans.setTransactionBalance(newBalance);
trans.setTransactionStatus("done");
//System.out.println("\n DEBUG : Server.processTransactions() - Deposit of " + trans.getTransactionAmount() + " in account " + trans.getAccountNumber());
}
else
/* Process withdraw operation */
if (trans.getOperationType().equals("WITHDRAW"))
{
newBalance = withdraw(accIndex, trans.getTransactionAmount());
trans.setTransactionBalance(newBalance);
trans.setTransactionStatus("done");
//System.out.println("\n DEBUG : Server.processTransactions() - Withdrawal of " + trans.getTransactionAmount() + " from account " + trans.getAccountNumber());
}
else
/* Process query operation */
if (trans.getOperationType().equals("QUERY"))
{
newBalance = query(accIndex);
trans.setTransactionBalance(newBalance);
trans.setTransactionStatus("done");
//System.out.println("\n DEBUG : Server.processTransactions() - Obtaining balance from account" + trans.getAccountNumber());
}
while( (objNetwork.getOutBufferStatus().equals("full")))
Thread.yield(); /* Alternatively, busy-wait until the network output buffer is available */
//System.out.println("\n DEBUG : Server.processTransactions() - transferring out account " + trans.getAccountNumber());
objNetwork.transferOut(trans); /* Transfer a completed transaction from the server to the network output buffer */
setNumberOfTransactions( (getNumberOfTransactions() + 1) ); /* Count the number of transactions processed */
}
}
//System.out.println("\n DEBUG : Server.processTransactions() - " + getNumberOfTransactions() + " accounts updated");
return true;
}
/**
* Processing of a deposit operation in an account
*
* @return balance
* @param i, amount
*/
public double deposit(int i, double amount)
{ double curBalance; /* Current account balance */
curBalance = account[i].getBalance( ); /* Get current account balance */
account[i].setBalance(curBalance + amount); /* Deposit amount in the account */
return account[i].getBalance (); /* Return updated account balance */
}
/**
* Processing of a withdrawal operation in an account
*
* @return balance
* @param i, amount
*/
public double withdraw(int i, double amount)
{ double curBalance; /* Current account balance */
curBalance = account[i].getBalance( ); /* Get current account balance */
account[i].setBalance(curBalance - amount); /* Withdraw amount in the account */
return account[i].getBalance (); /* Return updated account balance */
}
/**
* Processing of a query operation in an account
*
* @return balance
* @param i
*/
public double query(int i)
{ double curBalance; /* Current account balance */
curBalance = account[i].getBalance( ); /* Get current account balance */
return curBalance; /* Return current account balance */
}
/**
* Create a String representation based on the Server Object
*
* @return String representation
*/
public String toString()
{
return ("\n server IP " + objNetwork.getServerIP() + "connection status " + objNetwork.getServerConnectionStatus() + "Number of accounts " + getNumberOfAccounts());
}
/* *********************************************************************************************************************************************
* TODO : implement the method Run() to execute the server thread *
* *********************************************************************************************************************************************/
/**
* Code for the run method
*
* @return
* @param
*/
public void run()
{ Transactions trans = new Transactions();
long serverStartTime = 0, serverEndTime = 0;
//System.out.println("\n DEBUG : Server.run() - starting server thread " + objNetwork.getServerConnectionStatus());
serverStartTime = System.currentTimeMillis();
processTransactions(trans);
serverEndTime = System.currentTimeMillis();
System.out.println("\nTerminating server thread - " + " Running time " + (serverEndTime - serverStartTime) + " milliseconds");
objNetwork.disconnect(objNetwork.getServerIP());
}
}
| kkesslero/COMP346_A1 | Server.java | 2,269 | /** Server class
*
* @author Kerly Titus
*/ | block_comment | en | false | 2,142 | 14 | 2,269 | 16 | 2,650 | 16 | 2,269 | 16 | 2,990 | 18 | false | false | false | false | false | true |
193243_3 | /**
*
* @author Scott + Omar
* @date 03/01/17
*/
public class Order implements AccountsCommunication {
//Comment for github
private int orderID;
private static int counter;
private int assignedEmployee = -1;
private int[] itemIDs;
private int[] qtyRequired;
private int[] qtyPRequired;
public void notifyAccounts() {
// send email to accounts
}
public int getOrderID() {
return orderID;
}
public void setOrderID(int orderID) {
this.orderID = orderID;
}
// automatically assigns orderID based on a counter
public Order(int[] itemIDs, int[] qtyRequired, int[] qtyPRequired) {
this(counter, itemIDs, qtyRequired, qtyPRequired);
}
// allows a customer orderID to be inserted
public Order(int orderID, int[] itemIDs, int[] qtyRequired, int[] qtyPRequired) {
this.orderID = orderID;
counter = orderID + 1;
this.itemIDs = itemIDs;
this.qtyRequired = qtyRequired;
this.qtyPRequired = qtyPRequired;
}
public int getAssignedEmployee() {
return assignedEmployee;
}
public void setAssignedEmployee(int assignedEmployee) {
this.assignedEmployee = assignedEmployee;
}
public int[] getItemIDs() {
return itemIDs;
}
public void setItemIDs(int[] itemIDs) {
this.itemIDs = itemIDs;
}
public int[] getQtyRequired() {
return qtyRequired;
}
public void setQtyRequired(int[] qtyRequired) {
this.qtyRequired = qtyRequired;
}
public int[] getQtyPRequired() {
return qtyPRequired;
}
public void setQtyPRequired(int[] qtyPRequired) {
this.qtyPRequired = qtyPRequired;
}
}
| scottbagshaw/test | Order.java | 488 | // automatically assigns orderID based on a counter
| line_comment | en | false | 399 | 10 | 488 | 10 | 523 | 10 | 488 | 10 | 589 | 11 | false | false | false | false | false | true |
194586_0 | public class Main {
public static void main(String[] args) {
// Creating instances of Horse and Cat
Horse h1 = new Horse("Jack", 4);
Horse h2 = new Horse("Steve", 5);
Cat c1 = new Cat("Nickie", 6);
Cat c2 = new Cat("Rosy", 4);
Cat c3 = new Cat("Riri", 2);
Dog d1 = new Dog("Rocky", 2);
Dog d2 = new Dog("Max", 3);
// Accessing information and sounds of Horse and Cat and Dog
System.out.println("Horses:"+"\nSound: "+h1.sound());
System.out.println(h1.getInfo());
System.out.println(h2.getInfo());
System.out.println("\nCats:"+"\nSound: "+c1.sound());
System.out.println(c1.getInfo());
System.out.println(c2.getInfo());
System.out.println(c3.getInfo());
System.out.println("\nDogs:"+"\nSound: "+d1.sound());
System.out.println(d1.getInfo());
System.out.println(d2.getInfo());
}
}
| er-hiba/Animal-Abstract-Class-Java | Main.java | 289 | // Creating instances of Horse and Cat | line_comment | en | false | 244 | 7 | 289 | 8 | 299 | 7 | 289 | 8 | 325 | 8 | false | false | false | false | false | true |
195679_15 | package HolidayChecker;
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.time.temporal.ChronoUnit;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
/**
* HolidayValidator
*
* This base class is used to determine if a given date is a holiday.
* It supports fixed holidays, dynamic Islamic holidays, weekends, and custom holidays.
*/
public abstract class HolidayValidator {
protected static final List<String> FIXED_HOLIDAYS = List.of(
"01-01", // Yeni Yıl
"04-23", // Ulusal Egemenlik ve Çocuk Bayramı
"05-01", // İşçi Bayramı
"05-19", // Atatürk'ü Anma, Gençlik ve Spor Bayramı
"07-20", // Barış ve Özgürlük Bayramı
"08-30", // Zafer Bayramı
"10-29" // Cumhuriyet Bayramı
);
protected static final List<Holiday> BASE_DATES = List.of(
new Holiday("ramazanBayrami", LocalDate.of(2024, 4, 10), 3),
new Holiday("kurbanBayrami", LocalDate.of(2024, 6, 28), 4)
);
private static final double ISLAMIC_YEAR_DAYS = 354.36667;
private static final int BASE_YEAR = 2024;
protected final boolean includeSaturday;
protected final Set<CustomHoliday> customHolidays = new HashSet<>();
/**
* Constructor for the HolidayValidator class
*
* @param includeSaturday Boolean flag indicating whether to include Saturdays as holidays
*/
public HolidayValidator(boolean includeSaturday) {
this.includeSaturday = includeSaturday;
}
/**
* Check if the given date is a holiday
*
* @param date The date to check
* @return True if the date is a holiday, false otherwise
*/
public boolean isHoliday(LocalDate date) {
return isWeekend(date) || isFixedHoliday(date) || isIslamicHoliday(date) || isCustomHoliday(date);
}
/**
* Add a custom holiday
*
* @param date The date of the custom holiday
* @param recurring Whether the holiday recurs every year
* @param isIslamic Whether the holiday should be considered as an Islamic holiday
*/
public void addCustomHoliday(LocalDate date, boolean recurring, boolean isIslamic) {
customHolidays.add(new CustomHoliday(date, recurring, isIslamic));
}
/**
* Check if the given date is a weekend
*
* @param date The date to check
* @return True if the date is a weekend, false otherwise
*/
private boolean isWeekend(LocalDate date) {
int dayOfWeek = date.getDayOfWeek().getValue();
return dayOfWeek == 7 || (includeSaturday && dayOfWeek == 6);
}
/**
* Check if the given date is a fixed holiday
*
* @param date The date to check
* @return True if the date is a fixed holiday, false otherwise
*/
protected boolean isFixedHoliday(LocalDate date) {
String monthDay = date.format(DateTimeFormatter.ofPattern("MM-dd"));
return FIXED_HOLIDAYS.contains(monthDay);
}
/**
* Check if the given date is an Islamic holiday
*
* @param date The date to check
* @return True if the date is an Islamic holiday, false otherwise
*/
private boolean isIslamicHoliday(LocalDate date) {
List<LocalDate> islamicHolidays = calculateIslamicHolidays(date.getYear());
return islamicHolidays.contains(date);
}
/**
* Check if the given date is a custom holiday
*
* @param date The date to check
* @return True if the date is a custom holiday, false otherwise
*/
private boolean isCustomHoliday(LocalDate date) {
for (CustomHoliday holiday : customHolidays) {
if (holiday.isRecurring()) {
if (date.format(DateTimeFormatter.ofPattern("MM-dd")).equals(holiday.getDate().format(DateTimeFormatter.ofPattern("MM-dd")))) {
return true;
}
} else {
if (date.equals(holiday.getDate())) {
return true;
}
}
if (holiday.isIslamic()) {
if (isIslamicHoliday(holiday.getDate())) {
return true;
}
}
}
return false;
}
/**
* Calculate Islamic holidays for a given year
*
* @param year The year to calculate the holidays for
* @return A list of Islamic holidays
*/
private List<LocalDate> calculateIslamicHolidays(int year) {
int yearDifference = year - BASE_YEAR;
List<LocalDate> holidays = new ArrayList<>();
for (Holiday holiday : BASE_DATES) {
LocalDate startDate = calculateIslamicDate(holiday.getDate(), yearDifference);
holidays.addAll(generateHolidayDates(startDate, holiday.getDays()));
}
return holidays;
}
/**
* Calculate the date of an Islamic holiday
*
* @param baseDate The base date of the holiday
* @param yearDifference The difference in years from the base year
* @return The calculated date of the holiday
*/
private LocalDate calculateIslamicDate(LocalDate baseDate, int yearDifference) {
long daysToAdd = Math.round(yearDifference * ISLAMIC_YEAR_DAYS);
return baseDate.plus(daysToAdd, ChronoUnit.DAYS);
}
/**
* Generate a list of holiday dates
*
* @param startDate The start date of the holiday
* @param days The number of days the holiday lasts
* @return A list of holiday dates
*/
private List<LocalDate> generateHolidayDates(LocalDate startDate, int days) {
List<LocalDate> dates = new ArrayList<>();
for (int i = 0; i < days; i++) {
dates.add(startDate.plusDays(i));
}
return dates;
}
/**
* Holiday class representing a holiday with a name, date, and duration
*/
protected static class Holiday {
private final String name;
private final LocalDate date;
private final int days;
/**
* Constructor for the Holiday class
*
* @param name The name of the holiday
* @param date The date of the holiday
* @param days The number of days the holiday lasts
*/
public Holiday(String name, LocalDate date, int days) {
this.name = name;
this.date = date;
this.days = days;
}
/**
* Get the name of the holiday
*
* @return The name of the holiday
*/
public String getName() {
return name;
}
/**
* Get the date of the holiday
*
* @return The date of the holiday
*/
public LocalDate getDate() {
return date;
}
/**
* Get the number of days the holiday lasts
*
* @return The number of days the holiday lasts
*/
public int getDays() {
return days;
}
}
/**
* CustomHoliday class representing a custom holiday with a date, recurrence flag, and Islamic flag
*/
protected static class CustomHoliday {
private final LocalDate date;
private final boolean recurring;
private final boolean isIslamic;
/**
* Constructor for the CustomHoliday class
*
* @param date The date of the custom holiday
* @param recurring Whether the holiday recurs every year
* @param isIslamic Whether the holiday is considered an Islamic holiday
*/
public CustomHoliday(LocalDate date, boolean recurring, boolean isIslamic) {
this.date = date;
this.recurring = recurring;
this.isIslamic = isIslamic;
}
/**
* Get the date of the custom holiday
*
* @return The date of the custom holiday
*/
public LocalDate getDate() {
return date;
}
/**
* Check if the custom holiday recurs every year
*
* @return True if the holiday recurs every year, false otherwise
*/
public boolean isRecurring() {
return recurring;
}
/**
* Check if the custom holiday is considered an Islamic holiday
*
* @return True if the holiday is considered an Islamic holiday, false otherwise
*/
public boolean isIslamic() {
return isIslamic;
}
}
}
| baturkacamak/turkey-trnc-holiday-validator | Java/HolidayValidator.java | 2,082 | /**
* Calculate Islamic holidays for a given year
*
* @param year The year to calculate the holidays for
* @return A list of Islamic holidays
*/ | block_comment | en | false | 1,857 | 38 | 2,082 | 42 | 2,101 | 40 | 2,082 | 42 | 2,489 | 49 | false | false | false | false | false | true |
197107_4 | // Type.java, created Wed Mar 19 13:05:01 2003 by cananian
// Copyright (C) 2003 C. Scott Ananian ([email protected])
// Licensed under the terms of the GNU GPL; see COPYING for details.
package net.cscott.sinjdoc;
/**
* The <code>Type</code> interface represents a java type. A
* <code>Type</code> can be a (possibly-parameterized) class type,
* a primitive data type like int and char, or a type variable
* declared in a generic class or method.
*
* @author C. Scott Ananian ([email protected])
* @version $Id$
* @see com.sun.javadoc.Type
* @see java.lang.reflect.Type
*/
public interface Type {
/** Return the canonical name of the <em>erasure</em> of this type.
* (Anonymous types and types contained within anonymous types do not
* have canonical names, but are unrepresented here in any case).
* See section 6.7 of the JLS for the definition of canonical names;
* using the erasure of the type allows this definition to extend to
* parameterized types and type variables.
* @see ExecutableMemberDoc#signature()
*/
public String signature();
/** Accept a visitor. */
public <T> T accept(TypeVisitor<T> visitor);
}
| cscott/sinjdoc | src/Type.java | 350 | /** Return the canonical name of the <em>erasure</em> of this type.
* (Anonymous types and types contained within anonymous types do not
* have canonical names, but are unrepresented here in any case).
* See section 6.7 of the JLS for the definition of canonical names;
* using the erasure of the type allows this definition to extend to
* parameterized types and type variables.
* @see ExecutableMemberDoc#signature()
*/ | block_comment | en | false | 322 | 111 | 350 | 110 | 346 | 112 | 350 | 110 | 379 | 120 | false | false | false | false | false | true |
197701_2 |
/**
* Colleagues are the enemies in this game. They are used in the challenges by 'asking' quiz questions, and the game
* is ended if too many answers are wrong.
*
* Its attributes are:
* - String name for identification
* - boolean gender for gender
*
*
* @205232
* @11.01.2019
*
*
*/
public class Colleague
{
private String name;
private boolean gender;
/**
* Constructor for objects of class Colleague. Assigns parameters to attributes.
* @param String a String object representing this colleague's name
* @param boolean represents the colleague's gender -> true for femle, false for male
*/
public Colleague(String name, boolean gender)
{
this.name = name;
this.gender = gender;
}
/**
* The following method is an accessor used for printing information about thie colleague in the
* ColleagueManager. It returns a String objct containing the name of this colleague.
* @return String name
* @param none
*/
public String getName(){
return name;
}
/**
* The following method is an accessor used for printing information about thie colleague in the
* ColleagueManager. It returns a boolean containing the info if this colleague is female (it counts as
* female when true; as male when false).
* @return boolean gender
* @param none
*/
public boolean isFemale(){
return gender;
}
}
| L-ENA/SpyGame | Colleague.java | 351 | /**
* The following method is an accessor used for printing information about thie colleague in the
* ColleagueManager. It returns a String objct containing the name of this colleague.
* @return String name
* @param none
*/ | block_comment | en | false | 344 | 54 | 351 | 53 | 388 | 57 | 351 | 53 | 413 | 61 | false | false | false | false | false | true |
197776_16 | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you 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.apache.cassandra.db.partitions;
import java.nio.ByteBuffer;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.atomic.AtomicIntegerFieldUpdater;
import java.util.concurrent.atomic.AtomicReferenceFieldUpdater;
import org.apache.cassandra.config.CFMetaData;
import org.apache.cassandra.config.DatabaseDescriptor;
import org.apache.cassandra.db.*;
import org.apache.cassandra.db.rows.EncodingStats;
import org.apache.cassandra.db.rows.Row;
import org.apache.cassandra.db.rows.Rows;
import org.apache.cassandra.index.transactions.UpdateTransaction;
import org.apache.cassandra.utils.FBUtilities;
import org.apache.cassandra.utils.ObjectSizes;
import org.apache.cassandra.utils.btree.BTree;
import org.apache.cassandra.utils.btree.UpdateFunction;
import org.apache.cassandra.utils.concurrent.Locks;
import org.apache.cassandra.utils.concurrent.OpOrder;
import org.apache.cassandra.utils.memory.HeapAllocator;
import org.apache.cassandra.utils.memory.MemtableAllocator;
/**
* A thread-safe and atomic Partition implementation.
*
* Operations (in particular addAll) on this implementation are atomic and
* isolated (in the sense of ACID). Typically a addAll is guaranteed that no
* other thread can see the state where only parts but not all rows have
* been added.
*/
public class AtomicBTreePartition extends AbstractBTreePartition
{
public static final long EMPTY_SIZE = ObjectSizes.measure(new AtomicBTreePartition(CFMetaData.createFake("keyspace", "table"),
DatabaseDescriptor.getPartitioner().decorateKey(ByteBuffer.allocate(1)),
null));
// Reserved values for wasteTracker field. These values must not be consecutive (see avoidReservedValues)
private static final int TRACKER_NEVER_WASTED = 0;
private static final int TRACKER_PESSIMISTIC_LOCKING = Integer.MAX_VALUE;
// The granularity with which we track wasted allocation/work; we round up
private static final int ALLOCATION_GRANULARITY_BYTES = 1024;
// The number of bytes we have to waste in excess of our acceptable realtime rate of waste (defined below)
private static final long EXCESS_WASTE_BYTES = 10 * 1024 * 1024L;
private static final int EXCESS_WASTE_OFFSET = (int) (EXCESS_WASTE_BYTES / ALLOCATION_GRANULARITY_BYTES);
// Note this is a shift, because dividing a long time and then picking the low 32 bits doesn't give correct rollover behavior
private static final int CLOCK_SHIFT = 17;
// CLOCK_GRANULARITY = 1^9ns >> CLOCK_SHIFT == 132us == (1/7.63)ms
private static final AtomicIntegerFieldUpdater<AtomicBTreePartition> wasteTrackerUpdater = AtomicIntegerFieldUpdater.newUpdater(AtomicBTreePartition.class, "wasteTracker");
private static final AtomicReferenceFieldUpdater<AtomicBTreePartition, Holder> refUpdater = AtomicReferenceFieldUpdater.newUpdater(AtomicBTreePartition.class, Holder.class, "ref");
/**
* (clock + allocation) granularity are combined to give us an acceptable (waste) allocation rate that is defined by
* the passage of real time of ALLOCATION_GRANULARITY_BYTES/CLOCK_GRANULARITY, or in this case 7.63Kb/ms, or 7.45Mb/s
*
* in wasteTracker we maintain within EXCESS_WASTE_OFFSET before the current time; whenever we waste bytes
* we increment the current value if it is within this window, and set it to the min of the window plus our waste
* otherwise.
*/
private volatile int wasteTracker = TRACKER_NEVER_WASTED;
private final MemtableAllocator allocator;
private volatile Holder ref;
public AtomicBTreePartition(CFMetaData metadata, DecoratedKey partitionKey, MemtableAllocator allocator)
{
// involved in potential bug? partition columns may be a subset if we alter columns while it's in memtable
super(metadata, partitionKey);
this.allocator = allocator;
this.ref = EMPTY;
}
protected Holder holder()
{
return ref;
}
protected boolean canHaveShadowedData()
{
return true;
}
/**
* Adds a given update to this in-memtable partition.
*
* @return an array containing first the difference in size seen after merging the updates, and second the minimum
* time detla between updates.
*/
public long[] addAllWithSizeDelta(final PartitionUpdate update, OpOrder.Group writeOp, UpdateTransaction indexer)
{
RowUpdater updater = new RowUpdater(this, allocator, writeOp, indexer);
DeletionInfo inputDeletionInfoCopy = null;
boolean monitorOwned = false;
try
{
if (usePessimisticLocking())
{
Locks.monitorEnterUnsafe(this);
monitorOwned = true;
}
indexer.start();
while (true)
{
Holder current = ref;
updater.ref = current;
updater.reset();
if (!update.deletionInfo().getPartitionDeletion().isLive())
indexer.onPartitionDeletion(update.deletionInfo().getPartitionDeletion());
if (update.deletionInfo().hasRanges())
update.deletionInfo().rangeIterator(false).forEachRemaining(indexer::onRangeTombstone);
DeletionInfo deletionInfo;
if (update.deletionInfo().mayModify(current.deletionInfo))
{
if (inputDeletionInfoCopy == null)
inputDeletionInfoCopy = update.deletionInfo().copy(HeapAllocator.instance);
deletionInfo = current.deletionInfo.mutableCopy().add(inputDeletionInfoCopy);
updater.allocated(deletionInfo.unsharedHeapSize() - current.deletionInfo.unsharedHeapSize());
}
else
{
deletionInfo = current.deletionInfo;
}
PartitionColumns columns = update.columns().mergeTo(current.columns);
Row newStatic = update.staticRow();
Row staticRow = newStatic.isEmpty()
? current.staticRow
: (current.staticRow.isEmpty() ? updater.apply(newStatic) : updater.apply(current.staticRow, newStatic));
Object[] tree = BTree.update(current.tree, update.metadata().comparator, update, update.rowCount(), updater);
EncodingStats newStats = current.stats.mergeWith(update.stats());
if (tree != null && refUpdater.compareAndSet(this, current, new Holder(columns, tree, deletionInfo, staticRow, newStats)))
{
updater.finish();
return new long[]{ updater.dataSize, updater.colUpdateTimeDelta };
}
else if (!monitorOwned)
{
boolean shouldLock = usePessimisticLocking();
if (!shouldLock)
{
shouldLock = updateWastedAllocationTracker(updater.heapSize);
}
if (shouldLock)
{
Locks.monitorEnterUnsafe(this);
monitorOwned = true;
}
}
}
}
finally
{
indexer.commit();
if (monitorOwned)
Locks.monitorExitUnsafe(this);
}
}
public boolean usePessimisticLocking()
{
return wasteTracker == TRACKER_PESSIMISTIC_LOCKING;
}
/**
* Update the wasted allocation tracker state based on newly wasted allocation information
*
* @param wastedBytes the number of bytes wasted by this thread
* @return true if the caller should now proceed with pessimistic locking because the waste limit has been reached
*/
private boolean updateWastedAllocationTracker(long wastedBytes)
{
// Early check for huge allocation that exceeds the limit
if (wastedBytes < EXCESS_WASTE_BYTES)
{
// We round up to ensure work < granularity are still accounted for
int wastedAllocation = ((int) (wastedBytes + ALLOCATION_GRANULARITY_BYTES - 1)) / ALLOCATION_GRANULARITY_BYTES;
int oldTrackerValue;
while (TRACKER_PESSIMISTIC_LOCKING != (oldTrackerValue = wasteTracker))
{
// Note this time value has an arbitrary offset, but is a constant rate 32 bit counter (that may wrap)
int time = (int) (System.nanoTime() >>> CLOCK_SHIFT);
int delta = oldTrackerValue - time;
if (oldTrackerValue == TRACKER_NEVER_WASTED || delta >= 0 || delta < -EXCESS_WASTE_OFFSET)
delta = -EXCESS_WASTE_OFFSET;
delta += wastedAllocation;
if (delta >= 0)
break;
if (wasteTrackerUpdater.compareAndSet(this, oldTrackerValue, avoidReservedValues(time + delta)))
return false;
}
}
// We have definitely reached our waste limit so set the state if it isn't already
wasteTrackerUpdater.set(this, TRACKER_PESSIMISTIC_LOCKING);
// And tell the caller to proceed with pessimistic locking
return true;
}
private static int avoidReservedValues(int wasteTracker)
{
if (wasteTracker == TRACKER_NEVER_WASTED || wasteTracker == TRACKER_PESSIMISTIC_LOCKING)
return wasteTracker + 1;
return wasteTracker;
}
// the function we provide to the btree utilities to perform any column replacements
private static final class RowUpdater implements UpdateFunction<Row, Row>
{
final AtomicBTreePartition updating;
final MemtableAllocator allocator;
final OpOrder.Group writeOp;
final UpdateTransaction indexer;
final int nowInSec;
Holder ref;
Row.Builder regularBuilder;
long dataSize;
long heapSize;
long colUpdateTimeDelta = Long.MAX_VALUE;
final MemtableAllocator.DataReclaimer reclaimer;
List<Row> inserted; // TODO: replace with walk of aborted BTree
private RowUpdater(AtomicBTreePartition updating, MemtableAllocator allocator, OpOrder.Group writeOp, UpdateTransaction indexer)
{
this.updating = updating;
this.allocator = allocator;
this.writeOp = writeOp;
this.indexer = indexer;
this.nowInSec = FBUtilities.nowInSeconds();
this.reclaimer = allocator.reclaimer();
}
private Row.Builder builder(Clustering clustering)
{
boolean isStatic = clustering == Clustering.STATIC_CLUSTERING;
// We know we only insert/update one static per PartitionUpdate, so no point in saving the builder
if (isStatic)
return allocator.rowBuilder(writeOp);
if (regularBuilder == null)
regularBuilder = allocator.rowBuilder(writeOp);
return regularBuilder;
}
public Row apply(Row insert)
{
Row data = Rows.copy(insert, builder(insert.clustering())).build();
indexer.onInserted(insert);
this.dataSize += data.dataSize();
this.heapSize += data.unsharedHeapSizeExcludingData();
if (inserted == null)
inserted = new ArrayList<>();
inserted.add(data);
return data;
}
public Row apply(Row existing, Row update)
{
Row.Builder builder = builder(existing.clustering());
colUpdateTimeDelta = Math.min(colUpdateTimeDelta, Rows.merge(existing, update, builder, nowInSec));
Row reconciled = builder.build();
indexer.onUpdated(existing, reconciled);
dataSize += reconciled.dataSize() - existing.dataSize();
heapSize += reconciled.unsharedHeapSizeExcludingData() - existing.unsharedHeapSizeExcludingData();
if (inserted == null)
inserted = new ArrayList<>();
inserted.add(reconciled);
discard(existing);
return reconciled;
}
protected void reset()
{
this.dataSize = 0;
this.heapSize = 0;
if (inserted != null)
{
for (Row row : inserted)
abort(row);
inserted.clear();
}
reclaimer.cancel();
}
protected void abort(Row abort)
{
reclaimer.reclaimImmediately(abort);
}
protected void discard(Row discard)
{
reclaimer.reclaim(discard);
}
public boolean abortEarly()
{
return updating.ref != ref;
}
public void allocated(long heapSize)
{
this.heapSize += heapSize;
}
protected void finish()
{
allocator.onHeap().adjust(heapSize, writeOp);
reclaimer.commit();
}
}
}
| wendelicious/cassandra | src/java/org/apache/cassandra/db/partitions/AtomicBTreePartition.java | 3,091 | // the function we provide to the btree utilities to perform any column replacements | line_comment | en | false | 2,789 | 15 | 3,091 | 15 | 3,263 | 15 | 3,091 | 15 | 3,858 | 18 | false | false | false | false | false | true |
201381_4 | import java.util.ArrayList;
/**
* This class is used to model a hand of Single 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 to check whether a given hand is
* a valid Single.
* <br>
*
*
* <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-08
*/
public class Single extends Hand
{
// Private variable storing the type of this hand in String
private String type;
/**
* This constructor construct a Single 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 Single(CardGamePlayer player, CardList cards)
{
super(player,cards);
this.type = "Single";
}
/**
* This method is used to check if this is a valid Single.
* <br>
* @return a boolean value specifying whether this hand is a valid Single
*/
public boolean isValid()
{
return Single.isValid(this);
}
/*
* This method is used to check whether a given hand is a valid Single hand.
* This method is a static method.
* <br>
* @param hand the hand given to be checked validity
* @return the boolean value to specify whether the given hand is a valid Single
* Single in Big Two Game.
*/
public static boolean isValid(CardList hand)
{
if(hand.size() == 1)
{
Card card = hand.getCard(0);
int suit = card.getSuit();
int rank = card.getRank();
if(-1 < suit && suit < 4 && -1 < rank && rank < 13)
{
return true;
}
}
return false;
}
/**
* 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/Single.java | 730 | /*
* This method is used to check whether a given hand is a valid Single hand.
* This method is a static method.
* <br>
* @param hand the hand given to be checked validity
* @return the boolean value to specify whether the given hand is a valid Single
* Single in Big Two Game.
*/ | block_comment | en | false | 632 | 67 | 730 | 73 | 711 | 73 | 730 | 73 | 767 | 74 | false | false | false | false | false | true |
201850_1 | package Model;
import java.io.Serializable;
import java.util.Arrays;
public class Religion implements Serializable{
private final int MAX_LENGTH = 11;
private int orderOfCult_3; //Holds id of player who took this area
private int orderOfCult_2_1; //Holds id of player who took this area
private int orderOfCult_2_2; //Holds id of player who took this area
private int orderOfCult_2_3; //Holds id of player who took this are
private boolean keyPlaced;
private int[] playerPositions;
private int[] roundBasedPosition;
private int[] powerAwardPositions; //placed /wrt the higher value of track number
public Religion(int playerCount, int[] initial_religion_points){
orderOfCult_3 = -1;
orderOfCult_2_1 = -1;
orderOfCult_2_2 = -1;
orderOfCult_2_3 = -1;
keyPlaced = false;
playerPositions = new int[playerCount];
setupReligion(playerCount,initial_religion_points);
roundBasedPosition = new int[playerCount];
}
private void setupReligion(int playerCount, int[] initial_religion_points){
powerAwardPositions = new int[MAX_LENGTH+1];
for (int i = 0; i < playerPositions.length ; i++){
powerAwardPositions[i] = 0;
}
powerAwardPositions[3] = 1;
powerAwardPositions[5] = 2;
powerAwardPositions[7] = 2;
powerAwardPositions[10] = 3;
for(int i = 0; i< playerCount; i++){
updateReligion(initial_religion_points[i], i, 0);
}
}
/**
* Updates the place of given player and returns
* the amount of power obtained by end of progress.
* @param count the number of advance in religion track
* @param player_id the id of player whose round
* @return powerAward the amount of power player gained
*
*/
public int[] updateReligion(int count, int player_id, int key){
int[] returnInfo = {0,0,0};
//powerGain, case, kaç ilerledi
int powerAward = 0;
int currentPos = playerPositions[player_id];
int endPos = currentPos + count;
int awardSearchLength = powerAwardPositions.length;
if(currentPos >= MAX_LENGTH){
returnInfo[1] = 4;
}
else if (endPos >= MAX_LENGTH-1){
if(keyPlaced){
//System.out.println("Since someone used key, you can't reach end"); // Can be replaced with an GUI message
awardSearchLength -= 1;
endPos = MAX_LENGTH-2;
returnInfo[1] = 1;
}if (key == 0){
//System.out.println("Since there is no key end pos is stuck on 9"); // Can be replaced with an GUI message
awardSearchLength -= 1;
endPos = MAX_LENGTH-2;
returnInfo[1] = 2;
}else{
keyPlaced = true;
endPos = MAX_LENGTH-1;
returnInfo[1] = 3;
}
}
for (int i = 0; i< awardSearchLength; i++ ){
if (currentPos < i && endPos >= i){
powerAward += powerAwardPositions[i];
}
}
playerPositions[player_id] = endPos;
returnInfo[0] = powerAward;
returnInfo[2] = endPos - currentPos;
return returnInfo;
}
public boolean isOccupied(int index) {
switch (index) {
case 0:
return (orderOfCult_3 != -1);
case 1:
return (orderOfCult_2_1 != -1);
case 2:
return (orderOfCult_2_2 != -1);
case 3:
return (orderOfCult_2_3 != -1);
}
return false;
}
public int[] placePriest(int player_id,int key) {
return updateReligion(1, player_id, key);
}
public int[] addOrderOfReligion(int player_id, int key){
int[] returnInfo = {-1,-1,-1};
if(orderOfCult_3 == -1) {
returnInfo = this.updateReligion(3, player_id, key);
if (returnInfo[1] == 0)
orderOfCult_3 = player_id;
}else if (orderOfCult_2_1 == -1){
returnInfo = this.updateReligion(2, player_id, key);
if (returnInfo[1] == 0)
orderOfCult_2_1 = player_id;
}else if (orderOfCult_2_2 == -1){
returnInfo = this.updateReligion(2, player_id, key);
if (returnInfo[1] == 0)
orderOfCult_2_2 = player_id;
}else if (orderOfCult_2_3 == -1){
returnInfo = this.updateReligion(2, player_id, key);
if (returnInfo[1] == 0)
orderOfCult_2_3 = player_id;
}else
System.out.println("ORDER IS FULL");
return returnInfo; // Error value which indicates there is no empty place
}
public int[] getPlayerPositions()
{
return playerPositions;
}
public void updateRoundBasedPositions(int amount, int playerIndex){
roundBasedPosition[playerIndex] += amount;
}
public void resetRoundBasedPosition(){
Arrays.fill(roundBasedPosition, 0);
}
public int[] getRoundBasedPosition() {
return roundBasedPosition;
}
public void setRoundBasedPosition(int[] roundBasedPosition) {
this.roundBasedPosition = roundBasedPosition;
}
} | tolgacatalpinar/-JavaFX-TerraHistorica-1G-TM | src/Model/Religion.java | 1,444 | //Holds id of player who took this area | line_comment | en | false | 1,361 | 10 | 1,444 | 10 | 1,510 | 10 | 1,444 | 10 | 1,633 | 10 | false | false | false | false | false | true |
202350_13 | /**
* The Patch class represents a patch of muscle fibers in the body.
* It includes properties such as anabolic and catabolic hormone levels,
* and methods to update and regulate these levels.
*/
public class Patch {
private double anabolicHormone; // The level of anabolic hormones
private double catabolicHormone; // The level of catabolic hormones
// Constants for hormone regulation
private static final double DIFFUSE_RATE = 0.75;
private static final double ANABOLIC_HORMONE_MAX = 200.0;
private static final double ANABOLIC_HORMONE_MIN = 50.0;
private static final double CATABOLIC_HORMONE_MAX = 250.0;
private static final double CATABOLIC_HORMONE_MIN = 52.0;
/**
* Default constructor for the Patch class.
* Initializes anabolic and catabolic hormone levels to their default starting values.
*/
public Patch() {
this.anabolicHormone = 50.0; // default starting value
this.catabolicHormone = 52.0; // default starting value
// No need to regulate hormones here, since they are already within the allowed limits
//regulateHormones();
}
/**
* Constructs a new Patch with the given anabolic and catabolic hormone levels.
* @param anabolicHormone The level of anabolic hormones.
* @param catabolicHormone The level of catabolic hormones.
*/
public Patch(double anabolicHormone, double catabolicHormone) {
this.anabolicHormone = anabolicHormone;
this.catabolicHormone = catabolicHormone;
}
/**
* Diffuses hormones to the neighboring patches in the grid.
* @param grid The grid of patches.
* @param x The x-coordinate of the current patch in the grid.
* @param y The y-coordinate of the current patch in the grid.
*/
public void diffuse(Patch[][] grid, int x, int y) {
int[] dx = {-1, -1, -1, 0, 0, 1, 1, 1};
int[] dy = {-1, 0, 1, -1, 1, -1, 0, 1};
double anabolicShare = (anabolicHormone * DIFFUSE_RATE) / 8.0;
double catabolicShare = (catabolicHormone * DIFFUSE_RATE) / 8.0;
double anabolicRemaining = anabolicHormone;
double catabolicRemaining = catabolicHormone;
for (int i = 0; i < 8; i++) {
int nx = x + dx[i];
int ny = y + dy[i];
// Check if the neighboring patch is within the grid
if (nx >= 0 && nx < grid.length && ny >= 0 && ny < grid[0].length) {
grid[nx][ny].receiveHormones(anabolicShare, catabolicShare);
anabolicRemaining -= anabolicShare;
catabolicRemaining -= catabolicShare;
}
}
// Set the remaining hormone levels back to the patch
this.anabolicHormone = anabolicRemaining;
this.catabolicHormone = catabolicRemaining;
}
/**
* Updates hormone levels based on daily activities.
* @param fiberSize The size of the muscle fiber.
*/
public void updateHormonesFromDailyActivities(double fiberSize) {
double logFiberSize = Math.log10(fiberSize);
anabolicHormone += 2.5 * logFiberSize;
catabolicHormone += 2.0 * logFiberSize;
}
/**
* Updates hormone levels based on weight lifting.
* @param fiberSize The size of the muscle fiber.
* @param intensity The intensity of the workout.
*/
public void updateHormonesFromWeightLifting(double fiberSize, int intensity) {
double probability = Math.pow(intensity / 100.0, 2);
if (Math.random() * 1.0 < probability) {
double logFiberSize = Math.log10(fiberSize);
anabolicHormone += logFiberSize * 55.0;
catabolicHormone += logFiberSize * 44.0;
}
}
/**
* Updates hormone levels based on sleep.
* @param hoursOfSleep The hours of sleep.
*/
public void updateHormonesFromSleep(double hoursOfSleep) {
anabolicHormone -= 0.48 * Math.log10(anabolicHormone) * hoursOfSleep;
catabolicHormone -= 0.5 * Math.log10(catabolicHormone) * hoursOfSleep;
}
/**
* Balances hormone levels to be within the allowed limits.
*/
public void balanceHormones() {
anabolicHormone = Math.max(ANABOLIC_HORMONE_MIN,
Math.min(this.anabolicHormone, ANABOLIC_HORMONE_MAX));
catabolicHormone = Math.max(CATABOLIC_HORMONE_MIN,
Math.min(this.catabolicHormone, CATABOLIC_HORMONE_MAX));
}
/**
* Receives hormones from neighboring patches.
* @param anabolic The amount of anabolic hormones received.
* @param catabolic The amount of catabolic hormones received.
*/
public void receiveHormones(double anabolic, double catabolic) {
this.anabolicHormone += anabolic;
this.catabolicHormone += catabolic;
}
/**
* Returns the level of anabolic hormones.
* @return The level of anabolic hormones.
*/
public double getAnabolicHormone() {
return anabolicHormone;
}
/**
* Returns the level of catabolic hormones.
* @return The level of catabolic hormones.
*/
public double getCatabolicHormone() {
return catabolicHormone;
}
/**
* Sets the level of anabolic hormones.
* @param v The new level of anabolic hormones.
*/
public void setAnabolicHormone(double v) {
this.anabolicHormone = v;
}
/**
* Sets the level of catabolic hormones.
* @param v The new level of catabolic hormones.
*/
public void setCatabolicHormone(double v) {
this.catabolicHormone = v;
}
}
| kdyxnm/MCSS-ass2 | Patch.java | 1,660 | /**
* Updates hormone levels based on daily activities.
* @param fiberSize The size of the muscle fiber.
*/ | block_comment | en | false | 1,494 | 26 | 1,660 | 29 | 1,582 | 29 | 1,660 | 29 | 1,868 | 35 | false | false | false | false | false | true |
203067_6 | import CHG4343_Design_Project_CustomExcpetions.NumericalException;
/**
* Chemical species class represents a chemical species that might be present in the system. Current implementation
* includes species name and molar mass (molar mass is not utilized in the implementatin of the current project
* but might be useful if system is further extended to non-isothermal systems).
*/
public class ChemicalSpecies {
private double molarMass; // appropriate units
private String name; // name of chemical species
/**
* ChemicalSpecies object constructor.
* @param name Name of chemical species.
* @param molarMass Molar mass of species in appropriate units (if 0 then molar mass is unknown)
*/
public ChemicalSpecies(String name, double molarMass) {
// Check if name is valid
if(name == null || name.isEmpty()) {
throw new IllegalArgumentException("Name of chemical specie must be specified.");
}
// Check for negative molar mass. 0 is reserved for unspecified molar masses.
if(molarMass < 0) {
throw new NumericalException("Invalid molar mass value. Molar mass must not be negative.");
}
this.molarMass = molarMass;
this.name = name;
}
/**
* Copy constructor.
* @param source source object of type ChemicalSpecies
*/
public ChemicalSpecies(ChemicalSpecies source) {
this.name = source.name;
this.molarMass = source.molarMass;
}
/**
* Clone method.
* @return copy of current object
*/
public ChemicalSpecies clone() {
// Call to copy constructor
return new ChemicalSpecies(this);
}
/* Accessors & Mutators */
/**
* Molar mass accessor.
* @return molar mass.
*/
public double getMolarMass() { return this.molarMass; }
/**
* Molar mass mutator.
* @param molarMass molar mass in appropriate units.
*/
public void setMolarMass(double molarMass) {
if(molarMass < 0) throw new NumericalException("Attempting to assign negative molar mass to ChemicalSpecies object");
this.molarMass = molarMass;
}
/**
* Name accessor.
* @return name of chemical species.
*/
public String getName() { return this.name; }
/**
* Name mutator.
* @param name name of chemical species.
*/
public boolean setName(String name) {
if(name == null || name.isEmpty()) throw new IllegalArgumentException("Attempting to assign invalid name to ChemicalSpecies object");
this.name = name;
return true;
}
/**
* Equals method.
* @param comparator
* @return true if comparator is equal to current object.
*/
@Override
public boolean equals(Object comparator) {
if(comparator == null || comparator.getClass() != this.getClass()) return false;
return this.name.equals(((ChemicalSpecies) comparator).name) && this.molarMass == ((ChemicalSpecies) comparator).molarMass;
}
/**
* toString method.
* @return name of the chemical species.
*/
@Override
public String toString() {
return this.name;
}
}
| nilliax/CSTRSimulator.Java | src/ChemicalSpecies.java | 747 | /**
* Copy constructor.
* @param source source object of type ChemicalSpecies
*/ | block_comment | en | false | 705 | 20 | 747 | 20 | 793 | 22 | 747 | 20 | 903 | 24 | false | false | false | false | false | true |
204029_9 | // Class TestEnum reads in a letter as a string, and converts
// it to the appropriate LetterGrade. The number of times
// each grade appears is summed, using a switch statement.
// The tallies are printed, using a switch statement.
import java.io.*;
import java.util.*;
public class TestEnum
{
enum LetterGrade {A,B,C,D,F}
public static void main(String[] args) throws IOException
{
Scanner inFile = new Scanner(new FileReader("Enum.dat"));
LetterGrade grade;
String strGrade;
int ACount = 0;
int BCount = 0;
int CCount = 0;
int DCount = 0;
int FCount = 0;
while (inFile.hasNext())
{
grade = LetterGrade.valueOf(inFile.nextLine());
// Add one to tally associated with grade
switch (/* TO BE FILLED IN: Exercise 1 */)
{
/* TO BE FILLED IN: Exercise 2 */
}
}
for ( /* TO BE FILLED IN: Exercise 3 */
// Iterate through each value of LetterGrade
{
System.out.print(counter + ": ");
// Print tally associated with each LetterGrade
switch (counter)
{
/* TO BE FILLED IN: Exercise 4 */
}
}
}
}
| LoopGlitch26/Laboratory-Course-for-Java | TestEnum.java | 327 | // Print tally associated with each LetterGrade
| line_comment | en | false | 289 | 9 | 327 | 10 | 358 | 9 | 327 | 10 | 397 | 12 | false | false | false | false | false | true |
204647_0 | /**
* An object of type Card represents a playing card from a
* standard Poker deck, including Jokers. The card has a suit, which
* can be spades, hearts, diamonds, clubs, or joker. A spade, heart,
* diamond, or club has one of the 13 values: ace, 2, 3, 4, 5, 6, 7,
* 8, 9, 10, jack, queen, or king. Note that "ace" is considered to be
* the smallest value. A joker can also have an associated value;
* this value can be anything and can be used to keep track of several
* different jokers.
*/
public class Card {
public final static int SPADES = 0; // Codes for the 4 suits, plus Joker.
public final static int HEARTS = 1;
public final static int DIAMONDS = 2;
public final static int CLUBS = 3;
public final static int JOKER = 4;
public final static int ACE = 1; // Codes for the non-numeric cards.
public final static int JACK = 11; // Cards 2 through 10 have their
public final static int QUEEN = 12; // numerical values for their codes.
public final static int KING = 13;
/**
* This card's suit, one of the constants SPADES, HEARTS, DIAMONDS,
* CLUBS, or JOKER. The suit cannot be changed after the card is
* constructed.
*/
private final int suit;
/**
* The card's value. For a normal card, this is one of the values
* 1 through 13, with 1 representing ACE. For a JOKER, the value
* can be anything. The value cannot be changed after the card
* is constructed.
*/
private final int value;
/**
* Creates a Joker, with 1 as the associated value. (Note that
* "new Card()" is equivalent to "new Card(1,Card.JOKER)".)
*/
public Card() {
suit = JOKER;
value = 1;
}
/**
* Creates a card with a specified suit and value.
* @param theValue the value of the new card. For a regular card (non-joker),
* the value must be in the range 1 through 13, with 1 representing an Ace.
* You can use the constants Card.ACE, Card.JACK, Card.QUEEN, and Card.KING.
* For a Joker, the value can be anything.
* @param theSuit the suit of the new card. This must be one of the values
* Card.SPADES, Card.HEARTS, Card.DIAMONDS, Card.CLUBS, or Card.JOKER.
* @throws IllegalArgumentException if the parameter values are not in the
* permissible ranges
*/
public Card(int theValue, int theSuit) {
if (theSuit != SPADES && theSuit != HEARTS && theSuit != DIAMONDS &&
theSuit != CLUBS && theSuit != JOKER)
throw new IllegalArgumentException("Illegal playing card suit");
if (theSuit != JOKER && (theValue < 1 || theValue > 13))
throw new IllegalArgumentException("Illegal playing card value");
value = theValue;
suit = theSuit;
}
/**
* Returns the suit of this card.
* @returns the suit, which is one of the constants Card.SPADES,
* Card.HEARTS, Card.DIAMONDS, Card.CLUBS, or Card.JOKER
*/
public int getSuit() {
return suit;
}
/**
* Returns the value of this card.
* @return the value, which is one of the numbers 1 through 13, inclusive for
* a regular card, and which can be any value for a Joker.
*/
public int getValue() {
return value;
}
/**
* Returns a String representation of the card's suit.
* @return one of the strings "Spades", "Hearts", "Diamonds", "Clubs"
* or "Joker".
*/
public String getSuitAsString() {
switch ( suit ) {
case SPADES: return "Spades";
case HEARTS: return "Hearts";
case DIAMONDS: return "Diamonds";
case CLUBS: return "Clubs";
default: return "Joker";
}
}
/**
* Returns a String representation of the card's value.
* @return for a regular card, one of the strings "Ace", "2",
* "3", ..., "10", "Jack", "Queen", or "King". For a Joker, the
* string is always numerical.
*/
public String getValueAsString() {
if (suit == JOKER)
return "" + value;
else {
switch ( value ) {
case 1: return "Ace";
case 2: return "2";
case 3: return "3";
case 4: return "4";
case 5: return "5";
case 6: return "6";
case 7: return "7";
case 8: return "8";
case 9: return "9";
case 10: return "10";
case 11: return "Jack";
case 12: return "Queen";
default: return "King";
}
}
}
/**
* Returns a string representation of this card, including both
* its suit and its value (except that for a Joker with value 1,
* the return value is just "Joker"). Sample return values
* are: "Queen of Hearts", "10 of Diamonds", "Ace of Spades",
* "Joker", "Joker #2"
*/
public String toString() {
if (suit == JOKER) {
if (value == 1)
return "Joker";
else
return "Joker #" + value;
}
else
return getValueAsString() + " of " + getSuitAsString();
}
} // end class Card | CodeMari/cardGame | Card.java | 1,466 | /**
* An object of type Card represents a playing card from a
* standard Poker deck, including Jokers. The card has a suit, which
* can be spades, hearts, diamonds, clubs, or joker. A spade, heart,
* diamond, or club has one of the 13 values: ace, 2, 3, 4, 5, 6, 7,
* 8, 9, 10, jack, queen, or king. Note that "ace" is considered to be
* the smallest value. A joker can also have an associated value;
* this value can be anything and can be used to keep track of several
* different jokers.
*/ | block_comment | en | false | 1,428 | 157 | 1,466 | 171 | 1,519 | 158 | 1,466 | 171 | 1,665 | 167 | false | true | false | true | false | false |
204747_1 | import java.util.ArrayList;
import java.util.List;
/**
* Classname: UnaryExpression
* An abstract class made to share common code between all unary expressions(for operator on one operands).
*
* @author Elad Israel
* @version 1.0 01/05/2018
*/
public abstract class UnaryExpression extends BaseExpression {
/**
* Returns a list of the variables in the expression.
*
* @return list of Strings
*/
public List<String> getVariables() {
List<String> vars = new ArrayList<String>();
if (getExp().getVariables() != null) {
//joins all lists returning from the recursion(which adds all vars)
vars.addAll(getExp().getVariables());
}
//remove vars that appear more the once in the expression
vars = removeDuplicates(vars);
return vars;
}
/**
* getter for Expression.
*
* @return Expression
*/
public abstract Expression getExp();
}
| israelElad/OOP-Math-Expressions-Differentitation-Simplification | ass4/src/UnaryExpression.java | 233 | /**
* Returns a list of the variables in the expression.
*
* @return list of Strings
*/ | block_comment | en | false | 210 | 25 | 233 | 24 | 263 | 29 | 233 | 24 | 283 | 32 | false | false | false | false | false | true |
205199_0 | public class Help extends Command
{
public Help(CommandWord firstWord, String secondWord){
super(firstWord, secondWord);
}
/**
* Print out some help information.
* Here we print some stupid, cryptic message and a list of the
* command words.
*/
public String processCommand(Player player)
{
String yeahCommandWords_YEET = CommandWord.getCommandWords();
player.currentRoom.displayItems();
return "You are lost. You are alone. You wander"
+"\n"
+ "around at the university."
+"\n"
+"\n"
+"Your command words are:"
+"\n"
+ yeahCommandWords_YEET + "\n"
+"\n";
}
}
| vuducle/harambe-saving-1 | Help.java | 174 | /**
* Print out some help information.
* Here we print some stupid, cryptic message and a list of the
* command words.
*/ | block_comment | en | false | 165 | 33 | 174 | 33 | 189 | 36 | 174 | 33 | 206 | 37 | false | false | false | false | false | true |
205521_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 add expressions.
*/
public class Add extends BinArithExpr {
/** Default constructor.
*/
public Add(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 "Add"; }
}
| zipwith/minitour | 08/ast/Add.java | 268 | /** Return a string that provides a simple description of this
* particular type of operator node.
*/ | block_comment | en | false | 257 | 23 | 268 | 22 | 288 | 24 | 268 | 22 | 328 | 24 | false | false | false | false | false | true |
205843_3 | package GUI;
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import java.io.*;
public class UserInfoForm extends JFrame implements ActionListener {
private JLabel nameLabel;
private JTextField nameField;
private JLabel genderLabel;
private JRadioButton maleRadioButton;
private JRadioButton femaleRadioButton;
private JLabel interestsLabel;
private JCheckBox sportsCheckBox;
private JCheckBox moviesCheckBox;
private JCheckBox musicCheckBox;
private JButton submitButton;
public UserInfoForm() {
super("User Information Form");
setLayout(new FlowLayout());
// Create name input field
nameLabel = new JLabel("Name:");
add(nameLabel);
nameField = new JTextField(20);
add(nameField);
// Create gender input field
genderLabel = new JLabel("Gender:");
add(genderLabel);
maleRadioButton = new JRadioButton("Male");
femaleRadioButton = new JRadioButton("Female");
ButtonGroup genderGroup = new ButtonGroup();
genderGroup.add(maleRadioButton);
genderGroup.add(femaleRadioButton);
JPanel genderPanel = new JPanel();
genderPanel.add(maleRadioButton);
genderPanel.add(femaleRadioButton);
add(genderPanel);
// Create interests input field
interestsLabel = new JLabel("Interests:");
add(interestsLabel);
sportsCheckBox = new JCheckBox("Sports");
moviesCheckBox = new JCheckBox("Movies");
musicCheckBox = new JCheckBox("Music");
JPanel interestsPanel = new JPanel();
interestsPanel.add(sportsCheckBox);
interestsPanel.add(moviesCheckBox);
interestsPanel.add(musicCheckBox);
add(interestsPanel);
// Create submit button
submitButton = new JButton("Submit");
submitButton.addActionListener(this);
add(submitButton);
pack();
setVisible(true);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
@Override
public void actionPerformed(ActionEvent e) {
// Get user information
String name = nameField.getText();
String gender = maleRadioButton.isSelected() ? "Male" : "Female";
String interests = "";
if (sportsCheckBox.isSelected()) {
interests += "Sports, ";
}
if (moviesCheckBox.isSelected()) {
interests += "Movies, ";
}
if (musicCheckBox.isSelected()) {
interests += "Music, ";
}
interests = interests.isEmpty() ? "None" : interests.substring(0, interests.length() - 2);
// Write user information to file
try (PrintWriter writer = new PrintWriter(new FileWriter("user_info.txt", true))) {
writer.printf("Name: %s\n", name);
writer.printf("Gender: %s\n", gender);
writer.printf("Interests: %s\n", interests);
writer.println();
writer.flush();
JOptionPane.showMessageDialog(this, "User information saved successfully!", "Success",
JOptionPane.INFORMATION_MESSAGE);
} catch (IOException ex) {
ex.printStackTrace();
JOptionPane.showMessageDialog(this, "Failed to save user information.", "Error", JOptionPane.ERROR_MESSAGE);
}
}
public static void main(String[] args) {
new UserInfoForm();
}
}
| rishavnathpati/JAVA | GUI/UserInfoForm.java | 730 | // Create submit button | line_comment | en | false | 646 | 4 | 730 | 4 | 775 | 4 | 730 | 4 | 892 | 4 | false | false | false | false | false | true |
206446_14 | // This file is part of OpenTSDB.
// Copyright (C) 2010 StumbleUpon, Inc.
//
// This program is free software: you can redistribute it and/or modify it
// under the terms of the GNU Lesser General Public License as published by
// the Free Software Foundation, either version 3 of the License, or (at your
// option) any later version. This program 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 Lesser
// General Public License for more details. You should have received a copy
// of the GNU Lesser General Public License along with this program. If not,
// see <http://www.gnu.org/licenses/>.
package net.opentsdb.graph;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.Map;
import java.util.TimeZone;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import net.opentsdb.core.DataPoint;
import net.opentsdb.core.DataPoints;
/**
* Produces files to generate graphs with Gnuplot.
* <p>
* This class takes a bunch of {@link DataPoints} instances and generates a
* Gnuplot script as well as the corresponding data files to feed to Gnuplot.
*/
public final class Plot {
private static final Logger LOG = LoggerFactory.getLogger(Plot.class);
/** Start time (UNIX timestamp in seconds) on 32 bits ("unsigned" int). */
private int start_time;
/** End time (UNIX timestamp in seconds) on 32 bits ("unsigned" int). */
private int end_time;
/** All the DataPoints we want to plot. */
private ArrayList<DataPoints> datapoints =
new ArrayList<DataPoints>();
/** Per-DataPoints Gnuplot options. */
private ArrayList<String> options = new ArrayList<String>();
/** Global Gnuplot parameters. */
private Map<String, String> params;
/** Minimum width / height allowed. */
private static final short MIN_PIXELS = 100;
/** Width of the graph to generate, in pixels. */
private short width = (short) 1024;
/** Height of the graph to generate, in pixels. */
private short height = (short) 768;
/**
* Number of seconds of difference to apply in order to get local time.
* Gnuplot always renders timestamps in UTC, so we simply apply a delta
* to get local time. If the local time changes (e.g. due to DST changes)
* we won't pick up the change unless we restart.
* TODO(tsuna): Do we want to recompute the offset every day to avoid this
* problem?
*/
private static final int utc_offset =
TimeZone.getDefault().getOffset(System.currentTimeMillis()) / 1000;
/**
* Constructor.
* @param start_time Timestamp of the start time of the graph.
* @param end_time Timestamp of the end time of the graph.
* @throws IllegalArgumentException if either timestamp is 0 or negative.
* @throws IllegalArgumentException if {@code start_time >= end_time}.
*/
public Plot(final long start_time, final long end_time) {
if ((start_time & 0xFFFFFFFF00000000L) != 0) {
throw new IllegalArgumentException("Invalid start time: " + start_time);
} else if ((end_time & 0xFFFFFFFF00000000L) != 0) {
throw new IllegalArgumentException("Invalid end time: " + end_time);
} else if (start_time >= end_time) {
throw new IllegalArgumentException("start time (" + start_time
+ ") is greater than or equal to end time: " + end_time);
}
this.start_time = (int) start_time;
this.end_time = (int) end_time;
}
private long startTime() {
return start_time & 0x00000000FFFFFFFFL;
}
private long endTime() {
return end_time & 0x00000000FFFFFFFFL;
}
/**
* Sets the global parameters for this plot.
* @param params Each entry is a Gnuplot setting that will be written as-is
* in the Gnuplot script file: {@code set KEY VALUE}.
* When the value is {@code null} the script will instead contain
* {@code unset KEY}.
*/
public void setParams(final Map<String, String> params) {
this.params = params;
}
/**
* Sets the dimensions of the graph (in pixels).
* @param width The width of the graph produced (in pixels).
* @param height The height of the graph produced (in pixels).
* @throws IllegalArgumentException if the width or height are negative,
* zero or "too small" (e.g. less than 100x100 pixels).
*/
public void setDimensions(final short width, final short height) {
if (width < MIN_PIXELS || height < MIN_PIXELS) {
final String what = width < MIN_PIXELS ? "width" : "height";
throw new IllegalArgumentException(what + " smaller than " + MIN_PIXELS
+ " in " + width + 'x' + height);
}
this.width = width;
this.height = height;
}
/**
* Adds some data points to this plot.
* @param datapoints The data points to plot.
* @param options The options to apply to this specific series.
*/
public void add(final DataPoints datapoints,
final String options) {
// Technically, we could check the number of data points in the
// datapoints argument in order to do something when there are none, but
// this is potentially expensive with a SpanGroup since it requires
// iterating through the entire SpanGroup. We'll check this later
// when we're trying to use the data, in order to avoid multiple passes
// through the entire data.
this.datapoints.add(datapoints);
this.options.add(options);
}
/**
* Returns a view on the datapoints in this plot.
* Do not attempt to modify the return value.
*/
public Iterable<DataPoints> getDataPoints() {
return datapoints;
}
/**
* Generates the Gnuplot script and data files.
* @param basepath The base path to use. A number of new files will be
* created and their names will all start with this string.
* @return The number of data points sent to Gnuplot. This can be less
* than the number of data points involved in the query due to things like
* aggregation or downsampling.
* @throws IOException if there was an error while writing one of the files.
*/
public int dumpToFiles(final String basepath) throws IOException {
int npoints = 0;
final int nseries = datapoints.size();
final String datafiles[] = nseries > 0 ? new String[nseries] : null;
for (int i = 0; i < nseries; i++) {
datafiles[i] = basepath + "_" + i + ".dat";
final PrintWriter datafile = new PrintWriter(datafiles[i]);
try {
for (final DataPoint d : datapoints.get(i)) {
final long ts = d.timestamp();
if (ts >= start_time && ts <= end_time) {
npoints++;
}
datafile.print(ts + utc_offset);
datafile.print(' ');
if (d.isInteger()) {
datafile.print(d.longValue());
} else {
final double value = d.doubleValue();
if (value != value || Double.isInfinite(value)) {
throw new IllegalStateException("NaN or Infinity found in"
+ " datapoints #" + i + ": " + value + " d=" + d);
}
datafile.print(value);
}
datafile.print('\n');
}
} finally {
datafile.close();
}
}
if (npoints == 0) {
// Gnuplot doesn't like empty graphs when xrange and yrange aren't
// entirely defined, because it can't decide on good ranges with no
// data. We always set the xrange, but the yrange is supplied by the
// user. Let's make sure it defines a min and a max.
params.put("yrange", "[0:10]"); // Doesn't matter what values we use.
}
writeGnuplotScript(basepath, datafiles);
return npoints;
}
/**
* Generates the Gnuplot script.
* @param basepath The base path to use.
* @param datafiles The names of the data files that need to be plotted,
* in the order in which they ought to be plotted. It is assumed that
* the ith file will correspond to the ith entry in {@code datapoints}.
* Can be {@code null} if there's no data to plot.
*/
private void writeGnuplotScript(final String basepath,
final String[] datafiles) throws IOException {
final String script_path = basepath + ".gnuplot";
final PrintWriter gp = new PrintWriter(script_path);
try {
// XXX don't hardcode all those settings. At least not like that.
gp.append("set terminal png size ")
// Why the fuck didn't they also add methods for numbers?
.append(Short.toString(width)).append(",")
.append(Short.toString(height)).append("\n"
+ "set xdata time\n"
+ "set timefmt \"%s\"\n"
+ "set format x \"").append(xFormat())
.append("\"\n"
+ "set xtic rotate\n"
+ "set output \"").append(basepath + ".png").append("\"\n"
+ "set xrange [\"")
.append(String.valueOf(start_time + utc_offset))
.append("\":\"")
.append(String.valueOf(end_time + utc_offset))
.append("\"]\n");
final int nseries = datapoints.size();
if (nseries > 0) {
gp.write("set grid\n"
+ "set style data linespoints\n");
if (!params.containsKey("key")) {
gp.write("set key right box\n");
}
} else {
gp.write("unset key\n");
if (params == null || !params.containsKey("label")) {
gp.write("set label \"No data\" at graph 0.5,0.9 center\n");
}
}
if (params != null) {
for (final Map.Entry<String, String> entry : params.entrySet()) {
final String key = entry.getKey();
final String value = entry.getValue();
if (value != null) {
gp.append("set ").append(key)
.append(' ').append(value).write('\n');
} else {
gp.append("unset ").append(key).write('\n');
}
}
}
for (final String opts : options) {
if (opts.contains("x1y2")) {
// Create a second scale for the y-axis on the right-hand side.
gp.write("set y2tics border\n");
break;
}
}
gp.write("plot ");
for (int i = 0; i < nseries; i++) {
final DataPoints dp = datapoints.get(i);
final String title = dp.metricName() + dp.getTags();
gp.append(" \"").append(datafiles[i]).append("\" using 1:2 title \"")
// TODO(tsuna): Escape double quotes in title.
.append(title).write('"');
final String opts = options.get(i);
if (!opts.isEmpty()) {
gp.append(' ').write(opts);
}
if (i != nseries - 1) {
gp.print(", \\");
}
gp.write('\n');
}
if (nseries == 0) {
gp.write('0');
}
} finally {
gp.close();
LOG.info("Wrote Gnuplot script to " + script_path);
}
}
/**
* Finds some sensible default formatting for the X axis (time).
* @return The Gnuplot time format string to use.
*/
private String xFormat() {
long timespan = end_time - start_time;
if (timespan < 2100) { // 35m
return "%H:%M:%S";
} else if (timespan < 86400) { // 1d
return "%H:%M";
} else if (timespan < 604800) { // 1w
return "%a %H:%M";
} else if (timespan < 1209600) { // 2w
return "%a %d %H:%M";
} else if (timespan < 7776000) { // 90d
return "%b %d";
} else {
return "%Y/%m/%d";
}
}
}
| otus/otus | opentsdb/src/graph/Plot.java | 3,093 | /** End time (UNIX timestamp in seconds) on 32 bits ("unsigned" int). */ | block_comment | en | false | 2,883 | 20 | 3,093 | 20 | 3,340 | 20 | 3,093 | 20 | 3,580 | 21 | false | false | false | false | false | true |
206671_36 | /*
* $Id: 62b80dcf70d6a06295956bf4c388ea1ec148abed $
*
* This file is part of the iText (R) project.
* Copyright (c) 1998-2016 iText Group NV
* Authors: Bruno Lowagie, Paulo Soares, et al.
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License version 3
* as published by the Free Software Foundation with the addition of the
* following permission added to Section 15 as permitted in Section 7(a):
* FOR ANY PART OF THE COVERED WORK IN WHICH THE COPYRIGHT IS OWNED BY
* ITEXT GROUP. ITEXT GROUP DISCLAIMS THE WARRANTY OF NON INFRINGEMENT
* OF THIRD PARTY RIGHTS
*
* This program 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 Affero General Public License for more details.
* You should have received a copy of the GNU Affero General Public License
* along with this program; if not, see http://www.gnu.org/licenses or write to
* the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
* Boston, MA, 02110-1301 USA, or download the license from the following URL:
* http://itextpdf.com/terms-of-use/
*
* The interactive user interfaces in modified source and object code versions
* of this program must display Appropriate Legal Notices, as required under
* Section 5 of the GNU Affero General Public License.
*
* In accordance with Section 7(b) of the GNU Affero General Public License,
* a covered work must retain the producer line in every PDF that is created
* or manipulated using iText.
*
* You can be released from the requirements of the license by purchasing
* a commercial license. Buying such a license is mandatory as soon as you
* develop commercial activities involving the iText software without
* disclosing the source code of your own applications.
* These activities include: offering paid services to customers as an ASP,
* serving PDFs on the fly in a web application, shipping iText with a closed
* source product.
*
* For more information, please contact iText Software Corp. at this
* address: [email protected]
*/
package com.itextpdf.text;
import java.lang.reflect.Field;
import com.itextpdf.text.error_messages.MessageLocalization;
/**
* The <CODE>PageSize</CODE>-object contains a number of rectangles representing the most common paper sizes.
*
* @see Rectangle
*/
public class PageSize {
// membervariables
/** This is the letter format */
public static final Rectangle LETTER = new RectangleReadOnly(612,792);
/** This is the note format */
public static final Rectangle NOTE = new RectangleReadOnly(540,720);
/** This is the legal format */
public static final Rectangle LEGAL = new RectangleReadOnly(612,1008);
/** This is the tabloid format */
public static final Rectangle TABLOID = new RectangleReadOnly(792,1224);
/** This is the executive format */
public static final Rectangle EXECUTIVE = new RectangleReadOnly(522,756);
/** This is the postcard format */
public static final Rectangle POSTCARD = new RectangleReadOnly(283,416);
/** This is the a0 format */
public static final Rectangle A0 = new RectangleReadOnly(2384,3370);
/** This is the a1 format */
public static final Rectangle A1 = new RectangleReadOnly(1684,2384);
/** This is the a2 format */
public static final Rectangle A2 = new RectangleReadOnly(1191,1684);
/** This is the a3 format */
public static final Rectangle A3 = new RectangleReadOnly(842,1191);
/** This is the a4 format */
public static final Rectangle A4 = new RectangleReadOnly(595,842);
/** This is the a5 format */
public static final Rectangle A5 = new RectangleReadOnly(420,595);
/** This is the a6 format */
public static final Rectangle A6 = new RectangleReadOnly(297,420);
/** This is the a7 format */
public static final Rectangle A7 = new RectangleReadOnly(210,297);
/** This is the a8 format */
public static final Rectangle A8 = new RectangleReadOnly(148,210);
/** This is the a9 format */
public static final Rectangle A9 = new RectangleReadOnly(105,148);
/** This is the a10 format */
public static final Rectangle A10 = new RectangleReadOnly(73,105);
/** This is the b0 format */
public static final Rectangle B0 = new RectangleReadOnly(2834,4008);
/** This is the b1 format */
public static final Rectangle B1 = new RectangleReadOnly(2004,2834);
/** This is the b2 format */
public static final Rectangle B2 = new RectangleReadOnly(1417,2004);
/** This is the b3 format */
public static final Rectangle B3 = new RectangleReadOnly(1000,1417);
/** This is the b4 format */
public static final Rectangle B4 = new RectangleReadOnly(708,1000);
/** This is the b5 format */
public static final Rectangle B5 = new RectangleReadOnly(498,708);
/** This is the b6 format */
public static final Rectangle B6 = new RectangleReadOnly(354,498);
/** This is the b7 format */
public static final Rectangle B7 = new RectangleReadOnly(249,354);
/** This is the b8 format */
public static final Rectangle B8 = new RectangleReadOnly(175,249);
/** This is the b9 format */
public static final Rectangle B9 = new RectangleReadOnly(124,175);
/** This is the b10 format */
public static final Rectangle B10 = new RectangleReadOnly(87,124);
/** This is the archE format */
public static final Rectangle ARCH_E = new RectangleReadOnly(2592,3456);
/** This is the archD format */
public static final Rectangle ARCH_D = new RectangleReadOnly(1728,2592);
/** This is the archC format */
public static final Rectangle ARCH_C = new RectangleReadOnly(1296,1728);
/** This is the archB format */
public static final Rectangle ARCH_B = new RectangleReadOnly(864,1296);
/** This is the archA format */
public static final Rectangle ARCH_A = new RectangleReadOnly(648,864);
/** This is the American Foolscap format */
public static final Rectangle FLSA = new RectangleReadOnly(612,936);
/** This is the European Foolscap format */
public static final Rectangle FLSE = new RectangleReadOnly(648,936);
/** This is the halfletter format */
public static final Rectangle HALFLETTER = new RectangleReadOnly(396,612);
/** This is the 11x17 format */
public static final Rectangle _11X17 = new RectangleReadOnly(792,1224);
/** This is the ISO 7810 ID-1 format (85.60 x 53.98 mm or 3.370 x 2.125 inch) */
public static final Rectangle ID_1 = new RectangleReadOnly(242.65f,153);
/** This is the ISO 7810 ID-2 format (A7 rotated) */
public static final Rectangle ID_2 = new RectangleReadOnly(297,210);
/** This is the ISO 7810 ID-3 format (B7 rotated) */
public static final Rectangle ID_3 = new RectangleReadOnly(354,249);
/** This is the ledger format */
public static final Rectangle LEDGER = new RectangleReadOnly(1224,792);
/** This is the Crown Quarto format */
public static final Rectangle CROWN_QUARTO = new RectangleReadOnly(535,697);
/** This is the Large Crown Quarto format */
public static final Rectangle LARGE_CROWN_QUARTO = new RectangleReadOnly(569,731);
/** This is the Demy Quarto format. */
public static final Rectangle DEMY_QUARTO = new RectangleReadOnly(620,782);
/** This is the Royal Quarto format. */
public static final Rectangle ROYAL_QUARTO = new RectangleReadOnly(671,884);
/** This is the Crown Octavo format */
public static final Rectangle CROWN_OCTAVO = new RectangleReadOnly(348,527);
/** This is the Large Crown Octavo format */
public static final Rectangle LARGE_CROWN_OCTAVO = new RectangleReadOnly(365,561);
/** This is the Demy Octavo format */
public static final Rectangle DEMY_OCTAVO = new RectangleReadOnly(391,612);
/** This is the Royal Octavo format. */
public static final Rectangle ROYAL_OCTAVO = new RectangleReadOnly(442,663);
/** This is the small paperback format. */
public static final Rectangle SMALL_PAPERBACK = new RectangleReadOnly(314,504);
/** This is the Pengiun small paperback format. */
public static final Rectangle PENGUIN_SMALL_PAPERBACK = new RectangleReadOnly(314,513);
/** This is the Penguin large paperback format. */
public static final Rectangle PENGUIN_LARGE_PAPERBACK = new RectangleReadOnly(365,561);
// Some extra shortcut values for pages in Landscape
/**
* This is the letter format
* @since iText 5.0.6
* @deprecated
*/
public static final Rectangle LETTER_LANDSCAPE = new RectangleReadOnly(612, 792, 90);
/**
* This is the legal format
* @since iText 5.0.6
* @deprecated
*/
public static final Rectangle LEGAL_LANDSCAPE = new RectangleReadOnly(612, 1008, 90);
/**
* This is the a4 format
* @since iText 5.0.6
* @deprecated
*/
public static final Rectangle A4_LANDSCAPE = new RectangleReadOnly(595, 842, 90);
/**
* This method returns a Rectangle based on a String.
* Possible values are the the names of a constant in this class
* (for instance "A4", "LETTER",...) or a value like "595 842"
* @param name the name as defined by the constants of PageSize or a numeric pair string
* @return the rectangle
*/
public static Rectangle getRectangle(String name) {
name = name.trim().toUpperCase();
int pos = name.indexOf(' ');
if (pos == -1) {
try {
Field field = PageSize.class.getDeclaredField(name.toUpperCase());
return (Rectangle) field.get(null);
} catch (Exception e) {
throw new RuntimeException(MessageLocalization.getComposedMessage("can.t.find.page.size.1", name));
}
}
else {
try {
String width = name.substring(0, pos);
String height = name.substring(pos + 1);
return new Rectangle(Float.parseFloat(width), Float.parseFloat(height));
} catch(Exception e) {
throw new RuntimeException(MessageLocalization.getComposedMessage("1.is.not.a.valid.page.size.format.2", name, e.getMessage()));
}
}
}
}
| Bojo38/tourma | src/com/itextpdf/text/PageSize.java | 2,882 | /** This is the American Foolscap format */ | block_comment | en | false | 2,731 | 10 | 2,882 | 11 | 2,947 | 9 | 2,882 | 11 | 3,397 | 11 | false | false | false | false | false | true |
206768_4 | package com.blogspot.agilisto.classifieds.services;
import java.util.List;
import com.blogspot.agilisto.classifieds.model.Enquiry;
/**
* CRUD service for Enquiry domain model
*/
public interface EnquiryService {
/**
* Store the Enquiry record.
*
* @param listing
* @return The <code>enquiry.id</code> of the record created.
*/
String save(Enquiry enquiry);
/**
* Get all the Enquiry records associated with the query.
*
* @param queryKey The field in {@link Enquiry} to match.
* @param queryValue The value of the field to match.
* @return List<Enquiry> object, <code>null</code> if not found.
*/
List<Enquiry> getEnquiries(String queryKey, Object queryValue);
/**
* Update multiple Enquiry(s)
*
* @param queryKey The field in {@link Enquiry} to match.
* @param queryValue The value of the field to match.
* @param updateKey The field in <code>Enquiry</code> to update.
* @param updateValue The object to update.
*/
void updateEnquiries(String queryKey, Object queryValue, String updateKey, Object updateValue);
/**
* Delete a single Enquiry.
*
* @param id The <code>Enquiry.id</code> of the record to delete.
*/
void deleteEnquiry(String id);
/**
* Delete multiple Enquiry(s).
*
* @param queryKey The field in {@link Enquiry} to match.
* @param queryValue The value of the field to match.
*/
void deleteEnquiries(String queryKey, Object queryValue);
}
| johnnymitrevski/classifiedsMVC | src/main/java/com/blogspot/agilisto/classifieds/services/EnquiryService.java | 425 | /**
* Delete a single Enquiry.
*
* @param id The <code>Enquiry.id</code> of the record to delete.
*/ | block_comment | en | false | 385 | 35 | 425 | 35 | 444 | 36 | 425 | 35 | 503 | 43 | false | false | false | false | false | true |
207230_2 | import javax.swing.JLabel;
/**
* A simple bank account. Still 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;
}
/**
* Change the balance by the given amount and update the label.
*
* @param change the amount by which to change the balance
*/
public void changeBalance(int change) {
balance = balance + change;
display.setText("" + balance);
// alternate:
// int newBalance = balance + change;
// display.setText("" + newBalance);
// balance = newBalance;
}
}
| SienaCSISAdvancedProgramming/ATMConcurrency | Danger2/Account.java | 312 | /**
* 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
*/ | block_comment | en | false | 302 | 55 | 312 | 51 | 344 | 58 | 312 | 51 | 367 | 59 | false | false | false | false | false | true |
207772_5 | package ku.util;
import java.util.EmptyStackException;
/**
* A stack with LIFO access and a fixed capacity.
* @author jim
*
* @param <T> the type of element the stack can hold
*/
public interface Stack<T> {
/**
* Remove the top element from stack and return it.
* @return the top element from stack.
* @throws EmptyStackException if stack is empty
*/
public T pop();
/**
* Return the top element from stack without removing it.
* @return the top element from stack, or null if empty.
*/
public T peek();
/**
* Push an element onto the stack.
* @param obj an item to push onto the top of the stack.
* @throws RuntimeException if stack is full
*/
public void push(T obj);
/**
* Test if stack is empty.
* @return true if the stack is empty, false otherwise.
*/
public boolean isEmpty();
/**
* Test if stack is full.
* @return true if the stack is full, false otherwise.
*/
public boolean isFull();
/**
* Get the capacity of the stack.
* @return capacity of the stack
*/
public int capacity();
/**
* Get the number of elements in the stack.
* @return number of elements currently in stack.
*/
public int size();
} | SSD2015/219244 | week8/Stack.java | 327 | /**
* Test if stack is full.
* @return true if the stack is full, false otherwise.
*/ | block_comment | en | false | 292 | 25 | 327 | 25 | 346 | 28 | 327 | 25 | 364 | 28 | false | false | false | false | false | true |
207794_22 |
// Queue.java
// =================
// This is a vanilla implementation of queues that supports O(1) enqueu() and
// dequeue() operations. Notice that we are able to easily re-use our
// VanillaLinkedList code to implement queues.
//
// O(1) enqueue is achieved by inserting nodes at the tail of the linked list
// O(1) dequeue is achieved by removing nodes from the head of the linked list
//
// Note: We can't remove nodes from the end of our lists in O(1) time because
// our nodes don't have 'previous' pointers. Therefore, we don't want to
// enqueue at the head of our list and dequeue from the tail; that would
// give those operations O(1) and O(n) runtimes, respectively.
import java.io.*;
// A basic queue class
public class Queue<AnythingYouLike> {
// We'll store our information in a linked list (using the VanillaLinkedList
// class, not the fancy version with generics).
LinkedList<AnythingYouLike> L;
// enqueue an element (insert at the end of the list)
void enqueue(AnythingYouLike data) {
L.insert(data);
}
// dequeue an element (remove from the head of the list)
AnythingYouLike dequeue() {
return L.removeHead();
}
// is the list empty?
boolean isEmpty() {
return (L.isEmpty());
}
// constructor; create the linked list
Queue() {
L = new LinkedList<AnythingYouLike>();
}
public static void main(String [] args) {
// create a new queue
Queue<Integer> q = new Queue<Integer>();
// load up the queue with some random integers
for (int i = 0; i < 10; i++)
{
int SomeRandomJunk = (int)(Math.random() * 100) + 1;
System.out.println("Enqueuing " + SomeRandomJunk);
q.enqueue(SomeRandomJunk);
}
// empty out the queue, printing the elements as we go
while (!q.isEmpty())
System.out.print(q.dequeue() + " ");
System.out.println();
Queue<String> qt = new Queue<String>();
qt.enqueue("Jim");
qt.enqueue("Rox");
while(!qt.isEmpty()){
System.out.print(qt.dequeue() + " ");
}
System.out.println();
}
} | JimVanG/Computer-Science-2 | src/Queue.java | 608 | // empty out the queue, printing the elements as we go | line_comment | en | false | 532 | 12 | 608 | 12 | 606 | 12 | 608 | 12 | 693 | 12 | false | false | false | false | false | true |
209303_0 | package model;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;
import javax.persistence.CascadeType;
import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.NamedQueries;
import javax.persistence.NamedQuery;
import javax.persistence.OneToMany;
/**
* User class is a Java representative of User table in database.
*
* @author Mateusz
*/
@Entity
@NamedQueries({
@NamedQuery(name="User.findAll", query="SELECT u FROM User u"),
@NamedQuery(name="User.findBySurname", query="SELECT u FROM User u where u.surname = :surname") })
public class User implements Serializable {
private static final long serialVersionUID = 1L;
private static final String adminLogin = "admin";
private static final String adminPassword = "admin123";
@Id
private String email;
private String name;
private String password;
private String phone;
private String surname;
@OneToMany(cascade = CascadeType.ALL, mappedBy="host")
private List<Apartment> apartments;
@OneToMany(cascade = CascadeType.ALL, mappedBy="sender")
private List<Message> messagesSent;
@OneToMany(cascade = CascadeType.ALL, mappedBy="receiver")
private List<Message> messagesReceived;
@OneToMany(cascade = CascadeType.ALL, mappedBy="user")
private List<Reservation> reservations;
public User() {
}
public User(String email, String name, String surname, String password, String phone, List<Apartment> apartments,
List<Message> messagesSent, List<Message> messagesReceived, List<Reservation> reservations) {
super();
this.email = email;
this.name = name;
this.password = password;
this.phone = phone;
this.surname = surname;
this.apartments = apartments;
this.messagesSent = messagesSent;
this.messagesReceived = messagesReceived;
this.reservations = reservations;
}
public User(String email, String name, String surname, String password, String phone) {
super();
this.email = email;
this.name = name;
this.password = password;
this.phone = phone;
this.surname = surname;
this.apartments = new ArrayList<Apartment>();
this.messagesSent = new ArrayList<Message>();
this.messagesReceived = new ArrayList<Message>();
this.reservations = new ArrayList<Reservation>();
}
public User(String email, String name, String phone, String surname)
{
super();
this.email = email;
this.name = name;
this.phone = phone;
this.surname = surname;
}
public String getEmail() {
return this.email;
}
public void setEmail(String email) {
this.email = email;
}
public String getName() {
return this.name;
}
public void setName(String name) {
this.name = name;
}
public String getPassword() {
return this.password;
}
public void setPassword(String password) {
this.password = password;
}
public String getPhone() {
return this.phone;
}
public void setPhone(String phone) {
this.phone = phone;
}
public String getSurname() {
return this.surname;
}
public void setSurname(String surname) {
this.surname = surname;
}
public List<Apartment> getApartments() {
return this.apartments;
}
public void setApartments(List<Apartment> apartments) {
this.apartments = apartments;
}
public Apartment addApartment(Apartment apartment) {
getApartments().add(apartment);
apartment.setHost(this);
return apartment;
}
public Apartment removeApartment(Apartment apartment) {
getApartments().remove(apartment);
apartment.setHost(null);
return apartment;
}
public List<Message> getMessagesSent() {
return this.messagesSent;
}
public void setMessagesSent(List<Message> messagesSent) {
this.messagesSent = messagesSent;
}
public Message addMessagesSent(Message messagesSent) {
getMessagesSent().add(messagesSent);
messagesSent.setSender(this);
return messagesSent;
}
public Message removeMessagesSent(Message messagesSent) {
getMessagesSent().remove(messagesSent);
messagesSent.setSender(null);
return messagesSent;
}
public List<Message> getMessagesReceived() {
return this.messagesReceived;
}
public void setMessagesReceived(List<Message> messagesReceived) {
this.messagesReceived = messagesReceived;
}
public Message addMessagesReceived(Message messagesReceived) {
getMessagesReceived().add(messagesReceived);
messagesReceived.setReceiver(this);
return messagesReceived;
}
public Message removeMessagesReceived(Message messagesReceived) {
getMessagesReceived().remove(messagesReceived);
messagesReceived.setReceiver(null);
return messagesReceived;
}
public List<Reservation> getReservations() {
return this.reservations;
}
public void setReservations(List<Reservation> reservations) {
this.reservations = reservations;
}
public Reservation addReservation(Reservation reservation) {
getReservations().add(reservation);
reservation.setUser(this);
return reservation;
}
public Reservation removeReservation(Reservation reservation) {
getReservations().remove(reservation);
reservation.setUser(null);
return reservation;
}
public static String getAdminlogin() {
return adminLogin;
}
public static String getAdminpassword() {
return adminPassword;
}
@Override
public String toString() {
return "User [email=" + email + ", name=" + name + ", password=" + password + ", phone=" + phone + ", surname="
+ surname + "]";
}
} | PiotrDucki/airbnb | src/main/java/model/User.java | 1,554 | /**
* User class is a Java representative of User table in database.
*
* @author Mateusz
*/ | block_comment | en | false | 1,162 | 23 | 1,554 | 27 | 1,576 | 27 | 1,554 | 27 | 1,830 | 28 | false | false | false | false | false | true |
209513_20 | package agent;
import Exceptions.NoPathException;
import agent.explorer.AStar;
import agent.explorer.Lee;
import agent.explorer.Vertex;
import agent.explorer.BaMMatrix;
import agent.explorer.BrickAndMortar;
import agent.sensation.SmellMatrix;
import agent.sensation.SoundMatrix;
import agent.sensation.VisionMatrix;
import controller.GameRunner;
import map.Tile;
import map.Vector2d;
import map.scenario.Area;
import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;
import java.util.Random;
import java.util.concurrent.atomic.AtomicReference;
public class Guard extends Agent{
private int exploredTilesCount;
private int lastDirection;
private boolean avoidOtherGuard;
private List<Tile> heardSounds;
private List<Tile> smelled;
private Vertex[][] graph = null;
private LinkedList<Vertex> path = new LinkedList<>();
private boolean spawned = true;
private Tile target;
private int count;
private Lee lee;
private BaMMatrix BaM;
/**
* @param position the current/initial position
* @param w the head facing vector
* @param theta the vision angle
* @param d the vision distance
* @param speed the base speed
* @param visionMatrix personal vision matrix
*/
public Guard(Tile position, Vector2d w, double theta, double d,
double smellDistance,
double speed,
VisionMatrix visionMatrix,
SmellMatrix smellMatrix,
KnowledgeMatrix knowledgeMatrix,
SoundMatrix soundMatrix) {
super(position, w, theta, d, smellDistance, speed, visionMatrix, smellMatrix, knowledgeMatrix, soundMatrix);
this.BaM = new BaMMatrix(visionMatrix,this);
lee = new Lee(visionMatrix, this);
}
@Override
public void act() {
boolean investigate = somethingToInvestigate();
for(int i = 0; i < speed; i++){
for(Tile tile : this.getTilesInFOV()) {
if(tile.getType().equals(Tile.Type.WALL) && !this.explored(tile)){
//if there is a new wall in the vision we need to recalculate the path
path.clear();
graph = null;
}
this.explore(tile);
}
if((investigate || !path.isEmpty())){
investigationExploration();
// System.out.println("I'M INVESTIGATING!");
} else {
//randomExploration();
hluExploration();
//BrickAndMortarExploration();
//lee.step();
}
}
// do something
produceSound();
reachedTarget();
count++;
// System.out.println("MOVE DONE!");
}
public void reachedTarget(){
if(target != null && this.position.getX() == target.getX() && this.position.getY() == target.getY()){
target = null;
path.clear();
}
}
private void randomExploration() {
Random rand = new Random();
List<Tile> neighbors = this.visionMatrix.getNeighborsOf(this.position);
boolean moved = false;
while (!moved) {
int randomIndex = rand.nextInt(neighbors.size());
moved = move(neighbors.get(randomIndex));
}
}
private void hluExploration(){
Vector2d newPosVector = knowledgeMatrix.decision(position, avoidOtherGuard);
avoidOtherGuard = false;
Tile newPos = visionMatrix.getTileFromVector(newPosVector);
explore(newPos);
visionMatrix.explore(newPos);
List<Tile> visionTiles = visionMatrix.getTilesInFOV(newPos, this.getW(), this.getTheta(), this.getD());
for(Tile t : visionTiles){
visionMatrix.explore(t);
}
move(newPos);
}
public void investigationExploration(){
Random rand = new Random();
if(!path.isEmpty()){
AStar(null);
}
else if(smelled.size() != 0){ // guards know the smell of guards
if(target == null){
int id = rand.nextInt(smelled.size());
target = smelled.get(id);
smelled.remove(id);
}
AStar(target);
// System.out.println("SMELL");
}
else if(heardSounds.size() != 0) { // an unknown sound
if(target == null) {
int id = rand.nextInt(heardSounds.size());
target = heardSounds.get(id);
heardSounds.remove(id);
}
AStar(target);
// System.out.println("SOUND");
}
else {
hluExploration();
// System.out.println("INVESTI - HLU");
}
}
private void AStar(Tile target){
//path from current position to goal
if(graph == null){
graph = visionMatrix.toGraph();
}
Tile goal = target;
//no need to recalculate path if there are still valid instructions left.
if(path.isEmpty()){
try {
path = AStar.path(graph[(int)position.getY()][(int)position.getX()],graph[(int)goal.getY()][(int)goal.getX()]);
path.remove(0);
} catch (NoPathException e) {
e.printStackTrace();
}
}
//move by first element of the path (not the one we are on)
try{
Tile newPos = path.remove(0).getTile();
avoidOtherGuard = false;
explore(newPos);
visionMatrix.explore(newPos);
boolean valid = move(newPos);
if(!valid){
path.clear();
}
else {
List<Tile> visionTiles = visionMatrix.getTilesInFOV(newPos, this.getW(), this.getTheta(), this.getD());
for(Tile t : visionTiles){
visionMatrix.explore(t);
// already explored
heardSounds.removeIf(t2 -> t.getX() == t2.getX() && t.getY() == t2.getY());
smelled.removeIf(t2 -> t.getX() == t2.getX() && t.getY() == t2.getY());
}
}
// System.out.println(newPos.toString());
}
catch(IndexOutOfBoundsException e){
}
}
private void BrickAndMortarExploration(){
Tile newPos = BrickAndMortar.explore(BaM, position);
visionMatrix.explore(newPos);
List<Tile> visionTiles = visionMatrix.getTilesInFOV(newPos, this.getW(), this.getTheta(), this.getD());
for(Tile t : visionTiles){
visionMatrix.explore(t);
}
move(newPos);
}
@Override
public void explore(Tile t) {
SoundMatrix soundMatrix = GameRunner.runner.getController().getGameState().getSoundMatrix();
soundMatrix.guardYell(this.getPosition(), this.getW(), this);
for(Intruder i:GameRunner.runner.getController().getGameState().getIntruders()){
if(i.getPosition().equals(t)){
soundMatrix.intruderYell(i.getPosition(), i.getW(), i);
caughtIntruder(i);
}
}
for(Guard g: GameRunner.runner.getController().getGameState().getGuards()){
if(! this.equals(g) && g.getPosition().equals(t)) {
avoidOtherGuard = true;
break;
}
}
if(!this.getVisionMatrix().isExplored(t)){
this.getVisionMatrix().explore(t);
exploredTilesCount++;
}
this.getKnowledgeMatrix().explore(t);
}
public double getExploredRatio() {
return (double) exploredTilesCount / (getVisionMatrix().getHeight()* getVisionMatrix().getWidth());
}
public void caughtIntruder(Intruder i){
i.hasBeenCaught();
//if all intruders have been caught guards win!!!
if(Intruder.getAmtCaught() == GameRunner.runner.getScene().getNumIntruders()){
if(GameRunner.PAUSE_AFTER_END) GameRunner.runner.getController().pause();
System.out.println("GUARDS WON!!!");
GameRunner.winner = "Guards";
GameRunner.FINISHED = true;
if(GameRunner.PRINT_INFORMATION_AFTER){
System.out.println("After game information:");
double progress = GameRunner.runner.getController().getGameState().getProgressGuards();
System.out.println("Guards explored " + progress + "% of the map");
System.out.println("Intruders caught: " + Intruder.getAmtCaught());
AtomicReference<Double> distance = new AtomicReference<Double>();
distance.set((double)Integer.MAX_VALUE);
GameRunner.runner.getController().getGameState().getIntruders().forEach(intr ->{
Tile pos = intr.getPosition();
Area tarArea = GameRunner.runner.getScene().getTargetArea();
Vector2d target = new Vector2d(tarArea.getBottomBoundary(),tarArea.getLeftBoundary());
double dist = target.getDistanceTo(pos);
distance.set(Math.min(distance.get(),dist));
});
System.out.println("Closest intruder to target: " + distance.get());
}
}
}
public List<Tile> getSmellTilesInSmell(){
List<Tile> smells = GameRunner.runner.getController().getGameState().marked;
List<Tile> smellArea = getTilesInSmell();
List<Tile> result = new ArrayList<>();
for(Tile t : smells){
if(smellArea.contains(t) && !pheromoneMarkers.contains(t) && !t.getType().equals(Tile.Type.WALL)){
boolean guardSmell = false;
for(Guard g : GameRunner.runner.getController().getGameState().getGuards()) {
if(g.getPheromoneMarkers().contains(t)) {
guardSmell = true;
}
}
if(!guardSmell) {
result.add(t);
}
}
}
return result;
}
public List<Tile> getSoundTilesInHearing(){
List<Tile> hearing = getTilesInHearing();
List<List<Tile>> sounds = new ArrayList<>(GameRunner.runner.getController().getGameState().getSounds());
sounds.remove(this.producedSound); // delete own sounds
for(Guard g : GameRunner.runner.getController().getGameState().getGuards()){
sounds.remove(g.getProducedSound());
}
List<Tile> result = new ArrayList<>();
for(List<Tile> soundArea : sounds){
for(Tile t : soundArea){
if(hearing.contains(t) && !t.getType().equals(Tile.Type.WALL)){
result.add(t);
}
}
}
return result;
}
public boolean somethingToInvestigate(){
// just spawned (ignore first 10 moves) or there does not exist intruders
if(spawned || GameRunner.runner.getController().getGameState().getIntruders().size() == 0 || count < 10) {
spawned = false;
return false;
}
List<Tile> sounds = getSoundTilesInHearing();
List<Tile> smells = getSmellTilesInSmell();
List<Tile> fov = getTilesInFOV();
for(Tile t : fov){
// remove already "investigated" tiles
smells.removeIf(t2 -> (t.getX() == t2.getX() && t.getY() == t2.getY()) ||
(this.position.getX() == t2.getX() && this.position.getY() == t2.getY()));
sounds.removeIf(t2 -> (t.getX() == t2.getX() && t.getY() == t2.getY()) ||
(this.position.getX() == t2.getX() && this.position.getY() == t2.getY()));
}
boolean result = sounds.size() != 0 || smells.size() != 0;
if(result){
this.heardSounds = new ArrayList<>(sounds);
this.smelled = new ArrayList<>(smells);
}
return result;
}
public boolean guardInVision(){
List<Tile> visionTiles = visionMatrix.getTilesInFOV(this.position, this.getW(), this.getTheta(), this.getD());
for(Tile t : visionTiles){
for(Guard g: GameRunner.runner.getController().getGameState().getGuards()){
if(!this.equals(g) && g.getPosition().equals(visionMatrix.getMap().getTileAt((int)t.getX(),(int)t.getY()))) {
System.out.println("true");
return true;
}
}
}
return false;
}
// checks that a guard is not in the 8 neighbors x4 of the current position tile
public boolean guardInRange(){
List<Tile> range = this.smellMatrix.getTilesInSmell(position, this.getW(), 4);
for(Tile t : range){
for(Guard g: GameRunner.runner.getController().getGameState().getGuards()){
if(!this.equals(g) && g.getPosition().equals(t)) {
return true;
}
}
}
return false;
}
}
| ericbanzuzi/multi_agent_surveillance | src/main/java/agent/Guard.java | 3,151 | // just spawned (ignore first 10 moves) or there does not exist intruders | line_comment | en | false | 2,760 | 19 | 3,151 | 20 | 3,326 | 17 | 3,151 | 20 | 3,775 | 20 | false | false | false | false | false | true |
209720_46 | import java.net.HttpURLConnection;
import java.net.URL;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
/**
* Almost whole class written by ChatGPT
*/
public class ApiCaller {
String apiKey;
/**
* ApiCaller class
* @param aApiKey Valid API key for Hypixel
*/
public ApiCaller (String aApiKey){
apiKey = aApiKey;
}
/**
* returns new auctions
* @return First page of new auctions
*/
public String CallNewAuctions() {
try {
// Construct the API endpoint URL with the UUID directly appended to it
String page = "10";
String apiUrl = "https://api.hypixel.net/v2/skyblock/auctions?key=" + apiKey + "&page=" + encodeValue(page);
// Create a URL object with the constructed API endpoint URL
URL url = new URL(apiUrl);
// Open a connection to the URL
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
// Set the request method to GET
connection.setRequestMethod("GET");
// Read the response from the API
BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getInputStream()));
StringBuilder response = new StringBuilder();
String line;
while ((line = reader.readLine()) != null) {
// Insert three line breaks before every occurrence of "{"uuid"
line = line.replaceAll("\\{\"uuid\"", "\n\n\n{\"uuid\"");
response.append(line);
}
// Close the reader and connection
reader.close();
connection.disconnect();
// Return the response from the API
return(response.toString());
} catch (Exception e) {
// Handle any exceptions that occur during the API call
System.err.println("Error: " + e.getMessage());
e.printStackTrace();
return("There was an error");
}
}
/**
* returns finished auctions
* @return last 60 seconds of called actions
*/
public String CallFinishedAuctions() {
try {
// Construct the API endpoint URL with the UUID directly appended to it
String page = "1";
String apiUrl = "https://api.hypixel.net/v2/skyblock/auctions_ended?key=" + apiKey;
// + "&page=" + encodeValue(page);
// Create a URL object with the constructed API endpoint URL
URL url = new URL(apiUrl);
// Open a connection to the URL
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
// Set the request method to GET
connection.setRequestMethod("GET");
// Read the response from the API
BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getInputStream()));
StringBuilder response = new StringBuilder();
String line;
while ((line = reader.readLine()) != null) {
// Insert three line breaks before every occurrence of "{"uuid"
line = line.replaceAll("\\{\"uuid\"", "\n\n\n{\"uuid\"");
response.append(line);
}
// Close the reader and connection
reader.close();
connection.disconnect();
// Return the response from the API
return(response.toString());
} catch (Exception e) {
// Handle any exceptions that occur during the API call
System.err.println("Error: " + e.getMessage());
e.printStackTrace();
return("There was an error");
}
}
/**
* Gets a specific auction
* @param type uuid or player or profile
* @param specific the uuid of the auction, player or profile
*/
public String CallSpecificAuction(String type, String specific) {
try {
// Construct the API endpoint URL with the UUID directly appended to it
type = "&" + type + "=";
String apiUrl = "https://api.hypixel.net/v2/skyblock/auction?key=" + apiKey + type + encodeValue(specific);
// Create a URL object with the constructed API endpoint URL
URL url = new URL(apiUrl);
// Open a connection to the URL
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
// Set the request method to GET
connection.setRequestMethod("GET");
// Read the response from the API
BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getInputStream()));
StringBuilder response = new StringBuilder();
String line;
while ((line = reader.readLine()) != null) {
// Insert three line breaks before every occurrence of "{"uuid"
line = line.replaceAll("\\{\"uuid\"", "\n\n\n{\"uuid\"");
response.append(line);
}
// Close the reader and connection
reader.close();
connection.disconnect();
// Return the response from the API
return(response.toString());
} catch (Exception e) {
// Handle any exceptions that occur during the API call
System.err.println("Error: " + e.getMessage());
e.printStackTrace();
return("There was an error");
}
}
/**
* Gets profile data of a player
* @param uuid uuid of the player profile
*/
public String CallProfileData(String uuid) {
try {
// Construct the API endpoint URL with the UUID directly appended to it
String apiUrl = "https://api.hypixel.net/v2/skyblock/profile?key=" + apiKey + "&profile=" + encodeValue(uuid);
// Create a URL object with the constructed API endpoint URL
URL url = new URL(apiUrl);
// Open a connection to the URL
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
// Set the request method to GET
connection.setRequestMethod("GET");
// Read the response from the API
BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getInputStream()));
StringBuilder response = new StringBuilder();
String line;
while ((line = reader.readLine()) != null) {
response.append(line);
}
// Close the reader and connection
reader.close();
connection.disconnect();
// Return the response from the API
return(response.toString());
} catch (Exception e) {
// Handle any exceptions that occur during the API call
System.err.println("Error: " + e.getMessage());
e.printStackTrace();
return("There was an error");
}
}
/**
* Helper method to encode URL parameters
*/
public static String encodeValue(String value) throws UnsupportedEncodingException {
return URLEncoder.encode(value, "UTF-8");
}
/**
* gives the details of the auction from coflnet
* @param uuid of the auction
* @return coflnet response
*/
public static String auctionDetails(String uuid){
try {
// Construct the API endpoint URL with the UUID directly appended to it
String apiUrl = "https://sky.coflnet.com/api/auction/" + encodeValue(uuid);
// Create a URL object with the constructed API endpoint URL
URL url = new URL(apiUrl);
// Open a connection to the URL
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
// Set the request method to GET
connection.setRequestMethod("GET");
// Read the response from the API
BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getInputStream()));
StringBuilder response = new StringBuilder();
String line;
while ((line = reader.readLine()) != null) {
response.append(line);
}
// Close the reader and connection
reader.close();
connection.disconnect();
// Return the response from the API
return(response.toString());
} catch (Exception e) {
// Handle any exceptions that occur during the API call
System.err.println("Error: " + e.getMessage());
e.printStackTrace();
return("There was an error");
}
}
}
| EliotParkRL/PriceCalculator | ApiCaller.java | 1,724 | /**
* Helper method to encode URL parameters
*/ | block_comment | en | false | 1,610 | 12 | 1,724 | 11 | 1,901 | 13 | 1,724 | 11 | 2,104 | 14 | false | false | false | false | false | true |
210378_12 | /*
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER.
*
* Copyright 1997-2007 Sun Microsystems, Inc. All rights reserved.
*
* The contents of this file are subject to the terms of either the GNU
* General Public License Version 2 only ("GPL") or the Common
* Development and Distribution License("CDDL") (collectively, the
* "License"). You may not use this file except in compliance with the
* License. You can obtain a copy of the License at
* http://www.netbeans.org/cddl-gplv2.html
* or nbbuild/licenses/CDDL-GPL-2-CP. See the License for the
* specific language governing permissions and limitations under the
* License. When distributing the software, include this License Header
* Notice in each file and include the License file at
* nbbuild/licenses/CDDL-GPL-2-CP. Sun designates this
* particular file as subject to the "Classpath" exception as provided
* by Sun in the GPL Version 2 section of the License file that
* accompanied this code. If applicable, add the following below the
* License Header, with the fields enclosed by brackets [] replaced by
* your own identifying information:
* "Portions Copyrighted [year] [name of copyright owner]"
*
* Contributor(s):
*
* The Original Software is NetBeans. The Initial Developer of the Original
* Software is Sun Microsystems, Inc. Portions Copyright 1997-2006 Sun
* Microsystems, Inc. All Rights Reserved.
* Portions Copyright 2008 Alexander Coles (Ikonoklastik Productions).
*
* If you wish your version of this file to be governed by only the CDDL
* or only the GPL Version 2, indicate your decision by adding
* "[Contributor] elects to include this software in this distribution
* under the [CDDL or GPL Version 2] license." If you do not indicate a
* single choice of license, a recipient has the option to distribute
* your version of this file under either the CDDL, the GPL Version 2 or
* to extend the choice of license to its licensees as provided above.
* However, if you add GPL Version 2 code and therefore, elected the GPL
* Version 2 license, then the option applies only if the new code is
* made subject to such option by the copyright holder.
*/
package org.nbgit;
import java.beans.PropertyChangeListener;
import java.beans.PropertyChangeSupport;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import java.util.logging.Level;
import java.util.logging.Logger;
import org.nbgit.util.GitUtils;
import org.netbeans.modules.versioning.spi.VCSContext;
import org.netbeans.modules.versioning.spi.VersioningSupport;
import org.openide.filesystems.FileObject;
import org.openide.filesystems.FileUtil;
import org.openide.util.RequestProcessor;
import org.spearce.jgit.lib.Repository;
/**
* Main entry point for Git functionality, use getInstance() to get the Git object.
*
* @author alexbcoles
* @author Maros Sandor
*/
public class Git {
public static final String GIT_OUTPUT_TAB_TITLE = org.openide.util.NbBundle.getMessage(Git.class, "CTL_Git_DisplayName"); // NOI18N
public static final String PROP_ANNOTATIONS_CHANGED = "annotationsChanged"; // NOI18N
public static final String PROP_VERSIONED_FILES_CHANGED = "versionedFilesChanged"; // NOI18N
public static final String PROP_CHANGESET_CHANGED = "changesetChanged"; // NOI18N
public static final Logger LOG = Logger.getLogger("org.nbgit"); // NOI18N
private static final int STATUS_DIFFABLE =
StatusInfo.STATUS_VERSIONED_UPTODATE |
StatusInfo.STATUS_VERSIONED_MODIFIEDLOCALLY |
StatusInfo.STATUS_VERSIONED_MODIFIEDINREPOSITORY |
StatusInfo.STATUS_VERSIONED_CONFLICT |
StatusInfo.STATUS_VERSIONED_MERGE |
StatusInfo.STATUS_VERSIONED_REMOVEDINREPOSITORY |
StatusInfo.STATUS_VERSIONED_MODIFIEDINREPOSITORY |
StatusInfo.STATUS_VERSIONED_MODIFIEDINREPOSITORY;
private final PropertyChangeSupport support = new PropertyChangeSupport(this);
private final StatusCache statusCache = new StatusCache(this);
private HashMap<String, RequestProcessor> processorsToUrl;
private final Map<File, Repository> repos = new HashMap<File, Repository>();
private static Git instance;
private Git() {
}
public static synchronized Git getInstance() {
if (instance == null) {
instance = new Git();
}
return instance;
}
public Repository getRepository(File root) {
Repository repo = repos.get(root);
if (repo == null) {
final File gitDir = new File(root, GitRepository.GIT_DIR);
try {
repo = new Repository(gitDir);
repos.put(root, repo);
} catch (IOException ex) {
}
}
return repo;
}
/**
* Gets the Status Cache for the Git repository.
*
* @return StatusCache for the repository
*/
public StatusCache getStatusCache() {
return statusCache;
}
/**
* Tests the <tt>.git</tt> directory itself.
*
* @param file
* @return
*/
public boolean isAdministrative(File file) {
String name = file.getName();
return isAdministrative(name) && file.isDirectory();
}
public boolean isAdministrative(String fileName) {
return fileName.equals(".git"); // NOI18N
}
/**
* Tests whether a file or directory should receive the STATUS_NOTVERSIONED_NOTMANAGED status.
* All files and folders that have a parent with CVS/Repository file are considered versioned.
*
* @param file a file or directory
* @return false if the file should receive the STATUS_NOTVERSIONED_NOTMANAGED status, true otherwise
*/
public boolean isManaged(File file) {
return VersioningSupport.getOwner(file) instanceof GitVCS && !GitUtils.isPartOfGitMetadata(file);
}
public File getTopmostManagedParent(File file) {
if (GitUtils.isPartOfGitMetadata(file)) {
for (; file != null; file = file.getParentFile()) {
if (isAdministrative(file)) {
file = file.getParentFile();
break;
}
}
}
File topmost = null;
for (; file != null; file = file.getParentFile()) {
if (org.netbeans.modules.versioning.util.Utils.isScanForbidden(file)) {
break;
}
if (new File(file, ".git").canWrite()) { // NOI18N
topmost = file;
break;
}
}
return topmost;
}
/**
* Uses content analysis to return the mime type for files.
*
* @param file file to examine
* @return String mime type of the file (or best guess)
*/
public String getMimeType(File file) {
FileObject fo = FileUtil.toFileObject(file);
String foMime;
if (fo == null) {
foMime = "content/unknown";
} else {
foMime = fo.getMIMEType();
if ("content/unknown".equals(foMime)) // NOI18N
{
foMime = "text/plain";
}
}
if ((statusCache.getStatus(file).getStatus() & StatusInfo.STATUS_VERSIONED) == 0) {
return GitUtils.isFileContentBinary(file) ? "application/octet-stream" : foMime;
} else {
return foMime;
}
}
public void versionedFilesChanged() {
support.firePropertyChange(PROP_VERSIONED_FILES_CHANGED, null, null);
}
public void refreshAllAnnotations() {
support.firePropertyChange(PROP_ANNOTATIONS_CHANGED, null, null);
}
public void changesetChanged(File repository) {
support.firePropertyChange(PROP_CHANGESET_CHANGED, repository, null);
}
public void addPropertyChangeListener(PropertyChangeListener listener) {
support.addPropertyChangeListener(listener);
}
public void removePropertyChangeListener(PropertyChangeListener listener) {
support.removePropertyChangeListener(listener);
}
public void getOriginalFile(File workingCopy, File originalFile) {
StatusInfo info = statusCache.getStatus(workingCopy);
LOG.log(Level.FINE, "getOriginalFile: {0} {1}", new Object[]{workingCopy, info}); // NOI18N
if ((info.getStatus() & STATUS_DIFFABLE) == 0) {
return; // We can get status returned as UptoDate instead of LocallyNew
// because refreshing of status after creation has been scheduled
// but may not have happened yet.
}
try {
File original = GitUtils.getFileRevision(workingCopy, GitRepository.REVISION_BASE);
if (original == null) {
return;
}
org.netbeans.modules.versioning.util.Utils.copyStreamsCloseAll(new FileOutputStream(originalFile), new FileInputStream(original));
original.delete();
} catch (IOException e) {
Logger.getLogger(Git.class.getName()).log(Level.INFO, "Unable to get original file", e); // NOI18N
}
}
/**
* Serializes all Git requests (moves them out of AWT).
*/
public RequestProcessor getRequestProcessor() {
return getRequestProcessor((String) null);
}
/**
* Serializes all Git requests (moves them out of AWT).
*/
public RequestProcessor getRequestProcessor(File file) {
return getRequestProcessor(file.getAbsolutePath());
}
public RequestProcessor getRequestProcessor(String url) {
if (processorsToUrl == null) {
processorsToUrl = new HashMap<String, RequestProcessor>();
}
String key;
if (url != null) {
key = url;
} else {
key = "ANY_URL";
}
RequestProcessor rp = processorsToUrl.get(key);
if (rp == null) {
rp = new RequestProcessor("Git - " + key, 1, true); // NOI18N
processorsToUrl.put(key, rp);
}
return rp;
}
public void clearRequestProcessor(String url) {
if (processorsToUrl != null & url != null) {
processorsToUrl.remove(url);
}
}
} | imyousuf/nbgit | src/org/nbgit/Git.java | 2,462 | /**
* Uses content analysis to return the mime type for files.
*
* @param file file to examine
* @return String mime type of the file (or best guess)
*/ | block_comment | en | false | 2,224 | 42 | 2,462 | 41 | 2,618 | 46 | 2,462 | 41 | 2,898 | 49 | false | false | false | false | false | true |
211114_0 | package chapter8Exersize;
import java.awt.*;
public class Frog extends RandomAnimals {
private int steps;
private int size;
public Frog(Point p, Graphics g) {
super("Frog", p, 120, 45, 7, g);
this.steps = 1;
this.size = 1;
}
public void draw() {
// create a drawing of the frog thing
Point p = super.getLocation();
Graphics g = super.getGraphics();
g.setColor(super.getColor());
g.fillRect(p.x, p.y, size, size);
}
public void move() {
super.move(1);
this.draw();
super.move(1);
super.draw();
super.move(1);
super.draw();
}
public String toString() {
return "F";
}
}
| jjemi8884/animalsGame | Frog.java | 233 | // create a drawing of the frog thing | line_comment | en | false | 180 | 8 | 233 | 9 | 235 | 8 | 233 | 9 | 265 | 9 | false | false | false | false | false | true |
211271_2 | import java.util.Scanner;
/**
* This class implements a shop simulation.
*
* @author Wei Tsang
* @version CS2030S AY20/21 Semester 2
*/
class ShopSimulation extends Simulation {
/**
* The availability of counters in the shop.
*/
public boolean[] available;
/**
* The list of customer arrival events to populate
* the simulation with.
*/
public Event[] initEvents;
/**
* Constructor for a shop simulation.
*
* @param sc A scanner to read the parameters from. The first
* integer scanned is the number of customers; followed
* by the number of service counters. Next is a
* sequence of (arrival time, service time) pair, each
* pair represents a customer.
*/
public ShopSimulation(Scanner sc) {
initEvents = new Event[sc.nextInt()];
int numOfCounters = sc.nextInt();
available = new boolean[numOfCounters];
for (int i = 0; i < numOfCounters; i++) {
available[i] = true;
}
int id = 0;
while (sc.hasNextDouble()) {
double arrivalTime = sc.nextDouble();
double serviceTime = sc.nextDouble();
initEvents[id] = new ShopEvent(ShopEvent.ARRIVAL,
arrivalTime, id, serviceTime, available);
id += 1;
}
}
/**
* Retrieve an array of events to populate the
* simulator with.
*
* @return An array of events for the simulator.
*/
@Override
public Event[] getInitialEvents() {
return initEvents;
}
}
| nus-cs2030s-2021-s2/lab1-skeleton | ShopSimulation.java | 385 | /**
* The list of customer arrival events to populate
* the simulation with.
*/ | block_comment | en | false | 374 | 21 | 385 | 20 | 426 | 23 | 385 | 20 | 470 | 23 | false | false | false | false | false | true |
211739_2 | // Environment code for project smarthome
import java.lang.Math;
import jason.asSyntax.*;
import jason.environment.*;
import jason.asSyntax.parser.*;
import java.util.logging.*;
import java.lang.Math.*;
public class Env extends Environment {
private Logger logger = Logger.getLogger("smarthome."+Env.class.getName());
private boolean veszelyvan = false;
private boolean ajtoNyitva = false;
/** Called before the MAS execution with the args informed in .mas2j */
@Override
public void init(String[] args) {
super.init(args);
try {
addPercept(ASSyntax.parseLiteral("percept("+args[0]+")"));
} catch (ParseException e) {
e.printStackTrace();
}
}
@Override
public boolean executeAction(String agName, Structure action) {
clearPercepts();
double rnd = Math.random();
switch(action.getFunctor()){
case "gyujtas" -> {
addPercept(Literal.parseLiteral("tuz"));
veszelyvan=true;
}
case "mozgas" -> {
if(!veszelyvan){
if(rnd>0.5){addPercept(Literal.parseLiteral("azonositasTrue"));}
else{addPercept(Literal.parseLiteral("azonositasFalse"));}
}
}
case "ajtonyitas" -> {
addPercept(Literal.parseLiteral("ajtonyitas"));
ajtoNyitva = true;
}
case "ajtocsukas" -> {
if(!veszelyvan){
addPercept(Literal.parseLiteral("ajtocsukas"));
ajtoNyitva = false;
}
}
case "elmultAVeszely" -> {
veszelyvan=false;
}
case "check" -> {
if(Math.random() > 0.85){
addPercept(Literal.parseLiteral("dirt"));
}
}
default -> logger.info("executing: " + action + ", but not implemented!");
}
informAgsEnvironmentChanged();
return true; // the action was executed with success
}
/** Called before the end of MAS execution */
@Override
public void stop() {
super.stop();
}
}
| pacsinta/SmartHome-agentSystem | src/Env.java | 539 | // the action was executed with success | line_comment | en | false | 489 | 7 | 539 | 7 | 575 | 7 | 539 | 7 | 632 | 7 | false | false | false | false | false | true |
212107_12 | import java.awt.Color;
import junit.framework.TestCase;
/*
* This testing framework provides basic level tests for
* each of the methods, however additional testing will be
* required, along with extensive testing of ALL helper methods
* that you write.
*/
public class PictureECTest extends TestCase {
/*
* Validate that flip(Picture.HORIZONTAL) works and does not modify the
* original Picture object.
*/
public void testFlipHorixontal_Logos()
{
Picture pic = Picture.loadPicture("Logos.bmp");
Picture picCopy = new Picture(pic);
Picture picCorrect = Picture.loadPicture("Logos_flipHorizontally.bmp");
Picture picTest = pic.flip(Picture.HORIZONTAL);
assertTrue(pic.equals(picCopy));
assertTrue(picCorrect.equals(picTest));
}
/*
* Validate that flip(Picture.HORIZONTAL) works and does not modify the
* original Picture object.
*/
public void testFlipHorixontal_Maria()
{
Picture pic = Picture.loadPicture("Maria1.bmp");
Picture picCopy = new Picture(pic);
Picture picCorrect = Picture.loadPicture("Maria1_flipHorizontally.bmp");
Picture picTest = pic.flip(Picture.HORIZONTAL);
assertTrue(pic.equals(picCopy));
assertTrue(picCorrect.equals(picTest));
}
/*
* Validate that flip(Picture.VERTICAL) works and does not modify the
* original Picture object.
*/
public void testFlipVertical_Logos()
{
Picture pic = Picture.loadPicture("Logos.bmp");
Picture picCopy = new Picture(pic);
Picture picCorrect = Picture.loadPicture("Logos_flipVertically.bmp");
Picture picTest = pic.flip(Picture.VERTICAL);
assertTrue(pic.equals(picCopy));
assertTrue(picCorrect.equals(picTest));
}
/*
* Validate that flip(Picture.VERTICAL) works and does not modify the
* original Picture object.
*/
public void testFlipVertical_Maria()
{
Picture pic = Picture.loadPicture("Maria1.bmp");
Picture picCopy = new Picture(pic);
Picture picCorrect = Picture.loadPicture("Maria1_flipVertically.bmp");
Picture picTest = pic.flip(Picture.VERTICAL);
assertTrue(pic.equals(picCopy));
assertTrue(picCorrect.equals(picTest));
}
/*
* Validate that flip(Picture.FORWARD_DIAGONAL) works and
* does not modify the original Picture object.
*/
public void testFlipForwardDiagonal_Logos()
{
Picture pic = Picture.loadPicture("Logos.bmp");
Picture picCopy = new Picture(pic);
Picture picCorrect = Picture.loadPicture("Logos_flipForwardSlash.bmp");
Picture picTest = pic.flip(Picture.FORWARD_DIAGONAL);
assertTrue(pic.equals(picCopy));
assertTrue(picCorrect.equals(picTest));
}
/*
* Validate that flip(Picture.FORWARD_DIAGONAL) works and
* does not modify the original Picture object.
*/
public void testFlipForwardDiagonal_Maria()
{
Picture pic = Picture.loadPicture("Maria1.bmp");
Picture picCopy = new Picture(pic);
Picture picCorrect = Picture.loadPicture("Maria1_flipForwardSlash.bmp");
Picture picTest = pic.flip(Picture.FORWARD_DIAGONAL);
assertTrue(pic.equals(picCopy));
assertTrue(picCorrect.equals(picTest));
}
/*
* Validate that flip(Picture.BACKWARD_DIAGONAL) works and
* does not modify the original Picture object.
*/
public void testFlipBackwardDiagonal_Logos()
{
Picture pic = Picture.loadPicture("Logos.bmp");
Picture picCopy = new Picture(pic);
Picture picCorrect = Picture.loadPicture("Logos_flipBackwardSlash.bmp");
Picture picTest = pic.flip(Picture.BACKWARD_DIAGONAL);
assertTrue(pic.equals(picCopy));
assertTrue(picCorrect.equals(picTest));
}
/*
* Validate that flip(Picture.BACKWARD_DIAGONAL) works and
* does not modify the original Picture object.
*/
public void testFlipBackwardDiagonal_Maria()
{
Picture pic = Picture.loadPicture("Maria1.bmp");
Picture picCopy = new Picture(pic);
Picture picCorrect = Picture.loadPicture("Maria1_flipBackwardSlash.bmp");
Picture picTest = pic.flip(Picture.BACKWARD_DIAGONAL);
assertTrue(pic.equals(picCopy));
assertTrue(picCorrect.equals(picTest));
}
/*
* Validate that blur works and does not modify the
* original Picture object.
*/
public void testBlur()
{
Picture pic = Picture.loadPicture("Creek.bmp");
Picture picCopy = new Picture(pic);
Picture picCorrect = Picture.loadPicture("Creek_blur.bmp");
Picture picTest = pic.blur(3);
assertTrue(pic.equals(picCopy));
assertTrue(picCorrect.equals(picTest));
}
/*
* Validate that chromaKey works and does not modify the
* original Picture object.
*/
public void testChromaKey_Logos()
{
Picture pic = Picture.loadPicture("Logos.bmp");
Picture bg = Picture.loadPicture("Creek.bmp");
Picture picCopy = new Picture(pic);
Picture picCorrect = Picture.loadPicture("Logos_chromaKeyCreek.bmp");
Picture picTest = pic.chromaKey(118, 54, bg, 30);
assertTrue(pic.equals(picCopy));
assertTrue(picCorrect.equals(picTest));
}
/*
* Validate that chromaKey works and does not modify the
* original Picture object.
*/
public void testChromaKey_Maria()
{
Picture pic = Picture.loadPicture("Maria1.bmp");
Picture bg = Picture.loadPicture("HMC.bmp");
Picture picCopy = new Picture(pic);
Picture picCorrect = Picture.loadPicture("Maria1_ChromaKeyHMC.bmp");
Picture picTest = pic.chromaKey(118, 54, bg, 30);
assertTrue(pic.equals(picCopy));
assertTrue(picCorrect.equals(picTest));
}
/*
* Validate that paintBucket works and does not modify the
* original Picture object.
*/
public void testPaintBucket()
{
Picture pic = Picture.loadPicture("Maria1.bmp");
Picture picCopy = new Picture(pic);
Picture picCorrect = Picture.loadPicture("Maria_paintBucket.bmp");
Picture picTest = pic.paintBucket(118, 54, 30, new Color(0, 255, 0));
assertTrue(pic.equals(picCopy));
assertTrue(picCorrect.equals(picTest));
}
/*
* Validate that showEdges works and does not modify the
* original Picture object
*/
public void testShowEdgesMickey()
{
Picture pic = Picture.loadPicture("mickey.bmp");
Picture picCopy = new Picture(pic);
Picture picCorrect = Picture.loadPicture("mickey_showEdges.bmp");
Picture picTest = pic.showEdges(20);
assertTrue(pic.equals(picCopy));
assertTrue(picCorrect.equals(picTest));
}
/*
* Validate that showEdges works and does not modify the
* original Picture object.
*/
public void testShowEdges_Geese()
{
// These are geese painted by Maria Klawe
Picture pic = Picture.loadPicture("SnowGeese.bmp");
Picture picCopy = new Picture(pic);
Picture picCorrect = Picture.loadPicture("SnowGeese_ShowEdges20.bmp");
Picture picTest = pic.showEdges(20);
assertTrue(pic.equals(picCopy));
assertTrue(picCorrect.equals(picTest));
}
}
| mattthewong/cs_60_files | picture_java/src/PictureECTest.java | 2,081 | /*
* Validate that paintBucket works and does not modify the
* original Picture object.
*/ | block_comment | en | false | 1,760 | 22 | 2,081 | 21 | 2,091 | 25 | 2,081 | 21 | 2,536 | 29 | false | false | false | false | false | true |
213371_6 | /*
* Copyright (c) 2009, Oracle and/or its affiliates. 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.
*
* - Neither the name of Oracle or the names of its
* contributors may be used to endorse or promote products derived
* from this software without specific prior written permission.
*
* 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 OWNER 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.
*/
import java.io.*;
import java.nio.file.*;
import java.nio.file.attribute.*;
import static java.nio.file.FileVisitResult.*;
import static java.nio.file.FileVisitOption.*;
import java.util.*;
/**
* Sample code that finds files that
* match the specified glob pattern.
* For more information on what
* constitutes a glob pattern, see
* http://docs.oracle.com/javase/javatutorials/tutorial/essential/io/fileOps.html#glob
*
* The file or directories that match
* the pattern are printed to
* standard out. The number of
* matches is also printed.
*
* When executing this application,
* you must put the glob pattern
* in quotes, so the shell will not
* expand any wild cards:
* java Find . -name "*.java"
*/
public class Find {
/**
* A {@code FileVisitor} that finds
* all files that match the
* specified pattern.
*/
public static class Finder
extends SimpleFileVisitor<Path> {
private final PathMatcher matcher;
private int numMatches = 0;
Finder(String pattern) {
matcher = FileSystems.getDefault()
.getPathMatcher("glob:" + pattern);
}
// Compares the glob pattern against
// the file or directory name.
void find(Path file) {
Path name = file.getFileName();
if (name != null && matcher.matches(name)) {
numMatches++;
System.out.println(file);
}
}
// Prints the total number of
// matches to standard out.
void done() {
System.out.println("Matched: "
+ numMatches);
}
// Invoke the pattern matching
// method on each file.
@Override
public FileVisitResult visitFile(Path file,
BasicFileAttributes attrs) {
find(file);
return CONTINUE;
}
// Invoke the pattern matching
// method on each directory.
@Override
public FileVisitResult preVisitDirectory(Path dir,
BasicFileAttributes attrs) {
find(dir);
return CONTINUE;
}
@Override
public FileVisitResult visitFileFailed(Path file,
IOException exc) {
System.err.println(exc);
return CONTINUE;
}
}
static void usage() {
System.err.println("java Find <path>" +
" -name \"<glob_pattern>\"");
System.exit(-1);
}
public static void main(String[] args)
throws IOException {
if (args.length < 3 || !args[1].equals("-name"))
usage();
Path startingDir = Paths.get(args[0]);
String pattern = args[2];
Finder finder = new Finder(pattern);
Files.walkFileTree(startingDir, finder);
finder.done();
}
}
| pingfangx/java-tutorials-in-chinese | essential/io/examples/Find.java | 989 | // matches to standard out. | line_comment | en | false | 907 | 6 | 989 | 6 | 1,071 | 6 | 989 | 6 | 1,313 | 6 | false | false | false | false | false | true |
213399_16 | /*
* Copyright (c) 2007, 2013, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code 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
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package util;
import javafx.geometry.Point2D;
import javafx.geometry.Point3D;
import javafx.scene.transform.Affine;
import javafx.scene.transform.NonInvertibleTransformException;
/**
* A ray used for picking.
*/
public class Ray {
private Point3D origin = new Point3D(0, 0, 0);
private Point3D direction = new Point3D(0, 0, 0);
private double nearClip = 0.0;
private double farClip = Double.POSITIVE_INFINITY;
// static final double EPS = 1.0e-13;
static final double EPS = 1.0e-5f;
public Ray() {
}
public Ray(Point3D origin, Point3D direction, double nearClip, double farClip) {
set(origin, direction, nearClip, farClip);
}
public Ray(double x, double y, double z, double nearClip, double farClip) {
set(x, y, z, nearClip, farClip);
}
public static Ray computePerspectivePickRay(
double x, double y, boolean fixedEye,
double viewWidth, double viewHeight,
double fieldOfViewRadians, boolean verticalFieldOfView,
Affine transform,
double nearClip, double farClip,
Ray pickRay) {
if (pickRay == null) {
pickRay = new Ray();
}
Point3D direction = pickRay.getDirectionNoClone();
double halfViewWidth = viewWidth / 2.0;
double halfViewHeight = viewHeight / 2.0;
double halfViewDim = verticalFieldOfView ? halfViewHeight : halfViewWidth;
// Distance to projection plane from eye
double distanceZ = halfViewDim / Math.tan(fieldOfViewRadians / 2.0);
direction = Point3D.ZERO.add(x - halfViewWidth, y - halfViewHeight, distanceZ);
Point3D eye = pickRay.getOriginNoClone();
if (fixedEye) {
eye = Point3D.ZERO;
} else {
// set eye at center of viewport and move back so that projection plane
// is at Z = 0
eye = new Point3D(halfViewWidth, halfViewHeight, -distanceZ);
}
pickRay.nearClip = nearClip * (direction.magnitude() / (fixedEye ? distanceZ : 1.0));
pickRay.farClip = farClip * (direction.magnitude() / (fixedEye ? distanceZ : 1.0));
pickRay.transform(transform);
return pickRay;
}
public static Ray computeParallelPickRay(
double x, double y, double viewHeight,
Affine transform,
double nearClip, double farClip,
Ray pickRay) {
if (pickRay == null) {
pickRay = new Ray();
}
// This is the same math as in the perspective case, fixed
// for the default 30 degrees vertical field of view.
final double distanceZ = (viewHeight / 2.0)
/ Math.tan(Math.toRadians(15.0));
pickRay.set(x, y, distanceZ, nearClip * distanceZ, farClip * distanceZ);
if (transform != null) {
pickRay.transform(transform);
}
return pickRay;
}
public final void set(Point3D origin, Point3D direction, double nearClip, double farClip) {
setOrigin(origin);
setDirection(direction);
this.nearClip = nearClip;
this.farClip = farClip;
}
public final void set(double x, double y, double z, double nearClip, double farClip) {
setOrigin(x, y, -z);
setDirection(0, 0, z);
this.nearClip = nearClip;
this.farClip = farClip;
}
public void setPickRay(Ray other) {
setOrigin(other.origin);
setDirection(other.direction);
nearClip = other.nearClip;
farClip = other.farClip;
}
public Ray copy() {
return new Ray(origin, direction, nearClip, farClip);
}
/**
* Sets the origin of the pick ray in world coordinates.
*
* @param origin the origin (in world coordinates).
*/
public void setOrigin(Point3D origin) {
this.origin = origin;
}
/**
* Sets the origin of the pick ray in world coordinates.
*
* @param x the origin X coordinate
* @param y the origin Y coordinate
* @param z the origin Z coordinate
*/
public void setOrigin(double x, double y, double z) {
this.origin = new Point3D(x, y, z);
}
public Point3D getOrigin(Point3D rv) {
rv = new Point3D(origin.getX(), origin.getY(), origin.getZ());
return rv;
}
public Point3D getOriginNoClone() {
return origin;
}
/**
* Sets the direction vector of the pick ray. This vector need not be
* normalized.
*
* @param direction the direction vector
*/
public void setDirection(Point3D direction) {
this.direction = direction;
}
/**
* Sets the direction of the pick ray. The vector need not be normalized.
*
* @param x the direction X magnitude
* @param y the direction Y magnitude
* @param z the direction Z magnitude
*/
public void setDirection(double x, double y, double z) {
this.direction = new Point3D(x, y, z);
}
public Point3D getDirection(Point3D rv) {
rv = new Point3D(direction.getX(), direction.getY(), direction.getZ());
return rv;
}
public Point3D getDirectionNoClone() {
return direction;
}
public double getNearClip() {
return nearClip;
}
public double getFarClip() {
return farClip;
}
public double distance(Point3D iPnt) {
double x = iPnt.getX() - origin.getX();
double y = iPnt.getY() - origin.getY();
double z = iPnt.getZ() - origin.getZ();
return Math.sqrt(x * x + y * y + z * z);
}
/**
* Project the ray through the specified (inverted) transform and onto the
* Z=0 plane of the resulting coordinate system. If a perspective projection
* is being used then only a point that projects forward from the eye to the
* plane will be returned, otherwise a null will be returned to indicate
* that the projection is behind the eye.
*
* @param inversetx the inverse of the model transform into which the ray is
* to be projected
* @param perspective true if the projection is happening in perspective
* @param tmpvec a temporary {@code Point3D} object for internal use (may be
* null)
* @param ret a {@code Point2D} object for storing the return value, or null
* if a new object should be returned.
* @return
*/
public Point2D projectToZeroPlane(Affine inversetx,
boolean perspective,
Point3D tmpvec, Point2D ret) {
if (tmpvec == null) {
tmpvec = new Point3D(0,0,0);
}
tmpvec = inversetx.transform(origin);
double origX = tmpvec.getX();
double origY = tmpvec.getX();
double origZ = tmpvec.getX();
tmpvec = origin.add(direction);
tmpvec = inversetx.transform(tmpvec);
double dirX = tmpvec.getX() - origX;
double dirY = tmpvec.getY() - origY;
double dirZ = tmpvec.getZ() - origZ;
// Handle the case where pickRay is almost parallel to the Z-plane
if (almostZero(dirZ)) {
return null;
}
double t = -origZ / dirZ;
if (perspective && t < 0) {
// TODO: Or should we use Infinity? (RT-26888)
return null;
}
if (ret == null) {
ret = Point2D.ZERO;
}
ret = new Point2D((float) (origX + (dirX * t)),
(float) (origY + (dirY * t)));
return ret;
}
// Good to find a home for commonly use util. code such as EPS.
// and almostZero. This code currently defined in multiple places,
// such as Affine3D and GeneralTransform3D.
private static final double EPSILON_ABSOLUTE = 1.0e-5;
static boolean almostZero(double a) {
return ((a < EPSILON_ABSOLUTE) && (a > -EPSILON_ABSOLUTE));
}
private static boolean isNonZero(double v) {
return ((v > EPS) || (v < -EPS));
}
public void transform(Affine t) {
t.transform(origin);
t.deltaTransform(direction);
}
public void inverseTransform(Affine t)throws NonInvertibleTransformException {
t.inverseTransform(origin);
t.inverseDeltaTransform(direction);
}
public Ray project(Affine inversetx,
boolean perspective,
Point3D tmpvec, Point2D ret) {
if (tmpvec == null) {
tmpvec = new Point3D(0, 0, 0);
}
tmpvec = inversetx.transform(origin);
double origX = tmpvec.getX();
double origY = tmpvec.getY();
double origZ = tmpvec.getZ();
tmpvec = tmpvec.add(direction);
tmpvec = inversetx.transform(tmpvec);
double dirX = tmpvec.getX() - origX;
double dirY = tmpvec.getY() - origY;
double dirZ = tmpvec.getZ() - origZ;
Ray pr = new Ray();
pr.setOrigin(origX, origY, origZ);
pr.setDirection(dirX, dirY, dirZ);
return pr;
}
@Override
public String toString() {
return "origin: " + origin + " direction: " + direction;
}
}
| FXyz/FYzx | src/util/Ray.java | 2,670 | // and almostZero. This code currently defined in multiple places, | line_comment | en | false | 2,544 | 13 | 2,670 | 13 | 2,886 | 13 | 2,670 | 13 | 3,165 | 13 | false | false | false | false | false | true |
213965_0 | __________________________________________________________________________________________________
sample 1 ms submission
class Solution {
public int findMinMoves(int[] machines) {
if (machines == null || machines.length <= 1) {
return 0;
}
int sum = 0;
for (int machine : machines) {
sum += machine;
}
if (sum % machines.length != 0) {
return -1;
}
int target = sum / machines.length;
int cur = 0, max = 0;
for (int machine : machines) {
cur += machine - target; //load-avg is "gain/lose"
max = Math.max(Math.max(max, Math.abs(cur)), machine - target);
}
return max;
}
}
__________________________________________________________________________________________________
sample 34876 kb submission
class Solution {
public int findMinMoves(int[] machines) {
int sum = Arrays.stream(machines).sum(), n = machines.length;
if (sum % n != 0)
return -1;
int avg = sum / n, cn = 0, ans = 0;
for (int m : machines) {
cn += m - avg;
ans = Math.max(ans, Math.max(Math.abs(cn), m - avg));
}
return ans;
}
}
__________________________________________________________________________________________________
| strengthen/LeetCode | Java/517.java | 314 | //load-avg is "gain/lose" | line_comment | en | false | 283 | 10 | 314 | 10 | 348 | 10 | 314 | 10 | 380 | 12 | false | false | false | false | false | true |
214493_5 | /**
* This is a java program that tries to recover crypto hashes using
* a dictionary aka wordlist (not included)
* @author Copyright 2007 rogeriopvl, <http://www.rogeriopvl.com>
* @version 0.2
*
* Changelog:
* v0.2 - minor code corrections, now with GUI hash prompt for better usability.
*
* This program 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.
*
* This program 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 this program. If not, see <http://www.gnu.org/licenses/>.
*
* Instructions: Just compile it as a normal java class and run it. You will need
* a dictionary file not included with the source. The file must have each word in a new line.
*
* PERSONAL DISCLAIMER: This program was made exclusively for educational purposes, therefore
* I can't be held responsible for the actions of others using it.
*/
import java.util.Scanner;
import java.io.FileReader;
import java.io.FileNotFoundException;
import java.security.NoSuchAlgorithmException;
import javax.swing.JOptionPane;
public class HashRecovery {
private static final String PROGNAME = "HashRecovery";
private static final String VERSION = "v0.5";
private static final int MIN_HASH_LENGTH = 32;
private static final String EMPTY_HASH = "d41d8cd98f00b204e9800998ecf8427e";
/**
* Main method
* @param args command line arguments
* @throws FileNotFoundException
*/
public static void main (String [] args) throws FileNotFoundException {
String algo = null;
String dictionaryPath = null;
if (args.length < 1) {
usage();
}
else if (args[0].equals("-a")) {
if (args.length != 3) {
usage();
}
else {
algo = args[1];
dictionaryPath = args[2];
}
}
else {
usage();
}
if (algo.equals(null)) {
algo = "MD5";
}
//let's ask for the hash to recover in a fancy dialog :)
String hash = JOptionPane.showInputDialog(null, "Hash to recover: ", PROGNAME+" "+VERSION, 1);
if (hash.length() < MIN_HASH_LENGTH)
System.err.println ("Warning: probably not a valid hash, proceeding anyway...");
Scanner infile = new Scanner(new FileReader(dictionaryPath));
String line;
int count = 0;
while (infile.hasNext()) {
line = infile.nextLine();
count++;
//no need to spend CPU cycles calculating this one...
if (hash.equals(EMPTY_HASH)) {
System.out.println ("Done it! That's the hash of an empty string!");
System.exit(0);
}
try {
if (hash.equals(HashUtils.generateHash(line, algo))) {
System.out.println ("Houston, we've done it!: "+line);
System.out.println ("Sucess after "+count+" words.");
System.exit(0);
}
}
catch(NoSuchAlgorithmException e) {
System.err.println("Error: Unsupported algorithm - "+algo);
System.exit(1);
}
}
infile.close();
System.out.println ("Unable to recover hash. Try using a better dictionary file.");
}//end of main
/**
* Prints the usage example and exits the program
*/
private static void usage() {
System.err.println ("Usage: "+PROGNAME+" [-a <algo>] <dictionary file>");
System.exit(1);
}
}//end of class
| rogeriopvl/HashRecovery | HashRecovery.java | 1,013 | /**
* Prints the usage example and exits the program
*/ | block_comment | en | false | 892 | 14 | 1,013 | 13 | 1,032 | 15 | 1,013 | 13 | 1,255 | 17 | false | false | false | false | false | true |
214544_19 | /**
* Server.java
* author: Yukun Jiang
* Date: April 05, 2023
*
* This is the implementation for the Server instance
* in our Two Phase Commit distributed consensus protocol
*
* The Server acts as the single only coordinator for the system
* and initiate, make decisions on various transaction commits
*/
import java.io.*;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashSet;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentLinkedDeque;
public class Server implements ProjectLib.CommitServing, ProjectLib.MessageHandling {
/**
* Wrapper class for an outgoing CoordinatorMsg
* it tracks when this is sent
* and thus can be tracked if it has timed out and needs to be resent
*/
static class OutboundMsg {
public CoordinatorMsg msg;
public Long sent_time;
public String dest;
public OutboundMsg(CoordinatorMsg msg, String dest) {
this.msg = msg;
this.dest = dest;
this.sent_time = System.currentTimeMillis();
}
public boolean isExpired() {
return (System.currentTimeMillis() - this.sent_time) > TIMEOUT;
}
}
/* big data structure for persistent storage */
private TxnMasterLog log;
public static ProjectLib PL;
private static final String SEP = ":";
private static final int PARTICIPANT_IDX = 0;
private static final int FILENAME_IDX = 1;
private static final String MODE = "rws";
private static final String LOG_NAME = "LOG_COORDINATOR";
/* how often to check if outbound message has timeout */
private static final Long INTERVAL = 1000L;
/* the timeout threshold for a message since one-way latency is at most 3 seconds as specified */
private static final Long TIMEOUT = 6000L;
private final ConcurrentLinkedDeque<OutboundMsg> outboundMsgs;
/* protect the recovery stage upon re-booting */
private boolean finish_recovery = false;
private void timeMsg(CoordinatorMsg msg, String dest) {
outboundMsgs.addLast(new OutboundMsg(msg, dest));
}
/*
Main Loop for checking timeout messages
if a message is in Phase I prepare and has not received feedback
Coordinator think it's an implicit Denial and immediately abort
if a message is in Phase II requiring an ACK from participant
it must be resent until ACKed
*/
@SuppressWarnings("unchecked")
public void inspectTimeout() {
ArrayList<OutboundMsg> expired_msgs = new ArrayList<>();
synchronized (outboundMsgs) {
// prune the timing queue
for (OutboundMsg msg : outboundMsgs) {
if (msg.isExpired()) {
expired_msgs.add(msg);
}
}
outboundMsgs.removeAll(expired_msgs);
}
// deal with expired msgs
for (OutboundMsg msg : expired_msgs) {
TxnMasterRecord record = log.retrieveRecord(msg.msg.txn_id);
if (msg.msg.phase == TxnPhase.PHASE_I && record.status == TxnMasterRecord.Status.PREPARE) {
// deemed as implicit DENIAL
System.out.println("Server's txn=" + msg.msg.txn_id + " to Node " + msg.dest
+ " in Phase I has expired, deemed as DENIAL");
record.decision = TxnDecision.ABORT;
record.status = TxnMasterRecord.Status.DECISION;
record.outstanding_participants = (HashSet<String>) record.participants.clone();
flushLog(); // FLUSH LOG
resumeTxnPhaseII(record);
}
if (msg.msg.phase == TxnPhase.PHASE_II && record.status == TxnMasterRecord.Status.DECISION) {
// must continue resending until ACKed
System.out.println("Server's txn=" + msg.msg.txn_id + " to Node " + msg.dest
+ " in Phase II has expired, RESEND");
msg.msg.sendMyselfTo(PL, msg.dest);
timeMsg(msg.msg, msg.dest);
}
}
}
/* persistent log */
private synchronized void flushLog() {
Long start = System.currentTimeMillis();
try (FileOutputStream f = new FileOutputStream(LOG_NAME, false);
BufferedOutputStream b = new BufferedOutputStream(f);
ObjectOutputStream o = new ObjectOutputStream(b)) {
o.writeObject(log);
o.flush();
} catch (Exception e) {
e.printStackTrace();
} finally {
PL.fsync();
}
}
/* Upon recovery */
private synchronized TxnMasterLog loadLog() {
TxnMasterLog disk_log = null;
try (FileInputStream f = new FileInputStream(LOG_NAME);
BufferedInputStream b = new BufferedInputStream(f);
ObjectInputStream o = new ObjectInputStream(b)) {
disk_log = (TxnMasterLog) o.readObject();
} catch (Exception e) {
e.printStackTrace();
}
return disk_log;
}
/* Continue Phase I of a txn */
private void resumeTxnPhaseI(TxnMasterRecord record) {
assert (record.status == TxnMasterRecord.Status.PREPARE);
ConcurrentHashMap<String, ArrayList<String>> distributed_sources = new ConcurrentHashMap<>();
/* split the sources into mapping based by per destination UserNode */
for (String source_file : record.sources) {
String[] source_and_file = source_file.split(SEP);
String participant = source_and_file[PARTICIPANT_IDX];
String file = source_and_file[FILENAME_IDX];
if (!distributed_sources.containsKey(participant)) {
distributed_sources.put(participant, new ArrayList<>());
}
distributed_sources.get(participant).add(file);
}
/* send outstanding messages */
for (String outstanding_participant : record.outstanding_participants) {
ArrayList<String> single_sources = distributed_sources.get(outstanding_participant);
String[] outstanding_sources = single_sources.toArray(new String[0]);
CoordinatorMsg msg = CoordinatorMsg.GeneratePhaseIMsg(
record.id, record.filename, record.img, outstanding_sources);
msg.sendMyselfTo(PL, outstanding_participant);
timeMsg(msg, outstanding_participant); // Under Timeout monitor
}
}
/* Continue Phase II of a txn */
private void resumeTxnPhaseII(TxnMasterRecord record) {
assert (record.decision != TxnDecision.UNDECIDED
&& record.status == TxnMasterRecord.Status.DECISION);
// trim all the outbound Phase I message for this txn
ArrayList<OutboundMsg> useless = new ArrayList<>();
synchronized (outboundMsgs) {
for (OutboundMsg msg : outboundMsgs) {
CoordinatorMsg inner_msg = msg.msg;
if (inner_msg.txn_id == record.id && inner_msg.phase == TxnPhase.PHASE_I) {
useless.add(msg);
}
}
outboundMsgs.removeAll(useless);
}
CoordinatorMsg msg = CoordinatorMsg.GeneratePhaseIIMsg(record.id, record.decision);
for (String destination : record.outstanding_participants) {
msg.sendMyselfTo(PL, destination);
timeMsg(msg, destination);
}
}
@SuppressWarnings("unchecked")
private void dealVote(String from, ParticipantMsg msg) {
assert (msg.phase == TxnPhase.PHASE_I);
TxnMasterRecord record = log.retrieveRecord(msg.txn_id);
if (record.status == TxnMasterRecord.Status.END) {
return;
}
if (record.status == TxnMasterRecord.Status.DECISION) {
// already made a decision, inform
CoordinatorMsg decision_msg = CoordinatorMsg.GeneratePhaseIIMsg(record.id, record.decision);
decision_msg.sendMyselfTo(PL, from);
timeMsg(decision_msg, from);
return;
}
if (msg.vote == TxnVote.DENIAL) {
// this txn is aborted for sure, move to Phase II
System.out.println("Server Aborts txn " + record.id);
record.decision = TxnDecision.ABORT;
record.status = TxnMasterRecord.Status.DECISION;
record.outstanding_participants = (HashSet<String>) record.participants.clone();
flushLog(); // FLUSH LOG
resumeTxnPhaseII(record);
return;
}
record.outstanding_participants.remove(from);
if (record.outstanding_participants.isEmpty()) {
// every participant has voted
if (record.decision == TxnDecision.UNDECIDED) {
record.decision = TxnDecision.COMMIT;
}
record.status = TxnMasterRecord.Status.DECISION;
record.outstanding_participants = (HashSet<String>) record.participants.clone();
// commit point to outside world
// might have a race after flushLog and before outwrite the img to disk, IGNORE for now
if (record.decision == TxnDecision.COMMIT) {
System.out.println("Server commits and saves collage " + record.filename);
try {
RandomAccessFile f = new RandomAccessFile(record.filename, MODE);
f.write(record.img);
f.close();
} catch (Exception e) {
e.printStackTrace();
}
}
flushLog(); // FLUSH LOG
// move to Phase II to distribute decision and collect ACK
resumeTxnPhaseII(record);
}
}
private void dealACK(String from, ParticipantMsg msg) {
assert (msg.phase == TxnPhase.PHASE_II);
TxnMasterRecord record = log.retrieveRecord(msg.txn_id);
assert (record.status != TxnMasterRecord.Status.PREPARE);
if (record.status == TxnMasterRecord.Status.END) {
// no more need for ACKs
return;
}
record.outstanding_participants.remove(from);
// flushLog(); // FLUSH LOG
if (record.outstanding_participants.isEmpty()) {
// all ACKs collected, this txn is completed
System.out.println("Server: txn " + record.id + " is ENDED");
record.status = TxnMasterRecord.Status.END;
flushLog(); // FLUSH LOG
synchronized (outboundMsgs) {
// prune all outbound messages for this txn
ArrayList<OutboundMsg> useless = new ArrayList<>();
for (OutboundMsg outboundMsg : outboundMsgs) {
if (outboundMsg.msg.txn_id == record.id) {
useless.add(outboundMsg);
}
}
outboundMsgs.removeAll(useless);
}
}
}
@SuppressWarnings("unchecked")
public void recover() {
if (new File(LOG_NAME).exists()) {
System.out.println("Server comes online with DISK log");
this.log = loadLog();
for (TxnMasterRecord record : this.log.all_txns.values()) {
if (record.status == TxnMasterRecord.Status.PREPARE) {
// ABORT
System.out.println("Serer Abort ongoing txn " + record.id);
record.decision = TxnDecision.ABORT;
record.status = TxnMasterRecord.Status.DECISION;
record.outstanding_participants = (HashSet<String>) record.participants.clone();
flushLog(); // FLUSH LOG
resumeTxnPhaseII(record);
} else if (record.status == TxnMasterRecord.Status.DECISION) {
System.out.println("Serer continue committed txn " + record.id);
resumeTxnPhaseII(record);
}
}
} else {
System.out.println("Server comes online with FRESH log");
this.log = new TxnMasterLog();
}
finish_recovery = true;
}
public Server() {
this.outboundMsgs = new ConcurrentLinkedDeque<>();
}
@Override
public boolean deliverMessage(ProjectLib.Message msg) {
while (!this.finish_recovery) {
} // guard recovery
String from = msg.addr;
ParticipantMsg participantMsg = ParticipantMsg.deserialize(msg);
System.out.println(
"Server Got message from " + msg.addr + " about Msg: " + participantMsg.toString());
if (participantMsg.phase == TxnPhase.PHASE_I) {
dealVote(from, participantMsg);
}
if (participantMsg.phase == TxnPhase.PHASE_II) {
dealACK(from, participantMsg);
}
return true;
}
@Override
public void startCommit(String filename, byte[] img, String[] sources) {
System.out.println(
"Server: Got request to commit " + filename + " with sources " + Arrays.toString(sources));
TxnMasterRecord new_record = log.createRecord(filename, img, sources);
flushLog(); // FLUSH LOG
resumeTxnPhaseI(new_record);
}
public static void main(String args[]) throws Exception {
if (args.length != 1)
throw new Exception("Need 1 arg: <port>");
Server srv = new Server();
PL = new ProjectLib(Integer.parseInt(args[0]), srv, srv);
srv.recover();
// main loop for inspecting timeout messages
while (true) {
Thread.sleep(INTERVAL);
srv.inspectTimeout();
}
}
}
| YukunJ/Two-Phase-Commit | 2pc/Server.java | 3,065 | // trim all the outbound Phase I message for this txn | line_comment | en | false | 2,803 | 11 | 3,065 | 11 | 3,286 | 11 | 3,065 | 11 | 3,862 | 14 | false | false | false | false | false | true |
215267_2 | import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.Scanner;
import javax.swing.JMenu;
import javax.swing.JMenuBar;
import javax.swing.JMenuItem;
import javax.swing.JOptionPane;
import javax.swing.UIManager;
import javax.swing.UnsupportedLookAndFeelException;
/** JMenBar that shows options in the BorderFrame
* @author Jared Moore
* @version Nov 16, 2012
*/
public class MenuBar extends JMenuBar {
BorderFrame frame;
JMenuItem beginner = new JMenuItem("Beginner"), intermediate = new JMenuItem("Intermediate"), expert = new JMenuItem("Expert"),
custom = new JMenuItem("Custom"), scores = new JMenuItem("Scores"), hint = new JMenuItem("Hint");
/** Constructor for MenuBar
*/
public MenuBar(BorderFrame frame) {
try {
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName()); // changes the look a little, my system is themed so this looks pretty sweet
} catch (ClassNotFoundException | InstantiationException
| IllegalAccessException | UnsupportedLookAndFeelException e) {
System.err.println("You have an issue"); // if one of these comes up, just comment out this block, your system has issues or does not have a look and feel (so no UI?)
e.printStackTrace();
System.exit(1);
}
this.frame = frame;
JMenu fileMenu = new JMenu("File");
fileMenu.setMnemonic('F');
JMenu newGame = new JMenu("New");
newGame.setMnemonic('N');
Action l = new Action();
beginner.addActionListener(l);
beginner.setMnemonic('B');
intermediate.addActionListener(l);
intermediate.setMnemonic('I');
expert.addActionListener(l);
expert.setMnemonic('E');
custom.addActionListener(l);
custom.setMnemonic('C');
newGame.add(beginner);
newGame.add(intermediate);
newGame.add(expert);
newGame.add(custom);
fileMenu.add(newGame);
scores.setMnemonic('S');
scores.addActionListener(l);
fileMenu.add(scores);
add(fileMenu);
JMenu helpMenu = new JMenu("Help");
helpMenu.setMnemonic('H');
hint.addActionListener(l);
hint.setMnemonic('I');
helpMenu.add(hint);
add(helpMenu);
setVisible(true);
}
/** ActionListener for the menu items
* @author Jared Moore
* @version Nov 19, 2012
*/
private class Action implements ActionListener {
/* (non-Javadoc)
* @see java.awt.event.ActionListener#actionPerformed(java.awt.event.ActionEvent)
*/
@Override
public void actionPerformed(ActionEvent e) {
if (e.getSource().equals(beginner)) {
frame.setVisible(false);
BorderFrame newGame = new BorderFrame(8, 8, 10); // set the old frame to invisible and make a new one
}
else if (e.getSource().equals(intermediate)) {
frame.setVisible(false);
BorderFrame newGame = new BorderFrame(16, 16, 40);
}
else if (e.getSource().equals(expert)) {
frame.setVisible(false);
BorderFrame newGame = new BorderFrame(30, 16, 99);
}
else if (e.getSource().equals(custom)) {
frame.setVisible(false);
String text = JOptionPane.showInputDialog("Enter the number of rows, columns, and mines, separated by spaces");
if (text == null)
return;
Scanner input = new Scanner(text);
BorderFrame newGame = new BorderFrame(Integer.parseInt(input.next()), Integer.parseInt(input.next()), Integer.parseInt(input.next()));
input.close();
}
else if (e.getSource().equals(hint))
frame.getPanel().showHint();
else if (e.getSource().equals(scores))
frame.getPanel().displayScores();
}
}
}
| jmoney4769/MineSweeper | src/MenuBar.java | 1,029 | // changes the look a little, my system is themed so this looks pretty sweet | line_comment | en | false | 858 | 16 | 1,029 | 17 | 1,030 | 16 | 1,029 | 17 | 1,295 | 17 | false | false | false | false | false | true |
215377_4 | package world;
/**
* Movable is an interface which assures that any object capable of moving from
* room to room has certain commands. It also acts as a marker for both Player
* and Mobile objects. It extends the DatabaseItem and GearList interfaces, as
* movables are database items and gear holders and share much in common with
* GearContainers. The are a GearList, in that respect as well as have a
* GearList instance variables.
*/
public interface Movable extends DatabaseItem, GearList {
/**
* sendToPlayer() is used to send text to the client of the player's
* controller directly if the movable is a player or send text to the mob if
* the movable is a mobile. If a mobile, the mobile can react the the text.
*
* @param message
* The message to be sent to the Player's console or the mob.
*/
public void sendToPlayer(String message);
/**
* Attack is the method called when a Mobile's turn comes up in a combat. A
* Mobile looks to it's strategy in order to determine an appropriate
* response - For many mobs, this response is to call resolveAttack, and
* deal damage to another Movable.
*
* @enemy - The Movable to attack.
*/
public void attack(Movable enemy);
/**
* The moveToRoom command handles the upkeep of a room movement by shiftign
* the Mobile object from one room to another, and then forms the String to
* be given to the Mobile after changing rooms. Mobiles need this less than
* players, but other behavior might depend on keywords in room
* descriptions, or a reaction to other DatabaseObjects in the room.
*
* @param destination
* This is a room reference for the destination of the move.
*/
public void moveToRoom(Room destination);
/**
* setStat is a universal setter. It accepts an integer and a Trait enum,
* which it then uses to change the appropriate private variable
* representing the requested stat to be changed. This cuts down on the
* number of methods required to set all instance variables.
*
* @param value
* The integer value one wishes to set.
* @param stat
* The enum member representing the stat the caller wishes
* modified.
*/
public void setStat(int value, Trait stat);
/**
* getStat is a universal getter. It accepts a Trait enum, which it then
* uses to get the appropriate private variable representing the requested
* stat requested. This cuts down on the number of methods required to get
* all instance variables.
*
* @return int - An int that represents the value of the requested stat.
*/
public int getStat(Trait stat);
/**
* use will be called whenever the movable wants to an item that they
* currently have. If a player does attempt to use something that they
* currently don't have the method will not do anything.
*
* @param itemName
* The name of the gear to be used
*/
public void use(String itemName);
/**
* This method insures the correct roomId of the movable, in case there is a
* synch or serialization issue.
*
* @return An int that represents the movables object reference id in the
* database.
*/
public int getRoomId();
/**
* getFighting is a small method that is used to prevent a player from
* getting into more than one fight at once. A MOB, however, can be attacked
* by multiple human players.
*
* @return True if fighting, false otherwise
*/
public boolean getFighting();
/**
* setFighting will be used once a player enters combat. It pass in a true
* value to set to the player's isFighting variable.
*
* @param fighting
* Ture if entering a fight, false if ending combat
*/
public void setFighting(boolean fighting);
}
| thezboe/Wasteland-MUD | world/Movable.java | 924 | /**
* setStat is a universal setter. It accepts an integer and a Trait enum,
* which it then uses to change the appropriate private variable
* representing the requested stat to be changed. This cuts down on the
* number of methods required to set all instance variables.
*
* @param value
* The integer value one wishes to set.
* @param stat
* The enum member representing the stat the caller wishes
* modified.
*/ | block_comment | en | false | 890 | 106 | 924 | 103 | 1,021 | 117 | 924 | 103 | 1,082 | 121 | false | false | false | false | false | true |
216050_9 | import java.util.*;
/**
* FlipSolver.
*/
public class Solver {
/**
* Return the minimum number of indexes you have to flip to find the solution.
*
* @param values the game values.
* @return the indexes you have to flip to find the solution.
*/
public int[] solve(boolean[] values) {
/*
The algorithm tries all the possible solutions and chooses the one with the minimum answer.
It tries all the possible combinations of the cells to be flipped in the first row.
After flipping these cells we will have some another grid with different values than the
one given in the input. For this grid, we iterate over the rows from the second to the last one.
For each row, we iterate over the columns. For each column, we flip a cell if the cell above it
has a value true. This guarantees us that all cells in the above rows will be false after iterating
over all the columns in the current row. After iterating over all the rows we check if the last row
has all values of false, if yes, it means that this's a possible solution (because we already know
that the cells above the last row have values false). Then, we compare all the possible solutions, and
we chose the one with the minimum number of flips needed.
*/
// find the length/width of the grid by finding the square root of number of elements
int n = (int) Math.sqrt(values.length);
// create an array of booleans that will be modified in the while flipping the cells
boolean[] temp = new boolean[n * n];
// cost variable represents the optimal solution found so far
// maskAns variable represents the mask of the optimal solution found so far
int maskAns = 0, cost = 36, tempCost;
// try all possible combinations of the cells to be flipped from the first all
// a combination of cells indexes is called a mask
for (int mask = 0; mask < (1 << n); mask++) {
// initialize array temp to have the same values as the given input
System.arraycopy(values, 0, temp, 0, n * n);
// play a game according to the current mask
tempCost = play(temp, n, mask, cost);
// save the mask if it leads to a correct solution (all cells are false) with a
// less number of cells to be flipped
if (cost > tempCost && check(temp, n)) {
maskAns = mask;
cost = tempCost;
}
}
// create an array of integers to be returned
int ret[] = new int[cost];
// repeat the steps of playing a game for a specific mask but with saving the indexes of flipped cells in array ret
int index = 0;
System.arraycopy(values, 0, temp, 0, n * n);
for (int j = 0; j < n; j++) {
if ((maskAns & (1 << j)) > 0) {
flip(temp, j, n);
ret[index] = j;
index++;
}
}
for (int i = 1; i < n; i++) {
for (int j = 0; j < n; j++) {
if (temp[((i - 1) * n) + j]) {
flip(temp, (i * n) + j, n);
ret[index] = (i * n) + j;
index++;
}
}
}
// return the answer
return ret;
}
/**
* @param values the game values
* @param n the length/width of the square grid
* @param mask the combination of indexes from the first row to be flipped
* @param curCost the optimal solution found so far
* @return number of cells needed to be flipped
*/
private int play(boolean[] values, int n, int mask, int curCost) {
// number of cells needed to be flipped for the given arguments
int cost = 0;
// flip the cells of the first row according to the give mask
// break if the cost of this mask became more or equal to the optimal solution found so far
for (int j = 0; curCost >= cost && j < n; j++) {
// flip the index j if it exists in the given mask
if ((mask & (1 << j)) > 0) {
flip(values, j, n);
// increase number of flips needed
cost++;
}
}
// iterate over all cells between second and last row, and between first and last column
// break if the cost of this mask became more or equal to the optimal solution found so far
for (int i = 1; curCost >= cost && i < n; i++) {
for (int j = 0; curCost >= cost && j < n; j++) {
// flip the cell if the value of the cell above it is true
if (values[((i - 1) * n) + j]) {
// flip the cell in row i and column j (its index is ((i*n) + j))
flip(values, (i * n) + j, n);
// increase number of flips needed
cost++;
}
}
}
// return the number of cells needed to be flipped
return cost;
}
/**
* Check if all the cells in the last row of the grid are false
*
* @return true if all cells are false
*/
private boolean check(boolean[] values, int n) {
for (int i = 0; i < n; i++) {
// return false if at least one cell has a value true
if (values[(n * (n - 1)) + i])
return false;
}
return true;
}
/**
* In the given matrix, flip the value at the given index, and at the neighbours' indexes
* (up, down, left and right).
*
* @param matrix the matrix.
* @param index the index.
* @param cols the number of columns.
*/
public void flip(boolean[] matrix, int index, int cols) {
// first flip the index itself
matrix[index] = !matrix[index];
// next its neighbours
int[] neighbours = MatrixUtil.neighbours4(matrix.length, index, cols);
for (int neighbourIndex : neighbours) {
matrix[neighbourIndex] = !matrix[neighbourIndex];
}
}
/**
* Returns random, unique ints in the given range (inclusive).
*
* @param min minimum value.
* @param max maximum value.
* @return random, unique ints in the given range (inclusive).
*/
public static int[] randomIntegers(int min, int max, int num) {
List<Integer> list = new ArrayList<>();
for (int i = min; i <= max; i++) {
list.add(i);
}
Collections.shuffle(list);
int[] result = new int[num];
for (int i = 0; i < num; i++) {
result[i] = list.get(i);
}
return result;
}
} | epfl-dojo/flipsolver | src/main/java/Solver.java | 1,619 | // initialize array temp to have the same values as the given input | line_comment | en | false | 1,586 | 13 | 1,619 | 13 | 1,739 | 13 | 1,619 | 13 | 1,846 | 13 | false | false | false | false | false | true |
216215_4 | /*
Licensed to the Apache Software Foundation (ASF) under one
or more contributor license agreements. See the NOTICE file
distributed with this work for additional information
regarding copyright ownership. The ASF licenses this file
to you 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.
*/
/* Small Finite Field arithmetic */
/* AMCL mod p functions */
public final class FP {
private final BIG x;
private static BIG p=new BIG(ROM.Modulus);
/* Constructors */
public FP(int a)
{
x=new BIG(a);
nres();
}
public FP()
{
x=new BIG(0);
}
public FP(BIG a)
{
x=new BIG(a);
nres();
}
public FP(FP a)
{
x=new BIG(a.x);
}
/* convert to string */
public String toString()
{
String s=redc().toString();
return s;
}
public String toRawString()
{
String s=x.toRawString();
return s;
}
/* convert to Montgomery n-residue form */
public void nres()
{
if (ROM.MODTYPE!=ROM.PSEUDO_MERSENNE)
{
DBIG d=new DBIG(x);
d.shl(ROM.NLEN*ROM.BASEBITS);
x.copy(d.mod(p));
}
}
/* convert back to regular form */
public BIG redc()
{
if (ROM.MODTYPE!=ROM.PSEUDO_MERSENNE)
{
DBIG d=new DBIG(x);
return BIG.mod(d);
}
else
{
BIG r=new BIG(x);
return r;
}
}
/* test this=0? */
public boolean iszilch() {
reduce();
return x.iszilch();
}
/* copy from FP b */
public void copy(FP b)
{
x.copy(b.x);
}
/* set this=0 */
public void zero()
{
x.zero();
}
/* set this=1 */
public void one()
{
x.one(); nres();
}
/* normalise this */
public void norm()
{
x.norm();
}
/* swap FPs depending on d */
public void cswap(FP b,int d)
{
x.cswap(b.x,d);
}
/* copy FPs depending on d */
public void cmove(FP b,int d)
{
x.cmove(b.x,d);
}
/* this*=b mod Modulus */
public void mul(FP b)
{
int ea=BIG.EXCESS(x);
int eb=BIG.EXCESS(b.x);
if ((ea+1)*(eb+1)+1>=ROM.FEXCESS) reduce();
DBIG d=BIG.mul(x,b.x);
x.copy(BIG.mod(d));
}
/* this*=c mod Modulus, where c is a small int */
public void imul(int c)
{
norm();
boolean s=false;
if (c<0)
{
c=-c;
s=true;
}
int afx=(BIG.EXCESS(x)+1)*(c+1)+1;
if (c<ROM.NEXCESS && afx<ROM.FEXCESS)
{
x.imul(c);
}
else
{
if (afx<ROM.FEXCESS) x.pmul(c);
else
{
DBIG d=x.pxmul(c);
x.copy(d.mod(p));
}
}
if (s) neg();
norm();
}
/* this*=this mod Modulus */
public void sqr()
{
DBIG d;
int ea=BIG.EXCESS(x);
if ((ea+1)*(ea+1)+1>=ROM.FEXCESS)
reduce();
d=BIG.sqr(x);
x.copy(BIG.mod(d));
}
/* this+=b */
public void add(FP b) {
x.add(b.x);
if (BIG.EXCESS(x)+2>=ROM.FEXCESS) reduce();
}
/* this = -this mod Modulus */
public void neg()
{
int sb,ov;
BIG m=new BIG(p);
norm();
ov=BIG.EXCESS(x);
sb=1; while(ov!=0) {sb++;ov>>=1;}
m.fshl(sb);
x.rsub(m);
if (BIG.EXCESS(x)>=ROM.FEXCESS) reduce();
}
/* this-=b */
public void sub(FP b)
{
FP n=new FP(b);
n.neg();
this.add(n);
}
/* this/=2 mod Modulus */
public void div2()
{
x.norm();
if (x.parity()==0)
x.fshr(1);
else
{
x.add(p);
x.norm();
x.fshr(1);
}
}
/* this=1/this mod Modulus */
public void inverse()
{
BIG r=redc();
r.invmodp(p);
x.copy(r);
nres();
}
/* return TRUE if this==a */
public boolean equals(FP a)
{
a.reduce();
reduce();
if (BIG.comp(a.x,x)==0) return true;
return false;
}
/* reduce this mod Modulus */
public void reduce()
{
x.mod(p);
}
/* return this^e mod Modulus */
public FP pow(BIG e)
{
int bt;
FP r=new FP(1);
e.norm();
x.norm();
FP m=new FP(this);
while (true)
{
bt=e.parity();
e.fshr(1);
if (bt==1) r.mul(m);
if (e.iszilch()) break;
m.sqr();
}
r.x.mod(p);
return r;
}
/* return sqrt(this) mod Modulus */
public FP sqrt()
{
reduce();
BIG b=new BIG(p);
if (ROM.MOD8==5)
{
b.dec(5); b.norm(); b.shr(3);
FP i=new FP(this); i.x.shl(1);
FP v=i.pow(b);
i.mul(v); i.mul(v);
i.x.dec(1);
FP r=new FP(this);
r.mul(v); r.mul(i);
r.reduce();
return r;
}
else
{
b.inc(1); b.norm(); b.shr(2);
return pow(b);
}
}
/* return jacobi symbol (this/Modulus) */
public int jacobi()
{
BIG w=redc();
return w.jacobi(p);
}
/*
public static void main(String[] args) {
BIG m=new BIG(ROM.Modulus);
BIG x=new BIG(3);
BIG e=new BIG(m);
e.dec(1);
System.out.println("m= "+m.nbits());
BIG r=x.powmod(e,m);
System.out.println("m= "+m.toString());
System.out.println("r= "+r.toString());
BIG.cswap(m,r,0);
System.out.println("m= "+m.toString());
System.out.println("r= "+r.toString());
// FP y=new FP(3);
// FP s=y.pow(e);
// System.out.println("s= "+s.toString());
} */
}
| brentzundel/incubator-milagro-crypto | java/FP.java | 2,229 | /* convert to string */ | block_comment | en | false | 1,723 | 5 | 2,229 | 5 | 2,163 | 5 | 2,229 | 5 | 2,547 | 5 | false | false | false | false | false | true |
216320_13 | import java.util.ArrayList;
import java.util.Collections;
public class Member {
private String username;
private String password;
private int status;
private String address;
private ArrayList<String> vehicles;
private int preference; //multiple preferences can be bits
private String firstName;
private String lastName;
private String cellNumber;
private String licenseNumber;
private String Email;
public Member(){
}
/**
* @return the username
*/
public String getUsername() {
return username;
}
/**
* @param username the username to set
*/
public void setUsername(String username) {
this.username = username;
}
/**
* @return the password
*/
public String getPassword() {
return password;
}
/**
* @param password the password to set
*/
public void setPassword(String password) {
this.password = password;
}
/**
* @return the firstName
*/
public String getFirstName() {
return firstName;
}
/**
* @param firstName the firstName to set
*/
public void setFirstName(String firstName) {
this.firstName = firstName;
}
/**
* @return the lastName
*/
public String getLastName() {
return lastName;
}
/**
* @param lastName the lastName to set
*/
public void setLastName(String lastName) {
this.lastName = lastName;
}
/**
* @return the cellNumber
*/
public String getCellNumber() {
return cellNumber;
}
/**
* @param cellNumber the cellNumber to set
*/
public void setCellNumber(String cellNumber) {
this.cellNumber = cellNumber;
}
/**
* Set Status of Member
* @param status 0 none, 1 passenger, 2 driver, 3 both
*/
public void setStatus(int status){
this.status = status;
}
/**
* Set Address of member
* @param addr Address of member
*/
public void setAddress(String addr){
this.address = addr;
}
/**
* Copy vehicles over into list of vehicles
* @param vehicles Initialize Vehicles
*/
public void setVehicles(ArrayList<String> vehicles){
Collections.copy(this.vehicles, vehicles);
}
/**
* Member's preference set
* @param preference
*/
public void setPreference(int preference){
this.preference = preference;
}
/**
* Get Status of member
* @return status
*/
public int getStatus(){
return this.status;
}
/**
* Get address of member
* @return member's address
*/
public String getAddress(){
return address;
}
/**
* List of vehicles owned by member
* @return a list of vehicles
*/
public ArrayList<String> getVehicles(){
return vehicles;
}
/**
* Preference of member
* @return member's preference
*/
public int getPreference(){
return this.preference;
}
/**
* Add new vehicle to list
* @param vehicle vehicle to be added
*/
public void addVehicle(String vehicle){
this.vehicles.add(vehicle);
}
/**
* @return the licenseNumber
*/
public String getLicenseNumber() {
return licenseNumber;
}
/**
* @param licenseNumber the licenseNumber to set
*/
public void setLicenseNumber(String licenseNumber) {
this.licenseNumber = licenseNumber;
}
public void setEmail(String email ) {
// TODO Auto-generated method stub
this.Email = email;
}
}
| jakubkalinowski/SJSU_SE133 | src/Member.java | 901 | /**
* Copy vehicles over into list of vehicles
* @param vehicles Initialize Vehicles
*/ | block_comment | en | false | 760 | 21 | 901 | 21 | 964 | 22 | 901 | 21 | 1,046 | 24 | false | false | false | false | false | true |
216347_5 | import java.util.ArrayList;
import java.util.Date;
import java.util.List;
public class Floor1 implements Floor{
/** This floor is to park all non-electric 4 wheelers
* Has 200 parking spots, out of which the first 20 are reserved for handicapped
*/
final int MAX_SPOTS = 200;
// Creating a list of objects of class Parking Spot, which contains details of each spot.
List<ParkingSpot> spots = new ArrayList<>(MAX_SPOTS);
// Creating a boolean array to check if a given spot is vacant or not.
boolean[] spots_available =new boolean[MAX_SPOTS];
//Initially, marking all spots in the floor as available.
private void initialize_spots_available(){
for(int i=0; i<MAX_SPOTS; ++i){
spots_available[i] = true;
}
}
//Initializing the array list.
private void initialize_array_list(){
for(int i=0; i<MAX_SPOTS; ++i){
spots.add(i, null);
}
}
//Constructor initializes both the array and the list.
public Floor1() {
initialize_spots_available();
initialize_array_list();
}
@Override
public boolean isFull() {
boolean k = true;
for(int i=0; i<MAX_SPOTS; ++i){
if(spots_available[i]){
k = false;
break;
}
}
return k;
}
@Override
public void slotsAvailable() {
System.out.println("GENERAL PARKING SLOTS");
int cnt = 0;
for(int i=20; i<MAX_SPOTS; ++i){
if(spots_available[i]){
++cnt;
System.out.print(i+1 + " ");
}
if(cnt > 20) {
cnt = 0;
System.out.println();
}
}
}
@Override
public void display_entry_points() {
System.out.println("1. Handicapped Road");
System.out.println("2. South Gate Road");
System.out.println("3. North Gate Road");
System.out.println("4. East Gate Road");
}
@Override
public void display_exit_points() {
System.out.println("1. Handicapped Road");
System.out.println("2. South Gate Road");
System.out.println("3. North Gate Road");
System.out.println("4. East Gate Road");
}
@Override
public void display_reserved_spots() {
System.out.println("\nRESERVED FOR HANDICAPPED");
for(int i=0; i<20; ++i){
if(spots_available[i]){
System.out.print(i+1 + " ");
}
}
}
@Override
public Vehicle findVehicle(int slotno) {
return null;
}
@Override
public Date findDate(int slotno) {
return spots.get(slotno-1).getEntry();
}
@Override
public void clearSpots(int slotno) {
spots_available[slotno - 1] = true;
}
@Override
public void add_vehicle(ParkingSpot p) {
int slotno = p.getSlotNo();
if(spots_available[slotno-1]){
spots_available[slotno-1] = false;
spots.set(slotno-1,p);
}
}
@Override
public void vehicle_exit(int slotno) {
if(!spots_available[slotno-1]){
spots_available[slotno-1] = true;
spots.set(slotno-1,null);
}
}
@Override
public void display_vehicles_details() {
boolean isempty = false;
for(int i=0; i<MAX_SPOTS; ++i){
if(!spots_available[i]){
isempty = true;
Vehicle v = spots.get(i).getVehicle();
System.out.println(v.getName() + " - " + v.getLicenseNumber() + " - " + v.getColor() + " - " + spots.get(i).getEntry());
}
}
if(!isempty){
System.out.println("No vehicles parked yet!");
}
}
}
| CS21B043/PM-Team-8-Parking-Lot | Floor1.java | 1,049 | //Constructor initializes both the array and the list.
| line_comment | en | false | 897 | 11 | 1,049 | 11 | 1,155 | 10 | 1,049 | 11 | 1,275 | 11 | false | false | false | false | false | true |
218369_2 | /*
* Copyright (c) 2008-2009, Motorola, Inc.
*
* 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.
*
* - Neither the name of the Motorola, Inc. nor the names of its contributors
* may be used to endorse or promote products derived from this software
* without specific prior written permission.
*
* 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.
*/
package javax.obex;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
/**
* The <code>Operation</code> interface provides ways to manipulate a single
* OBEX PUT or GET operation. The implementation of this interface sends OBEX
* packets as they are built. If during the operation the peer in the operation
* ends the operation, an <code>IOException</code> is thrown on the next read
* from the input stream, write to the output stream, or call to
* <code>sendHeaders()</code>.
* <P>
* <STRONG>Definition of methods inherited from <code>ContentConnection</code>
* </STRONG>
* <P>
* <code>getEncoding()</code> will always return <code>null</code>. <BR>
* <code>getLength()</code> will return the length specified by the OBEX Length
* header or -1 if the OBEX Length header was not included. <BR>
* <code>getType()</code> will return the value specified in the OBEX Type
* header or <code>null</code> if the OBEX Type header was not included.<BR>
* <P>
* <STRONG>How Headers are Handled</STRONG>
* <P>
* As headers are received, they may be retrieved through the
* <code>getReceivedHeaders()</code> method. If new headers are set during the
* operation, the new headers will be sent during the next packet exchange.
* <P>
* <STRONG>PUT example</STRONG>
* <P>
* <PRE>
* void putObjectViaOBEX(ClientSession conn, HeaderSet head, byte[] obj) throws IOException {
* // Include the length header
* head.setHeader(head.LENGTH, new Long(obj.length));
* // Initiate the PUT request
* Operation op = conn.put(head);
* // Open the output stream to put the object to it
* DataOutputStream out = op.openDataOutputStream();
* // Send the object to the server
* out.write(obj);
* // End the transaction
* out.close();
* op.close();
* }
* </PRE>
* <P>
* <STRONG>GET example</STRONG>
* <P>
* <PRE>
* byte[] getObjectViaOBEX(ClientSession conn, HeaderSet head) throws IOException {
* // Send the initial GET request to the server
* Operation op = conn.get(head);
* // Retrieve the length of the object being sent back
* int length = op.getLength();
* // Create space for the object
* byte[] obj = new byte[length];
* // Get the object from the input stream
* DataInputStream in = trans.openDataInputStream();
* in.read(obj);
* // End the transaction
* in.close();
* op.close();
* return obj;
* }
* </PRE>
*
* <H3>Client PUT Operation Flow</H3> For PUT operations, a call to
* <code>close()</code> the <code>OutputStream</code> returned from
* <code>openOutputStream()</code> or <code>openDataOutputStream()</code> will
* signal that the request is done. (In OBEX terms, the End-Of-Body header
* should be sent and the final bit in the request will be set.) At this point,
* the reply from the server may begin to be processed. A call to
* <code>getResponseCode()</code> will do an implicit close on the
* <code>OutputStream</code> and therefore signal that the request is done.
* <H3>Client GET Operation Flow</H3> For GET operation, a call to
* <code>openInputStream()</code> or <code>openDataInputStream()</code> will
* signal that the request is done. (In OBEX terms, the final bit in the request
* will be set.) A call to <code>getResponseCode()</code> will cause an implicit
* close on the <code>InputStream</code>. No further data may be read at this
* point.
* @hide
*/
public interface Operation {
/**
* Sends an ABORT message to the server. By calling this method, the
* corresponding input and output streams will be closed along with this
* object. No headers are sent in the abort request. This will end the
* operation since <code>close()</code> will be called by this method.
* @throws IOException if the transaction has already ended or if an OBEX
* server calls this method
*/
void abort() throws IOException;
/**
* Returns the headers that have been received during the operation.
* Modifying the object returned has no effect on the headers that are sent
* or retrieved.
* @return the headers received during this <code>Operation</code>
* @throws IOException if this <code>Operation</code> has been closed
*/
HeaderSet getReceivedHeader() throws IOException;
/**
* Specifies the headers that should be sent in the next OBEX message that
* is sent.
* @param headers the headers to send in the next message
* @throws IOException if this <code>Operation</code> has been closed or the
* transaction has ended and no further messages will be exchanged
* @throws IllegalArgumentException if <code>headers</code> was not created
* by a call to <code>ServerRequestHandler.createHeaderSet()</code>
* or <code>ClientSession.createHeaderSet()</code>
* @throws NullPointerException if <code>headers</code> if <code>null</code>
*/
void sendHeaders(HeaderSet headers) throws IOException;
/**
* Returns the response code received from the server. Response codes are
* defined in the <code>ResponseCodes</code> class.
* @see ResponseCodes
* @return the response code retrieved from the server
* @throws IOException if an error occurred in the transport layer during
* the transaction; if this object was created by an OBEX server
*/
int getResponseCode() throws IOException;
String getEncoding();
long getLength();
int getHeaderLength();
String getType();
InputStream openInputStream() throws IOException;
DataInputStream openDataInputStream() throws IOException;
OutputStream openOutputStream() throws IOException;
DataOutputStream openDataOutputStream() throws IOException;
void close() throws IOException;
void noEndofBody();
int getMaxPacketSize();
}
| gp-b2g/frameworks_base | obex/javax/obex/Operation.java | 1,829 | /**
* Sends an ABORT message to the server. By calling this method, the
* corresponding input and output streams will be closed along with this
* object. No headers are sent in the abort request. This will end the
* operation since <code>close()</code> will be called by this method.
* @throws IOException if the transaction has already ended or if an OBEX
* server calls this method
*/ | block_comment | en | false | 1,737 | 96 | 1,829 | 91 | 1,813 | 96 | 1,829 | 91 | 2,163 | 102 | false | false | false | false | false | true |
218741_0 | import java.util.Random;
import java.util.Scanner;
import java.time.Instant;
import java.time.Duration;
public class Lab02 {
public static String[] letterCode = {"A", "R", "N", "D", "C", "Q", "E", "G", "H", "I",
"L", "K", "M", "F", "P", "S", "T", "W", "Y", "V"};
public static String[] aminoAcids = {"alanine", "arginine", "asparagine", "aspartic acid", "cysteine",
"glutamine", "glutamic acid", "glycine", "histidine", "isoleucine",
"leucine", "lysine", "methionine", "phenylalanine", "proline",
"serine", "threonine", "tryptophan", "tyrosine", "valine"};
public static void main(String[] args) {
int score = 0;
Instant startTime = Instant.now();
while (Duration.between(startTime, Instant.now()).getSeconds() < 30) {
int randomIndex = getRandomIndex();
String aminoAcid = aminoAcids[randomIndex];
System.out.println("What is the one-letter code for the amino acid: " + aminoAcid + "?");
Scanner scanner = new Scanner(System.in);
String userInput = scanner.nextLine().trim().toUpperCase();
if (userInput.equals(letterCode[randomIndex])) {
System.out.println("That's correct!\n");
score++;
} else {
System.out.println("That's incorrect! The one letter code for " + aminoAcid + " is " + letterCode[randomIndex] + "\n");
break;
}
scanner.close();
}
System.out.println("Your score: " + score + "/" + aminoAcids.length);
}
static int getRandomIndex() {
Random random = new Random();
return random.nextInt(aminoAcids.length);
}
}
/*
* Discussion: I ran out of time before being able to dig into the extra credit tasks but just looking at my code
* vs ChatGPT's (AminoAcidQuiz.java), it looks like chatGPT actually over-complicated both the code and the underlying logic
* and employs a constant countdown method that is very distracting when taking the quiz. It did seem to meet all
* specifications for the assignment as far as I can tell but I can't say that I understand everything that its doing
* to achieve a similar result.
* The benefit that this countdown has over my code is that it immediately ends the quiz at the 30 second mark instead of
* checking for time after each new response.
*/ | AlexandraTew/HelloWorld | Lab02.java | 654 | /*
* Discussion: I ran out of time before being able to dig into the extra credit tasks but just looking at my code
* vs ChatGPT's (AminoAcidQuiz.java), it looks like chatGPT actually over-complicated both the code and the underlying logic
* and employs a constant countdown method that is very distracting when taking the quiz. It did seem to meet all
* specifications for the assignment as far as I can tell but I can't say that I understand everything that its doing
* to achieve a similar result.
* The benefit that this countdown has over my code is that it immediately ends the quiz at the 30 second mark instead of
* checking for time after each new response.
*/ | block_comment | en | false | 590 | 151 | 654 | 162 | 650 | 154 | 654 | 162 | 739 | 174 | false | false | false | false | false | true |
218876_8 | /*
* $Id: PDFXref.java,v 1.4 2009/02/12 13:53:56 tomoke Exp $
*
* Copyright 2004 Sun Microsystems, Inc., 4150 Network Circle,
* Santa Clara, California 95054, U.S.A. All rights reserved.
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* This library 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
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
*/
package com.sun.pdfview;
import net.sf.andpdf.refs.SoftReference;
/**
* a cross reference representing a line in the PDF cross referencing
* table.
* <p>
* There are two forms of the PDFXref, destinguished by absolutely nothing.
* The first type of PDFXref is used as indirect references in a PDFObject.
* In this type, the id is an index number into the object cross reference
* table. The id will range from 0 to the size of the cross reference
* table.
* <p>
* The second form is used in the Java representation of the cross reference
* table. In this form, the id is the file position of the start of the
* object in the PDF file. See the use of both of these in the
* PDFFile.dereference() method, which takes a PDFXref of the first form,
* and uses (internally) a PDFXref of the second form.
* <p>
* This is an unhappy state of affairs, and should be fixed. Fortunatly,
* the two uses have already been factored out as two different methods.
*
* @author Mike Wessler
*/
public class PDFXref {
private int id;
private int generation;
private boolean compressed;
// this field is only used in PDFFile.objIdx
private SoftReference<PDFObject> reference = null;
/**
* create a new PDFXref, given a parsed id and generation.
*/
public PDFXref(int id, int gen) {
this.id = id;
this.generation = gen;
this.compressed = false;
}
/**
* create a new PDFXref, given a parsed id, compressedObjId and index
*/
public PDFXref(int id, int gen, boolean compressed) {
this.id = id;
this.generation = gen;
this.compressed = compressed;
}
/**
* create a new PDFXref, given a sequence of bytes representing the
* fixed-width cross reference table line
*/
public PDFXref(byte[] line) {
if (line == null) {
id = -1;
generation = -1;
} else {
id = Integer.parseInt(new String(line, 0, 10));
generation = Integer.parseInt(new String(line, 11, 5));
}
compressed = false;
}
/**
* get the character index into the file of the start of this object
*/
public int getFilePos() {
return id;
}
/**
* get the generation of this object
*/
public int getGeneration() {
return generation;
}
/**
* get the generation of this object
*/
public int getIndex() {
return generation;
}
/**
* get the object number of this object
*/
public int getID() {
return id;
}
/**
* get compressed flag of this object
*/
public boolean getCompressed() {
return compressed;
}
/**
* Get the object this reference refers to, or null if it hasn't been
* set.
* @return the object if it exists, or null if not
*/
public PDFObject getObject() {
if (reference != null) {
return (PDFObject) reference.get();
}
return null;
}
/**
* Set the object this reference refers to.
*/
public void setObject(PDFObject obj) {
this.reference = new SoftReference<PDFObject>(obj);
}
}
| StEaLtHmAn/AndroidPDFViewerLibrary | src/com/sun/pdfview/PDFXref.java | 1,078 | /**
* get the generation of this object
*/ | block_comment | en | false | 1,027 | 12 | 1,078 | 11 | 1,151 | 13 | 1,078 | 11 | 1,231 | 13 | false | false | false | false | false | true |
220092_7 | package edu.usca.acsc492l.flightplanner;
import java.util.ArrayList;
/**
* A helper class to hold information regarding each destination in the flight plan.
*
* @author Dylon Edwards
*/
public class Destination {
/** Holds the Vertex to be used as this destination */
protected final Vertex destination;
/** Holds the reasons for visiting this destination */
protected ArrayList<String> reasons;
/**
* Constructs a Desintation object with the given Vertex node
*
* @param destination The destination, either an Airport or NAVBeacon
* @throws NullPointerException When destination is null
*/
public Destination(Vertex destination) {
if (destination == null) {
throw new NullPointerException("destination may not be null");
}
this.destination = destination;
reasons = new ArrayList<String>();
}
/**
* Add a reason for stopping at the destination
*
* @param reason The reason for stopping at the destination
* @throws NullPointerException When reason is null
*/
public void addReason(String reason) {
if (reason == null) {
throw new NullPointerException("reason may not be null");
}
reasons.add(reason);
}
/**
* Returns the reasons for visiting this Destination
*
* @return The {@link #reasons} attribute
*/
public ArrayList<String> getReasons() {
return reasons;
}
/**
* Returns the Vertex serving as this Destination
*
* @return The {@link #destination} attribute
*/
public Vertex getDestination() {
return destination;
}
/**
* Overrides the toString() method of the Object class to return all the
* {@link #reasons} for visiting this Destination
*
* @return The String representation of this Destination
*/
@Override
public String toString() {
int counter = 1;
int max = reasons.size();
int longestLabelWidth = destination.getLongestLabelWidth();
String toString = "";
for (String reason : reasons.toArray(new String[0])) {
toString += String.format(" => %-" + longestLabelWidth + "s %s",
"Reason:", reason);
if (counter < max) {
toString += '\n';
}
counter ++;
}
return toString;
}
} | aczietlow/Flight-Planner-Java | Destination.java | 554 | /**
* Overrides the toString() method of the Object class to return all the
* {@link #reasons} for visiting this Destination
*
* @return The String representation of this Destination
*/ | block_comment | en | false | 503 | 45 | 554 | 43 | 592 | 47 | 554 | 43 | 681 | 53 | false | false | false | false | false | true |
220242_0 | import java.util.Random;
class Skill {
private Random rand = new Random();
private double acc = 100.0;
private boolean passive = false;
private boolean offense = true;
private boolean hurtSelf = false;
private Damage dam = null;
private final static int magic = 0, blunt = 1, sharp = 2;
enum Type {
MAGIC,
BLUNT,
SHARP,
NORMAL
}
private Type type = null;
// Called to create a skill instance
Skill(double acc, boolean passive, boolean offense, Type type, Damage dam) {
this.acc = acc;
this.passive = passive;
this.offense = offense;
this.type = type;
this.dam = dam;
if (this.dam.getSelfDam() > 0) {
hurtSelf = true;
}
}
public double getBase(){
return dam.getDam();
}
// Called to get the amount of damage this skill will note favor closer to 1
// means more liekly to hit max damage
public double getDam(double[] resistances, double favor, boolean notSelf) {
double accCheck = rand.nextDouble() * 100;
if (acc <= accCheck) {
return 0;
}
if (!this.getOffense()) {
return dam.getDam();
} else if (this.passive){
return dam.getDam();
}
double randNum = rand.nextDouble() + .5;
randNum = randNum + favor;
if (notSelf) {
if (randNum > 1.5) {
randNum = 1.5;
}
randNum = randNum * dam.getDam();
} else if (!notSelf) {
randNum = randNum * dam.getSelfDam();
}
switch (type) {
case MAGIC:
if (resistances[magic] > 0) {
randNum = randNum / resistances[magic];
}
case BLUNT:
if (resistances[blunt] > 0) {
randNum = randNum / resistances[blunt];
}
case SHARP:
if (resistances[sharp] > 0) {
randNum = randNum / resistances[sharp];
}
case NORMAL:
return randNum;
}
return randNum;
}
// Overloading method to call to get amount of damage without favor
public double getDam(double[] resistances, boolean notSelf) {
return this.getDam(resistances, 0.0, notSelf);
}
// Call to get wether or not this skill is a passive skill
public boolean getPassive() {
return passive;
}
// Call to get wether or not this skill is an offensive skill
public boolean getOffense() {
return offense;
}
// Call to see wether or not this skill hurts the mob using the skill
public boolean getHurtSelf() {
return hurtSelf;
}
// Call to get the type of the skill, see enum Type to see types
public Type getType() {
return type;
}
}
| jpang9431/Basic-Dungeon-Crawler-Game | Skill.java | 741 | // Called to create a skill instance
| line_comment | en | false | 697 | 8 | 741 | 8 | 791 | 8 | 741 | 8 | 864 | 9 | false | false | false | false | false | true |
220501_8 | package task3;
/**
* Class Monitor To synchronize dining philosophers.
*
* @author Serguei A. Mokhov, [email protected]
*/
public class Monitor {
/*
* ------------ Data members ------------
*/
// *** TASK-2 ***
enum State {
thinking, hungry, eating, talking;
};
// *** TASK-3 ***
enum PriorityState {
hungry, eating, thinking;
}
State[] state;
PriorityState[] priorityState;
int[] priority;
int numOfPhil;
boolean talking;
/**
* Constructor
*/
public Monitor(int piNumberOfPhilosophers) {
// TODO: set appropriate number of chopsticks based on the # of philosophers
state = new State[piNumberOfPhilosophers];
priorityState = new PriorityState[piNumberOfPhilosophers];
priority = new int[piNumberOfPhilosophers];
numOfPhil = piNumberOfPhilosophers;
for (int i = 0; i < piNumberOfPhilosophers; i++) {
state[i] = State.thinking;
}
priority[0] = 3;
priority[1] = 2;
priority[2] = 0;
priority[3] = 5;
}
/*
* ------------------------------- User-defined monitor procedures
* -------------------------------
*/
/**
* Grants request (returns) to eat when both chopsticks/forks are available.
* Else forces the philosopher to wait()
*/
// *** Task-2 *** Implementing pickUp Method
public synchronized void pickUp(final int piTID) {
int id = piTID - 1;
state[id] = State.hungry;
// *** Task-2 *** If any neighbors are eating then wait.
while((state[(id + (numOfPhil - 1)) % numOfPhil] == State.eating)
|| (state[(id + 1) % numOfPhil] == State.eating)) {
try {
wait();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
// Checks priority before entering
enter(id);
// If none of the neighbors are eating then start eating
state[id] = State.eating;
}
// ***Task-3 *** This method waits if the priorities doesn't match
public synchronized void enter(int TID) {
priorityState[TID] = PriorityState.hungry;
while(isHigherPriority(TID) == false) {
try {
wait();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
priorityState[TID] = PriorityState.eating;
}
// ***Task-3*** This method exits
public synchronized void exit(int TID) {
priorityState[TID] = PriorityState.thinking;
notifyAll();
}
// ***Task-3*** This method checks the priority
public synchronized boolean isHigherPriority(int TID) {
boolean isHigherPriority = true;
for(int i = 0; i < numOfPhil; i++) {
if(TID == i || priorityState[i] == PriorityState.thinking) {
// do nothing
}
else {
if(priority[TID] > priority[i]) {
isHigherPriority = false;
}
}
}
return isHigherPriority;
}
/**
* When a given philosopher's done eating, they put the chopstiks/forks down and
* let others know they are available.
*/
// *** Task-2 *** Implementing putDown Method
public synchronized void putDown(final int piTID) {
int id = piTID - 1;
exit(id);
state[id] = State.thinking;
notifyAll();
}
/**
* Only one philopher at a time is allowed to philosophy (while she is not
* eating).
*/
// *** Task-2 *** Implementing requestTalk Method
public synchronized void requestTalk(int tid) {
int id = tid - 1;
// Wait if the philosopher is eating or others are talking
while((state[id] == State.eating) || (isTalking(id) == true) || talking) {
try {
wait();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
talking = true;
state[id] = State.talking;
}
// Public boolean isTalking()
// Checking if somebody is talking or not
public synchronized boolean isTalking(int id) {
boolean talking = false;
int i = id;
for(int j = 0; j < numOfPhil; j++) {
if(i == j) {
// do nothing
}
// Check if others are talking or not
else {
if (state[id] == State.talking) {
talking = true;
}
}
}
// Return if they are talking or not
return talking;
}
/**
* When one philosopher is done talking stuff, others can feel free to start
* talking.
*/
// *** Task-2 *** Implementing endTalk Method
public synchronized void endTalk(int id) {
int i = id-1;
talking = false;
state[i] = State.thinking;
notifyAll();
}
}
// EOF
| mushfiqur-anik/Dining-Philosopher-Problem | task3/Monitor.java | 1,409 | // *** Task-2 *** Implementing pickUp Method | line_comment | en | false | 1,251 | 11 | 1,409 | 11 | 1,404 | 10 | 1,409 | 11 | 1,777 | 12 | false | false | false | false | false | true |
220642_0 | import java.util.Scanner;
public class switchs {
System.out.p
Scanner sc = new Scanner(System.in);
// Taking input from the user.
int button = sc.nextInt();
// If we have multiple cases the we wil use switch statement.
switch(button){
// Case 1, if user gave input 1.
case 1: System.out.println("Hello.");
// break.
break;
// case 2, if user gave input 2.
case 2: System.out.println("Namaste.");
// break.
break;
// case 3, if user gave input 3.
case 3: System.out.println("Bonjure.");
// break.
break;
// Using default if the user gave different input .
default: System.out.println("Invalid option.");
}
}
| Shivam-tamboli/Java-repository | switchs.java | 198 | // Taking input from the user. | line_comment | en | false | 176 | 7 | 198 | 8 | 216 | 7 | 198 | 8 | 225 | 8 | false | false | false | false | false | true |
222384_9 | /** Board.java
* Creates a board based on user input and runs an interactive loop to either allow the user to solve the board or to automatically solve it
* if the board is solvable, prints out a step-by-step solution
* if the board is unsolvable, prints out a best-found solution
*
* created by 1530b
*/
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Random;
import java.util.Scanner;
import static java.lang.System.exit;
public class Board {
public int grid[][];
HashMap<Integer, Coordinate> mapFromIntegerToCoord = new HashMap<>();
public Board(int choice) {
if (choice == 1) {
generateBoard(new Random(System.currentTimeMillis()));
} else if (choice == 2) {
generateBoard();
} else {
Constants.outputStream.println("Invalid input given.");
exit(1);
}
}
/**
* Performs a deep copy of a board by copying its grid and mappings.
* @param b
*/
public Board(Board b) {
grid = new int[Constants.dimX][Constants.dimY];
for (int i = 0; i < Constants.dimX; i++) {
for (int j = 0; j < Constants.dimY; j++) {
grid[i][j] = b.grid[i][j];
mapFromIntegerToCoord.put(b.grid[i][j], new Coordinate(i, j));
}
}
}
/**
* compares the grid of this to board b for equality
* @param b
* @return
*/
public boolean equals(Board b) {
for (int i = 0; i < Constants.dimX; i++) {
if (!grid[i].equals(b.grid[i])) {
return false;
}
}
return true;
}
/**
* generated a board using a random seeded with time.
* 1. generate 9 unique, random integers (0-9)
* 2. export them into an array
* 3. convert into an integer array
* 4. set up grid
*
* @param rand
*/
private void generateBoard(Random rand) {
grid = new int[Constants.dimX][Constants.dimY];
int[] boardVals = new int[Constants.gridSize];
for (int i = 0; i < (Constants.gridSize); i++) {
boardVals[i] = i;
}
shuffleNumbers(boardVals, rand);
int arrIndex = 0;
for (int i = 0; i < Constants.dimX; i++) {
for (int j = 0; j < Constants.dimY; j++) {
int num = boardVals[arrIndex++];
mapFromIntegerToCoord.put(num, new Coordinate(i, j));
grid[i][j] = num;
}
}
}
/**
* Generates board based on user input
* 1. take input from user
* 2. parse char by char
* 3. input into grid
*/
private void generateBoard() {
Scanner scan = new Scanner(Constants.inputStream);
Constants.outputStream.println("Some boards such as 728045163 are impossible.");
Constants.outputStream.println("Others such as 245386107 are possible.");
Constants.outputStream.print("Enter a string of 6 digits (including 0) for the board --> ");
String input = scan.nextLine().trim();
grid = new int[Constants.dimX][Constants.dimY];
int strIndex = 0;
for (int i = 0; i < Constants.dimX; i++) {
for (int j = 0; j < Constants.dimY; j++) {
int num = Character.getNumericValue(input.charAt(strIndex++));
mapFromIntegerToCoord.put(num, new Coordinate(i, j));
grid[i][j] = num;
}
}
}
/**
* Takes an array and shuffles it a random number of times
* @param arr
* @param rand
*/
private void shuffleNumbers(int[] arr, Random rand) {
int numTimesToSwap = rand.nextInt(200);
for (int i = 0; i < numTimesToSwap; i++) {
int index1 = rand.nextInt((Constants.gridSize) - 1);
int index2 = rand.nextInt((Constants.gridSize) - 1);
int tmp = arr[index2];
arr[index2] = arr[index1];
arr[index1] = tmp;
}
}
/**
* prints out the current grid
*/
public void printBoard() {
for (int i = 0; i < Constants.dimX; i++) {
Constants.outputStream.print(" ");
for (int j = 0; j < Constants.dimY; j++) {
Constants.outputStream.print(grid[i][j] == 0 ? " " : grid[i][j] + " ");
}
Constants.outputStream.print("\n");
}
}
/**
* determines whether the current grid is already solved
* @return
*/
public boolean isSolved() {
for (int i = 0; i < Constants.dimX; i++) {
for (int j = 0; j < Constants.dimY; j++) {
if (i == Constants.dimX - 1 && j == Constants.dimY - 1) { //if at bottom right corner, index should be 0
if (grid[i][j] != 0) {
return false;
}
} else if (grid[i][j] != (i * Constants.dimX) + j + 1) //every other index should satisfy its spot
return false;
}
}
return true;
}
/**
* slides a piece into the empty slot
* @param n
*/
public void makeMove(int n) {
if (mapFromIntegerToCoord.containsKey(n)) {
Coordinate coord = mapFromIntegerToCoord.remove(n);
Coordinate zeroCoord = mapFromIntegerToCoord.remove(0);
grid[zeroCoord.X][zeroCoord.Y] = grid[coord.X][coord.Y];
grid[coord.X][coord.Y] = 0;
mapFromIntegerToCoord.put(0, new Coordinate(coord.X, coord.Y));
mapFromIntegerToCoord.put(n, new Coordinate(zeroCoord.X, zeroCoord.Y));
}
}
/**
* determines whether a given move is valid
* @param n
* @return
*/
public boolean isValidMove(int n) {
Coordinate coord = mapFromIntegerToCoord.get(n);
if (mapFromIntegerToCoord.containsKey(n)) {
if (coord.X + 1 <= Constants.dimX - 1) {
if (grid[coord.X + 1][coord.Y] == 0) {
return true;
}
}
if (coord.Y + 1 <= Constants.dimY - 1) {
if (grid[coord.X][coord.Y + 1] == 0) {
return true;
}
}
if (coord.X - 1 >= 0) {
if (grid[coord.X - 1][coord.Y] == 0) {
return true;
}
}
if (coord.Y - 1 >= 0) {
if (grid[coord.X][coord.Y - 1] == 0) {
return true;
}
}
}
return false;
}
/**
* while the board is unsolved, allows the user to:
* a. make a move (if it is valid)
* b. prompt for an automatic solution (if one exists, otherwise print the best board found)
* c. quit
*
*/
public void interactiveLoop() {
Scanner scan = new Scanner(Constants.inputStream);
int boardCounter = 1;
Constants.outputStream.println("Initial board is:");
boolean autoSolve = false;
while (!isSolved() && !autoSolve) {
Constants.outputStream.println(boardCounter++ + ".");
printBoard();
Constants.outputStream.println("Heuristic Value: " + currentHeuristic());
Constants.outputStream.print("\nPiece to move: ");
String move = scan.next();
char m = move.charAt(0);
if (m == 's') {
autoSolve = true;
} else {
int numericInput = Character.getNumericValue(m);
if (numericInput == 0) {
Constants.outputStream.println("\nExiting program.");
exit(0);
}
if (isValidMove(numericInput)) {
makeMove(numericInput);
} else {
Constants.outputStream.println("*** Invalid move. Please retry.");
}
}
}
if (!isSolved()) {
SearchTree tree = autoSolve();
if (tree.bestBoardHeuristic > 0) {
Constants.outputStream.println("\nAll " +tree.oldBoards.size() + " moves have been tried.");
Constants.outputStream.println("That puzzle is impossible to solve. Best board found:");
tree.bestBoardFound.printBoard();
Constants.outputStream.println("Heuristic value: " + tree.bestBoardHeuristic);
Constants.outputStream.println("\nExiting program.");
} else {
Constants.outputStream.println("1.");
printBoard();
ArrayList<Board> list = tree.createPath();
for (int i = 0; i < list.size(); i++) {
Constants.outputStream.println(i + 2 + ".");
list.get(i).printBoard();
}
Constants.outputStream.println("\nDone.");
}
}
}
/**
* attempts to solve the board by:
* repeatedly making the best move possible by using a calculated heuristic at each step
* @return SearchTree
*/
private SearchTree autoSolve() {
Constants.outputStream.println("Solving puzzle automatically..........................");
Node v = new Node(null, this);
SearchTree tree = new SearchTree(v);
boolean unsolvable = false;
while (!v.board.isSolved() && !unsolvable) {
ArrayList<Board> children = v.board.getChildren();
for (Board b : children) {
tree.addNode(new Node(v.board, b));
}
Node nextMove = tree.pop();
if (nextMove == null) {
unsolvable = true;
} else {
v = nextMove;
}
}
return tree;
}
/**
* Calculates the intended coordinate of a given integer.
* ex:
* 1's intended coordinate in a 3x3 grid is (0,0)
* 2's intended coordinate in a 3x3 grid is (0,1)
* 8's intended coordinate in a 3x3 grid is (2,1)
* @param n
* @return a coordinate with the intended position of n
*/
private static Coordinate getIntendedCoordinate(int n) {
int intX = (n - 1) / Constants.dimX;
int intY = (n - 1) % Constants.dimY;
return new Coordinate(intX, intY);
}
/**
* calculates the number of moves required to get a given number into it's intended location
* @param n
* @return
*/
private int movesFromIntendedSlot(int n) {
Coordinate currCoordinate = mapFromIntegerToCoord.get(n);
if (n == 0) {
return Math.abs((Constants.dimX - 1) - currCoordinate.X) + Math.abs((Constants.dimY - 1) - currCoordinate.Y);
} else {
Coordinate intendedCoordinate = getIntendedCoordinate(n);
return Math.abs(intendedCoordinate.X - currCoordinate.X) + Math.abs(intendedCoordinate.Y - currCoordinate.Y);
}
}
/**
* calculates the heuristic of the current board by calculating the moves required to get the number at each index into it's desired index
* @return
*/
public int currentHeuristic() {
int total = 0;
for (int i = 0; i < Constants.dimX; i++) {
for (int j = 0; j < Constants.dimY; j++) {
total += movesFromIntendedSlot(grid[i][j]);
}
}
return total;
}
/**
* returns an ArrayList of board objects containing potential children of the current board
* @return
*/
public ArrayList<Board> getChildren() {
ArrayList<Board> children = new ArrayList<>();
Coordinate posOfZero = mapFromIntegerToCoord.get(0);
if (posOfZero.X + 1 <= Constants.dimX - 1) {
Board aBoard = new Board(this);
aBoard.makeMove(grid[posOfZero.X + 1][posOfZero.Y]);
children.add(aBoard);
}
if (posOfZero.Y + 1 <= Constants.dimY - 1) {
Board aBoard = new Board(this);
aBoard.makeMove(grid[posOfZero.X][posOfZero.Y + 1]);
children.add(aBoard);
}
if (posOfZero.X - 1 >= 0) {
Board aBoard = new Board(this);
aBoard.makeMove(grid[posOfZero.X - 1][posOfZero.Y]);
children.add(aBoard);
}
if (posOfZero.Y - 1 >= 0) {
Board aBoard = new Board(this);
aBoard.makeMove(grid[posOfZero.X][posOfZero.Y - 1]);
children.add(aBoard);
}
return children;
}
}
| sbukhari17/EightTileCommandLine | src/Board.java | 3,219 | //every other index should satisfy its spot | line_comment | en | false | 2,972 | 8 | 3,219 | 8 | 3,501 | 8 | 3,219 | 8 | 3,755 | 8 | false | false | false | false | false | true |
222409_3 | import java.util.List;
import java.util.ArrayList;
public class Student implements Comparable{
String name;
int idNum;
int gradYear;
int drawNumber;
public List<Course> requests;
public List<Course> schedule;
/**
* @param name: string the student's first and last name;
* @param idNum: int the student's 999 number.
* @param gradYear: 4 digit graduation year.
* @param drawNumber: the draw number determines the student's place in the algorithm.
*/
public Student(String name, int idNum, int gradYear,int drawNumber){
this.name = name;
this.idNum = idNum;
this.gradYear = gradYear;
this.drawNumber = drawNumber;
this.requests = new ArrayList<Course>();
this.schedule = new ArrayList<Course>();
}
/**
* Returns true if idNumbers are the same;
* @param Object: any possible object.
*
* @return boolean: true if idNumbers are the same.
*/
public boolean equals(Object o){
if((o instanceof Student)){
return idNum == ((Student)(o)).idNum;
}
return false;
}
/**
* ToString returns a string representation including
* name, graduation year and draw number.
*/
public String toString(){
return name + " " + gradYear + " " + drawNumber;
}
/**
* Write a compareTo that sorts the student by draw number and
* class year.
* The first person should be a 4th year with draw number 1.
* The last person should be a 1st year with a the largest draw number.
* All 4th years come before all 3rd years, etc.
*
* @return retval:
* 1 if the first thing comes first,
* 0 if they are equal
* -1 if the second thing comes firt.
*/
public int compareTo(Object s){
Student toCompare = (Student)s;
if(this.gradYear < toCompare.gradYear){
return -1;
}
else if(this.gradYear > toCompare.gradYear){
return 1;
}
else{
if(this.drawNumber < toCompare.drawNumber){return -1;}
if(this.drawNumber == toCompare.drawNumber){return 0;}
else{
return 1;
}
}
}
/**
* Check to see if the student is registered for any section of a course.
* @param maybe: Course. The potential course to register for.
*
* @return boolean: true if the student is registered for any section of the course.
*/
public boolean isRegisteredFor(Course maybe){
//TODO
// supposed to check if the dept and the section already exists in the schedule. We should not check the section because
//a class can have different sections. example: check if CMPU 102 already exists. This will check all the sections.
for(Course c: this.schedule){
if(c.dept.equals(maybe.dept) && (c.courseNum == maybe.courseNum)){
return true;
}
}
return false;
}
/**
* @return the total registered credits (limit is 4.5)
*/
public double totalRegisteredCredits(){
double totalCredits = 0.0;
for(Course c : this.schedule){
totalCredits += c.credits;
}
//TODO
return totalCredits;
}
/**
* @param maybe: Course the potential course
*
* @return true if the student already has something at that time.
*/
public boolean hasAConflict(Course maybe){
for (Course c: this.schedule){
if(c.conflictsWith(maybe)){
return true;
}
}
//TODO
return false;
}
}
| Felomondi/Course_Pre-registration_Algorithm- | Student.java | 881 | /**
* Write a compareTo that sorts the student by draw number and
* class year.
* The first person should be a 4th year with draw number 1.
* The last person should be a 1st year with a the largest draw number.
* All 4th years come before all 3rd years, etc.
*
* @return retval:
* 1 if the first thing comes first,
* 0 if they are equal
* -1 if the second thing comes firt.
*/ | block_comment | en | false | 856 | 123 | 881 | 116 | 1,003 | 130 | 881 | 116 | 1,066 | 132 | false | false | false | false | false | true |
222572_2 | /* a Soups instance holds
a collection of TriSoup instances,
one for each texture
*/
import java.util.ArrayList;
public class Soups{
private TriSoup[] soups;
// accumulate triangles here
private ArrayList<Triangle> triangles;
// build a "soups" object with
// given number of separate images,
// create empty soup's for each,
// and create empty list of triangles
public Soups( int numTextures ){
soups = new TriSoup[ numTextures ];
for( int k=0; k<soups.length; k++ ){
soups[k] = new TriSoup();
}
triangles = new ArrayList<Triangle>();
}
// add this triangle to soups
public void addTri( Triangle tri ) {
triangles.add( tri );
System.out.println("after adding " + tri + " this soups has " +
triangles.size() + " tris" );
}
// go through list of triangles and add
// them to the soups
public void addTris( ArrayList<Triangle> list ) {
for( int k=0; k<list.size(); k++ ) {
triangles.add( list.get(k) );
}
}
// sort triangles into individual soups
// for each image
public void sortByTexture(){
for( int k=0; k<triangles.size(); k++ ){
Triangle tri = triangles.get(k);
soups[ tri.getTexture() ].add( tri );
}
}
// draw all the TriSoup's
public void draw(){
System.out.println("draw the soups " + this );
// actually draw each soup
for( int k=0; k<soups.length; k++ ){
OpenGL.selectTexture( Pic.get(k) );
System.out.println("soup for texture # " + k +
" has " + soups[k].size() + " triangles" );
soups[ k ].draw();
}
}
// release all the TriSoup's in this soups
public void cleanup(){
for( int k=0; k<soups.length; k++ ){
soups[k].cleanup();
}
}
}
| boxoforanmore/carscene | Soups.java | 502 | // build a "soups" object with | line_comment | en | false | 482 | 10 | 502 | 9 | 547 | 9 | 502 | 9 | 602 | 9 | false | false | false | false | false | true |
223132_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();
int a[] = new int[n];
for (int i = 0 ; i < n ; i++ ) a[i] = sc.nextInt();
Arrays.sort( a );
int min = Integer.MAX_VALUE;
for ( int i = 0 ; i < n - 1 ; i++ ) {
min = Math.min( min , a[i + 1] - a[i] );
}
System.out.println( min );
}
}
}
| harsh-agrwal/Code-chef-Sorting | Racing Horses.java | 238 | /* Name of the class has to be "Main" only if the class is public. */ | block_comment | en | false | 205 | 19 | 238 | 19 | 257 | 19 | 238 | 19 | 278 | 19 | false | false | false | false | false | true |
223891_58 | import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
/**
* @authorFelipe Custódio, Gabriel Scalici
*/
public class Chain {
// image properties
int h; // height
int w; // width
// shape properties
int height;
int width;
// bitmaps
int pixels[][]; // image with treshold 1 or 0
int visited[][]; // stores visited pixels
// initial coordinates of the shape
int begin[];
// final coordinates of the shape
int end[];
// perimeter
int points;
double perimeter;
public Chain() throws IOException {
// read input file
System.out.print("Filename: ");
String filename = new String();
filename = Input.readString();
File shape = new File(filename);
BufferedImage image = ImageIO.read(shape);
// setar propriedades da image para uso posterior
h = image.getHeight(); // height
w = image.getWidth(); // width
// initialize coordinates vectors
begin = new int[2];
end = new int[2];
points = 0;
perimeter = 0;
// treshold image
pixels = new int[h][w];
visited = new int [h][w];
for (int i = 0; i < h; i++) {
for (int j = 0; j < w; j++) {
pixels[i][j] = image.getRGB(j, i);
if (pixels[i][j] != -1) {
// shades of gray -> black
pixels[i][j] = 1;
} else {
// background -> white
pixels[i][j] = 0;
}
// set pixel as unvisited
visited[i][j] = 0;
}
}
}
public void firstPixel() {
boolean flag = false;
// locate first black pixel
for (int i = 0; i < h; i++) {
for (int j = 0; j < w; j++) {
if (pixels[i][j] == 1 && !(flag)) {
// get coordinates
begin[0] = i;
begin[1] = j;
flag = true;
}
}
}
}
public void lastPixel() {
boolean flag = false;
// find first pixel from down-up
for (int i = h - 1; i >= 0; i--) {
for (int j = w - 1; j >= 0; j--) {
if (pixels[i][j] == 1 && !(flag)) {
// get coordinates
end[0] = i;
end[1] = j;
flag = true;
}
}
}
}
public void setHeight() {
// y of last pixel - y of first pixel
height = (end[0] - begin[0] + 1);
}
public void setWidth() {
// get x coordinates of first and final pixels
int aux[] = new int[2];
boolean flag = false;
// find first pixel to the left
for (int i = 0; i < w; i++) {
for (int j = 0; j < h; j++) {
if (pixels[j][i] == 1 && !(flag)) {
// get x coordinate
aux[0] = i;
flag = true;
}
}
}
flag = false;
// find first pixel to the right
for (int i = w - 1; i >= 0; i--) {
for (int j = h - 1; j >= 0; j--) {
if (pixels[j][i] == 1 && !(flag)) {
// get x coordinate
aux[1] = i;
flag = true;
}
}
}
// x of last pixel - x of first pixel
width = (aux[1] - aux[0] + 1);
}
public void border() {
for (int i = 0; i < h; i++) {
for (int j = 0; j < w; j++) {
if (pixels[i][j] == 1) {
// if a neighbor of a pixel is empty, that pixel
// is on the border of the shape
if (borderPixel(i, j)) points++;
}
}
}
}
public boolean borderPixel(int i, int j) {
// only check black pixels
if (pixels[i][j] == 0) return false;
// check left
if (j == 0) return true; // image border = shape border
if (j > 0) {
if (pixels[i][j - 1] == 0) {
return true;
}
}
// check up
if (i == 0) return true;
if (i > 0) {
if (pixels[i - 1][j] == 0) {
return true;
}
}
// check right
if (j == w) return true;
if (j < w) {
if (pixels[i][j + 1] == 0) {
return true;
}
}
// check down
if (i == h) return true;
if (i < h) {
if (pixels[i + 1][j] == 0) {
return true;
}
}
// no empty pixel around = not border pixel
return false;
}
public int[] borderNeighbors(int i, int j) {
int index[] = new int[2];
boolean flag = false;
// check around pixel for unvisited border pixels
// calculates chain codes distance
// check east
if (borderPixel(i, j+1) && !flag && !flag && visited[i][j+1] == 0) {
j = j + 1;
System.out.print("0 ");
perimeter += 1;
flag = true;
index[0] = i;
index[1] = j;
return index;
}
// check southeast
if (borderPixel(i+1, j+1) && !flag && visited[i+1][j+1] == 0) {
i = i + 1;
j = j + 1;
System.out.print("1 ");
perimeter += Math.sqrt(2);
flag = true;
index[0] = i;
index[1] = j;
return index;
}
// check south
if (borderPixel(i+1, j) && !flag && visited[i+1][j] == 0) {
i = i + 1;
System.out.print("2 ");
perimeter += 1;
flag = true;
index[0] = i;
index[1] = j;
return index;
}
// check southwest
if (borderPixel(i+1, j-1) && !flag && visited[i+1][j-1] == 0) {
i = i + 1;
j = j - 1;
System.out.print("3 ");
perimeter += Math.sqrt(2);
flag = true;
index[0] = i;
index[1] = j;
return index;
}
// check west
if (borderPixel(i, j-1) && !flag && visited[i][j-1] == 0) {
j = j - 1;
System.out.print("4 ");
perimeter += 1;
flag = true;
index[0] = i;
index[1] = j;
return index;
}
// check northwest
if (borderPixel(i-1, j-1) && !flag && visited[i-1][j-1] == 0) {
i = i - 1;
j = j - 1;
System.out.print("5 ");
perimeter += Math.sqrt(2);
flag = true;
index[0] = i;
index[1] = j;
return index;
}
// check north
if (borderPixel(i-1, j) && !flag && visited[i-1][j] == 0) {
i = i - 1;
System.out.print("6 ");
perimeter += 1;
flag = true;
index[0] = i;
index[1] = j;
return index;
}
// check northeast
if (borderPixel(i-1, j+1) && !flag && visited[i-1][j+1] == 0) {
i = i - 1;
j = j + 1;
System.out.print("7 ");
perimeter += Math.sqrt(2);
flag = true;
index[0] = i;
index[1] = j;
return index;
}
// no neighbor border pixels
index[0] = i;
index[1] = j;
return index;
}
public void chainCodes(int i, int j) {
/*
i e j = index of current pixel
index[0], index[1] = next border pixel (if exists)
*/
// coordinates of current pixel
int[] index = new int[2];
// check for border pixels around
index = borderNeighbors(i, j);
// set pixel as visited
visited[i][j] = 1;
// if next border pixel is visited, we're back to the first pixel
if (visited[index[0]][index[1]] == 0) {
chainCodes(index[0], index[1]);
} else {
System.out.println();
}
}
public static void main(String[] args) throws IOException {
Chain c = new Chain();
// get key coordinates
c.firstPixel();
c.lastPixel();
// calculate shape properties
c.setHeight();
c.setWidth();
System.out.println("Shape width: " + c.width);
System.out.println("Shape height: " + c.height);
// generate chain codes
// get coordinates of first border pixel after initial
int[] index = new int[2];
System.out.print("Chain Codes: ");
index = c.borderNeighbors(c.begin[0], c.begin[1]);
c.chainCodes(index[0], index[1]);
// get perimeter size
c.border();
System.out.println("Border pixels: " + c.points + " pixels");
System.out.println("Shape perimeter: " + c.perimeter);
}
} | felipecustodio/chain-codes | Chain.java | 2,581 | // generate chain codes | line_comment | en | false | 2,413 | 4 | 2,581 | 4 | 2,843 | 4 | 2,581 | 4 | 3,083 | 4 | false | false | false | false | false | true |
224516_0 | import java.util.*;
class NumberTheory {
static ArrayList<Integer> primes = new ArrayList();
/**Generate all prime numbers less than or equal to n. Sieve of Eratosthenes
* There are approximately n/log n prime numbers < n
* O(n*log(log n))
* @param n The largest number to consider
* @return All prime numbers less than or equal to n*/
static ArrayList<Integer> primes(int n) {
boolean[] visited = new boolean[n+1];
for(int p = 2; p <= n; ++p)
if(!visited[p]) {
primes.add(p);
for(int m = p*p; m <= n && m > p; m += p)
visited[m] = true;
}
return primes;
}
/**Generate a table specifying whether a number is prime or not, for all numbers up to n. Sieve of Eratosthenes
* There are approximately n/log n prime numbers < n
* O(n*log(log n))
* @param n The largest number to consider
* @return Which numbers less than or equal to n are prime*/
static boolean[] primeTable(int n) {
boolean[] primes = new boolean[n+1];
Arrays.fill(primes, true);
primes[0] = false;
primes[1] = false;
for(int p = 2; p <= Math.sqrt(n); ++p)
if(primes[p]) {
for(int m = p*p; m <= n; m += p)
primes[m] = false;
}
return primes;
}
/**Factorize the integer n. primes() must have been run beforehand
* O(sqrt n)
* @param n The number to factorize
* @return A list of primes and their power in the factorization*/
static ArrayList<Pair> factorize(int n) {
ArrayList<Pair> factors = new ArrayList();
for(int p : primes) {
if(p*p > n)
break;
int count = 0;
while(n%p == 0) {
count++;
n /= p;
}
if(count > 0)
factors.add(new Pair(p, count));
}
if(n > 1)
factors.add(new Pair(n, 1));
return factors;
}
/**Count how many times n! can be divided by the prime number p
* <=> Count how many times p appears in the factorization of n!
* O(log n)
* @param n The base of the factorial
* @param p The factor to count
* @return How many times n! can be divided by the prime number p*/
static int factorialDivisible(int n, int p) {
int factor = p;
int count = 0;
while(true) {
int times = n/factor;
if(times <= 0)
break;
count += times;
factor *= p;
}
return count;
}
/**Generate all binomial coefficients a choose b where a, b <= n
* O(n^2)
* @param n The largest binomial coefficient to generate
* @return An array where index [i][j] is the binomial coefficient i choose j*/
static int[][] binomialCoefficients(int n) {
int[][] pascal = new int[n+1][n+1];
for(int i = 1; i <= n; ++i) {
pascal[i][0] = 1;
for(int j = 1; j <= i; ++j)
pascal[i][j] = pascal[i-1][j-1] + pascal[i-1][j];
}
return pascal;
}
/**Find the binomial coefficient n choose k = n!/(k!*(n-k)!)
* O(k) time, O(1) space
* @param n Number of elements to choose from
* @param k Number of elements to choose
* @return Number of ways to choose k from n elements*/
static long binomialCoefficient(int n, int k) {
long res = 1;
if(n/2 < k)
k = n-k;
for(int i = 1; i <= k; ++i) {
res *= (n-i+1);
res /= i;
}
return res;
}
/**Generate the n first Catalan numbers
* O(n^2)
* @param n How many numbers to generate
* @return An array where index [i] is the i-th Catalan number*/
static int[] catalanNumbers(int n) {
int[] catalan = new int[n+1];
catalan[0] = 1;
for(int i = 1; i <= n; ++i)
for(int j = 0; j < i; ++j)
catalan[i] += catalan[j]*catalan[i-j-1];
return catalan;
}
/**Find the greatest common divisor of a and b. Euclid's division algorithm
* O(log min(|a|, |b|))
* @param a The first number
* @param b The second number
* @return The greatest common divisor*/
static int gcd(int a, int b) {
while(b != 0) {
int t = b;
b = a%b;
a = t;
}
return Math.abs(a);
}
/**Calculate Bezout's identity: x and y, such that a*x+b*y = gcd(a, b). Euclid's extended algorithm
* O((log min(|a|, |b|))^2)
* @param a The first number
* @param b The second number
* @return <x, y, z> such that a*x+b*y = gcd(a, b) = z*/
static Triple bezoutsIdentity(int a, int b) {
int[] t = {1, 0};
int[] s = {0, 1};
int[] r = {b, a};
int pos = 0;
while(r[pos] != 0) {
int npos = (pos+1)%2;
int q = r[npos]/r[pos];
r[npos] -= q*r[pos];
s[npos] -= q*s[pos];
t[npos] -= q*t[pos];
pos = npos;
}
pos = (pos+1)%2;
if(r[pos] < 0)
return new Triple(-s[pos], -t[pos], -r[pos]);
return new Triple(s[pos], t[pos], r[pos]);
}
/**Calculate the modular multiplicative inverse of a modulo m. Euclid's extended algorithm
* O((log min(|a|, |b|))^2)
* @param a A non-negative integer
* @param m An integer > 1
* @return The modular multiplicative inverse x such that ax === 1 (mod m), -1 if a and m are not coprime*/
static int multiplicativeInverse(int a, int m) {
Triple t = bezoutsIdentity(a, m);
if(t.trd != 1)
return -1;
return (t.fst+m)%m;
}
}
| halseth/algo_cheatsheet | NumberTheory.java | 1,726 | /**Generate all prime numbers less than or equal to n. Sieve of Eratosthenes
* There are approximately n/log n prime numbers < n
* O(n*log(log n))
* @param n The largest number to consider
* @return All prime numbers less than or equal to n*/ | block_comment | en | false | 1,603 | 67 | 1,726 | 68 | 1,877 | 73 | 1,726 | 68 | 2,010 | 77 | false | false | false | false | false | true |
224575_2 | package nachos.threads;
import java.util.PriorityQueue;
import nachos.machine.*;
/**
* Uses the hardware timer to provide preemption, and to allow threads to sleep
* until a certain time.
*/
public class Alarm {
/**
* Allocate a new Alarm. Set the machine's timer interrupt handler to this
* alarm's callback.
*
* <p>
* <b>Note</b>: Nachos will not function correctly with more than one alarm.
*/
public Alarm() {
Machine.timer().setInterruptHandler(new Runnable() {
public void run() {
timerInterrupt();
}
});
waitingPQ = new PriorityQueue<ThreadWake>();
}
/**
* The timer interrupt handler. This is called by the machine's timer
* periodically (approximately every 500 clock ticks). Causes the current
* thread to yield, forcing a context switch if there is another thread that
* should be run.
*/
public void timerInterrupt() {
boolean intStatus = Machine.interrupt().disable();
while (waitingPQ.peek() != null && Machine.timer().getTime() >= waitingPQ.peek().getWakeTime()) {
waitingPQ.poll().getThreadToWake().ready();
}
Machine.interrupt().restore(intStatus);
KThread.yield();
}
/**
* Put the current thread to sleep for at least <i>x</i> ticks, waking it up
* in the timer interrupt handler. The thread must be woken up (placed in
* the scheduler ready set) during the first timer interrupt where
*
* <p>
* <blockquote> (current time) >= (WaitUntil called time)+(x) </blockquote>
*
* @param x the minimum number of clock ticks to wait.
*
* @see nachos.machine.Timer#getTime()
*/
public void waitUntil(long x) {
// for now, cheat just to get something working (busy waiting is bad)
long wakeTime = Machine.timer().getTime() + x;
ThreadWake toAdd = new ThreadWake(KThread.currentThread(), wakeTime);
boolean intStatus = Machine.interrupt().disable();
waitingPQ.add(toAdd);
KThread.sleep();
Machine.interrupt().restore(intStatus);
}
private PriorityQueue<ThreadWake> waitingPQ;
private static class PingAlarmTest implements Runnable {
PingAlarmTest(int which, Alarm alarm) {
this.which = which;
this.alarm = alarm;
}
Alarm alarm;
public void run() {
System.out.println("thread " + which + " started.");
alarm.waitUntil(which);
System.out.println("Current Time: " + Machine.timer().getTime());
System.out.println("thread " + which + " ran.");
}
private int which;
}
public static void selfTest() {
Alarm myAlarm = new Alarm();
System.out.println("*** Entering Alarm self test");
KThread thread1 = new KThread(new PingAlarmTest(1000,myAlarm));
thread1.fork();
KThread thread2 = new KThread(new PingAlarmTest(500,myAlarm));
thread2.fork();
new PingAlarmTest(2000,myAlarm).run();
System.out.println("*** Exiting Alarm self test");
}
}
| Kodyin/EECS211-Nachos | threads/Alarm.java | 815 | /**
* The timer interrupt handler. This is called by the machine's timer
* periodically (approximately every 500 clock ticks). Causes the current
* thread to yield, forcing a context switch if there is another thread that
* should be run.
*/ | block_comment | en | false | 733 | 59 | 815 | 58 | 840 | 62 | 815 | 58 | 1,010 | 68 | false | false | false | false | false | true |
224751_13 | package burp.Utils;
import burp.AutoRepeater;
import burp.BurpExtender;
import burp.IExtensionStateListener;
import burp.Logs.LogEntry;
import burp.Logs.LogManager;
import com.google.gson.JsonArray;
import com.google.gson.JsonElement;
import javax.swing.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.PrintWriter;
import java.util.ArrayList;
public class AutoRepeaterMenu implements Runnable, IExtensionStateListener {
private final JRootPane rootPane;
private static ArrayList<AutoRepeater> autoRepeaters;
private static JMenu autoRepeaterJMenu;
private static JMenuItem toggleSettingsVisibility;
private static boolean showSettingsPanel;
public static boolean sendRequestsToPassiveScanner;
public static boolean addRequestsToSiteMap;
public AutoRepeaterMenu(JRootPane rootPane) {
this.rootPane = rootPane;
autoRepeaters = BurpExtender.getAutoRepeaters();
showSettingsPanel = true;
BurpExtender.getCallbacks().registerExtensionStateListener(this);
}
/**
* Action listener for setting visibility
*/
class SettingVisibilityListener implements ActionListener {
@Override
public void actionPerformed(ActionEvent e) {
// Toggling settings panel
if (toggleSettingsVisibility.getText().equals("Hide Settings Panel")) {
showSettingsPanel = false;
toggleSettingsVisibility.setText("Show Settings Panel");
} else {
showSettingsPanel = true;
toggleSettingsVisibility.setText("Hide Settings Panel");
}
// toggling every AutoRepeater tab
for (AutoRepeater ar : autoRepeaters) {
ar.toggleConfigurationPane(showSettingsPanel);
}
}
}
/**
* Action listener for import settings menu
*/
class ImportSettingListener implements ActionListener {
@Override
public void actionPerformed(ActionEvent e) {
final JFileChooser importPathChooser = new JFileChooser();
int replaceTabs = JOptionPane.showConfirmDialog(rootPane, "Would you like to replace the current tabs?", "Replace Tabs", JOptionPane.YES_NO_CANCEL_OPTION);
if (replaceTabs == 2) {
// cancel selected
return;
}
int returnVal = importPathChooser.showOpenDialog(rootPane);
if (returnVal != JFileChooser.APPROVE_OPTION) {
BurpExtender.getCallbacks().printOutput("Cannot open a file dialog for importing settings.");
return;
}
File file = importPathChooser.getSelectedFile();
String fileData = Utils.readFile(file);
if (fileData.equals("")) {
// file empty
return;
}
if (replaceTabs == 1) {
// do not replace current tabs
BurpExtender.initializeFromSave(fileData, false);
} else if (replaceTabs == 0) {
// replace current tabs
BurpExtender.getCallbacks().printOutput("Removing Tabs");
BurpExtender.initializeFromSave(fileData, true);
}
}
}
/**
* Action listener for export settings menu.
*/
class ExportSettingListener implements ActionListener {
@Override
public void actionPerformed(ActionEvent e) {
Object[] options = {"Current Tab", "Every Tab", "Cancel"};
int option = JOptionPane.showOptionDialog(rootPane, "Which tab would you like to export?", "Export Tabs",
JOptionPane.DEFAULT_OPTION, JOptionPane.QUESTION_MESSAGE, null, options, options[0]);
if (option == 2) { return; }
final JFileChooser exportPathChooser = new JFileChooser();
int returnVal = exportPathChooser.showSaveDialog(rootPane);
if (returnVal != JFileChooser.APPROVE_OPTION) {
BurpExtender.getCallbacks().printOutput("Cannot open a file dialog for exporting settings.");
return;
}
File file = exportPathChooser.getSelectedFile();
try (PrintWriter out = new PrintWriter(file.getAbsolutePath())) {
if (option == 0) {
// export current tab
out.println(BurpExtender.exportSave(BurpExtender.getSelectedAutoRepeater()));
} else if (option == 1) {
// export every tab
out.println(BurpExtender.exportSave());
}
} catch (FileNotFoundException error) {
error.printStackTrace();
}
}
}
/**
* Action listener for export logs menu.
*/
class ExportLogsListener implements ActionListener {
@Override
public void actionPerformed(ActionEvent e) {
Object[] options = {"Export", "Cancel"};
final String[] EXPORT_OPTIONS = {"CSV", "JSON"};
final String[] EXPORT_WHICH_OPTIONS = {"All Tab Logs", "Selected Tab Logs"};
final String[] EXPORT_VALUE_OPTIONS = {"Log Entry", "Log Entry + Full HTTP Request"};
final JComboBox<String> exportTypeComboBox = new JComboBox<>(EXPORT_OPTIONS);
final JComboBox<String> exportWhichComboBox = new JComboBox<>(EXPORT_WHICH_OPTIONS);
final JComboBox<String> exportValueComboBox = new JComboBox<>(EXPORT_VALUE_OPTIONS);
final JFileChooser exportLogsPathChooser = new JFileChooser();
JPanel exportLogsPanel = new JPanel();
exportLogsPanel.setLayout(new BoxLayout(exportLogsPanel, BoxLayout.PAGE_AXIS));
exportLogsPanel.add(exportWhichComboBox);
exportLogsPanel.add(exportValueComboBox);
exportLogsPanel.add(exportTypeComboBox);
JPanel buttonPanel = new JPanel();
exportLogsPanel.add(buttonPanel);
int option = JOptionPane.showOptionDialog(rootPane, exportLogsPanel,
"Export Logs", JOptionPane.DEFAULT_OPTION, JOptionPane.QUESTION_MESSAGE, null, options, options[0]);
if (option == 1) {
return;
}
int returnVal = exportLogsPathChooser.showSaveDialog(rootPane);
if (returnVal != JFileChooser.APPROVE_OPTION) {
BurpExtender.getCallbacks().printOutput("Cannot open a file dialog for exporting logs.");
return;
}
AutoRepeater autoRepeater = BurpExtender.getSelectedAutoRepeater();
LogManager logManager = autoRepeater.getLogManager();
File file = exportLogsPathChooser.getSelectedFile();
ArrayList<LogEntry> logEntries = new ArrayList<>();
// collect relevant entries
if ((exportWhichComboBox.getSelectedItem()).equals("All Tab Logs")) {
logEntries = autoRepeater.getLogTableModel().getLog();
} else if ((exportWhichComboBox.getSelectedItem()).equals("Selected Tab Logs")) {
int[] selectedRows = autoRepeater.getLogTable().getSelectedRows();
for (int row : selectedRows) {
logEntries.add(logManager.getLogEntry(autoRepeater.getLogTable().convertRowIndexToModel(row)));
}
}
// determine if whole request should be exported or just the log contents
boolean exportFullHttp = !((exportValueComboBox.getSelectedItem()).equals("Log Entry"));
try (PrintWriter out = new PrintWriter(file.getAbsolutePath())) {
if ((exportTypeComboBox.getSelectedItem()).equals("CSV")) {
out.println(Utils.exportLogEntriesToCsv(logEntries, exportFullHttp));
} else if ((exportTypeComboBox.getSelectedItem()).equals("JSON")) {
out.println(Utils.exportLogEntriesToJson(logEntries, exportFullHttp));
}
} catch (FileNotFoundException error) {
error.printStackTrace();
}
}
}
class DuplicateCurrentTabListener implements ActionListener {
@Override
public void actionPerformed(ActionEvent e) {
JsonArray serializedTab = BurpExtender.exportSaveAsJson(BurpExtender.getSelectedAutoRepeater());
for (JsonElement tabConfiguration : serializedTab) {
BurpExtender.addNewTab(tabConfiguration.getAsJsonObject());
}
}
}
@Override
public void extensionUnloaded() {
// unregister menu
JMenuBar burpMenuBar = rootPane.getJMenuBar();
BurpExtender.getCallbacks().printOutput("Unregistering menu");
burpMenuBar.remove(autoRepeaterJMenu);
burpMenuBar.repaint();
}
@Override
public void run() {
JMenuBar burpJMenuBar = rootPane.getJMenuBar();
autoRepeaterJMenu = new JMenu("AutoRepeater");
// initialize menu items and add action listeners
JMenuItem duplicateCurrentTab = new JMenuItem("Duplicate Selected Tab");
duplicateCurrentTab.addActionListener(new DuplicateCurrentTabListener());
toggleSettingsVisibility = new JMenuItem("Hide Settings Panel");
toggleSettingsVisibility.addActionListener(new SettingVisibilityListener());
JCheckBoxMenuItem toggleSendRequestsToPassiveScanner = new JCheckBoxMenuItem("Send Requests To Passive Scanner");
toggleSendRequestsToPassiveScanner.addActionListener(l ->
sendRequestsToPassiveScanner = toggleSendRequestsToPassiveScanner.getState());
JCheckBoxMenuItem toggleAddRequestsToSiteMap = new JCheckBoxMenuItem("Add Requests To Site Map");
toggleAddRequestsToSiteMap.addActionListener(l ->
addRequestsToSiteMap = toggleAddRequestsToSiteMap.getState());
JMenuItem showImportMenu = new JMenuItem("Import Settings");
showImportMenu.addActionListener(new ImportSettingListener());
JMenuItem showExportMenu = new JMenuItem("Export Settings");
showExportMenu.addActionListener(new ExportSettingListener());
JMenuItem showExportLogsMenu = new JMenuItem("Export Logs");
showExportLogsMenu.addActionListener(new ExportLogsListener());
// add menu items to the menu
autoRepeaterJMenu.add(duplicateCurrentTab);
autoRepeaterJMenu.add(toggleSettingsVisibility);
autoRepeaterJMenu.addSeparator();
autoRepeaterJMenu.add(toggleAddRequestsToSiteMap);
autoRepeaterJMenu.add(toggleSendRequestsToPassiveScanner);
autoRepeaterJMenu.addSeparator();
autoRepeaterJMenu.add(showImportMenu);
autoRepeaterJMenu.add(showExportMenu);
autoRepeaterJMenu.add(showExportLogsMenu);
// add menu to menu bar
burpJMenuBar.add(autoRepeaterJMenu, burpJMenuBar.getMenuCount() - 2);
}
}
| PortSwigger/auto-repeater | src/burp/Utils/AutoRepeaterMenu.java | 2,275 | // determine if whole request should be exported or just the log contents | line_comment | en | false | 2,079 | 13 | 2,275 | 13 | 2,423 | 13 | 2,275 | 13 | 2,825 | 14 | false | false | false | false | false | true |
224873_3 |
import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import java.util.ArrayList;
import java.util.MissingFormatArgumentException;
import java.util.Scanner;
/**
* Meant to recommend classes for next quarter based on major, current curriculum, unofficial
* transcripts, and what classes are being offered.
*
* @author albiterri
* @version 1.0
* Last Edited: 04/27/2020
*/
public class RecommendCourses {
private ArrayList<String> curriculumCourses = new ArrayList<>();
private ArrayList<String> takenCourses;
private ArrayList<String> recommendedCourses = new ArrayList<>();
private ArrayList<String> remainingCourses = new ArrayList<>();
private ArrayList<String> electivesNQ = new ArrayList<>();
private ArrayList<Course> prerequisiteRecommendations = new ArrayList<>();
/**
* Constructor that calls all logic that eventually will store necessary recommendations
* data into recommendedCourses, remainingCourses, electivesNQ, and prerequisitesRecommendations list
*
* @param major student's major (CS or SE)
* @param nextQuarter upcoming quarter (Fall = 1, Winter = 2, Spring = 3)
* @param curriculumFile student's curriculum (Currently only CS and SE available)
* @param transcriptFile unofficial transcript from my.msoe.edu
* @param offeringsFile offerings.csv from SE2800 blackboard
* @param electivesFile electives.csv from SE800 blackboard
* @param prerequisitesFile prerequisites.csv from SE800 blackboard
* @throws IOException for incorrect files or formatting
*/
public RecommendCourses(String major, String nextQuarter, File curriculumFile, File transcriptFile,
File offeringsFile, File electivesFile, File prerequisitesFile) throws IOException {
if(major.isBlank() | nextQuarter.isBlank()) {
throw new MissingFormatArgumentException("Your have not input a supported major. Please Try Again!");
}
if((major.equals("CS") | major.equals("SE")) &&
(Integer.parseInt(nextQuarter) > 3 && Integer.parseInt(nextQuarter) < 1)) {
parseCurriculum(major,curriculumFile);
takenCourses = new TranscriptParser(transcriptFile).getCoursesTaken();
recommendCourse(major,nextQuarter,offeringsFile,electivesFile, prerequisitesFile);
} else {
throw new IllegalArgumentException("Currently your major (" + major + ") or quarter (" + nextQuarter +
") is not supported for getting recommendations. Please try either CS/SE and quarters 1-3.");
}
}
/**
* Helper function that will parse the curriculum file in order to get what classes
* the student has to take overall.
*
* @param givenMajor student's major
* @param curriculumFile curriculum.csv from SE2800 blackboard
* @throws IOException for incorrect files or formatting
*/
private void parseCurriculum(String givenMajor, File curriculumFile) throws IOException {
String line = "";
String cvsSplitBy = ",";
int section = 0;
boolean majorLine = true;
BufferedReader br = new BufferedReader(new FileReader(curriculumFile));
while ((line = br.readLine()) != null) {
// use comma as separator
String[] currentLine = line.split(cvsSplitBy);
for(String column: currentLine) {
if(!column.equals(givenMajor) && majorLine) {
section++;
} else if(column.equals(givenMajor) && majorLine) {
break;
}
if(!majorLine) {
curriculumCourses.add(currentLine[section]);
break;
}
}
majorLine = false;
}
if(curriculumCourses.isEmpty()) {
throw new IOException("Current major is not supported. Try CS,SE,CE, or EE");
}
br.close();
}
/**
* Helper function to help breakdown recommendations data including classes for next
* quarter, electives for next quarter, prerequisites for recommended classes, and classes that the student
* has yet to take
*
* @param studentMajor student's major
* @param nextQuarter upcoming quarter
* @param offeringsFile offerings.csv from SE2800 blackboard
* @param electivesFile electives.csv from SE800 blackboard
* @param prerequisitesFile prerequisites.csv from SE800 blackboard
* @throws IOException for incorrect files or formatting
*/
private void recommendCourse(String studentMajor, String nextQuarter, File offeringsFile
, File electivesFile, File prerequisitesFile) throws IOException {
CSVParser recommendParser = new CSVParser();
ArrayList<String> nextQuarterCourses = recommendParser.quarterMajorCourses(offeringsFile
,studentMajor,nextQuarter);
CSVPrerequisite prerequisiteParser = new CSVPrerequisite();
prerequisiteParser.parse(prerequisitesFile);
ArrayList<Course> prerequisiteCourses = prerequisiteParser.getCourses();
for(String course: curriculumCourses) { //Curriculum - Taken = Remaining Classes
if(!takenCourses.contains(course)) {
remainingCourses.add(course);
}
}
for(String course: nextQuarterCourses) { //NextQ - Taken = Recommendations for Next Quarter
if(!takenCourses.contains(course)) {
recommendedCourses.add(course);
}
}
for(String course: recommendedCourses) { //Find prerequisites for recommended courses
Course foundCourse = hasPrerequisite(course,prerequisiteCourses);
if(!foundCourse.getName().equals("BlankCourse")) {
prerequisiteRecommendations.add(foundCourse);
}
}
ArrayList<String> allQuarterClasses = recommendParser.quarterMajorCourses(offeringsFile,
"all",nextQuarter);
ArrayList<String> allElectives = new CSVParser().getElectives(electivesFile,studentMajor,"all");
for(String elective: allElectives) { //Find electives offered next quarter for student's major
if(allQuarterClasses.contains(elective) && !electivesNQ.contains(elective)) {
electivesNQ.add(elective);
}
}
for(String course: electivesNQ) { //Find electives that have prerequisites
Course foundCourse = hasPrerequisite(course,prerequisiteCourses);
if(!foundCourse.getName().equals("BlankCourse")) {
prerequisiteRecommendations.add(foundCourse);
}
}
}
/**
* Helper function used to search through list of courses with prerequisites to find out
* if the given course has any prerequisites.
*
* @param course given course to check for prerequisites
* @param prerequisiteCourses parsed list of prerequisite data
* @return either a blank course or a course with prerequisite datat
*/
private Course hasPrerequisite(String course, ArrayList<Course> prerequisiteCourses) {
Course prereqCourse = new Course("BlankCourse");
for(Course c: prerequisiteCourses) {
if(c.getName().equals(course) && !c.getPrerequisites().isBlank()) {
return c;
}
}
return prereqCourse;
}
public ArrayList<String> getRecommendations() {
return recommendedCourses;
}
public ArrayList<String> getRemainingCourses() {
return remainingCourses;
}
public ArrayList<String> getElectivesNQ() {
return electivesNQ;
}
public ArrayList<Course> getPrerequisiteRecommendations() {
return prerequisiteRecommendations;
}
public static void main(String[] args) throws IOException {
File curriculum = new File(System.getProperty("user.dir") +
"\\docs\\newcurriculum.csv");
File transcriptAlbiter = new File(System.getProperty("user.dir") +
"\\docs\\TranscriptFiles\\transcript.pdf");
File transcriptChapman = new File(System.getProperty("user.dir") +
"\\docs\\TranscriptFiles\\Chapmann_transcript.pdf");
File offerings = new File(System.getProperty("user.dir") +
"\\docs\\offerings.csv");
File electives = new File(System.getProperty("user.dir") +
"\\docs\\electives.csv");
File prerequisites = new File(System.getProperty("user.dir") +
"\\docs\\prerequisites.csv");
Scanner in = new Scanner(System.in);
System.out.print("Enter major you would like to see courses for (Ex: CS, SE, etc): ");
String major = in.nextLine().toUpperCase();
System.out.print("Enter your upcoming quarter (Ex: Fall = 1, Winter = 2, Spring = 3): ");
String nextQuarter = in.nextLine();
RecommendCourses r = new RecommendCourses(major,nextQuarter,curriculum,transcriptChapman
,offerings,electives,prerequisites);
switch (nextQuarter) {
case "1":
nextQuarter = "Fall";
break;
case "2":
nextQuarter = "Winter";
break;
case "3":
nextQuarter = "Spring";
break;
default:
break;
}
System.out.println("\nAs an " + major + " you should take these classes for " + nextQuarter + " quarter:" +
" (Classes may be year specific)");
for(String recommended: r.getRecommendations()) {
System.out.println(recommended);
}
System.out.println("\n\nHere are some electives you can take next quarter: ");
for(String elective: r.getElectivesNQ()) {
System.out.println(elective);
}
System.out.println("\n\nThe following recommended courses have prereqs: ");
for(Course c: r.getPrerequisiteRecommendations()) {
System.out.println(c.getName() + "-- " + c.getPrerequisites());
}
System.out.println("\n\nThese are classes you have yet to take: ");
for(String remaining: r.getRemainingCourses()) {
System.out.println(remaining);
}
}
}
| raalbiteri/Software-Engineering-Process-Scrum-Project | RecommendCourses.java | 2,321 | // use comma as separator | line_comment | en | false | 2,079 | 5 | 2,321 | 5 | 2,364 | 5 | 2,321 | 5 | 2,856 | 5 | false | false | false | false | false | true |