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
69717_26
// ---------------------------------------------------------------------------- // Copyright (C) 2015 Strategic Facilities Technology Council // // This file is part of the Engineering Autonomous Space Software (EASS) Library. // // The EASS 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 3 of the License, or (at your option) any later version. // // The EASS 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 the EASS Library; if not, write to the Free Software // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA // // To contact the authors: // http://www.csc.liv.ac.uk/~lad // //---------------------------------------------------------------------------- package eass.mas.ev3; import java.io.PrintStream; /** * Interface for a sensor that encapsulates an EV3 robot sensor and which * can be used within an EASS environment. * @author louiseadennis * */ public interface EASSSensor { /** * Add a percept to this sensor. * @param env */ public void addPercept(EASSEV3Environment env); /** * Set the printstream where values from this sensor should be displayed. * @param o */ public void setPrintStream(PrintStream o); /** * Close the sensor and perform clean up. */ public void close(); }
mcapl/mcapl
src/classes/eass/mas/ev3/EASSSensor.java
427
/** * Close the sensor and perform clean up. */
block_comment
en
false
382
13
427
13
436
15
427
13
488
15
false
false
false
false
false
true
69745_14
/** * Class Hero that extends from DungeonCharacter class. * The class generates special skills for hero. * @author Emmiliia Fedina [email protected] * @version 25APR2021 */ public abstract class Hero extends DungeonCharacter { /** field for chance to block value*/ private int myChanceToBlock; /** field for if a character runs away*/ private boolean myRunAway; /** field for special skill percentage */ private double mySpecialSkillChance; /** field for hero's specific sound */ private String characterSpecificAttackSoundPath; /** field for hero's block sound*/ private static String blockSoundPath ="block.wav"; /** * Construct all the variables from DungeonCharacter class. * Initializes parameters specific for Hero class * @param theName is the String with a hero name. * @param theHitPoints is the integer with hit points. * @param theMinDamage is the integer with minimum points. * @param theMaxDamage is the integer with maximum points. * @param theChanceToHit is the double with a chance to hit. * @param theAttackSpeed is the integer with attack speed. * @param theChanceToBlock is the integer with a chance to block. * @param theSpecialSkillChance is a double with a special * skill chance. */ protected Hero(final String theName, final int theHitPoints, final int theMinDamage,final int theMaxDamage, final double theChanceToHit, final int theAttackSpeed, final int theChanceToBlock, final double theSpecialSkillChance ) { super(theName, theHitPoints,theMinDamage,theMaxDamage,theChanceToHit,theAttackSpeed); setChanceToBlock(theChanceToBlock); setRunAway(false); setSpecialSkillChance(theSpecialSkillChance); } /** * Construct all the variables from DungeonCharacter class. * Initializes parameters specific for Hero class * @param theName is the String with a hero name. * @param theHitPoints is the integer with hit points. * @param theMinDamage is the integer with minimum points. * @param theMaxDamage is the integer with maximum points. * @param theChanceToHit is the double with a chance to hit. * @param theAttackSpeed is the integer with attack speed. * @param theChanceToBlock is the integer with a chance to block. * @param theSpecialSkillChance is a double with a special * skill chance. */ protected Hero(final String theName, final int theHitPoints, final int theMinDamage,final int theMaxDamage, final double theChanceToHit, final int theAttackSpeed, final int theChanceToBlock, final double theSpecialSkillChance, final String characterSpecificAttackSoundPath) { super(theName, theHitPoints,theMinDamage,theMaxDamage,theChanceToHit,theAttackSpeed); setChanceToBlock(theChanceToBlock); setRunAway(false); setSpecialSkillChance(theSpecialSkillChance); setCharacterSpecificAttackSoundPath(characterSpecificAttackSoundPath); } /** * Initialize special skill chance. * Checks if special skills is bigger than 0 * @param theSpecialSkillChance is for special skill chance */ private void setSpecialSkillChance(double theSpecialSkillChance) { if (theSpecialSkillChance <= 0) { throw new IllegalArgumentException("SpecialSkill > 0"); } mySpecialSkillChance = theSpecialSkillChance; } /** * Checks if random number is less than special skill chance * @return true if random number is less than special skill chance * return false if random number is bigger than special skill chance */ protected final boolean canUseSpecialSkill() { return MY_RANDOM.nextInt(101) <= mySpecialSkillChance; } /** * Initialize chance to block. * Check if set chance to block in range of 100 * @param theChanceToBlock is for chance to block */ private final void setChanceToBlock(final int theChanceToBlock) { if (theChanceToBlock < 0 || theChanceToBlock > 100) { throw new IllegalArgumentException("theChanceToBlock < 0 || theChanceToBlock > 100"); } myChanceToBlock = theChanceToBlock; } /** * Initialize run away. * @param theRunAway */ private void setRunAway(final boolean theRunAway) { myRunAway = theRunAway; } protected void setCharacterSpecificAttackSoundPath(String path){ // SHOULD check to make sure this file path exists. // Either prevent compilation, or log error...?? characterSpecificAttackSoundPath = path; } /** * checks run away * @return true or false for run away. */ public final boolean runAway() { return myRunAway; } /** * The overrides attack method in the game. * This method overrides method from DungeonCharacter class * @param theOpponent is a monster in the game */ @Override public void attack(final DungeonCharacter theOpponent) { int attackChoice; int numberOfAttacks = getAttackTurns(theOpponent); while (numberOfAttacks > 0 && theOpponent.alive() && !runAway()) { attackChoice = getChoice(); if (attackChoice == 1) { // plays generic sound in super class. super.attack(theOpponent); } else if (attackChoice == 2) { specialAttack(theOpponent); } else { setRunAway(true); } numberOfAttacks--; } } /** * The method check how many attack a hero will get. * @param theOpponent is a monster in the game * @return number of turns based on the attack speed */ private final int getAttackTurns(final DungeonCharacter theOpponent) { int numberOfTurns = getAttackSpeed() / theOpponent.getAttackSpeed(); if (numberOfTurns == 0) { numberOfTurns = 1; } return numberOfTurns; } public String getCharacterSpecificAttackSoundPath(){ return characterSpecificAttackSoundPath; } /** * This method is an abstract and it will be used in child's * classes. * @param theOpponent passes a monster */ protected abstract void specialAttack(final DungeonCharacter theOpponent); /** * This method overrides from DungeonCharacter class * Method checks if random number is less than chance to block * If a random number is bigger that my chance to block than it will * override DungeonCharacter class. * @param theAmount is the amount of point that will be subtracted. */ @Override protected void substractHitPoints(final int theAmount) { if (MY_RANDOM.nextInt(101) <= myChanceToBlock) { System.out.println(getName()+ " blocked the attack! "); // PLAY SOUND soundPlayer.play(blockSoundPath); } else { super.substractHitPoints(theAmount); } } /** * The method asks uset to choose what attack he wants to do. * @return attack choice */ private final int getChoice() { System.out.println("Type attack choice"); System.out.println("1 - regular attack"); System.out.println("2 - special attack"); System.out.println("3 - run "); int attackChoice = input.nextInt(); return attackChoice; } }
anguyenq/dungeon_adventure
Hero.java
1,721
/** * checks run away * @return true or false for run away. */
block_comment
en
false
1,679
20
1,721
19
1,874
22
1,721
19
2,142
22
false
false
false
false
false
true
70167_10
/** * $RCSfile$ * $Revision: 7071 $ * $Date: 2007-02-11 16:59:05 -0800 (Sun, 11 Feb 2007) $ * * Copyright 2003-2007 Jive Software. * * All rights reserved. Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.jivesoftware.smackx.packet; import org.jivesoftware.smack.packet.PacketExtension; import java.text.SimpleDateFormat; import java.util.Date; import java.util.TimeZone; /** * Represents extended presence information whose sole purpose is to signal the ability of * the occupant to speak the MUC protocol when joining a room. If the room requires a password * then the MUCInitialPresence should include one.<p> * * The amount of discussion history provided on entering a room (perhaps because the * user is on a low-bandwidth connection or is using a small-footprint client) could be managed by * setting a configured History instance to the MUCInitialPresence instance. * @see MUCInitialPresence#setHistory(MUCInitialPresence.History). * * @author Gaston Dombiak */ public class MUCInitialPresence implements PacketExtension { private String password; private History history; public String getElementName() { return "x"; } public String getNamespace() { return "http://jabber.org/protocol/muc"; } public String toXML() { StringBuilder buf = new StringBuilder(); buf.append("<").append(getElementName()).append(" xmlns=\"").append(getNamespace()).append("\">"); if (getPassword() != null) { buf.append("<password>").append(getPassword()).append("</password>"); } if (getHistory() != null) { buf.append(getHistory().toXML()); } buf.append("</").append(getElementName()).append(">"); return buf.toString(); } /** * Returns the history that manages the amount of discussion history provided on * entering a room. * * @return the history that manages the amount of discussion history provided on * entering a room. */ public History getHistory() { return history; } /** * Returns the password to use when the room requires a password. * * @return the password to use when the room requires a password. */ public String getPassword() { return password; } /** * Sets the History that manages the amount of discussion history provided on * entering a room. * * @param history that manages the amount of discussion history provided on * entering a room. */ public void setHistory(History history) { this.history = history; } /** * Sets the password to use when the room requires a password. * * @param password the password to use when the room requires a password. */ public void setPassword(String password) { this.password = password; } /** * The History class controls the number of characters or messages to receive * when entering a room. * * @author Gaston Dombiak */ public static class History { private int maxChars = -1; private int maxStanzas = -1; private int seconds = -1; private Date since; /** * Returns the total number of characters to receive in the history. * * @return total number of characters to receive in the history. */ public int getMaxChars() { return maxChars; } /** * Returns the total number of messages to receive in the history. * * @return the total number of messages to receive in the history. */ public int getMaxStanzas() { return maxStanzas; } /** * Returns the number of seconds to use to filter the messages received during that time. * In other words, only the messages received in the last "X" seconds will be included in * the history. * * @return the number of seconds to use to filter the messages received during that time. */ public int getSeconds() { return seconds; } /** * Returns the since date to use to filter the messages received during that time. * In other words, only the messages received since the datetime specified will be * included in the history. * * @return the since date to use to filter the messages received during that time. */ public Date getSince() { return since; } /** * Sets the total number of characters to receive in the history. * * @param maxChars the total number of characters to receive in the history. */ public void setMaxChars(int maxChars) { this.maxChars = maxChars; } /** * Sets the total number of messages to receive in the history. * * @param maxStanzas the total number of messages to receive in the history. */ public void setMaxStanzas(int maxStanzas) { this.maxStanzas = maxStanzas; } /** * Sets the number of seconds to use to filter the messages received during that time. * In other words, only the messages received in the last "X" seconds will be included in * the history. * * @param seconds the number of seconds to use to filter the messages received during * that time. */ public void setSeconds(int seconds) { this.seconds = seconds; } /** * Sets the since date to use to filter the messages received during that time. * In other words, only the messages received since the datetime specified will be * included in the history. * * @param since the since date to use to filter the messages received during that time. */ public void setSince(Date since) { this.since = since; } public String toXML() { StringBuilder buf = new StringBuilder(); buf.append("<history"); if (getMaxChars() != -1) { buf.append(" maxchars=\"").append(getMaxChars()).append("\""); } if (getMaxStanzas() != -1) { buf.append(" maxstanzas=\"").append(getMaxStanzas()).append("\""); } if (getSeconds() != -1) { buf.append(" seconds=\"").append(getSeconds()).append("\""); } if (getSince() != null) { SimpleDateFormat utcFormat = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'"); utcFormat.setTimeZone(TimeZone.getTimeZone("UTC")); buf.append(" since=\"").append(utcFormat.format(getSince())).append("\""); } buf.append("/>"); return buf.toString(); } } }
masud-technope/BLIZZARD-Replication-Package-ESEC-FSE2018
Corpus/ecf/151.java
1,673
/** * Returns the number of seconds to use to filter the messages received during that time. * In other words, only the messages received in the last "X" seconds will be included in * the history. * * @return the number of seconds to use to filter the messages received during that time. */
block_comment
en
false
1,611
71
1,673
68
1,836
77
1,673
68
1,973
77
false
false
false
false
false
true
70256_3
import java.sql.Timestamp; import java.text.DecimalFormat; import java.text.NumberFormat; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import javax.swing.JComboBox; public class Archive { private newLinkedList<Record> weightStack; String[] monthArray; SimpleDateFormat allFormat = new SimpleDateFormat("yyyyMMdd"); SimpleDateFormat dayFormat = new SimpleDateFormat("dd"); SimpleDateFormat monthFormat = new SimpleDateFormat("MM"); SimpleDateFormat yearFormat = new SimpleDateFormat("yy"); SimpleDateFormat yearMonth = new SimpleDateFormat("yyyyMM"); NumberFormat findFormat = new DecimalFormat("00"); JComboBox monthList; ArrayList<Record> foundRecords = new ArrayList<Record>(); //makes Archive object from linkedlist public Archive (newLinkedList<Record> weightStack){ this.weightStack = weightStack; setMonths(); makeDropdown(); } //goes through list to see what months records exist for. Populates list of months. public void setMonths(){ ArrayList<String> tempList = new ArrayList<String>(); for (int i = 1; i<weightStack.size(); i++){ Record temp = weightStack.get(i); Timestamp t = temp.timestamp; String month = monthFormat.format(t); if (month.equals(new String("01")) && !tempList.contains("January")){ tempList.add("January"); } else if (month.equals(new String("02")) && !tempList.contains("February")){ tempList.add("February"); } else if (month.equals(new String("03")) && !tempList.contains("March")){ tempList.add("March"); } else if (month.equals(new String("04")) && !tempList.contains("April")){ tempList.add("April"); } else if (month.equals(new String("05")) && !tempList.contains("May")){ tempList.add("May"); } else if (month.equals(new String("06")) && !tempList.contains("June")){ tempList.add("June"); } else if (month.equals(new String("07")) && !tempList.contains("July")){ tempList.add("July"); } else if (month.equals(new String("08")) && !tempList.contains("August")){ tempList.add("August"); } else if (month.equals(new String("09")) && !tempList.contains("September")){ tempList.add("September"); } else if (month.equals(new String("10")) && !tempList.contains("October")){ tempList.add("October"); } else if (month.equals(new String("11")) && !tempList.contains("November")){ tempList.add("November"); } else if (month.equals(new String("12")) && !tempList.contains("December")){ tempList.add("December"); } } monthArray = new String[tempList.size()]; int k = tempList.size()-1; for (int n = 0; n < tempList.size() ; n++){ monthArray[n] = tempList.get(k); k--; } } //uses list of months to make the combo box public void makeDropdown(){ monthList = new JComboBox(monthArray); monthList.setSelectedIndex(0); } public JComboBox getDropdown(){ return monthList; } //searches through list for all records that match that selected month! public ArrayList<Record> findRecords(newLinkedList<Record> r) { String temp = monthList.getSelectedItem().toString(); String toFind = "2017"+compareMonths(temp); int toFindInd = monthList.getSelectedIndex()+1; String date = ""; int index =1; foundRecords = new ArrayList<Record>(); while (index < r.size()){ date = yearMonth.format(r.get(index).timestamp); if(date.compareTo(toFind) == 0) { foundRecords.add(r.get(index)); } index++; } return foundRecords; } //checks case to see what string is needed for that month on dropdown box public String compareMonths(String name){ String num = ""; if (name.equals(new String("January"))){ num="01"; } else if (name.equals(new String("February"))){ num="02"; } else if (name.equals(new String("March"))){ num="03"; } else if (name.equals(new String("April"))){ num="04"; } else if (name.equals(new String("May"))){ num="05"; } else if (name.equals(new String("June"))){ num="06"; } else if (name.equals(new String("July"))){ num="07"; } else if (name.equals(new String("August"))){ num="08"; } else if (name.equals(new String("September"))){ num="09"; } else if (name.equals(new String("October"))){ num="10"; } else if (name.equals(new String("November"))){ num="11"; } else if (name.equals(new String("December"))){ num="12"; } return num; } }
sarahsummerfield/AxiFi
Archive.java
1,424
//searches through list for all records that match that selected month!
line_comment
en
false
1,171
15
1,424
15
1,426
15
1,424
15
1,712
15
false
false
false
false
false
true
70954_16
package braincraft; import java.io.BufferedWriter; import java.io.FileWriter; import java.io.IOException; import java.util.ArrayList; //import java.util.Random; /** * @author Chris Donahue * * Braincraft is a platform for the evolution of Neural Networks and the * testing of genetic algorithms/population control algorithms. Heavily * inspired by NEAT: http://www.cs.ucf.edu/~kstanley/neat.html * * This class is a singleton to provide storage and convenience across * the library. Stores default values for all parameters. */ public class Braincraft { // ALL POPULATION PARAMETER DEFAULTS: protected static int populationSize = 100; protected static double sigmoidCoefficient = -4.9; protected static double perWeightMutationRate = 0.9; protected static double weightMutationRate = 0.8; protected static double linkMutationRate = 0.1; protected static double linkDisableRate = 0.1; protected static double nodeMutationRate = 0.05; protected static double disabledRate = 0.75; protected static double inheritFromHigherFitRate = 0.8; // POPULATION SUBCLASS PARAMETER DEFAULTS: protected static double c1 = 1.0; protected static double c2 = 1.0; protected static double c3 = 0.4; protected static double tribeCompatibilityThreshold = 3.0; protected static double percentageOfTribeToKillBeforeReproduction = 0.5; protected static double survivalRatePerGeneration = 0.2; // STATISTICS FIELDS: public static boolean gatherStats = false; protected static ArrayList<DNA> allDNA = new ArrayList<DNA>(); protected static ArrayList<String> genetics = new ArrayList<String>(); protected static ArrayList<Double> generationAverages = new ArrayList<Double>(); // FIELDS: public static boolean logToSystemOut = false; // private static Random rng = new Random(); private static ArrayList<Population> society = new ArrayList<Population>(); private static ArrayList<String> log = new ArrayList<String>(); private static ArrayList<String> errorLog = new ArrayList<String>(); // CONSTRUCTORS (to avoid public construction) /** * Unused constructor */ private Braincraft() { } // PUBLIC METHODS: /** * Writes the log messages to a specified file * * @param file * the file to write to * @return 1 if successful, -1 if unsuccessful */ public static int writeLog(String file) { return writeStringToFile(listToString(log), file); } /** * Writes the visualizer statistics to a specified file * * @param file * the file to write to * @return 1 if successful, -1 if unsuccessful */ public static int writeStats(String file) { return writeStringToFile(listToString(allDNA) + listToString(genetics) + listToString(generationAverages), file); } /** * Writes the error log messages to a specified file * * @param file * the file to write to * @return 1 if successful, -1 if unsuccessful */ public static int writeErrorLog(String file) { return writeStringToFile(listToString(errorLog), file); } // LIBRARY METHODS: /** * Bernoulli trial with percentage chance * * @param chance * the chance of success for this Bernoulli trial * @return whether or not the trial was a success */ protected static boolean randomChance(double chance) { if (Math.random() < chance) return true; return false; } /** * Get a random weight value * * @return double a weight value between -1 and 1 */ protected static double randomWeight() { int sign = (int) (Math.random() * 2); double value = Math.random(); if (sign == 0) { return value * -1; } return value; } /** * Gets a random integer between 0 (inclusive) and the specified range * (exclusive) * * @param range * get a random number greater than or equal to 0 but less than * range * @return a random integer */ protected static int randomInteger(int range) { // TODO: MAKE THIS MORE RANDOM return (int) (Math.random() * range); // return rng.nextInt(range); } /** * Adds a string to the library log * * @param message * message to add to the log */ protected static void report(String message) { if (logToSystemOut) System.out.println(message); log.add(message); } /** * Adds a string to the library error log * * @param message * error to report */ protected static void reportError(String message) { if (logToSystemOut) System.out.println(message); errorLog.add(message); } /** * Returns an integer representing the new Population ID * * @param p * Population to get an ID for * @return new Population ID */ protected static int getNewPopulationID(Population p) { int ret = society.size() + 1; society.add(p); return ret; } /** * Takes each element of an ArrayList and calls toString() on it, appending * newlines. * * @param list * the list to convert to a String * @return a String made up of all of the elements of the list */ protected static String listToString(ArrayList<?> list) { String ret = ""; for (Object o : list) ret += o.toString() + "\n"; return ret; } /** * Attempts to write a given string to a given file * * @param output * the output to write to file * @param file * the location of the file writing to * @return 1 if successful, -1 if unsuccessful */ protected static int writeStringToFile(String output, String file) { try { BufferedWriter out = new BufferedWriter(new FileWriter(file)); out.write(output); out.close(); } catch (IOException e) { Braincraft.reportError("Could not write to location " + file + "."); return -1; } return 1; } }
pradn/Aegis
src/braincraft/Braincraft.java
1,620
/** * Gets a random integer between 0 (inclusive) and the specified range * (exclusive) * * @param range * get a random number greater than or equal to 0 but less than * range * @return a random integer */
block_comment
en
false
1,435
65
1,620
59
1,649
68
1,620
59
1,850
73
false
false
false
false
false
true
71534_5
import java.awt.Color; import java.awt.Font; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.awt.image.BufferedImage; import java.io.File; import java.io.FileNotFoundException; import java.util.HashMap; import java.util.NoSuchElementException; import java.util.Scanner; import javax.swing.BoxLayout; import javax.swing.ImageIcon; import javax.swing.JButton; import javax.swing.JComboBox; import javax.swing.JFrame; import javax.swing.JLabel; import javax.swing.JPanel; import javax.swing.JTextArea; import javax.swing.JTextField; /** * * @author BrandonHall * */ public class HomePage extends JPanel implements ActionListener { // TODO: Change sort into a JComboBox String[] sortTypes = { " ", "Price", "Name" }; JComboBox sort = new JComboBox(sortTypes); JButton go = new JButton("Go!"); JButton faq = new JButton("FAQ"); JButton addEvent = new JButton("Create a new attraction"); JFrame mainFrame = new JFrame(); JPanel mainPanel = new JPanel(); Color pink = new Color(255, 192, 203); JTextField bar = new JTextField("Search", 30); /** * Creates the home page using a couple JPanels, a JButton, and a JMenu to sort * by a certain criteria * * @return the home page jpanel */ public JPanel searchBar() { // Creating the main JPanel JPanel search = new JPanel(); search.setLayout(new BoxLayout(search, BoxLayout.Y_AXIS)); // An internal panel that helps for aesthetics of the home page panel JPanel searchBarPanel = new JPanel(); searchBarPanel.setSize(100, 24); // An internal panel that houses the search button and the sort menu JPanel buttonPanel = new JPanel(); // Adding and formatting text for the label and text field JLabel label = new JLabel("CincySearch"); label.setSize(100, 100); label.setFont(label.getFont().deriveFont(64.0f)); label.setFont(new Font("Times New Roman", Font.BOLD, 64)); sort.addActionListener(this); // Adding all of the components to the internal panels searchBarPanel.add(bar); buttonPanel.add(go); buttonPanel.add(sort); buttonPanel.add(addEvent); buttonPanel.add(faq); addEvent.addActionListener(this); bar.setSize(200, 24); // Aligning all of the internal panels for aesthetic purposes bar.setAlignmentX(CENTER_ALIGNMENT); go.setAlignmentX(CENTER_ALIGNMENT); faq.setAlignmentX(CENTER_ALIGNMENT); faq.addActionListener(this); go.addActionListener(this); label.setAlignmentX(CENTER_ALIGNMENT); // Adding all of the smaller panels and label to the larger JFrame search.add(label); search.add(searchBarPanel); search.add(buttonPanel); search.setBackground(pink); buttonPanel.setBackground(pink); searchBarPanel.setBackground(pink); return search; } public void run() { mainPanel.add(searchBar()); mainFrame.setSize(500, 300); mainFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); mainFrame.add(mainPanel); mainPanel.setBackground(pink); mainFrame.setVisible(true); } public void FAQ() { JFrame j = new JFrame(); JPanel p = new JPanel(); JTextArea t = new JTextArea(); t.setText( "Welcome to the CincySearch application! To begin viewing events in the Cincinnati area, press search. You will then be redirected to our Catalogue page where you can view multiple events and their brief descriptions. To view a certain event in more detail, press the GO button where you will be able to get an in-depth description of that event. Return to a previous page anytime by using the Back buttons. If you are a business owner, you will be able to add your event to our application using the Create New Event button."); t.setLineWrap(true); t.setWrapStyleWord(true); t.setEditable(false); p.add(t); j.add(p); j.setVisible(true); j.setSize(500, 200); t.setSize(j.getSize()); t.setBackground(pink); p.setBackground(pink); // j.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); } public static void easterEgg() { JFrame easterEgg = new JFrame(); ImageIcon TA = new ImageIcon("TaEasterEgg.jpg"); easterEgg.add(new JLabel(TA)); easterEgg.setSize(TA.getIconHeight(), TA.getIconWidth()); easterEgg.setVisible(true); easterEgg.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); System.out.println("It work"); } public static void exactName(String name) throws NoSuchElementException { Scanner s = null; File f = null; String eventName = null; try { f = new File("data.txt"); s = new Scanner(f); s.useDelimiter("#"); } catch (FileNotFoundException e) { // TODO Auto-generated catch block e.printStackTrace(); } for (int i = 0; i < 10; i++) { eventName = s.next(); if (eventName.equals(name)) break; else { System.out.println(eventName); s.nextLine(); } } String type = s.next(); String price = s.next(); String monday = s.next(); String tuesday = s.next(); String wednesday = s.next(); String thursday = s.next(); String friday = s.next(); String saturday = s.next(); String sunday = s.next(); HashMap<String, String> map = new HashMap<String, String>(); map.put("Monday", monday); map.put("Tuesday", tuesday); map.put("Wednesday", wednesday); map.put("Thursday", thursday); map.put("Friday", friday); map.put("Saturday", saturday); map.put("Sunday", sunday); Event event = new Event(eventName, type, price, s.next(), s.next(), s.next(), s.next(), s.next(), map); EventPanelOOP2 eventpanel = new EventPanelOOP2(event.getName(), event.getType(), event.getPrice(), event.getUrl(), event.getPhoneNum(), event.getAddress(), event.getDescription(), event.getImageUrl(), map); } /** * This method creates a JFrame in which the main JPanel is added. * * @param args main parameter for the main method */ public static void main(String[] args) { HomePage home = new HomePage(); home.run(); // exactName("American Sign Museum"); } /** * The action listener that will be used for the search button and the sort by * menu */ @Override public void actionPerformed(ActionEvent e) { if (e.getSource() == go) { // System.out.println(bar.getText()); if (bar.getText().equals(new String("Search"))) { System.out.println("We searchin"); Catalogue.buildCatalogue(sort.getSelectedIndex()); System.out.println(sort.getSelectedIndex()); mainFrame.setContentPane(Catalogue.cataloguePanel); mainFrame.pack(); return; } //System.out.println(bar.getText()); else if (bar.getText().equals("Patricia Lennon")) { easterEgg(); } else { exactName(bar.getText()); } } if (e.getSource() == addEvent) { // mainPanel.setVisible(false); CreatePage c = new CreatePage(); mainFrame.setContentPane(c.eventAdd()); mainFrame.pack(); } if (e.getSource() == faq) { FAQ(); } } }
naiss19/CSE-201-Group-17
HomePage.java
2,118
// An internal panel that houses the search button and the sort menu
line_comment
en
false
1,652
14
2,118
15
2,077
14
2,118
15
2,575
14
false
false
false
false
false
true
72785_2
/* * FileIO TCSS 342 */ package application; import java.io.File; import java.io.FileNotFoundException; import java.util.Scanner; import structures.Vertex; import structures.WeightedGraph; /** * Provides a static method to populate a graph from a file. * * The file format is assumed to be: Line 1: an integer n representing the * number of vertices The next n lines should contain the text labels for the n * vertices, one per line The next n lines represent the matrix of edge costs in * the graph An edge weight of -1 represents that there is no such edge in the * graph * * @author Alan Fowler * @version 1.1 */ public final class FileIO { /** * The name of the default input file. */ private static final String DEFAULT_FILE_NAME = "distances.txt"; /** * Private constructor to inhibit external instantiation. */ private FileIO() { // do not instantiate objects of this class } /** * Populates a graph from a file. * * @param theGraph the graph to populate */ public static void createGraphFromFile(final WeightedGraph<String> theGraph) { Scanner fileInput = null; try { fileInput = new Scanner(new File(DEFAULT_FILE_NAME)); } catch (final FileNotFoundException exception) { exception.printStackTrace(); System.exit(1); } // read the size final int size = fileInput.nextInt(); fileInput.nextLine(); // read the EOL character // read the vertex labels final Vertex<String>[] vertices = new Vertex[size]; for (int index = 0; index < size; index++) { vertices[index] = new Vertex<String>(fileInput.nextLine()); theGraph.addVertex(vertices[index]); } // read the edge weights for (int row = 0; row < size; row++) { for (int col = 0; col < size; col++) { // read ALL data final int weight = fileInput.nextInt(); if (weight > 0 && col < row) { // add a new edge - do not // duplicate // edges theGraph.addEdge(vertices[row], weight, vertices[col]); } } } } }
ChadChapman/ThreeFourTwoHW5
FileIO.java
540
/** * The name of the default input file. */
block_comment
en
false
490
13
540
13
617
15
540
13
657
16
false
false
false
false
false
true
73761_1
/* * Pranjal Patni (pxp142030) * * @author Pranjal Patni * @email [email protected] * @version 1.0 * * This project focuses on the implementation of a distributed system, where * there are several nodes who communicate among each other via messages. Each * node generates a random value and adds its own value while passing the * message to the next node. */ import java.io.*; import java.net.*; /** * Client class creates an object which then connects to the server by creating * a TCP socket * * @author Pranjal * * @variable client_socket is used to connect to the server socket * @variable in is used to receive the token that has been sent by the client * @variable out is used to send the token to the next server * @variable client_token receives the token that has been passed to it as an * argument in its constructor */ public class Client { private Socket client_socket; private ObjectInputStream in; private ObjectOutputStream out; private Token client_token; /** * Client constructor instantiates the client object * * @param t is the token that the Client class receives during its object * creation */ public Client(Token t) { client_token = t; } /** * getToken method returns the token for the Client object * * @return token is returned */ public Token getToken() { return client_token; } /** * connect method takes the host name and port number as its arguments so * that it can connect to the corresponding server * * @param hostname host name of the server * @param port port number at which the server is listening * @throws IOException */ public void connect(String hostname, int port) throws IOException { try { client_socket = new Socket(hostname, port); out = new ObjectOutputStream(client_socket.getOutputStream()); out.writeObject(client_token); client_socket.close(); } catch (IOException e) { System.out.println("Server " + hostname + " is not responding"); System.out.println("Trying again after 3 sec"); long start = System.currentTimeMillis(); long end = start + 2 * 1000; // 2 seconds while (System.currentTimeMillis() < end) { // run } this.connect(hostname, port); } } }
pranjalpatni/Implementing-Distributed-System
Client.java
572
/** * Client class creates an object which then connects to the server by creating * a TCP socket * * @author Pranjal * * @variable client_socket is used to connect to the server socket * @variable in is used to receive the token that has been sent by the client * @variable out is used to send the token to the next server * @variable client_token receives the token that has been passed to it as an * argument in its constructor */
block_comment
en
false
532
101
572
106
611
105
572
106
636
107
false
false
false
false
false
true
73812_3
/****************************************************************************** * Compilation: javac Cat.java * Execution: java Cat input0.txt input1.txt ... output.txt * Dependencies: In.java Out.java * Data files: https://algs4.cs.princeton.edu/11model/in1.txt * https://algs4.cs.princeton.edu/11model/in2.txt * * Reads in text files specified as the first command-line * arguments, concatenates them, and writes the result to * filename specified as the last command-line arguments. * * % more in1.txt * This is * * % more in2.txt * a tiny * test. * * % java Cat in1.txt in2.txt out.txt * * % more out.txt * This is * a tiny * test. * ******************************************************************************/ package edu.princeton.cs.algs4; /** * The {@code Cat} class provides a client for concatenating the results * of several text files. * <p> * For additional documentation, see <a href="https://algs4.cs.princeton.edu/11model">Section 1.1</a> of * <i>Algorithms, 4th Edition</i> by Robert Sedgewick and Kevin Wayne. * * @author Robert Sedgewick * @author Kevin Wayne */ public class Cat { // this class should not be instantiated private Cat() { } /** * Reads in a sequence of text files specified as the first command-line * arguments, concatenates them, and writes the results to the file * specified as the last command-line argument. * * @param args the command-line arguments */ public static void main(String[] args) { Out out = new Out(args[args.length - 1]); for (int i = 0; i < args.length - 1; i++) { In in = new In(args[i]); String s = in.readAll(); out.println(s); in.close(); } out.close(); } } /****************************************************************************** * Copyright 2002-2019, Robert Sedgewick and Kevin Wayne. * * This file is part of algs4.jar, which accompanies the textbook * * Algorithms, 4th edition by Robert Sedgewick and Kevin Wayne, * Addison-Wesley Professional, 2011, ISBN 0-321-57351-X. * http://algs4.cs.princeton.edu * * * algs4.jar 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. * * algs4.jar 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 algs4.jar. If not, see http://www.gnu.org/licenses. ******************************************************************************/
pladgy/DS_ZJU_CY
algs4/Cat.java
828
/** * Reads in a sequence of text files specified as the first command-line * arguments, concatenates them, and writes the results to the file * specified as the last command-line argument. * * @param args the command-line arguments */
block_comment
en
false
721
57
828
57
844
63
828
57
912
64
false
false
false
false
false
true
75467_2
import java.io.IOException; import javax.servlet.ServletException; import javax.servlet.annotation.WebServlet; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; @WebServlet("/dailytips") public class DailyTipsServlet extends HttpServlet { protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { // For demonstration purposes, let's assume we have pre-defined recommendations and tips. String dailyRecommendation = getDailyRecommendation(); // Implement this method to get the daily recommendation. String dailyTip = getDailyTip(); // Implement this method to get the daily tip. // Store the daily recommendations and tips in request attributes to be accessed in the JSP. request.setAttribute("dailyRecommendation", dailyRecommendation); request.setAttribute("dailyTip", dailyTip); // Forward the request to the daily_tips.jsp to display the recommendations and tips. request.getRequestDispatcher("daily_tips.jsp").forward(request, response); } // Implement these methods to retrieve the daily recommendation and tip from your data source. private String getDailyRecommendation() { // Implement the logic to get the daily recommendation, e.g., fetching from a database. // For this example, we are returning a dummy recommendation. return "Today's recommendation: Exercise regularly and eat a balanced diet."; } private String getDailyTip() { // Implement the logic to get the daily tip, e.g., fetching from a database. // For this example, we are returning a dummy tip. return "Daily Tip: Stay hydrated by drinking enough water throughout the day."; } }
JakeWad/Software-Systems-Capstone-Project
tips.java
373
// Implement this method to get the daily tip.
line_comment
en
false
328
10
373
10
387
10
373
10
463
11
false
false
false
false
false
true
75645_11
import java.io.Serializable; import java.util.ArrayList; /** * Represents a movie stored in the movie database (in a movies.txt file). * There can be multiple movies stored in the movie database. * * @author Karishein Chandran * @version 1.0 * @since 2022-11-05 */ public class Movie implements Serializable { /** * The title of this movie. */ private final String title; /** * The synopsis of this movie. */ private final String synopsis; /** * The director of this movie. */ private final String director; /** * The cast of this movie. */ private final ArrayList<String> cast; /** * The genre of this movie. */ private final String genre; /** * The language (e.g. English, Korean, Tamil, etc.) of this movie. */ private final String language; /** * The duration of this movie. */ private final String runTime; /** * The movie rating (e.g. G, PG, PG13, NC16, M18, R21) of this movie. */ private final String movieRating; /** * The release date of this movie. */ private final String release; /** * The reviews of this movie written by the reviewers. */ private final ArrayList<String> pastReviews; /** * The number of tickets sold for this movie. */ private final int noOfTickets; /** * The average rating of this movie based of all the reviewer's ratings. */ private String overallReviewerRating; /** * Stores the current status of this movie. */ private ShowingStatus status; /** * The date when the movie is switched to end of showing */ private String endOfShowingDate; /** * Creates a new movie with the given parameters. * * @param title This Movie's title. * @param status This Movie's status. * @param synopsis This Movie's synopsis. * @param director This Movie's director. * @param cast This Movie's list of cast. * @param language This Movie's language. * @param genre This Movie's genres. * @param runTime This Movie's running time. * @param movieRating This Movie's rating. * @param release This Movie's release date. * @param overallReviewerRating This Movie's average viewer rating. * @param pastReviews This Movie's past reviews written by viewers. * @param noOfTickets This Movie's number of tickets sold. * @see #updateReviewsRatings() */ public Movie(String title, ShowingStatus status, String synopsis, String director, ArrayList<String> cast, String language, String genre, String runTime, String movieRating, String release, String overallReviewerRating, ArrayList<String> pastReviews, int noOfTickets) { this.title = title; this.status = status; this.synopsis = synopsis; this.director = director; this.cast = cast; this.genre = genre; this.language = language; this.runTime = runTime; this.movieRating = movieRating; this.release = release; this.overallReviewerRating = overallReviewerRating; this.pastReviews = pastReviews; this.noOfTickets = noOfTickets; this.endOfShowingDate = "31/12/2022"; updateReviewsRatings(); } /** * Gets the title of this Movie. * * @return this Movie's title. */ public String getTitle() { return title; } /** * Gets the current status of this Movie in cinemas. * * @return this Movie's current status. */ public ShowingStatus getStatus() { return status; } /** * Changes status of movie * * @param status new status */ public void setStatus(ShowingStatus status) { this.status = status; } /** * Gets the synopsis of this Movie. * * @return this Movie's synopsis. */ public String getSynopsis() { return synopsis; } /** * Gets the director of this Movie. * * @return this Movie's director. */ public String getDirector() { return director; } /** * Gets the cast of this Movie. * * @return this Movie's list of cast. */ public ArrayList<String> getCast() { return cast; } /** * Gets the genre of this Movie. * * @return this Movie's genre. */ public String getGenre() { return genre; } /** * Gets the language of this Movie. * * @return this Movie's language. */ public String getLanguage() { return language; } /** * Gets the running time of this Movie. * * @return this Movie's run time. */ public String getRunTime() { return runTime; } /** * Gets the rating of this Movie. * * @return this Movie's rating. */ public String getMovieRating() { return movieRating; } /** * Gets the release date of this Movie. * * @return this Movie's release date. */ public String getRelease() { return release; } /** * Gets the viewer's average rating of this Movie. * * @return this Movie's overall average rating. */ public String getOverallReviewerRating() { return overallReviewerRating; } /** * Gets the past reviews written by the reviewers of this Movie. * * @return this Movie's list of past reviews. */ public ArrayList<String> getPastReviews() { return pastReviews; } /** * Gets the number of tickets sold for this Movie. * * @return this Movie's current number of tickets sold. */ public int getNoOfTickets() { return noOfTickets; } /** * Computes and updates the average rating of the reviewers and reviews written, by reading from the review file.<br> * The pastReviews and overallReviewer rating for this Movie is updated with any new ratings and reviews from the review database.<br> * This method also checks if there's only one review and does the necessary updates.<br> */ private void updateReviewsRatings() { double ans = 0.0, result; int count = 0; try { String reviewFile = "data/reviews.txt"; ArrayList<Review> reviewList = ReviewDB.readReviews(reviewFile); pastReviews.clear(); for (Review review : reviewList) { if (review.getMovieTitle().equalsIgnoreCase(getTitle())) { pastReviews.add(review.getReviewerName()); pastReviews.add(String.valueOf(review.getRating())); pastReviews.add(review.getReviewDescription()); ans += review.getRating(); count++; } } if (pastReviews.isEmpty()) pastReviews.add("NA"); if (count > 1) { result = ans / count; result = Math.round(result * 10) / 10.0; overallReviewerRating = String.valueOf(result); } else overallReviewerRating = "NA"; } catch (Exception e) { System.out.println("IOException > " + e.getMessage()); } } /** * Returns EndOfShowingDate * * @return EndOfShowingDate * This movie's end of showing date */ public String getEndOfShowingDate() { return endOfShowingDate; } /** * Changes EndOfShowingDate * * @param endOfShowingDate The new value for the movie's end of showing date */ public void setEndOfShowingDate(String endOfShowingDate) { this.endOfShowingDate = endOfShowingDate; } /** * The showing status of this movie in Cinema. */ public enum ShowingStatus {COMING_SOON, PREVIEW, NOW_SHOWING, END_OF_SHOWING} /** * The type of this movie (2d,3d,blockbuster) */ public enum MovieType {IMAX_2D, IMAX_3D, BLOCKBUSTER} }
samuel1234ng/SC2002-group-project
Movie.java
1,907
/** * The number of tickets sold for this movie. */
block_comment
en
false
1,827
14
1,907
14
2,159
16
1,907
14
2,375
17
false
false
false
false
false
true
75976_9
package application; import java.time.LocalDate; import javafx.beans.property.*; /* * Brady Craig, Software Development 1, 04-14-2024 * * Book Class * * Used to give books identifiable property attributes such as barcode, title, author, genre and checked out/in status. * Updated book class to utilize Property data types so TableView could be used in the GUI. * Used to store book data in LMS database. */ /** * Represents a book with identifiable properties such as barcode, title, author, genre, and checked out/in status. * This class utilizes Property data types to enable integration with JavaFX TableView. * Used to store book data in the Library Management System (LMS) database. */ public class Book { private final IntegerProperty barcode; private final StringProperty title; private final StringProperty author; private final StringProperty genre; private final BooleanProperty checkedOut; private final ObjectProperty<LocalDate> dueDate; /** * Constructs a new Book object with the specified properties. * * @param barcode The barcode of the book. * @param title The title of the book. * @param author The author of the book. * @param genre The genre of the book. * @param checkedOut The checked out status of the book. * @param dueDate The due date of the book if it is checked out, otherwise null. */ public Book(int barcode, String title, String author, String genre, boolean checkedOut, LocalDate dueDate) { this.barcode = new SimpleIntegerProperty(barcode); this.title = new SimpleStringProperty(title); this.author = new SimpleStringProperty(author); this.genre = new SimpleStringProperty(genre); this.checkedOut = new SimpleBooleanProperty(checkedOut); this.dueDate = new SimpleObjectProperty<>(dueDate); } /** * Gets the barcode property of the book. * * @return The barcode property. */ public IntegerProperty barcodeProperty() { return barcode; } /** * Gets the value of the barcode property. * * @return The barcode value. */ public int getBarcode() { return barcode.get(); } /** * Sets the value of the barcode property. * * @param barcode The barcode value to set. */ public void setBarcode(int barcode) { this.barcode.set(barcode); } /** * Gets the title property of the book. * * @return The title property. */ public StringProperty titleProperty() { return title; } /** * Gets the value of the title property. * * @return The title value. */ public String getBookTitle() { return title.get(); } /** * Sets the value of the title property. * * @param barcode The title value to set. */ public void setBookTitle(String title) { this.title.set(title); } /** * Gets the author property of the book. * * @return The author property. */ public StringProperty authorProperty() { return author; } /** * Gets the value of the author property. * * @return The author value. */ public String getAuthorName() { return author.get(); } /** * Sets the value of the author property. * * @param barcode The author value to set. */ public void setAuthorName(String author) { this.author.set(author); } /** * Gets the genre property of the book. * * @return The genre property. */ public StringProperty genreProperty() { return genre; } /** * Gets the value of the genre property. * * @return The genre value. */ public String getGenre() { return genre.get(); } /** * Sets the value of the genre property. * * @param barcode The genre value to set. */ public void setGenre(String genre) { this.genre.set(genre); } /** * Gets the checkedOut property of the book. * * @return The checkedOut property. */ public BooleanProperty checkedOutProperty() { return checkedOut; } /** * Gets the value of the checkedOut property. * * @return The checkoOut value. */ public boolean isCheckedOut() { return checkedOut.get(); } /** * Sets the value of the checkedOut property. * * @param barcode The checkedOut value to set. */ public void setCheckedOut(boolean checkedOut) { this.checkedOut.set(checkedOut); } /** * Gets the dueDate property of the book. * * @return The dueDate property. */ public ObjectProperty<LocalDate> dueDateProperty() { return dueDate; } /** * Gets the value of the dueDate property. * * @return The dueDate value. */ public LocalDate getDueDate() { return dueDate.get(); } /** * Sets the value of the dueDate property. * * @param barcode The dueDate value to set. */ public void setDueDate(LocalDate dueDate) { this.dueDate.set(dueDate); } }
Brady-Craig/Craig_Brady_LMS
Book.java
1,227
/** * Gets the author property of the book. * * @return The author property. */
block_comment
en
false
1,178
23
1,227
23
1,399
27
1,227
23
1,493
28
false
false
false
false
false
true
77291_13
package com.company; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.PrintWriter; import java.util.Scanner; /** * @author Parker Amundsen * @description this program takes a formatted Input.txt file containing students grades and names of the student. * The program then processes the grades and gives statistics on individual students and questions of the test in a formatted Output.txt file. * @version 11/15/2018 */ public class HW5 { //global data members for use in multiple methods private static double[][] grades = null; private static String[] names = null; private static double[] totalScores = null; public static void main(String[] args) throws FileNotFoundException { //establishes input stream from Input.txt aswell as Scanner object to read file. FileInputStream input = new FileInputStream("Input.txt"); Scanner reader = new Scanner(input); //establishes output stream to Output.txt aswell as a PrintWriter object to write to file. FileOutputStream fos = new FileOutputStream("Output.txt"); PrintWriter writer = new PrintWriter(fos); //Below methods called in this order to achieve desired output format to Output.txt initializeArrays(reader); allScoresPrint(writer); sectionData(writer); overallPerStudent(writer); writer.close(); } /** * @param reader * @throws FileNotFoundException * @description this initializes (assigns size) the grades[][] and names[] arrays. */ public static void initializeArrays(Scanner reader) { int numOfStudents = reader.nextInt(); int numOfQuestions = (reader.nextInt() - 1); grades = new double[numOfStudents][numOfQuestions]; names = new String[numOfStudents]; assignArrays(reader, numOfStudents, numOfQuestions); } /** * @param reader * @throws FileNotFoundException * @description assignArrays() gives the values the arrays names[] and grades[][]. */ public static void assignArrays(Scanner reader, int numOfStudents, int numOfQuestions) { for (int studentNumber = 0; studentNumber < numOfStudents; studentNumber++) { names[studentNumber] = reader.next(); for (int questionNumber = 0; questionNumber < numOfQuestions; questionNumber++) { grades[studentNumber][questionNumber] = reader.nextDouble(); } } } /** * @param writer * @description allScoresPrint() prints to the output file (Output.txt) all the scores of each section by student. */ public static void allScoresPrint(PrintWriter writer) { int studentNumber = 0; writer.println("Score per section per student: \n============================================="); for (double[] student : grades) { writer.print(names[studentNumber] + ": "); studentNumber++; for (double grade : student) { writer.print(grade + " "); } writer.println(""); } } /** * @param writer * @param sectionNumber * @description Prints the maximum value along with student names of the given section number in grades[][] to the output file. */ public static void findMax(PrintWriter writer, int sectionNumber) { double max = 0; for (int i = 0; i < names.length; i++) { if (grades[i][sectionNumber] > max) { max = grades[i][sectionNumber]; } } writer.println("Highest score: " + max); for (int i = 0; i < names.length; i++) { if (grades[i][sectionNumber] == max) { writer.print(names[i] + " "); } } writer.println(""); } /** * @param writer * @param studentTotals * @description Prints the maximum value of the overall score among all the students to the output file along with student names. */ public static void findMax(PrintWriter writer, boolean studentTotals) { if (studentTotals == true) { double max = totalScores[0]; for (int i = 0; i < names.length; i++) { if (totalScores[i] > max) { max = totalScores[i]; } } writer.println("Highest score: " + max); for (int i = 0; i < names.length; i++) { if (max == totalScores[i]) { writer.print(names[i] + " "); } } writer.println(""); } } /** * @param writer * @param sectionNumber * @description Prints the minimum value along with student names of the given section number in grades[][] to the output file. */ public static void findMin(PrintWriter writer, int sectionNumber) { double min = grades[0][sectionNumber]; for (int i = 0; i < names.length; i++) { if (grades[i][sectionNumber] < min) { min = grades[i][sectionNumber]; } } writer.println("Lowest score: " + min); for (int i = 0; i < names.length; i++) { if (min == grades[i][sectionNumber]) { writer.print(names[i] + " "); } } writer.println(""); } /** * @param writer * @param studentTotals * @description Prints the minimum value of the overall score among all the students to the output file along with student names. */ public static void findMin(PrintWriter writer, boolean studentTotals) { if (studentTotals == true) { double min = totalScores[0]; for (int i = 0; i < names.length; i++) { if (totalScores[i] < min) { min = totalScores[i]; } } writer.println("Lowest score: " + min); for (int i = 0; i < names.length; i++) { if (min == totalScores[i]) { writer.print(names[i] + " "); } } writer.println(""); } } /** * @param writer * @param sectionNumber * @description findAverage() prints the average values of the given section number among all of the students to the output file. */ public static void findAverage(PrintWriter writer, int sectionNumber) { double sum = 0; for (int i = 0; i < names.length; i++) { sum += grades[i][sectionNumber]; } double average = sum / grades.length; writer.println("Average: " + average); } /** * @param writer * @param overallAverage * @description findAverage() prints the average value of the overall student scores to the output file. */ public static void findAverage(PrintWriter writer, boolean overallAverage) { if (overallAverage == true) { double sum = 0; for (int i = 0; i < names.length; i++) { sum += totalScores[i]; } double average = sum / grades.length; writer.println("Average: " + average); } } /** * @param writer * @description sectionData() formats the output of findMax(), findMin(), and findAverage() and loops through all sections. */ public static void sectionData(PrintWriter writer) { int numOfQuestions = grades[0].length; for (int questionNum = 0; questionNum < numOfQuestions; questionNum++) { writer.println("============================================="); writer.println("Question: " + (questionNum + 1)); findMax(writer, questionNum); findMin(writer, questionNum); findAverage(writer, questionNum); } writer.println("============================================="); } /** * @param writer * @descrition overallPerStudent() initializes the size of global data member totalScores(). * Aswell as prints the formatted overall statistics to the output file. */ public static void overallPerStudent(PrintWriter writer) { totalScores = new double[names.length]; writer.println("Overall scores by student: "); for (int student = 0; student < names.length; student++) { writer.print(names[student] + ": "); double total = 0; for (int questionNum = 0; questionNum < grades[0].length; questionNum++) { total += grades[student][questionNum]; } writer.println(total); totalScores[student] = total; } writer.println(""); writer.println("Overall highest, lowest, and average score:"); findMax(writer, true); findMin(writer, true); findAverage(writer, true); writer.println("============================================="); } }
Parkerba/CSS142C
HW5.java
2,012
/** * @param writer * @param overallAverage * @description findAverage() prints the average value of the overall student scores to the output file. */
block_comment
en
false
1,891
37
2,012
35
2,191
39
2,012
35
2,394
41
false
false
false
false
false
true
77620_0
import javax.swing.*; import java.awt.*; class App { private static void initWindow() { // create a window frame and set the title in the toolbar JFrame window = new JFrame("Alcohol Marble"); // when we close the window, stop the app window.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); // set container from window Container contentPane = window.getContentPane(); contentPane.setLayout(new GridLayout(1, 2)); // contentPane.setFocusable(true); // create the jpanel to draw on. // this also initializes the game loop Board board = new Board(); Board2 board2 = new Board2(); board2.setLayout(null); // add the jpanel to the contentpane contentPane.add(board); contentPane.add(board2); // don't allow the user to resize the window window.setResizable(false); // fit the window size around the components (just our jpanel). // pack() should be called after setResizable() to avoid issues on some // platforms window.pack(); // open window in the center of the screen window.setLocationRelativeTo(null); // display the window window.setVisible(true); } public static void main(String[] args) { // invokeLater() is used here to prevent our graphics processing from // blocking the GUI. https://stackoverflow.com/a/22534931/4655368 // this is a lot of boilerplate code that you shouldn't be too concerned about. // just know that when main runs it will call initWindow() once. SwingUtilities.invokeLater(new Runnable() { public void run() { initWindow(); } }); } }
chochita0311/alcohol-marble
App.java
402
// create a window frame and set the title in the toolbar
line_comment
en
false
368
12
402
12
425
12
402
12
469
12
false
false
false
false
false
true
77953_1
public class IslandMap extends Map { public IslandMap() { super(); } // Generates normal map then applies islandDistortion() public void generate(int seed) { super.generate(seed); islandDistortion(); } /** * Reduces the heights around the edge of the map by subtracting the square * of the distance from the center of the map. */ private void islandDistortion() { int halfSize = size / 2; float heightMultiplier = (float) Constants.ISLAND_GENERATION_STRENGTH / (size * size); for (int i = 0; i < size; i++) { for (int j = 0; j < size; j++) { int heightCorrection = (int) (Math.pow(i - halfSize, 2) + Math.pow(j - halfSize, 2)); int adjustedHeight = (int) (tiles[i][j].getHeight() - heightCorrection * heightMultiplier); tiles[i][j].setHeight((short)(Math.max(0, adjustedHeight))); } } } }
jaldridg/ProceduralGen
IslandMap.java
254
/** * Reduces the heights around the edge of the map by subtracting the square * of the distance from the center of the map. */
block_comment
en
false
236
33
254
34
268
33
254
34
301
37
false
false
false
false
false
true
78141_13
/** * Class represents SCARA robotic arm. * * @Arthur Roberts * @0.0 */ import ecs100.UI; import java.awt.Color; import java.util.*; public class Arm { // fixed arm parameters private int xm1; // coordinates of the motor(measured in pixels of the picture) private int ym1; private int xm2; private int ym2; private double r; // length of the upper/fore arm // parameters of servo motors - linear function pwm(angle) // each of two motors has unique function which should be measured // linear function cam be described by two points // motor 1, point1 private double pwm1_val_1; private double theta1_val_1; // motor 1, point 2 private double pwm1_val_2; private double theta1_val_2; // motor 2, point 1 private double pwm2_val_1; private double theta2_val_1; // motor 2, point 2 private double pwm2_val_2; private double theta2_val_2; // current state of the arm private double theta1; // angle of the upper arm private double theta2; private double xj1; // positions of the joints private double yj1; private double xj2; private double yj2; private double xt; // position of the tool private double yt; private boolean valid_state; // is state of the arm physically possible? /** * Constructor for objects of class Arm */ public Arm() { xm1 = 290; // set motor coordinates ym1 = 372; xm2 = 379; ym2 = 374; r = 156.0; theta1 = -90.0*Math.PI/180.0; // initial angles of the upper arms theta2 = -90.0*Math.PI/180.0; valid_state = false; } // draws arm on the canvas public void draw() { // draw arm int height = UI.getCanvasHeight(); int width = UI.getCanvasWidth(); // calculate joint positions xj1 = xm1 + r*Math.cos(theta1); yj1 = ym1 + r*Math.sin(theta1); xj2 = xm2 + r*Math.cos(theta2); yj2 = ym2 + r*Math.sin(theta2); pwm1_val_1 = -9.3 * ((theta1*180)/Math.PI) + 646.7; pwm1_val_2 = -10.4 * ((theta2*180)/Math.PI) + 717.6; //draw motors and write angles int mr = 20; UI.setLineWidth(5); UI.setColor(Color.BLUE); UI.drawOval(xm1-mr/2,ym1-mr/2,mr,mr); UI.drawOval(xm2-mr/2,ym2-mr/2,mr,mr); // write parameters of first motor String out_str=String.format("t1=%3.1f",theta1*180/Math.PI); UI.drawString(out_str, xm1-2*mr,ym1-mr/2+2*mr); out_str=String.format("xm1=%d",xm1); UI.drawString(out_str, xm1-2*mr,ym1-mr/2+3*mr); out_str=String.format("ym1=%d",ym1); UI.drawString(out_str, xm1-2*mr,ym1-mr/2+4*mr); out_str=(String)("vm1= " + (long)pwm1_val_1); UI.drawString(out_str, xm1-2*mr,ym1-mr/2+5*mr); // ditto for second motor out_str = String.format("t2=%3.1f",theta2*180/Math.PI); UI.drawString(out_str, xm2+2*mr,ym2-mr/2+2*mr); out_str=String.format("xm2=%d",xm2); UI.drawString(out_str, xm2+2*mr,ym2-mr/2+3*mr); out_str=String.format("ym2=%d",ym2); UI.drawString(out_str, xm2+2*mr,ym2-mr/2+4*mr); out_str=(String)("vm2= " + (long)pwm1_val_2); UI.drawString(out_str, xm2+2*mr,ym1-mr/2+5*mr); // draw Field Of View UI.setColor(Color.GRAY); UI.drawRect(0,0,640,480); //draw Estimated reach zone UI.setColor(Color.RED); UI.drawRect(230,100,200,150); // it can b euncommented later when // kinematic equations are derived if ( valid_state) { // draw upper arms UI.setColor(Color.GREEN); UI.drawLine(xm1,ym1,xj1,yj1); UI.drawLine(xm2,ym2,xj2,yj2); //draw forearms UI.drawLine(xj1,yj1,xt,yt); UI.drawLine(xj2,yj2,xt,yt); // draw tool double rt = 20; UI.drawOval(xt-rt/2,yt-rt/2,rt,rt); } } // calculate tool position from motor angles // updates variable in the class public void directKinematic(){ // midpoint between joints double xa = (xj1 + xj2) / 2; double ya = (yj1 + yj2) / 2; double la = Math.sqrt(Math.pow((xa - xj1),2) + Math.pow((ya - yj1),2)); // distance between joints double d = Math.sqrt( Math.pow( (xj2 - xj1),2) + Math.pow((yj2 - yj1),2)); if (d<2*r){ valid_state = true; // half distance between tool positions double h = Math.sqrt(Math.pow((r),2) - la); double alpha = Math.atan((yj1 - yj2) / (xj1 - xj2)); // tool position double xt = xa - h*Math.cos(Math.PI/2-alpha); double yt = ya - h*Math.sin(Math.PI/2-alpha); //xt2 = xa - h.*cos(alpha-pi/2); //yt2 = ya - h.*sin(alpha-pi/2); } else { valid_state = false; } } // motor angles from tool position // updetes variables of the class public void inverseKinematic(double xt_new,double yt_new){ valid_state = true; xt = xt_new; yt = yt_new; valid_state = true; double dx1 = xt - xm1; double dy1 = yt - ym1; // distance between pem and motor double d1 = Math.sqrt(dx1*dx1 + dy1*dy1); if (d1>2*r){ //UI.println("Arm 1 - can not reach"); valid_state = false; return; } double l1 = d1/2; double h1 = Math.sqrt(r*r - d1*d1/4); // elbows positions double alpha1 = Math.PI/2 - Math.PI + Math.atan2(yt-ym1,xt-xm1); xj1 = (xt+xm1)/2 + h1 * Math.cos(alpha1); yj1 = (yt+ym1)/2 + h1 * Math.sin(alpha1); theta1 = Math.atan2(yj1-ym1,xj1-xm1); if ((theta1>0)||(theta1<-Math.PI)){ valid_state = false; //UI.println("Ange 1 -invalid"); return; } double dx2 = xt - xm2; double dy2 = yt - ym2; double d2 = Math.sqrt(dx2*dx2 + dy2*dy2); if (d2>2*r){ // UI.println("Arm 2 - can not reach"); valid_state = false; return; } double l2 = d2/2; double h2 = Math.sqrt(r*r - d2*d2/4); // elbows positions double alpha2 = Math.PI/2 - Math.PI + Math.atan2(yt-ym2,xt-xm2); xj2 = (xt+xm2)/2 - h2 * Math.cos(alpha2); yj2 = (yt+ym2)/2 - h2 * Math.sin(alpha2); // motor angles for both 1st elbow positions theta2 = Math.atan2(yj2-ym2,xj2-xm2); if ((theta2>0)||(theta2<-Math.PI)){ valid_state = false; //UI.println("Ange 2 -invalid"); return; } //UI.printf("xt:%3.1f, yt:%3.1f\n",xt,yt); //UI.printf("theta1:%3.1f, theta2:%3.1f\n",theta1*180/Math.PI,theta2*180/Math.PI); return; } // returns angle of motor 1 public double get_theta1(){ return theta1; } // returns angle of motor 2 public double get_theta2(){ return theta2; } // sets angle of the motors public void set_angles(double t1, double t2){ theta1 = t1; theta2 = t2; } // returns motor control signal // for motor to be in position(angle) theta1 // linear intepolation public int get_pwm1(){ int pwm = 0; return pwm; } // ditto for motor 2 public int get_pwm2(){ int pwm =0; //pwm = (int)(pwm2_90 + (theta2 - 90)*pwm2_slope); return pwm; } }
jb567/SCARA-ARM
Arm.java
2,569
// positions of the joints
line_comment
en
false
2,362
5
2,569
6
2,688
5
2,569
6
2,952
6
false
false
false
false
false
true
78251_5
/* * Copyright (c) 2021 Daylam Tayari <[email protected]> * * This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License version 3as published by the Free Software Foundation. * * 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/ or write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. * * @author Daylam Tayari [email protected] https://github.com/daylamtayari * @version 1.0 * Github project home page: https://github.com/daylamtayari/Microsoft-To-Do-Export */ /** * List object class. */ public class Lists { private String listID; private String listName; /** * Constructor which initiates the lists object. */ public Lists(){} /** * Accessor for the listID variable. * @return String String value representing the ID of the list. */ public String getID(){ return listID; } /** * Accessor for the listName variable. * @return String String value representing the name of the list. */ public String getName(){ return listName; } /** * Mutator for the listID variable. * @param ID String value representing the ID of the list. */ public void setID(String ID){ listID=ID; } /** * Mutator for the listName variable. * @param name String value representing the name of the list. */ public void setName(String name){ listName=name; } }
daylamtayari/Microsoft-To-Do-Export
src/Lists.java
473
/** * Mutator for the listID variable. * @param ID String value representing the ID of the list. */
block_comment
en
false
440
28
473
28
498
31
473
28
552
31
false
false
false
false
false
true
78479_7
import greenfoot.*; // (World, Actor, GreenfootImage, Greenfoot and MouseInfo) /** * This is the goal class used for hit detection on the goal line. * * @author Liam Courtney * @version 1.1 */ public class Goal extends Actor { private int x; // Variables for drawing the goal line private int y; private int width; private int height; private GreenfootImage shapeImage; /** * This is the constructor for the Goal class. */ public Goal() { x = 0; // Setting the variables for drawing the goal line y = 0; width = 60; height = 5; shapeImage = new GreenfootImage(width, height); // Drawing the goal line in white over set dimensions shapeImage.setColor(Color.WHITE); shapeImage.drawRect(x, y, width-1,height-1); shapeImage.fill(); setImage(shapeImage); } /** * Act - do whatever the Goal wants to do. This method is called whenever * the 'Act' or 'Run' button gets pressed in the environment. */ public void act() { score(); } public void score() // Checks if the kicked ball interacts with the goal line and if so removes it and adds 1 to the score { Actor ball = getOneIntersectingObject(KickedBall.class); Pitch world = (Pitch) getWorld(); Score score = world.getScore(); if (ball != null) { world.removeObject(ball); score.addScore(1); } } }
LiamCourtney67/GoalOrNoGoal
Goal.java
378
// Checks if the kicked ball interacts with the goal line and if so removes it and adds 1 to the score
line_comment
en
false
359
23
378
25
424
23
378
25
448
26
false
false
false
false
false
true
78881_6
import java.io.Serializable; import java.util.Calendar; import java.util.GregorianCalendar; import java.util.Date; public class Account implements Serializable { private static final long serialVersionUID = 1L; private String name; private String url; private StandardPassword password; public static void main(String[] args) { // test class Account acct = new Account("testAcct", "www.google.com", "testPassword1"); // should print "testPassword1" System.out.println(acct.getPassword()); // should print "testAcct" System.out.println(acct.getName()); // should print "www.google.com" System.out.println(acct.getURL()); // test generatePassword acct.generatePass(15); System.out.println(acct.getPassword()); // set name to "testName" then print acct.setName("testName"); System.out.println(acct.getName()); // set password to "testPass" then print acct.setPassword("testPass"); System.out.println(acct.getPassword()); // set url to "www.test.com" then print acct.setURL("www.test.com"); System.out.println(acct.getURL()); // test checkPassAge acct.checkPassAge(); } // end main public Account(String name, String url, String pass) { this.name = name; this.url = url; this.password = new StandardPassword(pass); } // end constructor public void setName(String name) { this.name = name; } // end setName public void setURL(String url) { this.url = url; } // end setURL public void setPassword(String newPass) { this.password.setPassword(newPass); } // end setPassword public String getName() { return this.name; } // end getName public String getURL() { return this.url; } // end getURL public String getPassword() { return this.password.getPassword(); } // end getPassword public void generatePass(int length) { this.password.generatePass(length); } // end generatePass public void checkPassAge() { Calendar dateSet = new GregorianCalendar(); dateSet.setTime(this.password.getDate()); Calendar today = new GregorianCalendar(); today.setTime(new Date()); int yearsDiff = today.get(Calendar.YEAR) - dateSet.get(Calendar.YEAR); int monthsDiff = today.get(Calendar.MONTH) - dateSet.get(Calendar.MONTH); long diffInMonths = yearsDiff * 12 + monthsDiff; if (diffInMonths >= 6) { System.out.println("The password for " + this.name + " is over 6 months old"); System.out.println("It is recommended to change your password every 6 months"); } // end if } // end checkPassAge } // end class
mmammel12/basic_password_manager
Account.java
696
// set password to "testPass" then print
line_comment
en
false
606
10
696
10
746
10
696
10
818
10
false
false
false
false
false
true
79762_1
import java.util.ArrayList; import java.util.List; public class Q2 { public static void main(String[] args) { String result = ""; for (String substring : getFourChars("Lorem at'", 4)) { String reversed = reverseString(substring); result += reversed; } System.out.println(result); } // grouping array into groups of 4 characters private static List<String> getFourChars(String S, int groupSize) { List<String> group = new ArrayList<String>(); int count = S.length(); for (int i = 0; i < count; i += groupSize) { group.add(S.substring(i, Math.min(count, i + groupSize))); } return group; } // reversing substring parts public static String reverseString(String S) { char[] chars = S.toCharArray(); int H = S.length() / 2; int L = S.length() - 1; for (int j = 0; j < H; j++) { char temp = chars[j]; chars[j] = chars[L - j]; chars[L - j] = temp; } return new String(chars); } }
sylumx/Assignment-Answers
Q2.java
293
// reversing substring parts
line_comment
en
false
258
5
293
7
327
5
293
7
344
6
false
false
false
false
false
true
80008_2
import java.util.Arrays; import java.util.Random; //implementation of comb sort which is an optimised version of bubble sort //bubble sort compares two elements which are adjacent, which means that a gap bw two elements is 1 //comb sort looks at bigger gaps and iteratively changes the gap by shrink factor k //in such a way turtles are eliminated early on (smaller elements which are positioned at the end of the list) public class combSort { public static void main(String [] args) { int listSize = 10; int ar[]=new int[listSize]; Random rand = new Random(); for(int i=0;i<ar.length;i++) { ar[i]=rand.nextInt(100); } System.out.println(Arrays.toString(ar)); boolean changed=true; int gap=ar.length; double shrink = 1.3; int dummy; while(changed) { gap=(int) Math.floor(gap/shrink); if (gap <= 1) { gap=1; changed=false; } int k=0; while(gap+k<ar.length) { if(ar[k]>ar[gap+k]) { dummy=ar[k]; ar[k]=ar[gap+k]; ar[gap+k]=dummy; } k+=1; } } System.out.println(Arrays.toString(ar)); } }
KateKapranova/CodeSamples
combSort.java
384
//comb sort looks at bigger gaps and iteratively changes the gap by shrink factor k
line_comment
en
false
314
18
384
19
395
18
384
19
495
20
false
false
false
false
false
true
80350_8
import java.util.ArrayDeque; import java.util.Collections; import java.util.LinkedList; import java.util.List; /** * Class for running Breadth-First Search on a given graph as well as computing the shortest path * between two nodes of that graph. The paths are represented as lists of integers corresponding * to nodes. */ public final class BFS { /** * An implementation of the BFS algorithm * @param g, the graph to run BFS on * @param src, the start/source node * @param result, the list nodes in the order visited * @param marked, an array showing which nodes have been marked/discovered * @param parent, an array showing the parent of each node * @param frontiers, an array where each index contains the frontier that that index/node is in * @return the list of nodes visited in the BFS order * @throws IllegalArgumentException if src is not in the graph * @throws IllegalArgumentException if the specified graph is null */ public static List<Integer> bfsImpl(Graph g, int src, List<Integer> result, boolean[] marked, Integer[] parent, int[] frontiers) { // null graph case if (g == null) { throw new IllegalArgumentException("Graph can't be null"); } // source not present in graph case if (src > g.getSize() - 1 || src < 0) { throw new IllegalArgumentException("" + src + " is not present in the graph"); } // BFS algorithm ArrayDeque<Integer> q = new ArrayDeque<Integer>(); marked[src] = true; q.addLast(src); parent[src] = src; while (q.size() != 0) { int v = q.pollFirst(); result.add(v); for (int w : g.getNeighbors(v)) { if (!marked[w]) { frontiers[w] = frontiers[v] + 1; parent[w] = v; marked[w] = true; q.addLast(w); } } } // check if all nodes have been marked/discovered for (int i = 0; i < marked.length; i++) { if (!marked[i]) { return bfsImpl(g, i, result, marked, parent, frontiers); } } return result; } /** * A method for checking whether there exists a path between two given nodes * @param g, the graph to run BFS on * @param src, the start/source node * @param tgt, the target node * @param parent, an array showing the parent of each node * @return true if there exists a path and false otherwise * @throws IllegalArgumentException if src or the tgt is not in the graph * @throws IllegalArgumentException if the specified graph is null */ public static boolean bfsPath(Graph g, int src, int tgt, Integer[] parent) { // null graph case if (g == null) { throw new IllegalArgumentException("Graph can't be null"); } // source not present in graph case if (src > g.getSize() - 1 || src < 0) { throw new IllegalArgumentException("" + src + " is not present in the graph"); } // target not present in graph case if (tgt > g.getSize() - 1 || tgt < 0) { throw new IllegalArgumentException("" + tgt + " is not present in the graph"); } // BFS algorithm ArrayDeque<Integer> q = new ArrayDeque<Integer>(); boolean[] marked = new boolean[g.getSize()]; marked[src] = true; // variable used to check if the target has been found boolean found = false; q.addLast(src); parent[src] = src; while (q.size() != 0) { int v = q.pollFirst(); for (int w : g.getNeighbors(v)) { if (!marked[w]) { parent[w] = v; marked[w] = true; q.addLast(w); if (w == tgt) { found = true; break; } } } if (found) { break; } } return found; } /** * Method for checking whether whether a graph is connected or not * @param g, the input graph * @param src, the start/source node * @return true if the graph is connected and false otherwise * @throws IllegalArgumentException if src is not in the graph * @throws IllegalArgumentException if the specified graph is null */ public static boolean isConnected(Graph g, int src) { // null graph case if (g == null) { throw new IllegalArgumentException("Graph can't be null"); } // source not present in graph case if (src > g.getSize() - 1 || src < 0) { throw new IllegalArgumentException("" + src + " is not present in the graph"); } // BFS algorithm ArrayDeque<Integer> q = new ArrayDeque<Integer>(); boolean[] marked = new boolean[g.getSize()]; Integer[] parent = new Integer[g.getSize()]; marked[src] = true; q.addLast(src); parent[src] = src; while (q.size() != 0) { int v = q.pollFirst(); for (int w : g.getNeighbors(v)) { if (!marked[w]) { parent[w] = v; marked[w] = true; q.addLast(w); } } } // check if there are unmarked/undiscovered nodes for (int i = 0; i < marked.length; i++) { if (!marked[i]) { return false; } } return true; } /** * Returns a shortest path from the src to tgt by executing a breadth-first search. * If there are multiple shortest paths, this method returns any one of them. * @param g the graph * @param src the node from which to search * @param tgt the node to find via {@code src} * @return a list of nodes of the shortest path from src to tgt, or an * empty list if there is no path from src to tgt. * @throws IllegalArgumentException if src and/or tgt is not in the graph * @throws IllegalArgumentException if the specified graph is null */ public static List<Integer> getShortestPath(Graph g, int src, int tgt) { // null graph case if (g == null) { throw new IllegalArgumentException("Graph can't be null"); } // source not present in graph case if (src > g.getSize() - 1 || src < 0) { throw new IllegalArgumentException("" + src + " is not present in the graph"); } // target not present in graph case if (tgt > g.getSize() - 1 || tgt < 0) { throw new IllegalArgumentException("" + tgt + " is not present in the graph"); } // source is the same as target case if (src == tgt) { LinkedList<Integer> path = new LinkedList<Integer>(); path.add(src); return Collections.unmodifiableList(path); } LinkedList<Integer> path = new LinkedList<Integer>(); Integer[] parent = new Integer[g.getSize()]; // create the shortest path if (bfsPath(g, src, tgt, parent)) { int curr = tgt; path.addFirst(tgt); while (curr != src) { path.addFirst(parent[curr]); curr = parent[curr]; } return Collections.unmodifiableList(path); } else { return Collections.unmodifiableList(path); } } }
Neilshweky/HW5_PageRank
BFS.java
1,755
// source not present in graph case
line_comment
en
false
1,694
7
1,755
7
1,980
7
1,755
7
2,157
7
false
false
false
false
false
true
80384_0
public class Main { public static void main(String args[]) { Main main = new Main(); int arr[] = {2, 4, 7, 10, 11, 45, 50, 59, 60, 66, 69, 70, 79}; int result = main.binarySearch(arr, 11); if (result == -1) System.out.println("Element not present"); else System.out.println("Element found at index " + result); } public static int binarySearch(int [] list, int key) { int low = 0, high = list.length - 1; while (high >= low) { int mid = (low + high) / 2; if (key < list[mid]) high = mid - 1; else if (key == list[mid]) return mid; else low = mid + 1; } return -low - 1; // Key not found, cause high < low } }
yelmuratoff/ADS_java
8.2.java
246
// Key not found, cause high < low
line_comment
en
false
235
9
246
9
268
9
246
9
271
9
false
false
false
false
false
true
80782_0
/* Takes all of the information that user has and saves it onto a new textfile to be accessed again at a later date @author Nhi Ngo @version 06/16/2014 */ import java.util.*; import java.io.*; public class Save { private ArrayList<Class> classes; private ArrayList<String> names; private int quarter; private PrintWriter out; private Scanner scanData; private File savedData; /*Initializes instance fields*/ public Save(ArrayList<Class> classes, ArrayList<String> names, int quarter)throws IOException{ this.classes = classes; this.names = names; this.quarter = quarter; savedData = new File("savedData.txt"); scanData = new Scanner(savedData); out = new PrintWriter(savedData); print(); } /*Sends out all of the user's information into the new text document*/ private void print(){ for (int i = 0; i < names.size(); i++) { out.print(names.get(i) + " "); } out.println(" " + quarter); for (int i = 0; i < classes.size(); i++) { out.print(classes.get(i).getName() + " "); out.print(classes.get(i).getTeacher() + " "); out.print(classes.get(i).getTime() + " "); } out.close(); } }
rooseveltcs/personal-secretary
Save.java
340
/* Takes all of the information that user has and saves it onto a new textfile to be accessed again at a later date @author Nhi Ngo @version 06/16/2014 */
block_comment
en
false
297
46
340
52
368
48
340
52
381
52
false
false
false
false
false
true
82166_23
package edu.uwec.cs.stevende.rsa; // See associated word document on assignment for details of this algorithm // This is the version without any BigIntegers public class RSA { public static void main(String[] args) { //****************************************************************************** // Find P and Q //****************************************************************************** // Generate 2 random numbers, P and Q with the following properties: // 1. P and Q can be at most bitLength/2 bits long // 2. P and Q cannot be 0 or 1 // --> The above 2 constraints imply that P and Q are in the range [2..2^(bitLength/2)) // 3. P and Q must be primes // 4. P and Q cannot be the same number // 5. (PQ) must be at least 256 // Init P and Q so that (P * Q) is < 256 so the loop will run at least once long p = 0; long q = 0; // The number of bits we want P and Q to contain long bitLength = 15; long power = bitLength / 2; // Keep picking random P and Q until they are different and their product is >= 256 while ((p == q) || ((p * q) < 256)) { // Pick P double rand = Math.random(); // Get a random double in the range [0.0 ... 1.0) p = (long) (rand * Math.pow(2, power)); // Change the range to [0..2^power) boolean foundP = false; // Init the loop control so the loop will run at least once while (!foundP) { // Find out if the number is prime // This code considers 0 and 1 to not be prime which is perfect // since we don't want to include these anyway long i = 2; // Run from 2 up to, but not including, sqrt(P) while ((i < Math.sqrt(p)) && ((p % i) != 0)) { i++; } // If we made it all the way to P then it is prime because nothing divided it evenly if ((i >= Math.sqrt(p))) { foundP = true; } else { // We stoped early since something divided P evenly OR P was 0 or 1 // Generate a new canidate P rand = Math.random(); p = (long) (rand * Math.pow(2, power)); } } // Repeat the process for Q rand = Math.random(); // Get a random double in the range [0.0 ... 1.0) q = (long) (rand * Math.pow(2, power)); // Change the range to [0..128) boolean foundQ = false; while (!foundQ) { // Find out if the number is prime // This code considers 0 and 1 to not be prime which is perfect // since we don't want to include these anyway long i = 2; // Run from 2 up to, but not including, sqrt(Q) while ((i < Math.sqrt(q)) && ((q % i) != 0)) { i++; } // If we made it all the way to Q then it is prime because nothing divided it evenly if ((i >= Math.sqrt(q))) { foundQ = true; } else { // We stoped early since something divided Q evenly OR Q was 0 or 1 // Generate a new canidate Q rand = Math.random(); q = (long) (rand * Math.pow(2, power)); } } } // End of while loop testing to make sure P!=Q and (P*Q) >= 256 //****************************************************************************** // Find PQ and phiPQ //****************************************************************************** long pq = p * q; long phiPQ = (p - 1) * (q - 1); //****************************************************************************** // Find E //****************************************************************************** // Generate an E with the following properties: // 1. 1 < E < phiPQ // 2. E and phiPQ are relatively prime // --> the above constraint implies that gcd(E, phiPQ) == 1 // 3. There may be several candidates for E, so pick the smallest one (for consistency // with the rest of the class -- there is no theoretical reason for this constraint) long e = 2; // We will start at 2 and work our way up until we find an E that meets the constraints boolean foundE = false; while (!foundE) { // The following perform a standard GCD calculation -- Euclid's algorithm // Set the initial values of a and b to phiPQ and our current canidate for E long a = phiPQ; long b = e; long r = 1; // Initial starting value so we go through the loop at least once while (r != 0) { // When r reaches 0 then the gcd is the b value // Put the bigger of a and b into a and the smaller into b if (a < b) { // Swap them if they are in the wrong order long temp = a; a = b; b = temp; } r = a % b; // Compute the remainder of the bigger / smaller a = r; // Replace a with the remainder -- b stays the same } // Recall the gcd is stored in b at this point if (b == 1) { // We are done if the gcd was 1 foundE = true; } else { // Keep looking for an E value that works e++; } } //****************************************************************************** // Find D //****************************************************************************** // Generate D with the following properties: // 1. 0 < D <= PQ // 2. (DE-1) is evenly divisible by phiPQ // --> That is count up for D until we find a (DE-1)%phiPQ that equals 0 long d = 1; // Init to the starting range of possible D values // Keep looking until we find a D value that fits the constraints above while ((((d * e) - 1) % phiPQ) != 0) { d++; } //****************************************************************************** // Display results of P, Q, E, D to screen //****************************************************************************** System.out.println("P:" + p); System.out.println("Q:" + q); System.out.println("PQ:" + pq); System.out.println("phiPQ:" + phiPQ); System.out.println("E:" + e); System.out.println("D:" + d); //****************************************************************************** // Encrypt the messsage using only the public key (E, PQ) //****************************************************************************** // This part needs a plainTextMessage as well as the public key, (E, PQ) String plainTextMessage = "Hello World"; long[] cipherTextMessage = new long[plainTextMessage.length()]; // Encrypt each character of the message, one at a time for (int i = 0; i < plainTextMessage.length(); i++) { // Get the current character to encode and obtain its unicode (int) value // Note that the assumption we made above was that this unicode value was really // just an ASCII value (i.e. in the range 0..255). char currentCharacter = plainTextMessage.charAt(i); int unicodeValue = (int) currentCharacter; // Compute (unicodeValue ^ E) mod (PQ) // This causes us some problems because if we perform ^E first it will blow the // top off the int range (the long range as well) even for small E. So we either // need to use BigIntegers (we don't use this in this version) or we need to // use another method that combines the power and mod together so we don't blow // the top off the range. long tempE = e; long cipherValue = 1; while (tempE > 0) { // If E is odd if ( (tempE % 2) == 1 ) { cipherValue *= unicodeValue; cipherValue %= pq; } tempE /= 2; // Integer division unicodeValue *= unicodeValue; unicodeValue %= pq; } // Now save the cipher value -- we can't stick this into a String because the numbers // may be larger than what String chars can hold (unless we only used 7 bits for P and Q) cipherTextMessage[i] = cipherValue; } // At this point cipherTextMessage contains the encoded message //****************************************************************************** // Decrypt the cipher using only the private key (D, PQ) //****************************************************************************** // To decode we need this cipherTextMessage as well as the private key, (d, n) String decodedTextMessage = ""; // Encrypt each character of the message, one at a time for (int i = 0; i < cipherTextMessage.length; i++) { // Get the current character to encode and obtain its unicode (int) value long cipherValue = cipherTextMessage[i]; // Compute (cipherValue ^ D) mod (PQ) // Again this is a problem with blowing the top off the range so we do the same // thing as above. long tempD = d; long decodedValue = 1; while (tempD > 0) { // If D is odd if ( (tempD % 2) == 1 ) { decodedValue *= cipherValue; decodedValue %= pq; } tempD /= 2; // Integer division cipherValue *= cipherValue; cipherValue %= pq; } // And then pretend the int is a unicode character and produce a char from it to add to our cipher string char decodedCharacter = (char) decodedValue; decodedTextMessage += decodedCharacter; } // At this point the decoded message is in decodedTextMessage System.out.println(decodedTextMessage); System.exit(0); // To make sure we shut down } }
cjtrojan3/RSA
RSA.java
2,491
// If we made it all the way to P then it is prime because nothing divided it evenly
line_comment
en
false
2,438
19
2,491
20
2,525
19
2,491
20
3,127
20
false
false
false
false
false
true
82269_2
import java.sql.Connection; import java.sql.DriverManager; import java.sql.ResultSet; import java.sql.SQLException; import java.sql.Statement; import java.util.ArrayList; import java.util.List; import java.util.logging.Level; import java.util.logging.Logger; import java.io.BufferedReader; import java.io.FileReader; import java.io.IOException; /** * Write a description of class LocalInfo here. * * @author Muhammed Keeka * @version 2024.02.28 */ public class LocalInfo { private Connection conn = null; /** * Constructor for objects of class LocalInfo */ public LocalInfo() { try { Class.forName("org.sqlite.JDBC");//Specify the SQLite Java driver conn = DriverManager.getConnection("jdbc:sqlite:localInfo.db");//Specify the database, since relative in the main project folder conn.setAutoCommit(false);// Important as I want control of when data is written } catch(Exception e) { System.err.println(e.getClass().getName() + ": " + e.getMessage()); System.exit(0); } } private void execute(String query) { Statement stmt; try { stmt = conn.createStatement(); stmt.executeUpdate(query); stmt.close(); conn.commit(); } catch (SQLException e) { System.err.println(e.getClass().getName() + ": " + e.getMessage()); } } public List<RecyclingCentre> getDetailsofNearbyCentres(String[] postcodes) {//Executes the statement below and returns a single integer, of the field specified. This seems like an odd method but is useful when operating queries such as COUNT. String query = "SELECT * FROM RecyclingCentres WHERE postcode = '" + postcodes[0] + "'"; for(int i = 1; i < postcodes.length; i++) { query += " OR postcode = '" + postcodes[i] + "'"; } query += ";"; Statement stmt; ResultSet rs; List<RecyclingCentre> centreList = new ArrayList<RecyclingCentre>(); try { stmt = conn.createStatement(); rs = stmt.executeQuery(query); while(rs.next()) { centreList.add(new RecyclingCentre(rs.getString("Name"), rs.getInt("StreetNo"), rs.getString("StreetName"), rs.getString("Town"), rs.getString("Postcode"))); } rs.close(); stmt.close(); } catch (SQLException e) { System.err.println(e.getClass().getName() + ": " + e.getMessage()); } return centreList; } public void addCentres(RecyclingCentre[] centres) { for(RecyclingCentre centre : centres) { addCentre(centre); } } public void addCentre(RecyclingCentre centre) { execute("INSERT INTO RecyclingCentres VALUES ('" + centre.getName() + "', '" + centre.getStreetNo() + "', '" + centre.getStreetName() + "', '" + centre.getTown() + "', '" + centre.getPostcode() + "');"); } public void removeCentre(RecyclingCentre centre) { execute("DELETE FROM RecyclingCentres WHERE StreetNo = '" + centre.getStreetNo() + "' AND Postcode = '" + centre.getPostcode() + "';"); } public void importFromCSV(String filePath) { String line = ""; try (BufferedReader br = new BufferedReader(new FileReader(filePath))) { while ((line = br.readLine()) != null) { String[] data = line.split(","); addCentre(new RecyclingCentre(data[0], Integer.parseInt(data[1]), data[2], data[3], data[4])); } } catch (IOException e) { e.printStackTrace(); } } public void close() {//Closes the connection to the database try { conn.close(); } catch (SQLException ex) { Logger.getLogger(LocalInfo.class.getName()).log(Level.SEVERE, null, ex); } } }
mkeeka/Waste-Management-and-Education-App
LocalInfo.java
986
//Specify the SQLite Java driver
line_comment
en
false
857
6
986
6
1,053
6
986
6
1,180
7
false
false
false
false
false
true
82299_1
enum RelPos {LEFT, TOP, RIGHT} public class TreeLeaf { /* * Represents an oval leaf on the random tree * May recursively contain other leaves * This object is immutable and does not modify global state * It is thread-safe once created */ public final int depth; // Stores whether the leaf was positioned on any of the // tree's extremities upon creation. public final boolean isLeftMost; public final boolean isRightMost; public final boolean isCentre; //Each leaf may have up to three child leaves. public final TreeLeaf leftLeaf; public final TreeLeaf topLeaf; public final TreeLeaf rightLeaf; // Pixel coordinates on the screen public final int xPos; public final int yPos; public final int xRadius; public final int yRadius; public final int red; public final int green; public final int blue; /* This constructor is only meant to be called on the first leaf. * It will then recursively create all other leaves in the tree. */ public TreeLeaf () { depth = 0; xRadius = RandomTree.defaultCircleRadius; yRadius = RandomTree.defaultCircleRadius; xPos = RandomTree.screenWidth / 2; yPos = RandomTree.screenHeight - RandomTree.defaultCircleRadius; red = 128; green = 0; blue = 0; isRightMost = true; isLeftMost= true; isCentre = true; if (depth < RandomTree.MAX_DEPTH) { leftLeaf = new TreeLeaf(this, RelPos.LEFT); topLeaf = new TreeLeaf(this, RelPos.TOP); rightLeaf = new TreeLeaf(this, RelPos.RIGHT); } else { leftLeaf = null; topLeaf = null; rightLeaf = null; } } private TreeLeaf (TreeLeaf parent, RelPos relPos) { xRadius = (int)Math.round(parent.xRadius * getBiasedRandom(50)); yRadius = (int)Math.round(parent.xRadius * getBiasedRandom(50)); red = parent.red + 4; green = parent.green + 7; blue = parent.blue + 5; // // // //Sets the position of TreeLeaf adjacent to its parent. xPos = (relPos == RelPos.RIGHT) ? parent.xPos + xRadius / 2 + parent.xRadius / 2 : (relPos == RelPos.LEFT) ? parent.xPos - xRadius / 2 - parent.xRadius / 2 : parent.xPos; yPos = ((relPos == RelPos.TOP) ? parent.yPos - yRadius / 2 - parent.yRadius / 2 : parent.yPos); depth = parent.depth + 1; //Ensures that leaves only create new leaves on the edges isLeftMost = (relPos == RelPos.LEFT || relPos == RelPos.TOP) ? parent.isLeftMost : false; isRightMost = (relPos == RelPos.RIGHT || relPos == RelPos.TOP) ? parent.isRightMost : false; isCentre = (relPos == RelPos.TOP) ? parent.isCentre : false; //If the circle is off screen, don't give it any more children if (depth > RandomTree.MAX_DEPTH || xPos < 0 || xPos > RandomTree.screenWidth || yPos < 0 || yPos > RandomTree.screenHeight ) { leftLeaf = null; topLeaf = null; rightLeaf = null; } else { leftLeaf = isLeftMost ? new TreeLeaf(this, RelPos.LEFT) : null; topLeaf = isCentre ? new TreeLeaf(this, RelPos.TOP) : null; rightLeaf = isRightMost ? new TreeLeaf(this, RelPos.RIGHT) : null; } } public int getLeafCount() { int count = 1; count += leftLeaf != null ? leftLeaf.getLeafCount() : 0; count += topLeaf != null ? topLeaf.getLeafCount() : 0; count += rightLeaf != null ? rightLeaf.getLeafCount() : 0; return count; } // Returns a pseudorandom number biased towards the middle // Higher input int means heavier bias public static double getBiasedRandom(int n) { double sum = 0; int i = n; while (i > 0) { sum = sum + Math.random(); i--; } return sum * 2 / n; } }
MortenLohne/Circle-Tree
TreeLeaf.java
1,156
// Stores whether the leaf was positioned on any of the
line_comment
en
false
1,025
12
1,156
13
1,191
12
1,156
13
1,390
14
false
false
false
false
false
true
82554_2
import java.util.*; public class DFStest { //get child from source //visit child //iteratively visit every child //visit every child's child until all no further depth //go up one level, set children unvisited, set old source as visited, go to next source LinkedList<LinkedList<Node>> graph = new LinkedList<LinkedList<Node>>(); ArrayList<Stack<Integer>> paths = new ArrayList<Stack<Integer>>(100); ArrayList<ArrayList<Integer>> pathData = new ArrayList<ArrayList<Integer>>(100); ArrayList<Boolean> visited = new ArrayList<>(); int source = -1; int destination = -1; int currentPath = 0; int currentListIndex = -1; int[] fastestPaths = new int[3]; int[] cheapestPaths = new int[3]; public DFStest(LinkedList<LinkedList<Node>> intputGraph, int inputSource, int inputDestination) { this.graph = intputGraph; this.source = inputSource; this.destination = inputDestination; this.currentListIndex = source; searchPaths(); } public ArrayList<Stack<Integer>> sortPaths(int timeCost) { int[] fastestTimes = {Integer.MAX_VALUE, Integer.MAX_VALUE, Integer.MAX_VALUE}; int[] cheapestCost = {Integer.MAX_VALUE, Integer.MAX_VALUE, Integer.MAX_VALUE}; int[] fastestIndeces = new int[3]; int[] cheapestIndeces = new int[3]; ArrayList<Stack<Integer>> fastestArrays = new ArrayList<>(); ArrayList<Stack<Integer>> cheapestArrays = new ArrayList<>(); //storing the value and index of the highest values so that I dont replace the second highest or smallest elemen and potentially not finishing with 3 shortest paths //highest time, index, expensive cost, index int highesttimeIndex = 2; int highestpriceIndex = 2; //getting fastest/cheapest index for(int index = 0; index < pathData.size(); index++){ boolean sameTime = false, sameCost = false; if(pathData.get(index).get(0) > 0){ for(int j = 0; j < 3; j++){ if(pathData.get(index).get(0) == fastestTimes[j]){ sameTime = true; break; } } if(!sameTime) { //if lower than one of the elements put into top 3 array if(pathData.get(index).get(0) < fastestTimes[highesttimeIndex]){ fastestTimes[highesttimeIndex] = pathData.get(index).get(0); fastestIndeces[highesttimeIndex] = index; //find the new highest element so we can setup for next replacement for(int k = 0; k < fastestTimes.length; k++){ if(fastestTimes[k] > fastestTimes[highesttimeIndex]){ highesttimeIndex = k; } } } } for(int j = 0; j < 3; j++){ if(pathData.get(index).get(1) == cheapestCost[j]){ sameCost = true; break; } } if(!sameCost) { if(pathData.get(index).get(1) < cheapestCost[highestpriceIndex]){ cheapestCost[highestpriceIndex] = pathData.get(index).get(1); cheapestIndeces[highesttimeIndex] = index; for(int k = 0; k < cheapestCost.length; k++){ if(cheapestCost[k] > cheapestCost[highestpriceIndex]){ highestpriceIndex = k; } } } } } //System.out.println("fastest: " + Arrays.toString(fastestTimes)); //System.out.print("fastest times: " + Arrays.toString(fastestTimes) + ", cheapest: " + Arrays.toString(cheapestCost)); //System.out.println(", indeces: " + Arrays.toString(fastestIndeces) + " path third fastest: " + paths.get(fastestIndeces[1])); } //getting fastest/cheapest paths for(int i = 0; i < 3; i++){ //System.out.println("path size: " + paths.get(fastestIndeces[i]).size() + "fastest: " + Arrays.toString(fastestTimes)); fastestArrays.add(paths.get(fastestIndeces[i])); cheapestArrays.add(paths.get(cheapestIndeces[i])); } if(timeCost == 0){ setFastestIndeces(fastestIndeces); return fastestArrays; } else { setCheapestIndeces(cheapestIndeces); return cheapestArrays; } } private void setFastestIndeces(int[] fastestIndeces){ this.fastestPaths = fastestIndeces; } private void setCheapestIndeces(int[] cheapestIndeces){ this.cheapestPaths = cheapestIndeces; } public int[] getFastestPaths(){ int tempValue = 0; for(int i =0; i < fastestPaths.length; i++){ for(int j = 0; j < 3; j++){ if(pathData.get(fastestPaths[j]).get(0) > pathData.get(fastestPaths[i]).get(0)){ tempValue = fastestPaths[i]; fastestPaths[i] = fastestPaths[j]; fastestPaths[j] = tempValue; } } } return fastestPaths; } public int[] getCheapestPaths(){ int tempValue = 0; for(int i =0; i < cheapestPaths.length; i++){ for(int j = 0; j < 3; j++){ if(pathData.get(cheapestPaths[j]).get(1) > pathData.get(cheapestPaths[i]).get(1)){ tempValue = cheapestPaths[i]; cheapestPaths[i] = cheapestPaths[j]; cheapestPaths[j] = tempValue; } } } return cheapestPaths; } //getting every path from the source to the destination node public void searchPaths() { //initialize values Stack<Integer> sourceInitializer = new Stack<>(); sourceInitializer.push(source); //initializing lists with dummy values for (int i = 0; i < (100); i++) { ArrayList<Integer> tempArray = new ArrayList<>(); tempArray.add(0); tempArray.add(0); pathData.add(tempArray); paths.add(i, sourceInitializer); visited.add(false); } //initialize path with source Stack<Integer> tempStack = new Stack<>(); tempStack.push(source); boolean visitedAllSourceChildren = false; int lastTimeAdded = 0, lastCostAdded = 0; //search for connection to destination while (!tempStack.isEmpty()) { //to check when we need to backtrack, will be set to false when there is an available child boolean everythingVisited = true; for (int city = 0; city < graph.get(currentListIndex).size(); city++) { int graphIndex = graph.get(currentListIndex).get(city).cityIndex; //if the city has a connection to destination add to path structure if (graphIndex == destination) { //adding destination tempStack.push(graphIndex); //creating temp stack and adding path to arraylist Stack<Integer> newPathStack = new Stack<>(); newPathStack.addAll(tempStack); paths.set(currentPath, newPathStack); ArrayList<Integer> tempArray2 = new ArrayList<>(); tempArray2.clear(); tempArray2.add(pathData.get(currentPath).get(0)); tempArray2.add(pathData.get(currentPath).get(1)); //System.out.print("firstpath: " + currentPath + "current time: " + tempArray2.get(0)); //increment time and cost values with destination ArrayList<Integer> tempArray = new ArrayList<>(); tempArray.add(pathData.get(currentPath).get(0) + graph.get(currentListIndex).get(city).timeToTravel); tempArray.add(pathData.get(currentPath).get(1) + graph.get(currentListIndex).get(city).cost); pathData.set(currentPath, tempArray); //System.out.println("\ntempStack: " + tempStack + ", path: " + currentPath + "\tadding: " + graph.get(currentListIndex).get(city).timeToTravel + ", total: " + pathData.get(currentPath)); //System.out.print //next path this.currentPath++; //setting next path to the data of previous without the destination pathData.set(currentPath, tempArray2); tempStack.pop(); continue; } //if haven't visited the child yet, add it to the stack and move deeper if (!graph.get(currentListIndex).get(city).visited && !tempStack.contains(graphIndex)) { //System.out.print(" nodest path: " + tempStack + " time: " + pathData.get(currentPath).get(0)); //increment time and cost values ArrayList<Integer> tempArray = new ArrayList<>(); tempArray.add(pathData.get(currentPath).get(0) + graph.get(currentListIndex).get(city).timeToTravel); tempArray.add(pathData.get(currentPath).get(1) + graph.get(currentListIndex).get(city).cost); //System.out.println(", adding: " + graph.get(currentListIndex).get(city).timeToTravel + ", current lo: " + currentListIndex + ", dest: " + graphIndex); pathData.set(currentPath, tempArray); lastTimeAdded = graph.get(currentListIndex).get(city).timeToTravel; lastCostAdded = graph.get(currentListIndex).get(city).cost; everythingVisited = false; graph.get(currentListIndex).get(city).visited = true; tempStack.push(graphIndex); currentListIndex = graphIndex; break; } } //backtracking if (everythingVisited) { //System.out.print("path current: " + tempStack); int previousTop = tempStack.pop(); if(tempStack.isEmpty()){ break;} int currentTop = tempStack.peek(); //System.out.println(", previous: " + previousTop +"\t currentTop: " + currentTop); for(Node child : graph.get(currentTop)){ if(child.cityIndex == previousTop){ //decrement time and cost values ArrayList<Integer> tempArray = new ArrayList<>(); tempArray.add(pathData.get(currentPath).get(0) - lastTimeAdded); tempArray.add(pathData.get(currentPath).get(1) - lastCostAdded); //System.out.println("current time: " + pathData.get(currentPath).get(0) + "\tsubtracting: " + child.timeToTravel); pathData.set(currentPath, tempArray); } } currentListIndex = currentTop; //update previous time/cost added int temppop = tempStack.pop(); boolean skipForLoop = false; if(tempStack.isEmpty()){ lastTimeAdded = 0; lastCostAdded = 0; skipForLoop = true; } if(!skipForLoop){ for(int i = 0; i < graph.get(tempStack.peek()).size(); i++){ if(graph.get(tempStack.peek()).get(i).cityIndex == temppop){ lastTimeAdded = graph.get(tempStack.peek()).get(i).timeToTravel; lastCostAdded = graph.get(tempStack.peek()).get(i).cost; break; } } } tempStack.push(temppop); } } } }
cjpalmer330/DSA-Airline-Project
DFStest.java
2,871
//iteratively visit every child
line_comment
en
false
2,568
6
2,868
6
3,081
6
2,871
6
3,263
6
false
false
false
false
false
true
82600_3
import java.util.Scanner; import javax.swing.BorderFactory; import javax.swing.JButton; import javax.swing.JFrame; import javax.swing.JPanel; import javax.swing.JTextField; import javax.swing.*; import java.awt.Graphics; import java.awt.Color; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.io.File; import java.io.FileNotFoundException; import java.util.Collections; import java.util.HashMap; import java.util.Map; import java.util.ArrayList; //import java.awt.event.*; //import java.awt.*; /** * CheapHouses java program reads a csv file which contains data * of houses along with their coordinates and plots the data on graph * according to it, and the cut off price mentioned by the user * */ public class CheapHouses { static JTextField textField; /** * main function that only calls createAndShowGUI to run the program * @param args Unused * @return nothing */ public static void main(String[] args) { createAndShowGUI(); //data(); } /** * createAndShowGUI used to create GUI panel including * graphics panel, buttons, textfields and labels * @param unused * @return GUI */ public static void createAndShowGUI() { JFrame mainFrame = new JFrame("Assignment 2"); mainFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); mainFrame.setSize(500,575); JPanel mainPanel = new JPanel(null); JPanel graphicsPanel = new GPanel(); graphicsPanel.setLocation(0, 0); graphicsPanel.setSize(500,500); graphicsPanel.setBorder(BorderFactory.createLineBorder(Color.black)); mainPanel.add(graphicsPanel); JPanel widgetsPanel = new JPanel(); widgetsPanel.setLocation(0, 500); widgetsPanel.setSize(500,60); JLabel fileLabel = new JLabel("File: "); widgetsPanel.add(fileLabel); JTextField fileName = new JTextField("houses.csv"); fileName.setColumns(7); widgetsPanel.add(fileName); JLabel cutOff = new JLabel("Price: "); widgetsPanel.add(cutOff); JTextField priceField = new JTextField("250000"); priceField.setColumns(7); widgetsPanel.add(priceField); JButton okButton = new JButton("Plot"); okButton.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { System.out.println("Plotting points..."); Graphics g = graphicsPanel.getGraphics(); graphicsPanel.paint(g); g.setColor(Color.black); //HashMap and calculations to get data from the file //Calculating max/min of coordinates HashMap<Double[], Integer> butMap = data(fileName.getText()); ArrayList<Double> l1 = new ArrayList<>(); ArrayList<Double> l2 = new ArrayList<>(); for(Double[] i: butMap.keySet()) { l1.add(i[0]); l2.add(i[1]); } double maxl1 = Collections.max(l1); double minl1 = Collections.min(l1); double maxl2 = Collections.max(l2); double minl2 = Collections.min(l2); /*for(Double[] a: butMap.keySet()) { double rex = (a[0] - minl1)/(maxl1 - minl1) * 400; int rex1 = Double.valueOf(rex).intValue(); double rey = (a[1] - minl2)/(maxl2 - minl2) * 400; int rey1 = Double.valueOf(rey).intValue(); g.fillOval(rey1, rex1, 4, 4); }*/ //using the formula x' = x - x.min / x.max - x.min //to normalise the graph points //pri is the cut off price, and a are coordinates for (Map.Entry<Double[], Integer> entry : butMap.entrySet()) { Double[] a = entry.getKey(); Integer pri = entry.getValue(); if(pri <= (Integer.valueOf(priceField.getText()).intValue())) { double rex = (a[0] - minl1)/(maxl1 - minl1) * 400; int rex1 = Double.valueOf(rex).intValue(); double rey = (a[1] - minl2)/(maxl2 - minl2) * 400; int rey1 = Double.valueOf(rey).intValue(); g.fillOval(rey1, rex1, 5, 5); } } //System.out.println(Integer.valueOf(priceField.getText()).intValue()); } }); widgetsPanel.add(okButton); mainPanel.add(widgetsPanel); mainFrame.add(mainPanel); mainFrame.setVisible(true); } private static class GPanel extends JPanel { public void paintComponent(Graphics g) { int width = getSize().width; int height = getSize().height; g.setColor(Color.WHITE); g.fillRect(0, 0, width, height); g.setColor(Color.BLACK); g.drawString("", 10, 200); } } /** * HashMap function takes the name of file, and stores the data in HashMap * @param f * @return yourMap which is a hashmap with all data */ public static HashMap<Double[], Integer> data(String f){ HashMap<Double[], Integer> yourMap = new HashMap<>(); //String f = "/Users/adityagupta/Desktop/Sep 21 CSC 210 A2/houses.csv"; try(Scanner tfile = new Scanner (new File(f));) { String line = tfile.nextLine();; while (tfile.hasNext()) { line = tfile.nextLine(); String[] arr = line.split(","); Integer price = Integer.valueOf(arr[9]).intValue(); Double latit = Double.valueOf(arr[10]).doubleValue(); Double longit = Double.valueOf(arr[11]).doubleValue(); Double[] coord = {latit, longit}; yourMap.put(coord, price); } } catch(FileNotFoundException e) { e.getMessage(); } //for(Double[] a: yourMap.keySet()) { // System.out.println(a[0]); //} return yourMap; } }
adityagupta8121/CSC210
CheapHouses.java
1,678
/** * main function that only calls createAndShowGUI to run the program * @param args Unused * @return nothing */
block_comment
en
false
1,415
32
1,678
30
1,714
33
1,678
30
2,090
35
false
false
false
false
false
true
82751_4
package ast; import java.util.*; import visitor.*; /** * The AST Abstract class is the Abstract Syntax Tree representation; * each node contains<ol><li> references to its kids, <li>its unique node number * used for printing/debugging, <li>its decoration used for constraining * and code generation, and <li>a label for code generation</ol> * The AST is built by the Parser */ public abstract class AST { protected ArrayList<AST> kids; protected int nodeNum; protected AST decoration; protected String label = ""; // label for generated code of tree static int NodeCount = 0; public AST() { kids = new ArrayList<AST>(); NodeCount++; nodeNum = NodeCount; } public void setDecoration(AST t) { decoration = t; } public AST getDecoration() { return decoration; } public int getNodeNum() { return nodeNum; } /** * get the AST corresponding to the kid * @param i is the number of the needed kid; it starts with kid number one * @return the AST for the indicated kid */ public AST getKid(int i) { if ( (i <= 0) || (i > kidCount())) { return null; } return kids.get(i - 1); } /** * @return the number of kids at this node */ public int kidCount() { return kids.size(); } public ArrayList<AST> getKids() { return kids; } /** * accept the visitor for this node - this method must be defined in each of * the subclasses of AST * @param v is the ASTVisitor visiting this node (currently, a printer, * constrainer and code generator) * @return the desired Object, as determined by the visitor */ public abstract Object accept(ASTVisitor v); public AST addKid(AST kid) { kids.add(kid); return this; } public void setLabel(String label) { this.label = label; } public String getLabel() { return label; } }
bestkao/Compiler
src/ast/AST.java
514
/** * accept the visitor for this node - this method must be defined in each of * the subclasses of AST * @param v is the ASTVisitor visiting this node (currently, a printer, * constrainer and code generator) * @return the desired Object, as determined by the visitor */
block_comment
en
false
471
67
514
71
538
70
514
71
594
77
false
false
false
false
false
true
83483_20
package com.codegym.task.task25.task2515; import java.awt.event.KeyEvent; import java.util.ArrayList; import java.util.List; /** * The game's main class is Space */ public class Space { // Width and height of the game field private int width; private int height; // Spaceship private Spaceship ship; // List of UFOs private List<Ufo> ufos = new ArrayList<Ufo>(); // List of bombs private List<Bomb> bombs = new ArrayList<Bomb>(); // List of rockets private List<Rocket> rockets = new ArrayList<Rocket>(); public Space(int width, int height) { this.width = width; this.height = height; } /** * The program's main loop. * This is where all the important actions happen */ public void run() { // Create a drawing canvas. Canvas canvas = new Canvas(width, height); // Create a KeyboardObserver object and start it. KeyboardObserver keyboardObserver = new KeyboardObserver(); keyboardObserver.start(); // The game continues as long as the ship is alive while (ship.isAlive()) { // Does the observer have any key events? if (keyboardObserver.hasKeyEvents()) { KeyEvent event = keyboardObserver.getEventFromTop(); // If "left arrow", then move the game piece to the left System.out.print(event.getKeyCode()); if (event.getKeyCode() == KeyEvent.VK_LEFT) ship.moveLeft(); // If "right arrow", then move the game piece to the right else if (event.getKeyCode() == KeyEvent.VK_RIGHT) ship.moveRight(); // If "space", then launch a ball else if (event.getKeyCode() == KeyEvent.VK_SPACE) ship.fire(); } // Move all of the objects in the game moveAllItems(); // Detect collisions checkBombs(); checkRockets(); // Remove dead objects from the list removeDead(); // Create a UFO (once in every 10 calls) createUfo(); // Draw all the objects on the canvas and display the canvas on the screen canvas.clear(); draw(canvas); canvas.print(); // Pause 300 milliseconds Space.sleep(300); } // Display "Game Over" System.out.println("Game Over!"); } /** * Move all of the objects in the game */ public void moveAllItems() { for (BaseObject object : getAllItems()) { object.move(); } } /** * The method returns a single list that contains all objects in the game */ public List<BaseObject> getAllItems() { ArrayList<BaseObject> list = new ArrayList<BaseObject>(ufos); list.add(ship); list.addAll(bombs); list.addAll(rockets); return list; } /** * Create a new UFO. Once in every 10 calls. */ public void createUfo() { if (ufos.size() > 0) return; int random10 = (int) (Math.random() * 10); if (random10 == 0) { double x = Math.random() * width; double y = Math.random() * height / 2; ufos.add(new Ufo(x, y)); } } /** * Check the bombs. * a) collision with a ship (the bomb and the ship die) * b) movement beyond the bottom of the game field (the bomb dies) */ public void checkBombs() { for (Bomb bomb : bombs) { if (ship.intersects(bomb)) { ship.die(); bomb.die(); } if (bomb.getY() >= height) bomb.die(); } } /** * Check the rockets. * a) collision with a UFO (the rocket and the UFO die) * b) movement beyond the top of the playing field (the rocket dies) */ public void checkRockets() { for (Rocket rocket : rockets) { for (Ufo ufo : ufos) { if (ufo.intersects(rocket)) { ufo.die(); rocket.die(); } } if (rocket.getY() <= 0) rocket.die(); } } /** * Remove dead objects (bombs, rockets, ufos) from the lists */ public void removeDead() { for (BaseObject object : new ArrayList<BaseObject>(bombs)) { if (!object.isAlive()) bombs.remove(object); } for (BaseObject object : new ArrayList<BaseObject>(rockets)) { if (!object.isAlive()) rockets.remove(object); } for (BaseObject object : new ArrayList<BaseObject>(ufos)) { if (!object.isAlive()) ufos.remove(object); } } /** * Draw all game objects: * a) fill the entire canvas with periods. * b) draw all the objects on the canvas. */ public void draw(Canvas canvas) { // Draw the game for (int i = 0; i < width + 2; i++) { for (int j = 0; j < height + 2; j++) { canvas.setPoint(i, j, '.'); } } for (int i = 0; i < width + 2; i++) { canvas.setPoint(i, 0, '-'); canvas.setPoint(i, height + 1, '-'); } for (int i = 0; i < height + 2; i++) { canvas.setPoint(0, i, '|'); canvas.setPoint(width + 1, i, '|'); } for (BaseObject object : getAllItems()) { object.draw(canvas); } } public Spaceship getShip() { return ship; } public void setShip(Spaceship ship) { this.ship = ship; } public List<Ufo> getUfos() { return ufos; } public int getWidth() { return width; } public int getHeight() { return height; } public List<Bomb> getBombs() { return bombs; } public List<Rocket> getRockets() { return rockets; } public static Space game; public static void main(String[] args) throws Exception { game = new Space(40, 40); game.setShip(new Spaceship(10, 18)); game.run(); } /** * The method pauses for delay seconds. */ public static void sleep(int delay) { try { Thread.sleep(delay); } catch (InterruptedException ignored) { } } }
IbrahimAli-git/Space-Battle
Space.java
1,622
// Display "Game Over"
line_comment
en
false
1,488
7
1,622
7
1,856
6
1,622
7
2,007
6
false
false
false
false
false
true
84117_12
package geneticmidi; import javax.sound.midi.Track; import javax.sound.midi.MidiEvent; import java.lang.Long; import java.lang.Integer; import java.util.Vector; /** * Helper class for adding notes easily to tracks. */ public class Note { Track track; long startTick; long lengthTicks; int channel; int note; int velocity; MidiEvent noteOnEvent; MidiEvent noteOffEvent; public Note (long startTick, long lengthTicks, int channel, int note, int velocity) { this.startTick = startTick; this.lengthTicks = lengthTicks; this.channel = channel; this.note = note; this.velocity = velocity; noteOnEvent = MidiHelper.createNoteOnEvent(startTick, channel, note, velocity); noteOffEvent = MidiHelper.createNoteOffEvent(startTick + lengthTicks, channel, note, 127); } public Note (long startTick, long lengthTicks, int channel, String note, int velocity) { this(startTick, lengthTicks, channel, MidiHelper.getValueFromNote(note), velocity); } public Note (Track track, long startTick, long lengthTicks, int channel, String note, int velocity) { this(track, startTick, lengthTicks, channel, MidiHelper.getValueFromNote(note), velocity); } public Note (Track track, long startTick, long lengthTicks, int channel, int note, int velocity) { this(startTick, lengthTicks, channel, note, velocity); this.track = track; } /** * Remove this note from the track it is in. * Errors out if it is not in a track. */ public void removeFromTrack() { assert track != null; try { // This is needed because track.remove() will only take a // reference to an exact MidiEvent. It can't be an identical event. :-( boolean removeNoteOn = track.remove(MidiHelper.findSameEvent(track, noteOnEvent)); boolean removeNoteOff = track.remove(MidiHelper.findSameEvent(track, noteOffEvent)); if (!removeNoteOn) { System.out.println("in removeFromTrack() Could not remove note on..."); System.exit(1); } if (!removeNoteOff) { System.out.println("in removeFromTrack() Could not remove note off..."); System.exit(1); } } catch (Exception e) { e.printStackTrace(); System.exit(1); } } /** * Set the note value for this Note. If you want to update the MidiMessage on the * track, you have to first removeFromTrack(), then setNoteValue(), * then addToTrack(). */ public void setNoteValue(int noteValue) { this.note = noteValue; noteOnEvent = MidiHelper.createNoteOnEvent(startTick, channel, note, velocity); noteOffEvent = MidiHelper.createNoteOffEvent(startTick + lengthTicks, channel, note, 127); } /** * Set the channel for this Note. If you want to update the MidiMessage on the * track, you have to first removeFromTrack(), then setNoteValue(), * then addToTrack(). */ public void setChannel(int chan) { this.channel = chan; noteOnEvent = MidiHelper.createNoteOnEvent(startTick, channel, note, velocity); noteOffEvent = MidiHelper.createNoteOffEvent(startTick + lengthTicks, channel, note, 127); } /** * Set the start tick and the length of this Note. If you want to update * the MidiMessage on the track, you have to first removeFromTrack(), * then setStartTickAndLength(), then addToTrack(). */ public void setStartTickAndLength(long startTick, long length) { this.startTick = startTick; this.lengthTicks = length; noteOnEvent = MidiHelper.createNoteOnEvent(this.startTick, channel, note, velocity); noteOffEvent = MidiHelper.createNoteOffEvent(this.startTick + this.lengthTicks, channel, note, 127); } /** * Returns true if two notes have the same note value. * This is used in the fitness function for a midi individual. */ @Override public boolean equals(Object otherNote) { if (otherNote instanceof Note) { return this.getNoteValue() == ((Note)otherNote).getNoteValue(); } else { return false; } } /** * Returns true if two notes are completely the same. */ public boolean completelyEquals(Note otherNote) { return this.getNoteValue() == otherNote.getNoteValue() && this.getStartTick() == otherNote.getStartTick() && this.getEndTick() == otherNote.getEndTick() && this.toString().equals(otherNote.toString()) && this.getChannel() == otherNote.getChannel() && this.getVelocity() == otherNote.getVelocity(); } public int getNoteValue() { return note; } public long getStartTick() { return startTick; } public long getEndTick() { return startTick + lengthTicks; } public int getChannel() { return channel; } public int getVelocity() { return velocity; } public MidiEvent getNoteOnEvent() { return noteOnEvent; } public MidiEvent getNoteOffEvent() { return noteOffEvent; } /** * Add this note to the track it is associated with. */ public void addToTrack() { assert track != null; this.track.add(noteOnEvent); this.track.add(noteOffEvent); } /** * Associate this note with a track. */ public void setTrack(Track track) { this.track = track; } public String toString() { String result = ""; result += "Note: track=" + track + ", "; result += "start=" + startTick + ", "; result += "length=" + lengthTicks + ", "; result += "channel=" + channel + ", "; result += "value=" + note + " (" + MidiHelper.getNoteFromValue(note) + "), "; result += "velocity=" + velocity; return result; } public static String makeBitString(Vector<Note> notes) { StringBuilder finalString = new StringBuilder(); for (Note n : notes) { finalString.append(n.makeBitString()); } return finalString.toString(); } public static String makeBitString(long startTick, long lengthTicks, int noteValue) { // this is the amount of bits we will use for startTick and lengthTicks int LONG_PORTION = 25; // this is the amount of bits we will use for noteValue int INT_PORTION = 8; assert Long.toBinaryString(startTick).length() <= LONG_PORTION; assert Long.toBinaryString(lengthTicks).length() <= LONG_PORTION; assert Integer.toBinaryString(noteValue).length() <= INT_PORTION; StringBuilder startString = new StringBuilder(); StringBuilder lengthString = new StringBuilder(); StringBuilder noteString = new StringBuilder(); // create startString for (int i = 0; i < LONG_PORTION - Long.toBinaryString(startTick).length(); i++) { startString.append("0"); } startString.append(Long.toBinaryString(startTick)); // create lengthString for (int i = 0; i < LONG_PORTION - Long.toBinaryString(lengthTicks).length(); i++) { lengthString.append("0"); } lengthString.append(Long.toBinaryString(lengthTicks)); // create noteString for (int i = 0; i < INT_PORTION - Integer.toBinaryString(noteValue).length(); i++) { noteString.append("0"); } noteString.append(Integer.toBinaryString(noteValue)); /* System.out.println("startTick: " + startTick + ", binary: " + Long.toBinaryString(startTick) + ", modified binary: " + startString); System.out.println("lengthTicks: " + lengthTicks + ", binary: " + Long.toBinaryString(lengthTicks) + ", modified binary: " + lengthString); System.out.println("noteValue: " + noteValue + ", binary: " + Integer.toBinaryString(noteValue) + ", modified binary: " + noteString); */ return startString.toString() + lengthString.toString() + noteString.toString(); } /** * Return a bitstring representation of this Note. */ public String makeBitString() { // I need to represent the startTick, the lengthTicks, and the note value. //long startTick; //long lengthTicks; //int note; return makeBitString(startTick, lengthTicks, note); } public static void main(String[] args) { System.out.println("make bit string: " + makeBitString(232343, 0, 1)); } }
cdepillabout/geneticmidi
Note.java
2,407
// this is the amount of bits we will use for noteValue
line_comment
en
false
2,046
13
2,407
13
2,417
13
2,407
13
2,843
13
false
false
false
false
false
true
84125_4
package CS662_FinalProject; import javafx.scene.Scene; import javafx.scene.control.Button; import javafx.scene.control.Label; import javafx.scene.image.Image; import javafx.scene.image.ImageView; import javafx.scene.layout.AnchorPane; import javafx.stage.Stage; public class Tips { public void setRaningsView(){ Stage stage = new Stage(); stage.setTitle("Quiz Game"); AnchorPane anchorPane = new AnchorPane(); anchorPane.setStyle("-fx-background-color:#fff;"); Scene scene = new Scene(anchorPane, 640, 412); // declare scene size scene.getStylesheets().add(getClass().getResource("main.css").toExternalForm()); // Get external stylesheet ImageView imgView = new ImageView(); Image img = new Image("https://cms.qz.com/wp-content/uploads/2018/02/forgetting-curve-annotated.png?w=1400&strip=all&quality=75"); imgView.setFitWidth(635); imgView.setFitHeight(300); imgView.setLayoutX(0); imgView.setLayoutY(50); imgView.setImage(img); // Set up label Label label = new Label(" Forgetting Curve "); label.setStyle("-fx-text-fill: red; -fx-font-size:22; -fx-font-weight:bold;"); label.setLayoutX(230); label.setLayoutY(5); // set up begin button Button home = new Button(" Back To Home "); home.setLayoutX(200); home.setLayoutY(360); home.setPrefWidth(245); home.setPrefHeight(50); //add action on user click the begin button home.setOnAction(e -> { //System.out.println("button clicked"); HomeView homeView = new HomeView(); homeView.setHomeView(); stage.hide(); }); // add functions to the pane //anchorPane.getChildren().addAll(imageView, begin, label); anchorPane.getChildren().addAll(home, label, imgView); // show the scene stage.setScene(scene); stage.show(); } }
henry226/JavaFx-Quiz-Application
Tips.java
567
// set up begin button
line_comment
en
false
485
5
567
5
584
5
567
5
671
5
false
false
false
false
false
true
84431_8
import java.awt.Graphics; import java.awt.Image; import java.awt.event.MouseAdapter; import java.awt.event.MouseEvent; import java.util.Random; import javax.swing.ImageIcon; import javax.swing.JLabel; import javax.swing.JPanel; public class Board extends JPanel { private final int NUM_IMAGES = 13; private final int CELL_SIZE = 15; public final static int COVER_FOR_CELL = 10; private final int MARK_FOR_CELL = 10; private final int EMPTY_CELL = 0; private final int MINE_CELL = 9; private final int COVERED_MINE_CELL = MINE_CELL + COVER_FOR_CELL; private final int MARKED_MINE_CELL = COVERED_MINE_CELL + MARK_FOR_CELL; private final int DRAW_MINE = 9; private final int DRAW_COVER = 10; private final int DRAW_MARK = 11; private final int DRAW_WRONG_MARK = 12; private static int[] field; private static boolean inGame; private int mines_left; private Image[] img; private int mines; private static int rows; private static int cols; private int all_cells; private JLabel statusbar; private String mineStr = "Mines left: "; private static int difficulty; private static boolean solved = false; //Constructor public Board(JLabel statusbar, int noOfMines, int noOfRows, int noOfCols) { //Set the values of the member variables as determined by the MineFrame class this.statusbar = statusbar; mines = noOfMines; rows = noOfRows; cols = noOfCols; //Declare image array img = new Image[NUM_IMAGES]; //Load images into img for (int i = 0; i < NUM_IMAGES; i++) { img[i] = (new ImageIcon(this.getClass().getResource((i) + ".png"))).getImage(); } setDoubleBuffered(true); addMouseListener(new MinesAdapter()); newGame(); } // set solved (mutator/setter) public static void setSolved(boolean newState) { solved = newState; } // set inGame (mutator/setter) public static void setInGame(boolean newState) { inGame = newState; } //set difficulty (mutator/setter) public static void setDifficulty(int newDifficulty) { difficulty = newDifficulty; } //Gets the field and returns it (getter) public static int[] getField() { return field; } //Sets the field with a new array (mutator/setter) public static void setField(int[] arr) { field = arr; } // Push the array 'field' into the undoStack public static void pushFieldToUndoStack() { //Push the array 'field' into the undoStack MineFrame.undoStack.push(field.clone()); } // create a new game public void newGame() { Random random; int current_col; int i = 0; int position = 0; int cell = 0; random = new Random(); inGame = true; mines_left = mines; //Assign the amount of cells there are to all_cells all_cells = rows * cols; //Assign 'field' the size of all_cells field = new int[all_cells]; //Assign cover cell image to all cells on the board for (i = 0; i < all_cells; i++) { field[i] = COVER_FOR_CELL; } //Set the text for the status bar statusbar.setText(mineStr + Integer.toString(mines_left)); //Reset i to 0 i = 0; while (i < mines) { //Select a random cell on the board and place a mine in it position = (int) (all_cells * random.nextDouble()); if ((position < all_cells) && (field[position] != COVERED_MINE_CELL)) { current_col = position % cols; field[position] = COVERED_MINE_CELL; i++; if (current_col > 0) { cell = position - 1 - cols; if (cell >= 0) if (field[cell] != COVERED_MINE_CELL) { field[cell] += 1; } cell = position - 1; if (cell >= 0) if (field[cell] != COVERED_MINE_CELL) { field[cell] += 1; } cell = position + cols - 1; if (cell < all_cells) if (field[cell] != COVERED_MINE_CELL) { field[cell] += 1; } } cell = position - cols; if (cell >= 0) if (field[cell] != COVERED_MINE_CELL) { field[cell] += 1; } cell = position + cols; if (cell < all_cells) if (field[cell] != COVERED_MINE_CELL) { field[cell] += 1; } if (current_col < (cols - 1)) { cell = position - cols + 1; if (cell >= 0) if (field[cell] != COVERED_MINE_CELL) { field[cell] += 1; } cell = position + cols + 1; if (cell < all_cells) if (field[cell] != COVERED_MINE_CELL) { field[cell] += 1; } cell = position + 1; if (cell < all_cells) if (field[cell] != COVERED_MINE_CELL) { field[cell] += 1; } } } } // save first undo to stack pushFieldToUndoStack(); } // search & uncover cell when there isn't a mine around it public void find_empty_cells(int j) { int current_col = j % cols; int cell; if (current_col > 0) { cell = j - cols - 1; if (cell >= 0) if (field[cell] > MINE_CELL) { field[cell] -= COVER_FOR_CELL; if (field[cell] == EMPTY_CELL) { find_empty_cells(cell); } } cell = j - 1; if (cell >= 0) if (field[cell] > MINE_CELL) { field[cell] -= COVER_FOR_CELL; if (field[cell] == EMPTY_CELL) { find_empty_cells(cell); } } cell = j + cols - 1; if (cell < all_cells) if (field[cell] > MINE_CELL) { field[cell] -= COVER_FOR_CELL; if (field[cell] == EMPTY_CELL) { find_empty_cells(cell); } } } cell = j - cols; if (cell >= 0) if (field[cell] > MINE_CELL) { field[cell] -= COVER_FOR_CELL; if (field[cell] == EMPTY_CELL) { find_empty_cells(cell); } } cell = j + cols; if (cell < all_cells) if (field[cell] > MINE_CELL) { field[cell] -= COVER_FOR_CELL; if (field[cell] == EMPTY_CELL) { find_empty_cells(cell); } } if (current_col < (cols - 1)) { cell = j - cols + 1; if (cell >= 0) if (field[cell] > MINE_CELL) { field[cell] -= COVER_FOR_CELL; if (field[cell] == EMPTY_CELL) { find_empty_cells(cell); } } cell = j + cols + 1; if (cell < all_cells) if (field[cell] > MINE_CELL) { field[cell] -= COVER_FOR_CELL; if (field[cell] == EMPTY_CELL) { find_empty_cells(cell); } } cell = j + 1; if (cell < all_cells) if (field[cell] > MINE_CELL) { field[cell] -= COVER_FOR_CELL; if (field[cell] == EMPTY_CELL) { find_empty_cells(cell); } } } } @Override public void paint(Graphics g) { int cell = 0; int uncover = 0; for (int i = 0; i < rows; i++) { for (int j = 0; j < cols; j++) { cell = field[(i * cols) + j]; if (inGame && cell == MINE_CELL) { inGame = false; } //Paint mines corresponding to the images if (!inGame) { if (cell == COVERED_MINE_CELL) { cell = DRAW_MINE; } else if (cell == MARKED_MINE_CELL) { cell = DRAW_MARK; } else if (cell > COVERED_MINE_CELL) { cell = DRAW_WRONG_MARK; } else if (cell > MINE_CELL) { cell = DRAW_COVER; } } else { if (cell > COVERED_MINE_CELL) { cell = DRAW_MARK; } else if (cell > MINE_CELL) { cell = DRAW_COVER; uncover++; } } g.drawImage(img[cell], (j * CELL_SIZE), (i * CELL_SIZE), this); } } if (uncover == 0 && inGame && !solved) { inGame = false; statusbar.setText("Game won"); new SaveUser(difficulty); } else if (uncover == -1 && !inGame && solved) { statusbar.setText("Solved"); } else if (!inGame) { statusbar.setText("Game lost"); } } //Click event when user clicked a field class MinesAdapter extends MouseAdapter { public void mousePressed(MouseEvent e) { int x = e.getX(); int y = e.getY(); int cCol = x / CELL_SIZE; int cRow = y / CELL_SIZE; boolean rep = false; if (!inGame) { MineFrame.startNewGame(); } if ((x < cols * CELL_SIZE) && (y < rows * CELL_SIZE) && MineFrame.playingGame) { //Rightmouse button - set flag and update statusbar if (e.getButton() == MouseEvent.BUTTON3) { if (field[(cRow * cols) + cCol] > MINE_CELL) { rep = true; if (field[(cRow * cols) + cCol] <= COVERED_MINE_CELL) { if (mines_left > 0) { field[(cRow * cols) + cCol] += MARK_FOR_CELL; mines_left--; statusbar.setText(mineStr + Integer.toString(mines_left)); } else { statusbar.setText("No marks left"); } } else { field[(cRow * cols) + cCol] -= MARK_FOR_CELL; mines_left++; statusbar.setText(mineStr + Integer.toString(mines_left)); } } } else { //Nothing happens when we click on a marked cell if (field[(cRow * cols) + cCol] > COVERED_MINE_CELL) return; if ((field[(cRow * cols) + cCol] > MINE_CELL) && (field[(cRow * cols) + cCol] < MARKED_MINE_CELL)) { field[(cRow * cols) + cCol] -= COVER_FOR_CELL; rep = true; if (field[(cRow * cols) + cCol] == MINE_CELL) { inGame = false; } if (field[(cRow * cols) + cCol] == EMPTY_CELL) { find_empty_cells((cRow * cols) + cCol); } } } if (rep) { repaint(); pushFieldToUndoStack(); } } } } }
wegrzyns/mines
Board.java
3,048
//Sets the field with a new array (mutator/setter)
line_comment
en
false
2,718
14
3,047
14
3,318
14
3,048
14
3,842
16
false
false
false
false
false
true
84615_5
package jlox; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.nio.charset.Charset; import java.nio.file.Files; import java.nio.file.Paths; import java.util.List; /** * Lox * * @apiNote Error code follow UNIX `sysexits.h` * https://www.freebsd.org/cgi/man.cgi?query=sysexits&apropos=0&sektion=0&manpath=FreeBSD+4.3-RELEASE&format=html */ public class Lox { private static final Interpreter interpreter = new Interpreter(); static boolean hadError = false; static boolean hadRuntimeError = false; public static void main(String[] args) throws IOException { if (args.length > 1) { System.out.println("Usage: jlox [script]"); System.exit(64); } else if (args.length == 1) { runFile(args[0]); } else { runPrompt(); } } /** * If you start jlox from the command line and give it a path to a file, it * reads the file and executes it. */ private static void runFile(String path) throws IOException { byte[] bytes = Files.readAllBytes(Paths.get(path)); run(new String(bytes, Charset.defaultCharset())); // We’ll use this to ensure we don’t try to execute code that has a known error. if (hadError) { System.exit(65); } if (hadRuntimeError) { System.exit(70); } } private static void runPrompt() throws IOException { InputStreamReader input = new InputStreamReader(System.in); BufferedReader reader = new BufferedReader(input); for (;;) { System.out.print("> "); String line = reader.readLine(); // To kill an interactive command-line app, you usually type Control-D. Doing so // signals an “end-of-file” condition to the program. if (line == null) { break; } run(line); // If the user makes a mistake, it shouldn’t kill their entire session. hadError = false; } } private static void run(String source) { Scanner scanner = new Scanner(source); List<Token> tokens = scanner.scanTokens(); Parser parser = new Parser(tokens); List<Stmt> statements = parser.parse(); // Stop if there was a syntax error. if (hadError) { return; } interpreter.interpret(statements); } static void error(int line, String message) { report(line, "", message); } private static void report(int line, String where, String message) { System.err.println("[line " + line + "] Error" + where + ": " + message); hadError = true; } /** * This reports an error at a given token. It shows the token’s location and the * token itself. */ static void error(Token token, String message) { if (token.type == TokenType.EOF) { report(token.line, " at end", message); } else { report(token.line, " at '" + token.lexeme + "'", message); } } /** * If a runtime error is thrown while evaluating the expression, interpret() * catches it. This lets us report the error to the user and then gracefully * continue. */ static void runtimeError(RuntimeError error) { System.err.println(error.getMessage() + "\n[line " + error.token.line + "]"); hadRuntimeError = true; } }
saihaj/lox
jlox/Lox.java
930
// If the user makes a mistake, it shouldn’t kill their entire session.
line_comment
en
false
776
16
930
17
940
17
930
17
1,078
17
false
false
false
false
false
true
84734_3
/** The implementation of Triple data structure. * @author: Rafayel Mkrtchyan **/ public class Triple { /** The constructor of Triple. **/ public Triple(String predecessor, String successor, Double number) { _predecessor = predecessor; _successor = successor; _number = number; } /** Returns the value of the predecessor. **/ public String getPredecessor() { return this._predecessor; } /** Sets the value of the predecessor to STR. **/ public void setPredecessor(String str) { this._predecessor = str; } /** Returns the value of the successor. **/ public String getSuccessor() { return this._successor; } /** Sets the value of the successor to STR. **/ public void setSuccessor(String str) { this._successor = str; } /** Returns the value of number. **/ public Double getNumber() { return this._number; } /** Sets the value of the number to NUM. **/ public void setNumber(Double num) { this._number = num; } /** Contains the predecessor word when iterating through the data. **/ private String _predecessor; /** Contains the successor word when iterating through the data. **/ private String _successor; /** Contains the number of occurances of predecessor and successor * together. **/ private Double _number; }
MicBrain/Text_Generator
Triple.java
370
/** Sets the value of the predecessor to STR. **/
block_comment
en
false
303
12
370
12
347
11
370
12
418
15
false
false
false
false
false
true
84828_7
/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package videostoresimulator; import Videos.Comedy; import Videos.Drama; import Videos.Horror; import Videos.NewRelease; import Videos.Romance; import Videos.Video; import java.util.ArrayList; import java.util.List; /** * * @author owner */ public class Videoshelf { private final List<Video> videos; private Video newRelease; private Video comedy; private Video drama; private Video romance; private Video horror; private final String[] NewReleaseName = {"復仇者聯盟3","一級玩家","毀滅大作戰","死侍2"}; private final String[] ComedyName = {"大獨裁者落難記","王牌天神","麻辣間諜","豆豆秀"}; private final String[] DramaName = {"玩命再劫","寂寞拍賣師","告白","不存在的房間"}; private final String[] RomanceName = {"戀夏500日","P.S我愛你","生命中的美好缺憾 ","我就要你好好的"}; private final String[] HorrorName = {"七夜怪譚","逃出絕命鎮","安娜貝爾","牠"}; //when new a video shelf it will load all the videos and show all the video public Videoshelf(){ videos = new ArrayList<>(); loadvideos(); showAllVideos(); } //load all videos private void loadvideos(){ for(int i =0;i<4;i++){ newRelease = new NewRelease(NewReleaseName[i]); videos.add(newRelease); } for(int i =0;i<4;i++){ comedy = new Comedy(ComedyName[i]); videos.add(comedy); } for(int i =0;i<4;i++){ drama = new Drama(DramaName[i]); videos.add(drama); } for(int i =0;i<4;i++){ romance = new Romance(RomanceName[i]); videos.add(romance); } for(int i =0;i<4;i++){ horror = new Horror(HorrorName[i]); videos.add(horror); } } //show all videos private void showAllVideos(){ System.out.println("所有影片"); for(int i =0;i< videos.size();i++){ videos.get(i).printInformation(); } } //show remain videos in the list videos public void showRemainVideos(){ System.out.println("剩餘影片(共"+getTotalVideoNum()+"部)"); for(int i =0;i< videos.size();i++){ System.out.println(videos.get(i).getVideoName()); } } //get the video public Video getVideo(int whichVideo) { Video video = videos.get(whichVideo); videos.remove(whichVideo); return video; } //add back the video to list videos public void returnVideo(Video v){ videos.add(v); } //get the number of videos in list videos public int getTotalVideoNum(){ return videos.size(); } }
r0y6a3n0/videostoresimulator
Videoshelf.java
876
//add back the video to list videos
line_comment
en
false
702
9
876
9
846
9
876
9
1,010
9
false
false
false
false
false
true
84832_9
import java.io.*; import java.net.ServerSocket; import java.net.Socket; import java.util.List; import java.util.logging.Level; import java.util.logging.Logger; public class VideoServer { private static final Logger logger = Logger.getLogger(VideoServer.class.getSimpleName()); private int portNumber = 1983; private Socket clientSocket; private ServerSocket serverSocket; private PrintWriter out; private BufferedReader in; private String filename = "videos.ser"; private VideoServerEngine engine; public VideoServer() { init(); try { startServer(); } catch (IOException e) { System.err.println("Unrecoverable error whilst starting the server: " + e.getMessage()); } } private void init() { List<Video> videos = null; try { videos = VideoFileParser.fromSerialized(filename); } catch (FileNotFoundException e) { System.err.format("File not found. %n%n%s%n", e); } catch (ClassNotFoundException e) { System.err.format("Class not found. %n%n%s%n", e); } catch (IOException e) { System.err.format("Error while attempting to read from file: %s%n", e); } engine = new VideoServerEngine(videos); } private void startServer() throws IOException { //some statements are missing from here serverSocket = new ServerSocket(portNumber); System.out.printf("Server started on port %d ...", serverSocket.getLocalPort()); clientSocket = serverSocket.accept(); out = new PrintWriter( new BufferedWriter( new OutputStreamWriter( new DataOutputStream(clientSocket.getOutputStream()) ) ) ); in = new BufferedReader( new InputStreamReader( new DataInputStream(clientSocket.getInputStream()) ) ); //we only make it this far if the code above doesn't throw an exception welcomeClient(); //user interaction starts (and ends) here mainLoop(); //shut down closeAll(); } private void welcomeClient() { //welcome the client and show the available commands String commands = engine.getAvailableCommands(); String ip = clientSocket.getInetAddress().getHostAddress(); String local = serverSocket.getInetAddress().getHostAddress(); sendOutputToClient("Welcome IP address '" + ip + "' to the Video Library Server. Available commands:\n" + commands); } //our shutdown method. close all open streams private void closeAll() { //out of the loop. all done, close the connection try { in.close(); out.close(); clientSocket.close(); } catch (IOException e) { System.err.println("Error while shutting down: " + e.getMessage()); } } private void mainLoop() { //receive and respond to input boolean moreInput = true; while (moreInput) { try { String inputLine = null; while ((inputLine = in.readLine()) != null) { String output = engine.parseCommand(inputLine.trim()); sendOutputToClient(output); } moreInput = false; } catch (IOException e) { System.err.println("Error reading from client: " + e.getMessage()); moreInput = false; } catch (Exception e) { //engine has thrown some sort of student-based hissy fit; sendOutputToClient(e.toString()); } } } private void sendOutputToClient(String s) { out.println(s); out.println(ServerUtils.getEOM()); //The client won't know it has reached the end of our message without this out.flush(); } public static void main(String[] args) throws IOException { new VideoServer(); } }
AzengaKevin/FilmCollection
src/VideoServer.java
871
//The client won't know it has reached the end of our message without this
line_comment
en
false
792
16
871
16
962
17
871
16
1,028
17
false
false
false
false
false
true
84951_1
import java.text.DecimalFormat; import java.util.Stack; import java.util.Vector; enum Context{ Number, Operator, Function, Parenthesis, Constant, Invalid } class Token{ // type = 0->Number, 1->Operator, 2->Function, 3->Parenthesis, 4->Constant public static String ADD = "+",SUBTRACT = "-", MULTIPLY = "*", DIVIDE = "/", PERCENT = "%", POWER = "^", FACTORIAL = "!", RADICAL = "#", EOL = "$", PI = "@", EULER = "e", ESCI = "E"; public static String OperatorString = ADD + SUBTRACT + MULTIPLY + DIVIDE + PERCENT + POWER + FACTORIAL + RADICAL; Context type; String value; Token(String value, Context type){ this.value = value; this.type = type; } } class Tokenizer{ public static Vector<Token> tokenize(String expression){ Vector<Token> tokens = new Vector<Token>(); String s = String.valueOf(expression.charAt(0)); expression += Token.EOL; Context context = getContext(expression.charAt(0)); for(int i = 1; i < expression.length(); i++){ char ch = expression.charAt(i); if(ch == '2' && s.equals("log")){ tokens.add(new Token("log2", Context.Function)); s = ""; context = Context.Invalid; continue; } Context ct = getContext(ch); if(context != ct){ if((context == Context.Number && ct == Context.Constant) || (context == Context.Constant && ct == Context.Number) || (context == Context.Number && ct == Context.Function) || (context == Context.Number && ch == '(') ){ tokens.add(new Token(Token.MULTIPLY, Context.Operator)); } } if(context != ct ||ct == Context.Parenthesis || ct == Context.Operator){ // make unary plus and minus to binary by putting 0 before them if(context == Context.Operator && "+-".contains(s)){ if(i == 1 || expression.charAt(i-2) == '('){ tokens.add(new Token("0", Context.Number)); } } tokens.add(new Token(s, context)); s = ""; if(expression.charAt(i-1) == ')' && ct == Context.Number){ tokens.add(new Token(Token.MULTIPLY, Context.Operator)); } context = ct; } s += String.valueOf(ch); } return tokens; } private static Context getContext(char ch){ if(isDigit(ch) || ch == '.'){ return Context.Number; }else if(String.valueOf(ch).equals(Token.PI) || String.valueOf(ch).equals(Token.EULER)){ return Context.Constant; }else if(isAlpha(ch)){ return Context.Function; }else if(isOperator(ch)){ return Context.Operator; }else if(ch == '(' || ch == ')'){ return Context.Parenthesis; } return Context.Invalid; } private static boolean isOperator(char ch){ if(Token.OperatorString.contains(String.valueOf(ch))){ return true; } return false; } private static boolean isDigit(char ch){ if(ch >= 48 && ch <= 57){ return true; } return false; } private static boolean isAlpha(char ch){ if((ch >= 65 && ch <= 90) || (ch >= 97 && ch <= 122)){ return true; } return false; } } class Expression{ private String infix; private boolean degreeAngle = false; Expression(String exp){ infix = exp; } public void setDegreeAngle(Boolean b){ degreeAngle = b; } public String eval(){ Vector<Token> tokens = Tokenizer.tokenize(infix); Stack<Double> operandStack = new Stack<Double>(); Stack<Token> operatorStack = new Stack<Token>(); for(Token t: tokens){ // System.out.print(t.value); if(t.type == Context.Number){ operandStack.add(Double.parseDouble(t.value)); } else if(t.type == Context.Constant){ if(t.value.equals(Token.PI)){ operandStack.add(Math.PI); }else if(t.value.equals(Token.EULER)){ operandStack.add(Math.exp(1)); } } else{ if(t.type == Context.Operator){ if(t.value.equals(Token.PERCENT)){ double operand1 = operandStack.pop(); operandStack.push(operand1/100); }else if(t.value.equals(Token.FACTORIAL)){ double operand1 = operandStack.pop(); if(operand1 >= 0 && operand1 <= 20 && (operand1*10 - (int)operand1*10 == 0 )){ operandStack.push(factorial(operand1)); }else{ return "Can't do factorial. Error"; } } else if(operatorStack.isEmpty()){ operatorStack.push(t); } else if(getAssociativity(t) == 1 || getPrecedence(t)>getPrecedence(operatorStack.lastElement())){ operatorStack.push(t); }else{ while(!operatorStack.isEmpty() && getPrecedence(t)<=getPrecedence(operatorStack.lastElement())){ double operand2 = operandStack.pop(); double operand1 = operandStack.pop(); double result = calc(operand1, operand2, operatorStack.pop()); operandStack.push(result); } operatorStack.push(t); } } else if(t.type == Context.Parenthesis){ if(t.value.equals("(")){ operatorStack.push(t); }else{ while(!operatorStack.lastElement().value.equals("(")){ if(operatorStack.size() > 0){ double operand2 = operandStack.pop(); double operand1 = operandStack.pop(); double result = calc(operand1, operand2, operatorStack.pop()); operandStack.push(result); } } operatorStack.pop(); if(!operatorStack.isEmpty() && operatorStack.lastElement().type == Context.Function){ Token fuToken = operatorStack.pop(); double operand1 = operandStack.pop(); if(fuToken.value.equals("sin")){ if(degreeAngle){ operand1 = Math.toRadians(operand1); } operandStack.push(Math.sin(operand1)); }else if(fuToken.value.equals("cos")){ if(degreeAngle){ operand1 = Math.toRadians(operand1); } operandStack.push(Math.cos(operand1)); }else if(fuToken.value.equals("tan")){ if(degreeAngle){ operand1 = Math.toRadians(operand1); } operandStack.push(Math.tan(operand1)); }else if(fuToken.value.equals("lg")){ operandStack.push(Math.log10(operand1)); }else if(fuToken.value.equals("ln")){ operandStack.push(Math.log(operand1)); }else if(fuToken.value.equals("log2")){ operandStack.push(Math.log(operand1)/Math.log(2)); }else if(fuToken.value.equals("sinh")){ operandStack.push(Math.sinh(operand1)); }else if(fuToken.value.equals("cosh")){ operandStack.push(Math.cosh(operand1)); }else if(fuToken.value.equals("tanh")){ operandStack.push(Math.tanh(operand1)); }else if(fuToken.value.equals("asin")){ if(degreeAngle){ operandStack.push(Math.toDegrees(Math.asin(operand1))); }else{ operandStack.push(Math.asin(operand1)); } }else if(fuToken.value.equals("acos")){ if(degreeAngle){ operandStack.push(Math.toDegrees(Math.acos(operand1))); }else{ operandStack.push(Math.acos(operand1)); } }else if(fuToken.value.equals("atan")){ if(degreeAngle){ operandStack.push(Math.toDegrees(Math.atan(operand1))); }else{ operandStack.push(Math.atan(operand1)); } }else if(fuToken.value.equals("asinh")){ operandStack.push(Math.log(operand1 + Math.sqrt(operand1 * operand1 + 1))); }else if(fuToken.value.equals("acosh")){ operandStack.push(Math.log(operand1 + Math.sqrt(operand1 * operand1 - 1))); }else if(fuToken.value.equals("atanh")){ operandStack.push(0.5 * Math.log((1 + operand1) / (1 - operand1))); } } } } else if(t.type == Context.Function){ if(t.value.equals("Rand")){ operandStack.push(Math.random()); }else{ operatorStack.push(t); } } } } // System.out.println(); while(!operatorStack.isEmpty()){ double operand2 = operandStack.pop(); double operand1 = operandStack.pop(); double result = calc(operand1, operand2, operatorStack.pop()); operandStack.push(result); } double res = operandStack.pop(); DecimalFormat df = new DecimalFormat("#.###############"); // df.setRoundingMode(RoundingMode.CEILING); if(res > 10e15){ return String.valueOf(res); } return String.valueOf(df.format(res)); } private static double factorial(double operand1){ double r = 1; while(operand1 > 1){ r *= operand1--; } return r; } private static double calc(double operand1, double operand2, Token opToken) { if(opToken.value.equals(Token.ADD)){ return operand1 + operand2; }else if(opToken.value.equals(Token.SUBTRACT)){ return operand1 - operand2; }else if(opToken.value.equals(Token.MULTIPLY)){ return operand1 * operand2; }else if(opToken.value.equals(Token.DIVIDE)){ return operand1 / operand2; }else if(opToken.value.equals(Token.POWER)){ return Math.pow(operand1, operand2); }else if(opToken.value.equals(Token.RADICAL)){ return Math.pow(operand2, 1.0/operand1); } return 0; } private int getAssociativity(Token opToken){ // 0 -> left, 1-> right if(opToken.value.equals(Token.POWER)){ return 1; } return 0; } private int getPrecedence(Token opToken){ if(opToken.value.equals(Token.ADD) || opToken.value.equals(Token.SUBTRACT)){ return 1; }else if(opToken.value.equals(Token.MULTIPLY) || opToken.value.equals(Token.DIVIDE)){ return 2; }else if(opToken.value.equals(Token.POWER) || opToken.value.equals(Token.RADICAL)){ return 3; } return 0; } } public class Main{ public static void main(String[] args) { UserInput ui = new UserInput(); String infixExp = ui.input("Enter a mathematical expression: "); Expression exp = new Expression(infixExp); exp.setDegreeAngle(true); String value = exp.eval(); System.out.println(value); } }
subinay108/Mathematical-Expression-Evaluation
Main.java
2,824
// make unary plus and minus to binary by putting 0 before them
line_comment
en
false
2,424
14
2,824
14
3,099
14
2,824
14
3,537
15
false
false
false
false
false
true
86680_3
import java.awt.*; import javax.swing.*; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; public class Login extends JFrame { JLabel usLab; JLabel passLab; JTextField usTF; JTextField passTF; JButton submit; JButton reset; Login() { usLab=new JLabel("Username : "); passLab=new JLabel("Password : "); usTF=new JTextField(); passTF=new JTextField(); submit=new JButton("Submit"); reset=new JButton("Reset"); // Set layout setLayout(new GridLayout(3,3)); // Add components to the frame this.add(usLab); add(usTF); add(passLab); add(passTF); add(submit); add(reset); // Set frame properties setTitle("Login Page"); setSize(500,500); setVisible(true); // Add action listeners to buttons submit.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { String username=usTF.getText(); String password=passTF.getText(); if(username.equals(password)) { System.out.println("Successfully login with username "+usTF.getText()+" and password "+ passTF.getText()+"."); dispose(); } else { System.out.println("Invalid details."); } } }); reset.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { usTF.setText(""); passTF.setText(""); } }); } public static void main(String[] args) { new Login(); } }
saisravanichekuri/oops-lab-programs-
week10/Login.java
376
// Add action listeners to buttons
line_comment
en
false
330
6
376
6
429
6
376
6
467
7
false
false
false
false
false
true
86742_6
/* This file is part of the Fuzion language server protocol implementation. The Fuzion language server protocol implementation 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, version 3 of the License. The Fuzion language server protocol implementation 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 The Fuzion language implementation. If not, see <https://www.gnu.org/licenses/>. */ /*----------------------------------------------------------------------- * * Tokiwa Software GmbH, Germany * * Source of class IO * *---------------------------------------------------------------------*/ package dev.flang.lsp; import java.io.InputStream; import java.io.PrintStream; public class IO { // To be able to suppress the output of the // fuzion compiler we need to override // System.out etc. // In case of transport=stdio // will use these fields to write to stdout. // public static final PrintStream SYS_OUT = System.out; public static final PrintStream SYS_ERR = System.err; public static final InputStream SYS_IN = System.in; }
tokiwa-software/fuzion
src/dev/flang/lsp/IO.java
324
// will use these fields to write to stdout.
line_comment
en
false
284
10
324
10
329
10
324
10
378
10
false
false
false
false
false
true
87433_3
/* SHPE Hackathon 2016 App: Baseline used for "Build a farmer's future" project Copyright (C) 2016 Daniel Oliveros 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/>. */ package Components; public class Job { private int risk; private int waterNeeds; private int restMinutes; public Job(int risk, int waterNeeds, int restMinutes){ this.risk = risk; this.waterNeeds = waterNeeds; this.restMinutes = restMinutes; } /** * Time that has passed */ private int elapsedTime; /** * Time to work for the shift, specified in minutes */ private int workTime; /** * Start job time specified in military time format */ private int startTime; /** * End job time specified in military format */ private int endTime; public int getRisk() { return risk; } public void setRisk(int risk) { this.risk = risk; } public int getWaterNeeds() { return waterNeeds; } public void setWaterNeeds(int waterNeeds) { this.waterNeeds = waterNeeds; } public int getRestMinutes() { return restMinutes; } public void setRestMinutes(int restMinutes) { this.restMinutes = restMinutes; } public double getWorkTime() { return workTime; } public void setWorkTime(){ if (this.endTime<=this.startTime){ this.workTime = 0; } else{ int hours = (int)(endTime/100 - startTime/100); int minutes = (int)(endTime%100 - startTime%100); workTime = (hours*60)+(minutes); } } public void increaseElapsedTime(){ this.elapsedTime++; } public double getEndTime() { return endTime; } public void setEndTime(int endTime) { this.endTime = endTime; } public double getStartTime() { return startTime; } public void setStartTime(int startTime) { this.startTime = startTime; } public int getElapsedTime() { return elapsedTime; } public void setElapsedTime(int elapsedTime) { this.elapsedTime = elapsedTime; } }
DevilPepper/cohrnn
src/Job.java
724
/** * Start job time specified in military time format */
block_comment
en
false
608
14
724
14
761
16
724
14
892
17
false
false
false
false
false
true
88234_2
import java.util.*; import java.io.*; import java.math.*; /** * Auto-generated code below aims at helping you parse * the standard input according to the problem statement. **/ class Player { public static Factory[] factories; public static LinkedList<Troop> troops; public static void main(String args[]) { Scanner in = new Scanner(System.in); int factoryCount = in.nextInt(); // the number of factories factories = new Factory[factoryCount]; troops = new LinkedList<>(); for (int i=0; i<factories.length; i++) factories[i]=new Factory(); int linkCount = in.nextInt(); // the number of links between factories for (int i = 0; i < linkCount; i++) { int factory1 = in.nextInt(); int factory2 = in.nextInt(); int distance = in.nextInt(); factories[factory1].connections.add(new Integer[]{factory2, distance}); //initialize factory-connections factories[factory2].connections.add(new Integer[]{factory1, distance}); } // game loop while (true) { int entityCount = in.nextInt(); // the number of entities (e.g. factories and troops) for (int i = 0; i < entityCount; i++) { int entityId = in.nextInt(); String entityType = in.next(); int arg1 = in.nextInt(); int arg2 = in.nextInt(); int arg3 = in.nextInt(); int arg4 = in.nextInt(); int arg5 = in.nextInt(); if (entityType.equals("FACTORY")){ factories[entityId].init(arg1, arg2, arg3); } else { troops.add (new Troop(entityId, arg1, arg2, arg3, arg4, arg5)); } } for (int j=0; j<factories.length; j++) {System.err.println("Factory "+j+":\n"+ factories[j]);} //print out Factories System.err.println("Troops: "); for (Troop t:troops)System.err.println(t); //print out Troops troops = new LinkedList<Troop>(); System.out.println("WAIT"); } } } class Factory { public LinkedList<Integer[]> connections = new LinkedList<Integer[]>(); public int owner, nrCyborgs, production; public void init (int owner, int nrCyborgs, int production){ this.owner=owner; this.nrCyborgs=nrCyborgs; this.production=production; } public String toString (){ String output=""; for (Integer[] k:connections) output+=Arrays.toString(k)+"\n"; output += owner + " "+nrCyborgs+" "+production+"\n"; return output; } } class Troop { public int owner, id, factoryFrom, factoryTo, nrCyborgs, timeToArrival; public Troop (int id, int owner, int factoryFrom, int factoryTo, int nrCyborgs, int timeToArrival){ this.id=id; this.factoryFrom=factoryFrom; this.factoryTo=factoryTo; this.nrCyborgs=nrCyborgs; this.timeToArrival=timeToArrival; } public String toString(){ return "ID: "+id+" Owner: "+owner+" From: "+factoryFrom+" To: "+factoryTo+" NrCyborgs: "+nrCyborgs+" Arrival: "+timeToArrival; } }
mloesch/codin-ghost
28-02.java
825
// the number of links between factories
line_comment
en
false
771
7
825
7
906
7
825
7
987
8
false
false
false
false
false
true
89239_20
package me.figo.models; import java.util.Date; import java.util.HashMap; import com.google.gson.annotations.Expose; /** * Object representing an user * * @author Stefan Richter */ public class User { /** * Internal figo Connect user ID */ @Expose(serialize = false) private String user_id; /** * First and last name */ @Expose private String name; /** * Email address */ @Expose(serialize = false) private String email; /** * Postal address for bills, etc. */ @Expose private HashMap<String, String> address; /** * This flag indicates whether the email address has been verified */ @Expose(serialize = false) private boolean verified_email; /** * This flag indicates whether the user has agreed to be contacted by email */ @Expose private boolean send_newsletter; /** * Two-letter code of preferred language */ @Expose private String language; /** * This flag indicates whether the figo Account plan is free or premium */ @Expose(serialize = false) private boolean premium; /** * Timestamp of premium figo Account expiry */ @Expose(serialize = false) private Date premium_expires_on; /** * Provider for premium subscription or Null of no subscription is active */ @Expose(serialize = false) private String premium_subscription; /** * Timestamp of figo Account registration */ @Expose(serialize = false) private Date joined_at; public User() { } /** * @return the internal figo Connect user ID */ public String getUserId() { return user_id; } /** * @return the first and last name */ public String getName() { return name; } /** * @param name * the first and last name to set */ public void setName(String name) { this.name = name; } /** * @return the email address */ public String getEmail() { return email; } /** * @return the postal address for bills, etc */ public HashMap<String, String> getAddress() { return address; } /** * @param address * the postal address for bills, etc to set */ public void setAddress(HashMap<String, String> address) { this.address = address; } /** * @return whether the email address has been verified */ public boolean isVerifiedEmail() { return verified_email; } /** * @return whether the user has agreed to be contacted by email */ public boolean isSendNewsletter() { return send_newsletter; } /** * @param send_newsletter * the send newsletter setting to set */ public void setSendNewsletter(boolean send_newsletter) { this.send_newsletter = send_newsletter; } /** * @return the two-letter code of preferred language */ public String getLanguage() { return language; } /** * @param language * the two-letter code of preferred language to set */ public void setLanguage(String language) { this.language = language; } /** * @return whether the figo Account plan is free or premium */ public boolean isPremium() { return premium; } /** * @return the timestamp of premium figo Account expiry */ public Date getPremiumExpiresOn() { return premium_expires_on; } /** * @return the provider for premium subscription or Null of no subscription is active */ public String getPremiumSubscription() { return premium_subscription; } /** * @return the timestamp of figo Account registration */ public Date getJoinedAt() { return joined_at; } }
figo-connect/java-figo
src/main/java/me/figo/models/User.java
912
/** * @param send_newsletter * the send newsletter setting to set */
block_comment
en
false
868
21
912
20
1,028
22
912
20
1,140
24
false
false
false
false
false
true
90189_5
package chris_RSBot; import org.powerbot.script.rt4.ClientContext; import org.powerbot.script.rt4.GameObject; public class Mine extends Task<ClientContext> { public final int[] ironDepositId = {13446, 13444, 13445}; //Set deposit IDs public final int[] copperDepositId = {13450, 13451, 13452,}; public final int[] tinDepositId = {13447, 13449, 13448}; public Mine(ClientContext ctx) { super(ctx); } @Override //Activates if inventory is not full, there is a deposit nearby, //the player is not currently animated(mining), and the player is not //currently in motion. public boolean activate() { return ctx.inventory.select().count() < 28 && !ctx.objects.select().id(copperDepositId).isEmpty() && ctx.players.local().animation() == -1 && !ctx.players.local().inMotion(); } public void execute() { GameObject IronDeposit = ctx.objects.nearest().id(copperDepositId).poll(); //create a game object for the deposit if(IronDeposit.inViewport()) //Check if deposit is in viewport { IronDeposit.interact("Mine"); //Mine game object try { Thread.sleep(1000); //Sleep } catch(InterruptedException ex) { Thread.currentThread().interrupt(); } } else //If object is not in view, walk and turn camera towards it { ctx.movement.step(IronDeposit); ctx.camera.turnTo(IronDeposit); } try { Thread.sleep(1000); } catch(InterruptedException ex) { Thread.currentThread().interrupt(); } } }
ChrisHelmsC/Wrench
Mine.java
519
//Check if deposit is in viewport
line_comment
en
false
452
7
519
7
512
7
519
7
676
9
false
false
false
false
false
true
91259_9
/** * RogueAI class, extending AI * * This class can interact with the firewall in the cannon's software and set * alert levels. RogueAI can decrease the firewall at the expense of raising the * alert level. If the alert level exceeds the maximum alert level, then the self * destruct virus is triggered, and that instance of RogueAI is destroyed. * * @author jmcmath3 * @version 1.0 */ public class RogueAI extends AI { private int firewallProtection; private int alertLevel; private final int maxAlert; /** * Returns value of firewallProtection * * @return firewallProtection */ public int getFirewallProtection() { return firewallProtection; } /** * Returns value of alertLevel * * @return alertLevel */ public int getAlertLevel() { return alertLevel; } /** * Returns value of maxAlert * * @return maxAlert */ public int getMaxAlert() { return maxAlert; } /** * Constructor for RogueAI * * @param firewallProtection int to represent security level of the firewall * @param alertLevel int to represent alert level of computer * @param maxAlert constant level at which computer self destructs * @param cannonTarget coordinates of the cannon's target * @param secretHQ coordinates of the secret HQ */ public RogueAI(int firewallProtection, int alertLevel, int maxAlert, Coordinates cannonTarget, Coordinates secretHQ) { super(cannonTarget, secretHQ); this.firewallProtection = firewallProtection; this.alertLevel = alertLevel; this.maxAlert = maxAlert; } /** * Constructor for RogueAI (alertLevel = 0) * * @param firewallProtection int to represent security level of the firewall * @param maxAlert constant level at which computer self destructs * @param cannonTarget coordinates of the cannon's target * @param secretHQ coordinates of the secret HQ */ public RogueAI(int firewallProtection, int maxAlert, Coordinates cannonTarget, Coordinates secretHQ) { this(firewallProtection, 0, maxAlert, cannonTarget, secretHQ); } /** * Constructor for RogueAI (alertLevel = 0, maxAlert = 10) * * @param firewallProtection int to represent security level of the firewall * @param cannonTarget coordinates of the cannon's target * @param secretHQ coordinates of the secret HQ */ public RogueAI(int firewallProtection, Coordinates cannonTarget, Coordinates secretHQ) { this(firewallProtection, 0, 10, cannonTarget, secretHQ); } /** * Decrements firewallProtection by 2 * Increments alertLevel by 1 */ public void lowerFirewall() { firewallProtection -= 2; alertLevel++; } /** * Validates if cannon can swap target. * * @return true if firewallProtection <= 0, false otherwise */ @Override public boolean shouldSwapCannonTarget() { return firewallProtection <= 0; } /** * Validates if AI should self destruct. * * @return true if alertLevel >= maxAlert, false otherwise */ @Override public boolean shouldSelfDestruct() { return alertLevel >= maxAlert; } /** * {@inheritDoc} */ @Override public String toString() { return "Dr. Chipotle’s guacamole cannon is currently pointed at " + this.getCannonTarget() + ", and is at alert level " + alertLevel + " with firewall protection " + firewallProtection + "."; } }
jacksonmcmath/cs1331
hw4/RogueAI.java
855
/** * Validates if AI should self destruct. * * @return true if alertLevel >= maxAlert, false otherwise */
block_comment
en
false
825
29
856
29
916
34
855
29
1,027
34
false
false
false
false
false
true
91425_3
package com.assignments; //create a Loan class properties like tenure,principal,intrestRate,accountNumber and caluculateEMI() method //HomeLoan extends the Loan class with initilization logic print the emi per year. class Loan { int tenure; double principal; float interestRate; String accountNumber; public double calculateEMI(){ double simpleInterest = (principal*interestRate*tenure)/100; double emi = (simpleInterest+principal)/tenure; return emi; } } public class HomeLoan extends Loan{ HomeLoan() { tenure = 5; //reusing super class member variables principal = 20000; interestRate = 8.5f; accountNumber = "Acc12345"; } public static void main(String[] args) { HomeLoan hloan = new HomeLoan(); double amount = hloan.calculateEMI(); // sub class Object // invoking super class method System.out.println("emi per year..." + amount); } }
sathyasoma/Core-Jaava-Examples--2
HomeLoan.java
265
// sub class Object
line_comment
en
false
230
5
265
5
276
5
265
5
308
5
false
false
false
false
false
true
91527_2
package Chapter3; interface Comparable{ int compareTo(Object obj); } public abstract class Shape implements Comparable{ private String name; public Shape(String shapeName) {name = shapeName;} public String getName() {return name;} public abstract double area(); public abstract double perimeter(); public double semiPerimeter() {return perimeter()/2 ;} public int compareTo(Object obj) { final double EPSILON = 1.0e-15; //slightly bigger than //machine precision Shape rhs = (Shape) obj; double diff = area() - rhs.area(); if (Math.abs(diff) <= EPSILON * Math.abs(area())) return 0; //area of this shape equals area of obj else if (diff < 0) return -1; //area of this shape less than area of obj else return 1; //area of this shape greater than area of obj } public class delta extends Shape { private double sideA; private double sideB; private double sideC; public delta(double deltaSideA,double deltaSideB,double deltaSideC,String deltaName) { super(deltaName); sideA = deltaSideA; sideB = deltaSideB; sideC = deltaSideC; } public double perimeter() {return sideA + sideB + sideC;} public double area() {return Math.sqrt(semiPerimeter()*(semiPerimeter()-sideA)*(semiPerimeter()-sideB)*(semiPerimeter()-sideC));} } public class CFX extends Shape { private double length; private double wide; public CFX(double cfxLength,double cfxWide,String cfxName) { super(cfxName); length = cfxLength; wide = cfxWide; } public double perimeter() {return 2*length + 2*wide;} public double area() {return wide * length;} } public class Circle extends Shape { private double radius; public Circle(double circleRadius, String circleName) { super(circleName); radius = circleRadius; } public double perimeter() { return 2 * Math.PI * radius; } public double area() { return Math.PI * radius * radius; } } public class Square extends Shape { private double side; public Square(double squareSide, String squareName) { super(squareName); side = squareSide; } public double perimeter() { return 4 * side; } public double area() { return side * side; } } }
RF-Tar-Railt/19
Shape.java
708
//area of this shape equals area of obj
line_comment
en
false
604
9
708
9
703
9
708
9
826
9
false
false
false
false
false
true
91531_8
import java.awt.Color; import java.util.ArrayList; import java.util.List; /** * @author Dor Sror * The WideEasy class, implements LevelInformation - the second default level of the game. */ public class WideEasy implements LevelInformation { /** * Returns the number of balls in the level. * In this level, it will be 10. * @return number of balls. */ public int numberOfBalls() { return 10; } /** * Returns a list with all the initial velocities of the balls. * Each ball will always start with a speed of 3sqrt(3). * @return list of velocities for each ball. */ public List<Velocity> initialBallVelocities() { List<Velocity> initialVelocities = new ArrayList<>(); double speed = 3 * Math.sqrt(3); for (int i = 1; i <= 5; i++) { initialVelocities.add(Velocity.fromAngleAndSpeed(i * 10, speed)); initialVelocities.add(Velocity.fromAngleAndSpeed(-i * 10, speed)); } return initialVelocities; } /** * Returns the speed at which the paddle moves. * The speed of the paddle in this level is 2. * @return the speed of the paddle. */ public int paddleSpeed() { return 2; } /** * Returns the width of the paddle. * In this level, it will be 500. * @return width of the paddle. */ public int paddleWidth() { return 625; } /** * Returns the level name as a string. * The level name will be displayed at the top of the screen. * This level's name is `Wide Easy`. * @return the level's name. */ public String levelName() { return "Wide Easy"; } /** * Returns a sprite with the background of the level. * The background should be of a bright sunny day, a green ground and two green hills. * @return a background sprite that contains all the sprites that create said background. */ public Sprite getBackground() { Background background = new Background(); Block canvas = new Block(new Rectangle(new Point(-5, -5), 810, 610)); canvas.setColor(new Color(130, 200, 255)); Ball plain1 = new Ball(new Point(600, 1150), 800, new Color(80, 255, 80)); Ball plain2 = new Ball(new Point(-450, 4000), 3600, new Color(67, 210, 67)); Block soil = new Block(new Rectangle(new Point(-5, 475), 810, 200)); Block road = new Block(new Rectangle(new Point(-5, 495), 810, 40)); road.setColor(new Color(60, 60, 60)); Block tile1 = new Block(new Rectangle(new Point(20, 505), 100, 20)); Block tile2 = new Block(new Rectangle(new Point(155, 505), 100, 20)); Block tile3 = new Block(new Rectangle(new Point(290, 505), 100, 20)); Block tile4 = new Block(new Rectangle(new Point(425, 505), 100, 20)); Block tile5 = new Block(new Rectangle(new Point(560, 505), 100, 20)); Block tile6 = new Block(new Rectangle(new Point(695, 505), 100, 20)); for (Block block : new Block[]{tile1, tile2, tile3, tile4, tile5, tile6}) { block.setColor(new Color(220, 220, 220)); } soil.setColor(new Color(60, 200, 60)); Ball sun1 = new Ball(new Point(85, 75), 135, new Color(245, 225, 160)); Ball sun2 = new Ball(new Point(85, 75), 130, new Color(235, 195, 100)); Ball sun3 = new Ball(new Point(85, 75), 125, Color.YELLOW); Ball cloud1 = new Ball(new Point(600, 100), 35, new Color(215, 215, 215)); Ball cloud2 = new Ball(new Point(620, 85), 35, new Color(215, 215, 215)); Ball cloud3 = new Ball(new Point(640, 110), 35, new Color(215, 215, 215)); Ball cloud4 = new Ball(new Point(660, 80), 35, new Color(215, 215, 215)); Ball cloud5 = new Ball(new Point(690, 95), 35, new Color(215, 215, 215)); Sprite[] backgroundElements = new Sprite[]{canvas, plain1, plain2, soil, road, tile1, tile2, tile3, tile4, tile5, tile6, sun1, sun2, sun3, cloud1, cloud2, cloud3, cloud4, cloud5}; for (Sprite backgroundElement : backgroundElements) { background.addSprite(backgroundElement); } return background; } /** * Returns a list of blocks that make up this level, each block contains * its size, color and location. * @return a list of blocks. */ public List<Block> blocks() { List<Block> blocks = new ArrayList<>(); Color[] colorArray = new Color[]{Color.RED, Color.RED, Color.ORANGE, Color.ORANGE, Color.YELLOW, Color.YELLOW, Color.GREEN, Color.GREEN, Color.GREEN, Color.BLUE, Color.BLUE, Color.MAGENTA, Color.MAGENTA, Color.PINK, Color.PINK}; for (int i = 0; i < 15; i++) { Block block = new Block(new Rectangle(new Point(25 + (i * 50), 275), 50, 25)); block.setColor(colorArray[i]); block.drawOutlines(true); blocks.add(block); } return blocks; } /** * Number of blocks that should be removed before the level is considered to be "cleared". * Note that This number should be <= blocks.size(). * @return the number of blocks that needs to be removed for the level to be cleared. */ public int numberOfBlocksToRemove() { return this.blocks().size(); } }
DorSror/Arkanoid
WideEasy.java
1,697
/** * Number of blocks that should be removed before the level is considered to be "cleared". * Note that This number should be <= blocks.size(). * @return the number of blocks that needs to be removed for the level to be cleared. */
block_comment
en
false
1,599
57
1,697
55
1,808
60
1,697
55
1,944
63
false
false
false
false
false
true
92298_2
package com.xrtb.bidder; import java.util.HashMap; import java.util.Map; /** * A simple class to encode ad unit ids in the embedded web server, RTBServer.java * @author Ben M. Faul * */ public class AdUnitID { /** The mime types hash */ private static Map<Integer,String> adids = new HashMap<Integer, String>(); static { add(1,"Paid Search Units"); add(2,"Recommendation Widgets"); add(3,"Promoted Listings"); add(4,"In-Ad (IAB Standard) with Native Element Units"); add(5,"Custom /”Can’t Be Contained”"); } /** * Add ad unit id to hash * @param a Integer. The Ad unit id * @param b String. The type. */ static void add(Integer a, String b) { adids.put(a,b); } /** * Given the ad unit id descri, return the description. * @param key String. The file suffix. * @return String. The mime type, or null */ public static String substitute(Integer key) { return adids.get(key); } }
benmfaul/XRTB
src/com/xrtb/bidder/AdUnitID.java
300
/** * Add ad unit id to hash * @param a Integer. The Ad unit id * @param b String. The type. */
block_comment
en
false
256
34
300
32
307
36
300
32
326
36
false
false
false
false
false
true
92979_16
//FILE: Business.java //AUTHOR: Xhien Yi Tan ( Xavier ) //ID: 18249833 //UNIT: Object Oriented Software Engineering (COMP2003) //PURPOSE: A container class that stores and manages Business //RELATIONSHIP: Inherited from Property Class public class Business extends Property { private double revenue; private double wages; //Alternate Constructor public Business( String inName, double inMonetaryValue, double inRevenue, double inWages, Company inOwner ) { super( inName, inMonetaryValue, inOwner ); setRevenue( inRevenue ); setWages( inWages ); } //Mutator - set revenue public void setRevenue( double inRevenue ) { if( inRevenue < 0.0 ) { throw new IllegalArgumentException( "Revenue is invalid" ); } else { revenue = inRevenue; } } //Mutator - set wages public void setWages( double inWages ) { if( inWages < 0.0 ) { throw new IllegalArgumentException( "Wages is invalid" ); } else { wages = inWages; } } //Accessor - get wages public double getWages() { return wages; } //Accessor - get revenue public double getRevenue() { return revenue; } //PURPOSE: Get bank account from Property abstract method - throws InvalidOperationException //IMPORT: None //EXPORT: Bank account public BankAccount getBankAccount() throws InvalidOperationException { throw new InvalidOperationException( "Business does not have a bank account" ); } //PURPOSE: Returns details of a business //IMPORT: None //EXPORT: Details of business in String public String toString() { return new String( "Business" + super.toString() + " Revenue: " + getRevenue() + " Wages: " + getWages() ); } //PURPOSE: Calculate the profit of a business using the formula: REVENUE - WAGES, and set as profit //IMPORT: None //EXPORT: None public void calcProfit() { super.setProfit( revenue - wages ); } }
XavierTanXY/OOSE
Business.java
605
//EXPORT: Details of business in String
line_comment
en
false
523
10
605
10
628
10
605
10
766
11
false
false
false
false
false
true
93431_3
/** * Class representing a Notebook computer * @author Jacob/ Koffman & Wolfgang * */ public class Notebook extends Computer { //data fields private double screenSize; private double weight; private String batteryID; private double chargeLeft; private boolean wirelessAvailable; //methods /** * Initialize a Notebook with all original properties specified * @param man The computer manufacturer * @param proc The processor type * @param ram The RAM size * @param disk The disk size * @param procSpeed The processor speed * @param screen The screen size * @param wei The weight */ public Notebook(String man, String proc, double ram, int disk, double procSpeed, double screen, double wei) { super(man, proc, ram, disk, procSpeed); //parent class constructor screenSize = screen; weight = wei; } /** * Initialize a Notebook with all properties specified * @param man The computer manufacturer * @param proc The processor type * @param ram The RAM size * @param disk The disk size * @param procSpeed The processor speed * @param screen The screen size * @param wei The weight */ public Notebook(String man, String proc, double ram, int disk, double procSpeed, double cost, int slots, double screen, double wei, String id, double charge, boolean wireless) { super(man, proc, ram, disk, procSpeed, cost, slots); //parent class constructor screenSize = screen; weight = wei; batteryID = id; chargeLeft = charge; wirelessAvailable = wireless; } public Notebook() { super(); screenSize = 0.0; weight = 10.0; batteryID = "stock"; chargeLeft = 0.0; wirelessAvailable = false; } public double getScreenSize() { return screenSize; } public void setScreenSize(double screenSize) { this.screenSize = screenSize; } public double getWeight() { return weight; } public void setWeight(double weight) { this.weight = weight; } public String getBatteryID() { return batteryID; } public void setBatteryID(String batteryID) { this.batteryID = batteryID; } public double getChargeLeft() { return chargeLeft; } public void setChargeLeft(double chargeLeft) { this.chargeLeft = chargeLeft; } public boolean isWirelessAvailable() { return wirelessAvailable; } public void setWirelessAvailable(boolean wirelessAvailable) { this.wirelessAvailable = wirelessAvailable; } // Form of call to parent's constructor: // super(); // super(argumentList); }
jimlay14/Data-Structures
1.2/src/Notebook.java
710
/** * Initialize a Notebook with all original properties specified * @param man The computer manufacturer * @param proc The processor type * @param ram The RAM size * @param disk The disk size * @param procSpeed The processor speed * @param screen The screen size * @param wei The weight */
block_comment
en
false
622
77
710
70
720
78
710
70
800
81
false
false
false
false
false
true
93710_1
/**The class Flour represents a sub type of VM_Item * that will be an option in the available items that a regular * vending machine can have and combinations for the special * vending machine * * @author Paul Josef P. Agbuya * @author Vince Kenneth D. Rojo * @version 1.0 */ public class Flour extends VM_Item { /** * This constructor initializes a Flour's name, price and * calories based on the given parameters * * @param name name of this item * @param price price of this item * @param calories number of calories this contains */ public Flour(String name, double price, int calories) { super(name, price, calories); } }
pjagbuya/CCPROG3-MCO2
Flour.java
183
/** * This constructor initializes a Flour's name, price and * calories based on the given parameters * * @param name name of this item * @param price price of this item * @param calories number of calories this contains */
block_comment
en
false
171
60
183
58
186
63
183
58
203
68
false
false
false
false
false
true
93853_1
/** * Write a description of class LakeAnimal here. * * @author Nikhil Paranjape * @version 4/24/13 */ public class LakeAnimal extends Animal { // instance variables - replace the example below with your own private String creature; private String noise; private String place; private String statement; /** * Constructors for objects of class Animal */ public LakeAnimal(String lakecreature, String lakenoise, String lakeplace, String lakestatement) { creature = lakecreature; noise = lakenoise; statement = lakestatement; place = lakeplace; } public String toString(){ String line1 = "Old MacDonald had a " + place + ", " + statement; String line2 = "And on that " + place + " he had a " + creature + ", " + statement; String line3 = "With a " + noise + " " + noise + " here and a " + noise + " " + noise + " there"; String line4 = "Here a " + noise + ", there a " + noise + ", everywhere a " + noise + " " + noise; String line5 = "Old MacDonald had a " + place + ", " + statement; return line1 + "\n" + line2 + "\n" + line3 + "\n" + line4 + "\n" + line5 + "\n"; } }
indianpoptart/Inheritance-Practice-Java
LakeAnimal.java
335
// instance variables - replace the example below with your own
line_comment
en
false
314
11
335
11
348
11
335
11
360
11
false
false
false
false
false
true
95874_4
/** * The fire interface of all pokemon that are of * the type fire. * @author Crystal Chun * */ public interface Fire { /** The integer of the fire type */ public static final int type = 0; /** The fire type's special attack menu */ public static final String typeMenu = " 1. Ember" + "\r\n 2. Fire Blast" + "\r\n 3. Fire Punch"; /**The ember attack move that returns the attack damage*/ public int ember(); /**The fire blast move that returns the attack damage of this move*/ public int fireBlast(); /**The fire punch move that returns the attack damage of this move*/ public int firePunch(); }
CrystalChun/Pokemon-Game
Fire.java
186
/**The fire blast move that returns the attack damage of this move*/
block_comment
en
false
156
14
186
15
181
14
186
15
197
15
false
false
false
false
false
true
96974_0
package com.example.abhishek.newsapp.models; import com.example.abhishek.newsapp.network.NewsApi; import java.util.Locale; public class Specification { // List of available countries private static final String[] COUNTRIES_AVAILABLE = {"ae", "ar", "at", "au", "be", "bg", "br", "ca", "ch", "cn", "co", "cu", "cz", "de", "eg", "fr", "gb", "gr", "hk", "hu", "id", "ie", "il", "in", "it", "jp", "kr", "lt", "lv", "ma", "mx", "my", "ng", "nl", "no", "nz", "ph", "pl", "pt", "ro", "rs", "ru", "sa", "se", "sg", "si", "sk", "th", "tr", "tw", "ua", "us", "ve", "za"}; private String category; // Default country private String country = Locale.getDefault().getCountry().toLowerCase(); private String language = null; public String getLanguage() { return language; } public void setLanguage(String language) { this.language = language; } public String getCategory() { return category; } public void setCategory(NewsApi.Category category) { this.category = category.name(); } public String getCountry() { return country; } public void setCountry(String country) { this.country = country; } }
AbhishekChd/NewsApp
app/src/main/java/com/example/abhishek/newsapp/models/Specification.java
368
// List of available countries
line_comment
en
false
339
5
368
5
386
5
368
5
414
5
false
false
false
false
false
true
97501_35
import java.awt.*; import java.awt.image.BufferedImage; import java.io.File; import java.io.FileNotFoundException; import java.util.*; import java.util.ArrayList; import java.util.List; import java.util.Scanner; import javax.swing.*; /** Dataset class Author: S. Bhatnagar -mostly static methods which operate on the data set */ public class DataSet { ////////////////////////////////////////////////////////////////////////////////////////////////// // method that creates a list of dataPoints public static List<DataPoint> readDataSet(String file) throws FileNotFoundException { List<DataPoint> dataset = new ArrayList<DataPoint>(); Scanner scanner = new Scanner(new File(file)); String line; String[] columns; String label; while (scanner.hasNextLine()) { line = scanner.nextLine(); columns = line.split(","); // feature vector will append 1 as x_0, and then take in all // but the last column (which is assigned as label) double[] X = new double[columns.length]; X[0] = 1; for (int i = 1; i < columns.length; i++) { // check if feature is numeric if (isNumeric(columns[i - 1])) { X[i] = Double.parseDouble(columns[i - 1]); } else { // code to convert nominal X to numeric } } label = columns[columns.length - 1]; // special fix of label for handwritten digits data set: label "10" switched to "0" if (label.equals("10")) { label = "0"; } DataPoint dataPoint = new DataPoint(label, X); dataPoint.setTestOrTrain("held_out"); dataset.add(dataPoint); } scanner.close(); return dataset; } /////////////////////////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////////////////////////////////////// // method that creates a list of dataPoints with higher order polynomial X upto to user defined // degree public static List<DataPoint> readDataSetHigherOrderFeatures(String file, int degree) throws FileNotFoundException { List<DataPoint> dataset = new ArrayList<DataPoint>(); Scanner scanner = new Scanner(new File(file)); String line; String[] columns; String label; // all dataPoints in dataset given dummy labelAsDouble, which will be changed // from with call to Logistic.train, based on target label double labelAsDouble = -1.; while (scanner.hasNextLine()) { line = scanner.nextLine(); columns = line.split(","); // feature vector will append 1 as x_0, and then take in all // but the last column (which is assigned as label) double[] X = new double[columns.length]; X[0] = 1; for (int i = 1; i < columns.length; i++) { // check if feature is numeric if (isNumeric(columns[i - 1])) { X[i] = Double.parseDouble(columns[i - 1]); } else { // code to convert nominal X to numeric } } label = columns[columns.length - 1]; // add higher order X ArrayList<Double> higherOrderX = new ArrayList<Double>(); for (int n = 0; n <= degree; n++) { for (int k = 0; k <= n; k++) { double xnk = Math.pow(X[1], n - k) * Math.pow(X[2], k); higherOrderX.add(xnk); } } // convert list to array double[] allX = new double[higherOrderX.size()]; for (int i = 0; i < higherOrderX.size(); i++) { allX[i] = higherOrderX.get(i); } DataPoint dataPoint = new DataPoint(label, allX); dataPoint.setTestOrTrain("held_out"); dataset.add(dataPoint); } scanner.close(); System.out.print("Each data point now has the feature vector: "); for (int n = 0; n <= degree; n++) { for (int k = 0; k <= n; k++) { System.out.print(", x1^" + (n - k) + "*x2^" + k); } } System.out.println(); return dataset; } /////////////////////////////////////////////////////////////////////////////////// /////////////////////////////////////////////////////////////////////////////////// // check is data entry is nominal or numeric public static boolean isNumeric(String str) { return str.matches("-?\\d+(\\.\\d+)?"); // match a number with optional '-' and decimal. } /////////////////////////////////////////////////////////////////////////////////// /////////////////////////////////////////////////////////////////////////////////// // "split off" testSet by setting testOrTrain variable for each dataPoint based on fraction input // by user public static List<DataPoint> getTestSet(List<DataPoint> fullDataSet, double fractionTestSet) { // Random rnd = new Random(123); // Collections.shuffle(fullDataSet, rnd); Collections.shuffle(fullDataSet); List<DataPoint> testSet = new ArrayList<DataPoint>(); // shuffle dataSet and split into test and training sets by setting // testOrTrain variable for each dataPoint for (int i = 0; i < fractionTestSet * fullDataSet.size(); i++) { fullDataSet.get(i).setTestOrTrain("test_set"); testSet.add(fullDataSet.get(i)); } return testSet; } ////////////////////////////////////////////////////////////////////////////////////// /////////////////////////////////////////////////////////////////////////////////// // "split off" trainingSet by setting testOrTrain variable for each dataPoint based on fraction // input by user public static List<DataPoint> getTrainingSet( List<DataPoint> fullDataSet, double fractionTrainingSet) { // Random rnd = new Random(123); // Collections.shuffle(fullDataSet); Collections.shuffle(fullDataSet); List<DataPoint> trainingSet = new ArrayList<DataPoint>(); int count = 0; int i = 0; while (count < fractionTrainingSet * fullDataSet.size() && i < fullDataSet.size()) { String currentSetting = fullDataSet.get(i).getTestOrTrain(); if (currentSetting.equals("training_set")) { trainingSet.add(fullDataSet.get(i)); count++; } else if (!currentSetting.equals("test_set")) { fullDataSet.get(i).setTestOrTrain("training_set"); trainingSet.add(fullDataSet.get(i)); count++; } i++; } return trainingSet; } /////////////////////////////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////////////////////////////// // count & print frequencies of different labels public static void printLabelFrequencies(List<DataPoint> fullDataSet) { HashMap<String, Integer> labelFrequencies = new HashMap<String, Integer>(); List<String> labels = new ArrayList<String>(); for (DataPoint i : fullDataSet) { labels.add(i.getLabel()); } Set<String> uniqueSet = new HashSet<String>(labels); for (String temp : uniqueSet) { labelFrequencies.put(temp, Collections.frequency(labels, temp)); System.out.println(temp + " " + Collections.frequency(labels, temp) + " dataPoints"); } } /////////////////////////////////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////////////////// // get list (set) of unique labels public static Set<String> getLabels(List<DataPoint> fullDataSet) { List<String> labels = new ArrayList<String>(); for (DataPoint i : fullDataSet) { labels.add(i.getLabel()); } Set<String> uniqueSet = new HashSet<String>(labels); return uniqueSet; } //////////////////////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////////////////// // public static void printDataSet(List<DataPoint> fullDataSet) { for (DataPoint i : fullDataSet) { System.out.println( "X = " + Arrays.toString(i.getX()) + ", label = " + i.getLabel() + ", label as vector: " + Arrays.toString(i.getX())); } } //////////////////////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////////////////// // TASK 4: make a method here called distanceEuclid //////////////////////////////////////////////////////////////////////////// }
mcaniglia16/w19-360420-machine-learning
DataSet.java
1,852
// input by user
line_comment
en
false
1,708
4
1,852
4
2,102
4
1,852
4
2,278
4
false
false
false
false
false
true
99710_55
import java.util.*; public class Database { //============================================================== // BORROWERS METHODS //============================================================== /** * Return all borrowers in the database * @return All the borrowers in the database * @throws DataNotFoundException If there was a database issue * @throws InvalidArgumentException If there was a database issue */ public static ArrayList<Borrower> find_borrowers() throws DataNotFoundException, InvalidArgumentException { Mysql db = new Mysql(); return db.getBorrowers(); } /** * Return a single borrower with the specified ID * * @param id The id of the borrower * @return A borrower from the database * @throws DataNotFoundException If there was a database issue * @throws InvalidArgumentException If there was a database issue */ public static Borrower find_borrower(int id) throws DataNotFoundException, InvalidArgumentException { Mysql db = new Mysql(); return db.getBorrower(id); } /** * Search the database for borrowers based on search input hashtable called params, assume that each key=>value pair * is of a correct column (i.e. one of id, forename, surname, email) * @param params a hashtable with the search parameters where the key is the column and the value is the search value * @return An array list of borrowers matching those options * @throws DataNotFoundException If there was a database issue * @throws InvalidArgumentException If there was a database issue */ public static ArrayList<Borrower> find_borrowers(Hashtable params) throws DataNotFoundException, InvalidArgumentException { Mysql db = new Mysql(); return db.getBorrowers(params); } //============================================================== // LOANS METHODS //============================================================== /** * Return all loans in the database * @return All the loans in the database * @throws DataNotFoundException If there was a database issue * @throws InvalidArgumentException If there was a database issue */ public static ArrayList<Loan> find_loans() throws DataNotFoundException, InvalidArgumentException { Mysql db = new Mysql(); return db.getLoans(); } /** * Return all loans in the database belonging to user with a certain id * @param id The id of the borrower * @return An array list of loans that relate to a borrower * @throws DataNotFoundException If there was a database issue * @throws InvalidArgumentException If there was a database issue */ public static ArrayList<Loan> find_loans(int id) throws DataNotFoundException, InvalidArgumentException { Mysql db = new Mysql(); Hashtable<String,Object> params = new Hashtable<String,Object>(); params.put("borrowerID", id); return db.getLoans(params); } /** * Return all loans in the database with a dewey id * @param deweyid The dewey id to search for * @return An array list of loans that relate to a dewey id * @throws DataNotFoundException If there was a database issue * @throws InvalidArgumentException If there was a database issue */ public static Loan find_loans_by_deweyid(String deweyid) throws DataNotFoundException, InvalidArgumentException { Mysql db = new Mysql(); Hashtable<String,Object> params = new Hashtable<String,Object>(); params.put("deweyID", deweyid); Loan loan; try { loan = db.getLoans(params).get(0); } catch(IndexOutOfBoundsException e) { throw new DataNotFoundException("There is no loan with the dewey ID: "+deweyid+"!"); } return loan; } /** * Creates a new loan of a Copy to a Borrower, subject to rules that: * 1. Copy is not reference only * 2. Copy is not already on loan * 3. Borrower has less than six copies currently on loan * 4. Borrower has no overdue loans * 5. Copy is not reserved by another borrower * ALSO: If the borrower is first in the queue of reservations then the loan will be issued and the reservation deleted * * @param copy The copy to issue * @param borrower The borrower to issue a loan to * @throws Exception If there's some issue */ public static void issue_loan(Copy copy, Borrower borrower) throws LoanException, Exception { //1. if(copy.referenceOnly) { throw new LoanException("That copy is marked for reference only!"); } //2. if(copy.getLoan() != null) { throw new LoanException("That copy is already on loan!"); } //3. if(borrower.getLoans().size() > 5) { throw new LoanException("The borrower has reached their limit of six loans!"); } //4. if(borrower.hasLoansOverDue() == true) { throw new LoanException("The borrower has over due loans!"); } //5. //TODO: allow it if the borrower has reserved it and is first in the queue if(copy.item.isReserved()) { throw new LoanException("That copy has already been reserved by another borrower!"); } //MYSQL: insert the loan } /** * Renew an existing Loan * @param loan the loan to be renewed * @return True if the loan was renewed, false otherwise */ public static void renew_loan(Loan loan) throws LoanException, Exception { //1. check copy has not been recalled //TODO: check that copy exists //2. check Borrower has no overdue loans Borrower b = Database.find_borrower(loan.borrower_id); if(b.hasLoansOverDue()) { throw new LoanException("The borrower has over due loans!"); } } /** * Discharge an existing loan * @param loan the loan to be deleted * @return true if the loan was delete, false otherwise */ public static void delete_loan(Loan loan) { //If the Loan is overdue then there must be no fines due to be paid for the Loan } //============================================================== // ITEMS METHODS //============================================================== /** * Return all items in the database * * @return All the items in the database */ public static ArrayList<Item> find_items() throws DataNotFoundException, InvalidArgumentException { Mysql db = new Mysql(); ArrayList<Item> items = new ArrayList<Item>(); //Books items.addAll(db.getBooks()); //Periodicals items.addAll(db.getPeriodicals()); return items; } /** * Return all items in the database which match the search criteria * * @param params The search parameters i.e. Hashtable: {"author" => "J.K. Rowling", "title" => "Harry Potter"} * @return An array list of loans */ public static ArrayList<Item> find_items(Hashtable params) throws DataNotFoundException, InvalidArgumentException { Mysql db = new Mysql(); ArrayList<Item> items = new ArrayList<Item>(); // TODO: //Books items.addAll(db.getBooks(params)); //Periodicals items.addAll(db.getPeriodicals(params)); return items; } //============================================================== // COPIES METHODS //============================================================== /** * Return all copies in the database * * @return ArrayList<Copy> */ public static ArrayList<Copy> find_copies() throws DataNotFoundException, InvalidArgumentException { Mysql db = new Mysql(); return db.getCopies(); } /** * Return all copies with the specified issn in the database (for use with periodicals only) * * @return All the copies relating to that issn */ public static ArrayList<Copy> find_copies_by_issn(String issn) throws DataNotFoundException, InvalidArgumentException { Mysql db = new Mysql(); Hashtable<String,Object> params = new Hashtable<String,Object>(); params.put("issn", issn); return db.getCopies(params); } /** * Return all copies with the specified isbn in the database (for use with books only) * @param isbn The isbn to search or * @return All the copies with that isbn * @throws DataNotFoundException If that isbn wasn't found * @throws InvalidArgumentException If the search options were invalid */ public static ArrayList<Copy> find_copies_by_isbn(String isbn) throws DataNotFoundException, InvalidArgumentException { Mysql db = new Mysql(); Hashtable<String,Object> params = new Hashtable<String,Object>(); params.put("isbn", isbn); return db.getCopies(params); } /** * Finds a copy with a specified dewey id * @param dewey The dewey id to search for * @return A single copy * @throws DataNotFoundException If that dewey wasn't found * @throws InvalidArgumentException If the search options were invalid */ public static Copy find_copy_by_dewey(String dewey) throws DataNotFoundException, InvalidArgumentException { Mysql db = new Mysql(); return db.getCopy(dewey); } //============================================================== // RESERVATIONS METHODS //============================================================== /** * Return all Reservations in the database * @return An array list of reservations in the database * @throws DataNotFoundException If no reservations were found * @throws InvalidArgumentException If the search options were invalid */ public static ArrayList<Reservation> find_reservations() throws DataNotFoundException, InvalidArgumentException { Mysql db = new Mysql(); return db.getReservations(); } /** * Return all Reservations in the database belonging to a specified item * @param item The item to find a reservation for * @return The reservations that relates to that item * @throws DataNotFoundException If there are no reservations relating to that item * @throws InvalidArgumentException If the search options were invalid */ public static ArrayList<Reservation> find_reservations(Item item) throws DataNotFoundException, InvalidArgumentException { Mysql db = new Mysql(); ArrayList<Reservation> all_reservations = Database.find_reservations(); ArrayList<Reservation> result = new ArrayList<Reservation>(); Hashtable<String,Object> params = new Hashtable<String,Object>(); if(item.getType() == "Book") { params.put("isbn", item.isbn); }else{ params.put("issn", item.issn); } return db.getReservations(params); } /** * Cancel a reservation * @param borrower_id the id of the borrower * @param item The item to cancel * @throws ReservationException if there was an issue with reserving * @throws DataNotFoundException If there are no reservations in the database * @throws InvalidArgumentException If the search options were invalid */ public static void cancel_reservation(int borrower_id, Item item) throws ReservationException, DataNotFoundException, InvalidArgumentException { if(item.getType() == "Book") { //Delete by borrower_id and isbn }else{ //Delete by borrower_id and issn } } /** * Place a reservation on an item. If there are free copies then notify. Otherwise, the Copy that was loaned with the earliest issue * date is recalled and the Borrower is told to wait for a week * * @param borrower_id The id of the borrower * @param item The item to place the reservation on * @throws ReservationException If the reservation isn't valid * @throws DataNotFoundException If there was a database issue * @throws InvalidArgumentException If there was a database issue */ public static void place_reservation(int borrower_id, Item item) throws ReservationException, DataNotFoundException, InvalidArgumentException { ArrayList<Copy> copies = item.getCopies(); //1. Find the first free copy Copy free_copy = null; for(int i=0; i<copies.size(); i++) { if(copies.get(i).onLoan() == false) { free_copy = copies.get(i); break; } } //If there are free copies then notify if(free_copy != null) { throw new ReservationException("There are already copies of this item available!"); //Otherwise the Copy that was loaned with the earliest issue is recalled and Borrower is notified }else{ //MYSQL: code goes here to add a new reservation } } }
evanrolfe/Library-Database-Application
Database.java
3,068
//MYSQL: code goes here to add a new reservation
line_comment
en
false
2,757
11
3,068
11
3,146
11
3,068
11
3,725
13
false
false
false
false
false
true
100119_32
//Budget sigmaker for Ghidra (Version 1.0) //@author lexika //@category Functions //@keybinding //@menupath //@toolbar import ghidra.app.script.GhidraScript; import ghidra.program.model.address.Address; import ghidra.program.model.address.AddressSetView; import ghidra.program.model.listing.Function; import ghidra.program.model.listing.FunctionManager; import ghidra.program.model.listing.Instruction; import ghidra.program.model.listing.InstructionIterator; import ghidra.program.model.mem.MemoryAccessException; import java.security.InvalidParameterException; import java.util.Arrays; import java.util.LinkedList; import java.util.List; public class Sigga extends GhidraScript { // Helper class to convert a string signature to bytes + mask, also acts as a container for them private static class ByteSignature { public ByteSignature(String signature) throws InvalidParameterException { parseSignature(signature); } private void parseSignature(String signature) throws InvalidParameterException { // Remove all whitespaces signature = signature.replaceAll(" ", ""); if (signature.isEmpty()) { throw new InvalidParameterException("Signature cannot be empty"); } final List<Byte> bytes = new LinkedList<>(); final List<Byte> mask = new LinkedList<>(); for (int i = 0; i < signature.length(); ) { // Do not convert wildcards if (signature.charAt(i) == '?') { bytes.add((byte) 0); mask.add((byte) 0); i++; continue; } try { // Try to convert the hex string representation of the byte to the actual byte bytes.add(Integer.decode("0x" + signature.substring(i, i + 2)).byteValue()); } catch (NumberFormatException exception) { throw new InvalidParameterException(exception.getMessage()); } // Not a wildcard mask.add((byte) 1); i += 2; } // Lists -> Member arrays this.bytes = new byte[bytes.size()]; this.mask = new byte[mask.size()]; for (int i = 0; i < bytes.size(); i++) { this.bytes[i] = bytes.get(i); this.mask[i] = mask.get(i); } } public byte[] getBytes() { return bytes; } public byte[] getMask() { return mask; } private byte[] bytes; private byte[] mask; } private AddressSetView getCurrentFunctionBody() { FunctionManager functionManager = currentProgram.getFunctionManager(); if (currentLocation == null) { return null; } Address address = currentLocation.getAddress(); if (address == null) { return null; } Function function = functionManager.getFunctionContaining(address); if (function == null) { return null; } return function.getBody(); } private String cleanSignature(String signature) { // Remove trailing whitespace signature = signature.strip(); if (signature.endsWith("?")) { // Use recursion to remove wildcards at end return cleanSignature(signature.substring(0, signature.length() - 1)); } return signature; } private String buildSignatureFromInstructions(InstructionIterator instructions) throws MemoryAccessException { StringBuilder signature = new StringBuilder(); for (Instruction instruction : instructions) { // It seems that instructions that contain addresses which may change at runtime // are always something else then "fallthrough", so we just do this. // TODO: Do this more properly, like https://github.com/nosoop/ghidra_scripts/blob/master/makesig.py#L41 if (instruction.isFallthrough()) { for (byte b : instruction.getBytes()) { // %02X = byte -> hex string signature.append(String.format("%02X ", b)); } } else { for (byte b : instruction.getBytes()) { signature.append("? "); } } } return signature.toString(); } private String refineSignature(String signature, Address functionAddress) { // Strip trailing whitespaces and wildcards signature = cleanSignature(signature); // Remove last byte String newSignature = signature.substring(0, signature.length() - 2); // Try to find the new signature // We know the signature is valid and will at least be found once, // so no need to catch the InvalidParameterException or check for null Address foundAddress = findAddressForSignature(newSignature); // If the new signature is still unique, recursively refine it more if (foundAddress.equals(functionAddress)) { return refineSignature(newSignature, functionAddress); } // We cannot refine the signature anymore without making it not unique return signature; } private void createSignature() throws MemoryAccessException { // Get currently selected function's body AddressSetView functionBody = getCurrentFunctionBody(); // If we have no function selected, fail if (functionBody == null) { printerr("Failed to create signature: No function selected"); return; } // Get instructions for current function InstructionIterator instructions = currentProgram.getListing().getInstructions(functionBody, true); // Generate signature for whole function String signature = buildSignatureFromInstructions(instructions); // Try to find it once to make sure the first address found matches the one we generated it from // We know the signature is valid at this point, so no need to catch the InvalidParameterException if (!findAddressForSignature(signature).equals(functionBody.getMinAddress())) { // I don't see what other problem could cause this printerr("Failed to create signature: Function is (most likely) not big enough to create a unique signature"); return; } // Try to make the signature as small as possible while still being the first one found // Also strip trailing whitespaces and wildcards // TODO: Make this faster - Depending on the program's size and the size of the signature (function body) this could take quite some time signature = refineSignature(signature, functionBody.getMinAddress()); println(signature); } private Address findAddressForSignature(String signature) throws InvalidParameterException { // See class definition ByteSignature byteSignature = new ByteSignature(signature); // Try to find the signature return currentProgram.getMemory().findBytes(currentProgram.getMinAddress(), currentProgram.getMaxAddress(), byteSignature.getBytes(), byteSignature.getMask(), true, null); } private void findSignature(String signature) { Address address = null; try { address = findAddressForSignature(signature); } catch (InvalidParameterException exception) { printerr("Failed to find signature: " + exception.getMessage()); } if (address == null) { println("Signature not found"); return; } if (!currentProgram.getFunctionManager().isInFunction(address)) { println("Warning: The address found is not inside a function"); } println("Found signature at: " + address); } public void run() throws Exception { switch (askChoice("Sigga", "Choose a action to perform", Arrays.asList( "Create signature", "Find signature" ), "Create signature")) { case "Create signature": createSignature(); break; case "Find signature": findSignature(askString("Sigga", "Enter signature to find:", "")); break; } } }
fengjixuchui/Sigga
Sigga.java
1,715
// Try to make the signature as small as possible while still being the first one found
line_comment
en
false
1,592
17
1,715
17
1,871
17
1,715
17
2,046
17
false
false
false
false
false
true
100855_0
package cs3500.music.model; import java.util.ArrayList; import java.util.Collections; import java.util.List; import java.util.Map; import java.util.TreeMap; import java.util.stream.Collectors; import java.util.stream.Stream; /** * Represents a musical composition, with a List of IMusicNote to represent the notes to be * played, and a measure duration. */ public class Opus implements IMusicPiece { private double measureDuration; private List<IMusicNote> notes; private int tempo; /** * Constructs a new Opus object, whose measure length is represented by the given double. * @param measureDuration the number of beats that each measure is composed of. */ public Opus(double measureDuration, int tempo) { this.measureDuration = measureDuration; this.notes = new ArrayList<>(); this.tempo = tempo; } /** * Constructs a new Opus object, with a measure duration specified by the given double, and * contains the notes in the given List of IMusicNote. * * @param measureDuration the maximum number of beats to allow in a measure. * @param notes the notes that this Opus will contain. */ public Opus(double measureDuration, List<IMusicNote> notes, int tempo) { this.measureDuration = measureDuration; this.notes = notes; this.tempo = tempo; } @Override public int getTempo() { return this.tempo; } @Override public void setTempo(int newTempo) { this.tempo = newTempo; } @Override public List<IMusicNote> getNotes() { return new ArrayList<>(this.notes); } @Override public List<IMusicNote> getNotesAfter(int start) { Stream<IMusicNote> noteStream = this.notes.stream(); Stream<IMusicNote> filtered = noteStream.filter((IMusicNote note) -> note.getStartLocation() >= start); return filtered.collect(Collectors.toList()); } @Override public Map<Integer, List<IMusicNote>> computeMap() { int totalTime = (int) Math.ceil(getTotalDuration()); Map<Integer, List<IMusicNote>> map = new TreeMap<>(); List<SoundPair> sounds = ConsolePrinter.soundPairs(lowestNote(), highestNote()); for (int t = 0; t <= totalTime; t += 1) { List<IMusicNote> toPut = new ArrayList<>(); for (SoundPair sound : sounds) { IMusicNote noteToAdd = getNoteAt(sound, t); toPut.add(noteToAdd); } map.put(t, toPut); } return map; } @Override public double getMeasureDuration() { return this.measureDuration; } @Override public double getTotalDuration() { double currMax = 0; for (IMusicNote note : this.notes) { if (note.getEndLocation() > currMax) { currMax = note.getEndLocation(); } } return currMax; } @Override public void addNote(IMusicNote note) { this.notes.add(note); } @Override public void delete(IMusicNote note) throws IllegalArgumentException { if (!(this.notes.contains(note))) { throw new IllegalArgumentException("The Note specified to edit does not exist."); } this.notes.remove(note); } @Override public void replace(IMusicNote currentNote, IMusicNote newNote) throws IllegalArgumentException { if (!(this.notes.contains(currentNote))) { throw new IllegalArgumentException("The Note specified to edit does not exist."); } int currIdx = this.notes.indexOf(currentNote); this.notes.remove(currIdx); this.notes.add(currIdx, newNote); } @Override public void joinPieceIntegrated(IMusicPiece other) throws IllegalArgumentException { if (other.getMeasureDuration() != this.measureDuration) { throw new IllegalArgumentException("The provided piece has a different time signature than " + "the piece to which you are trying to join, must be same time signature."); } this.notes.addAll(other.getNotes()); } @Override public void joinPiecePlayAfter(IMusicPiece other) throws IllegalArgumentException { if (other.getMeasureDuration() != this.measureDuration) { throw new IllegalArgumentException("The provided piece has a different time signature than " + "the piece to which you are trying to join, must be same time signature."); } double songLen = getTotalDuration(); for (IMusicNote note : other.getNotes()) { note.changeLocations(songLen); } this.notes.addAll(other.getNotes()); } @Override public IMusicNote lowestNote() { return Collections.min(this.notes, new NoteSoundComparator()); } @Override public IMusicNote highestNote() { return Collections.max(this.notes, new NoteSoundComparator()); } @Override public IMusicNote getNoteAt(SoundPair sound, int beat) { IMusicNote output = new RestNote(sound.getPitch(), sound.getOctave()); for (IMusicNote note : this.notes) { if (note.getPitch().equals(sound.getPitch()) && note.getOctave() == sound.getOctave() && (beat >= note.getStartLocation()) && (beat <= note.getEndLocation())) { output = note; break; } } return output; } @Override public List<IMusicNote> sortByLocation(List<IMusicNote> collection) { Collections.sort(collection, new NoteLocationComparator()); return collection; } @Override public String visualize(List<IMusicNote> collection) { int totalTime = (int) Math.ceil(getTotalDuration()); ConsolePrinter viewer = new ConsolePrinter(lowestNote(), highestNote(), collection, totalTime); String header = viewer.headerLine(); String rest = viewer.subsequentLines(); return header + "\n" + rest; } @Override public boolean equals(Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } Opus opus = (Opus) o; if (Double.compare(opus.measureDuration, measureDuration) != 0) { return false; } if (tempo != opus.tempo) { return false; } return notes != null ? notes.equals(opus.notes) : opus.notes == null; } @Override public int hashCode() { int result; long temp; temp = Double.doubleToLongBits(measureDuration); result = (int) (temp ^ (temp >>> 32)); result = 31 * result + (notes != null ? notes.hashCode() : 0); result = 31 * result + tempo; return result; } }
LalBirali/MusicEditor
Opus.java
1,633
/** * Represents a musical composition, with a List of IMusicNote to represent the notes to be * played, and a measure duration. */
block_comment
en
false
1,486
30
1,633
33
1,868
33
1,633
33
2,033
36
false
false
false
false
false
true
100937_23
package models; import models.enums.RoleType; import models.utils.AppException; import models.utils.Hash; import play.data.format.Formats; import play.data.validation.Constraints; import com.avaje.ebean.Model; import play.Logger; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.Id; import java.util.Calendar; import java.util.Date; import java.util.List; import java.util.UUID; /** * User: yesnault Date: 20/01/12 */ @Entity public class User extends Model { @Id private Long id; @Constraints.Required @Formats.NonEmpty @Column(unique = true) private String email; @Constraints.Required @Formats.NonEmpty //@Column(unique = true) public String fullname; public String agency; public String confirmationToken; @Constraints.Required @Formats.NonEmpty public String passwordHash; @Formats.DateTime(pattern = "yyyy-MM-dd HH:mm:ss") public Date dateCreation; @Formats.DateTime(pattern = "yyyy-MM-dd") public Date datePasswordRemind; @Formats.DateTime(pattern = "yyyy-MM-dd") public Date dateRemind; @Formats.NonEmpty public Boolean validated = false; // Custom Fields... @Constraints.Required @Formats.NonEmpty // public String role; public RoleType role; public String approved; @Constraints.Required @Formats.NonEmpty public String userkey; public String updatedBy; @Formats.DateTime(pattern = "yyyy-MM-dd HH:mm:ss") public Date dateUpdated; // -- Queries (long id, user.class) public static Model.Finder<Long, User> find = new Model.Finder<Long, User>(Long.class, User.class); /** * Authenticate a User, from a email and clear password. * * @param email * email * @param clearPassword * clear password * @return User if authenticated, null otherwise * @throws AppException * App Exception */ public static User authenticate(String email, String clearPassword) throws AppException { // get the user with email only to keep the salt password User user = find.where().eq("email", email).findUnique(); if (user != null) { // get the hash password from the salt + clear password if (Hash.checkPassword(clearPassword, user.passwordHash)) { return user; } } return null; } public void changePassword(String password) throws AppException { this.passwordHash = Hash.createPassword(password); // Create reminder dates... // Update account... Calendar cal = null; Date result = null; cal = Calendar.getInstance(); cal.add(Calendar.MONTH, 6); result = cal.getTime(); this.dateRemind = result; // Password... cal = Calendar.getInstance(); cal.add(Calendar.MONTH, 3); result = cal.getTime(); this.datePasswordRemind = result; this.save(); } /** * Confirms an account. * * @return true if confirmed, false otherwise. * @throws AppException * App Exception */ public static boolean confirm(User user) throws AppException { if (user == null) { return false; } user.confirmationToken = null; user.validated = true; user.save(); return true; } public String createUserKey() { String userKey = null; // Make sure it is unique... userKey = UUID.randomUUID().toString().replaceAll("-", ""); Boolean isUnique = false; while (!isUnique) { User user = User.findByUserKey(userKey); if (user != null) { // Found user, not unique... Logger.debug("User.createUserKey: User Key " + userKey + " is not unique, creating a new one..."); userKey = UUID.randomUUID().toString().replaceAll("-", ""); } else { // User Key is unique... Logger.debug("User.createUserKey: User Key " + userKey + " is unique."); isUnique = true; } } return userKey; } /** * Retrieve a user from an email. * * @param email * email to search * @return a user */ public static User findByEmail(String email) { return find.where().eq("email", email).findUnique(); } /** * Retrieves a user from a confirmation token. * * @param token * the confirmation token to use. * @return a user if the confirmation token is found, null otherwise. */ public static User findByConfirmationToken(String token) { return find.where().eq("confirmationToken", token).findUnique(); } /** * Retrieve a user from a fullname. * * @param fullname * Full name * @return a user */ public static User findByFullname(String fullname) { return find.where().eq("fullname", fullname).findUnique(); } public static List<User> findByRemindDate(Date remindDate) { // Need to search for a date range... // Create a day before and a day after and use as parameters... Calendar cal = null; // Before date... cal = Calendar.getInstance(); cal.setTime(remindDate); cal.add(Calendar.DATE, -1); Date beforeDate = cal.getTime(); Logger.debug("User findByRemindDate - beforeDate: " + beforeDate); // After date... // Date has changed by a day earlier... // We need to add 2 days now to get day after the original remind // date... cal.add(Calendar.DATE, 2); Date afterDate = cal.getTime(); Logger.debug("User findByRemindDate - afterDate: " + afterDate); // Query... return find.where().gt("dateRemind", beforeDate).lt("dateRemind", afterDate).findList(); } /** * Retrieves a user by unique user key. * * @param unique * user key. * @return a user if the unique user key is found, null otherwise. */ public static User findByUserKey(String userKey) { return find.where().eq("userkey", userKey).findUnique(); } public static List<User> findUnapprovedEM() { return find.where().eq("approved", "N").findList(); } public Long getId() { return id; } public void setId(Long id) { this.id = id; } /** * @return the email */ public String getEmail() { return email; } /** * @param email * the email to set */ public void setEmail(String email) { this.email = email; } /** * @return the role */ public RoleType getRole() { return role; } /** * @param role * the role to set */ public void setRole(RoleType role) { this.role = role; } public String getRoleName(RoleType role) { String roleToDisplay = role.getRoleTextName(role); return roleToDisplay; } public String getRoleNameString(String role) { String roleToDisplay = RoleType.getRoleTextNameString(role); return roleToDisplay; } public void setFullname(String fullname) { this.fullname = fullname; } public String getFullname() { return fullname; } public void setUserkey(String userkey) { this.userkey = userkey; } public String getUserkey() { return userkey; } }
dzeller44/CO-Assist
app/models/User.java
1,991
// We need to add 2 days now to get day after the original remind
line_comment
en
false
1,668
16
1,991
17
2,014
16
1,991
17
2,299
17
false
false
false
false
false
true
103174_10
/** * Represents a Tic-tac-toe game. * * @author Ayo Opuiyo * @version 10/18/19 */ public class Game{ /**represents the game board as matrix of player symbols*/ char [][] board; /**represents board size, which will be a boardSize x boardSize matrix*/ final int boardsize; /**represents the game board as matrix of player symbols*/ APlayer [] players; /**the character to be used to represent a blank space on the board (' ')*/ char SYMBOL_BLANK =' '; /**the character to be used to represent a cpu move on the board ('O')*/ char SYMBOL_CPU = 'O'; /**the character to be used to represent a human move on the board ('X')*/ char SYMBOL_HUMAN = 'X'; /** * Constructor for objects of class TicGame. * @param boardSize - the game board size, which will be a boardSize x boardSize matrix * */ Game (int boardsize){ this.boardsize = boardsize; this.board = new char [boardsize][boardsize]; this.players = new APlayer [2]; for(int i = 0; i < board.length; i++){ for(int j = 0; j < board[i].length; j++){ board[i][j] = SYMBOL_BLANK; } } } /** * Creates a textual representation of the game board in the format: 1 2 3 A X | O | O ---|---|--- B | X | ---|---|--- C O | | X *@param * @return A String representing the game board in the aforementioned format. */ public String toString(){ String str = " "; for (int i = 0; i < board.length; i++){ int count = 1 + i; str = str + " " + count + " "; } for (int i = 0; i < board.length; i++){ char ltr = (char)(65 + i); str = str + "\n" + ltr + ""; for (int j = 0; j <= board[i].length - 1; j++){ if (j == (board.length - 1)){ str = str + " " + board[i][j] + "\n"; } else { str = str + " " + board [i][j] + " " + "|" + ""; } } for (int k = 0; k < board.length; k++){ if (k == board.length - 1){ str = str + "---"; } else if (k == 0){ str = str + " ---|"; } else { str = str + "---|"; } } } return str; } /** * Validates a potential move. Returns 'V' if the move is valid, or a different character indicating the reason why the move is invalid. * * @param move the move to be validated. * * @return 'V' is move is valid, 'R' if it specifies an invalid row, 'C' if it specifies an invalid column, or 'O' if it refers to an already-occupied position. */ public char isValidMove(Move move){ if (move.col < 0 || move.col >= board.length){ return 'C'; } else if (move.row < 0 || move.row >= board.length) { return 'R'; } else if (board[move.col][move.row] != SYMBOL_BLANK) return 'O'; else return 'V'; } /** * Executes the move passed as an argument. If the move is invalid it returns false. * * @param move the move to be executed * @param symbol the symbol of the player who is making the move * * @return true if the move was successfully executed */ protected boolean executeMove(Move move, char symbol){ char val = this.isValidMove(move); if (val == 'V'){ board[move.col][move.row] = symbol; return true; } else { return false; } } /** * A method that analyzes the board to determine the current game sate, which is then returned as a character. A game is over if either player has completed a row, a line, or a diagonal. * Moreover, a game is also over if the board is full, even if no player completed a row, line, or diagonal. That indicates a tie situation. * * @param * @return A character indicating the game state: '?' if the game isn't over yet, 'T' if the game is over and tied, or, if a player won, the winning player's symbol ('X' or 'O'). */ public char getGameStatus(){ for (int i = 0; i < board.length; i++){ int rowsx = 0; int rowsy = 0; for (int j = 0; j < board[i].length; j++){ if(board[i][j] == 'X') rowsx++; else if(board[i][j] == 'O') rowsy++; } if (rowsx == boardsize) return 'X'; else if (rowsy == boardsize) return 'O'; } for (int i = 0; i < board.length; i++){ int colsx = 0; int colsy = 0; for (int k = 0; k < board[i].length; k++){ if(board[k][i] == 'X') colsx++; else if(board[k][i] == 'O') colsy++; } if (colsx == boardsize) return 'X'; else if (colsy == boardsize) return 'O'; } int diagx = 0; int diagy = 0; for (int i = 0; i < board.length; i++){ if(board[i][i] == 'X') diagx++; else if(board[i][i] == 'O') diagy++; if(diagx == boardsize) return 'X'; else if(diagy == boardsize) return 'O'; } int antDiagx = 0; int antDiagy = 0; for (int i = 0, j = boardsize - 1; i < board.length; i++, j--){ if(board[i][j] == 'X') antDiagx++; else if(board[i][j] == 'O') antDiagy++; if(antDiagx == boardsize) return 'X'; else if(antDiagy == boardsize) return 'O'; } for (int i = 0; i < board.length; i++){ for (int j = 0; j < board[i].length; j++){ if (board[i][j] == SYMBOL_BLANK) return '?'; } } return 'T'; } /** * Resets the game state so we can play again. * @param * @return void */ protected void resetGame(){ for (int i = 0; i < board.length; i++){ for (int j = 0; j < board[i].length; j++){ board[i][j] = SYMBOL_BLANK; } } } /** * Plays a single game of Tic-tac-toe by having players pick moves in turn. The first player to play is choosen uniformly at random. * @param * @return A character representing the game's result: 'H' if the human player won, 'C' if the CPU won, 'T' if there was a tie, or 'Q' if the human quit the game. */ public char playSingleGame(){ GameStats gs = new GameStats(); players[0] = new HumanPlayer (this, 'X'); players[1] = new CpuPlayer (this, 'O'); int i = 0; System.out.println(this + "\n"); char val = this.getGameStatus(); if (Math.random() > .5) i = 1; while (val == '?'){ Move mo = players[i].pickMove(); if (mo != null) this.executeMove(mo, players[i].symbol); else return 'Q'; val = this.getGameStatus(); System.out.println(this + "\n"); if (i == 0) i = 1; else i = 0; } if (val == 'X') return 'H'; else if (val == 'O') return 'C'; return val; } /** * Runs consecutive Tic-tac-toe games until the user gets tired and quits. When the user quits, the win-loss-tie statistics are printed. * * @param args The first argument represents the desired game board size, which should be an integer in [1,9]. * If the provided board size does not comply with these rules or if no argument is provided, a default game board size of 3 x 3 will be used. * @return void */ public static void main(String[] args) { Game gm; //if user inputs args set game boardsize, otherwise make 3 X 3 matrix if (args.length == 0) gm = new Game(3); else { int arg1 = Integer.parseInt(args[0]); gm = new Game (arg1); } GameStats gs = new GameStats(); char val = gm.playSingleGame(); while (val != 'Q'){ val = gm.playSingleGame(); if (val == 'H'){ gs.recordWin(); System.out.println("Congratulations you won! Play Again?\n"); System.out.println("----------NEW GAME-------"); } else if (val == 'C'){ gs.recordLoss(); System.out.println("Your loss! Play Again?\n"); System.out.println("----------NEW GAME-------"); } else if (val == 'T'){ gs.recordTie(); System.out.println("You tied! Play Again?\n"); System.out.println("----------NEW GAME-------"); } gm.resetGame(); } if (val == 'Q'){ System.out.println(gs + "\n"); System.out.println("Goodbye and thanks for playing!"); } } }
AOpuiyo/tic-tac-toe
Game.java
2,460
/** * Executes the move passed as an argument. If the move is invalid it returns false. * * @param move the move to be executed * @param symbol the symbol of the player who is making the move * * @return true if the move was successfully executed */
block_comment
en
false
2,367
70
2,460
66
2,703
75
2,460
66
2,873
76
false
false
false
false
false
true
103507_9
/** * A class to represent a song. * @author Colleen Wurden * */ public class Song { private String songName; private String songID; private String songDescription; private String songArtist; private String songAlbum; private String songPrice; public Song() { } /** * @param songName is the name of the song. * @param songID is an unique integer ID assigned to the song. * @param songDescription is the genre the artist usually plays. * @param songArtist is the performer of the song. * @param songAlbum is the album the song is part of. * @param price is the cost to purchase the song. */ public Song(String songName, String songID, String songDescription, String songArtist, String songAlbum, String price) { this.songName = songName; this.songID = songID; this.songDescription = songDescription; this.songArtist = songArtist; this.songAlbum = songAlbum; this.songPrice = price; } public Song(String songID, String songDescription, String songArtist, String songAlbum, String price) { this.songID = songID; this.songDescription = songDescription; this.songArtist = songArtist; this.songAlbum = songAlbum; this.songPrice = price; } /* (non-Javadoc) * @see java.lang.Object#toString() */ @Override public String toString() { return this.songName + ", " + this.songID + ", " + this.songDescription + ", " + this.songArtist + ", " + this.songAlbum + ", " + this.songPrice; } public String toString1() { return this.songName; } /** * @return the songName */ public String getSongName() { return this.songName; } /** * @return the songID */ public String getSongID() { return this.songID; } /** * @return the songDescription */ public String getSongDescription() { return this.songDescription; } /** * @return the songArtist */ public String getSongArtist() { return this.songArtist; } /** * @return the songAlbum */ public String getSongAlbum() { return this.songAlbum; } /** * @return the songPrice */ public String getSongPrice() { return this.songPrice; } /** * @param songName the songName to set */ public void setSongName(String songName) { this.songName = songName; } /** * @param songID the songID to set */ public void setSongID(String songID) { this.songID = songID; } /** * @param songDescription the songDescription to set */ public void setSongDescription(String songDescription) { this.songDescription = songDescription; } /** * @param songArtist the songArtist to set */ public void setSongArtist(String songArtist) { this.songArtist = songArtist; } /** * @param songAlbum the songAlbum to set */ public void setSongAlbum(String songAlbum) { this.songAlbum = songAlbum; } /** * @param songPrice the songPrice to set */ public void setSongPrice(String songPrice) { this.songPrice = songPrice; } public boolean contains(String currentSong) { // TODO Auto-generated method stub return true; } }
gsprunner/SongDatabase
Song.java
862
/** * @param songName the songName to set */
block_comment
en
false
828
15
862
14
1,056
17
862
14
1,131
18
false
false
false
false
false
true
105110_12
/* ///////////////////////////////////////////////////// ///////////////////////////////////////////////////// ////////// Abigail H. Shriver ////////// ////////// CSci 4243 Senior Design Project ////////// ////////// Self-Tracking E-currency ////////// ///////////////////////////////////////////////////// ///////////////////////////////////////////////////// */ import java.io.IOException; public class SysUser extends AESencrp{ SysUser current; //randomly generated static String userID; static int userIDLength =8; //This MUST be encrypted as SOON as //it is entered into the browser //Prior to being stored ANYWHERE! static String password; //Payment Type-- Eventually change to an enumeration String paymentType; String nameFirst; String nameLast; String email; String phone; static String temp; public SysUser(){ } // User constructor public SysUser( String passwordIn, String paymentTypeIn, String nameFirstIn, String nameLastIn, String emailIn, String phoneIn) { userID = randomlyGenerateUserID(); try{ password = AESencrp.encrypt(passwordIn); }catch (Exception e){ return; } paymentType = passwordIn; nameFirst = nameFirstIn; nameLast = nameLastIn; email = emailIn; phone = phoneIn; } public String getPassword(){ return this.password; } //Take random userID and then add another randomly generated sufix to the userId //prior to encyrption, to prevent patterns of UserIDs being detected public static String getEncryptedUser(){ try{ return AESencrp.encrypt(userID + randomlyGenerateUserID()); }catch (Exception e){ return null; } } //Decrypt the encrypted UserID and only take the first 'userIDLength' characters public static String returnPlainTextUser(String encryptedUserID){ try{ return AESencrp.decrypt(encryptedUserID).substring(0,userIDLength); }catch (Exception e){ return null ; } } public static String randomlyGenerateUserID(){ UserID_Generator temp = new UserID_Generator(); return temp.nextSessionId().substring(0, userIDLength); } public static void main(String[] args) { /*//Test randomly generated ids for(int i = 0; i< 1000 ; i++){ System.out.println(randomlyGenerateUserID()); }*/ // SysUser test = new SysUser("test213", // "Credit", "TestUser1","TestUserLast", // "[email protected]", "123-456-7890"); // // Test to make sure the decryption code works // try{ // System.out.println( AESencrp.decrypt(password)); // }catch (Exception e){ // return; // } // System.out.println(AESencrp.decrypt(password)); // return; } }
gw-cs-sd/sd-2017-self-tracking-cryptocurrency
SysUser.java
666
// "Credit", "TestUser1","TestUserLast",
line_comment
en
false
645
15
666
15
769
15
666
15
847
16
false
false
false
false
false
true
106081_2
package com.reflection; import com.github.sarxos.webcam.Webcam; import com.github.sarxos.webcam.WebcamEvent; import com.github.sarxos.webcam.WebcamListener; import com.github.sarxos.webcam.WebcamPanel; import javax.swing.*; import java.awt.*; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.awt.event.MouseEvent; import java.awt.event.MouseListener; import java.util.ArrayList; /** * Created by JBarna on 11/29/2016. */ public class Display { private Webcam webcam; private InstantStart instantStart; private ArrayList<DisplayWindow> displays; private Timer timer; public Display() { init(); } public void start() { // check number of monitors / create classes updateDisplays(); instantStart.start(); for (DisplayWindow d : displays) { d.start(); } timer.restart(); } private void init() { instantStart = new InstantStart(); displays = new ArrayList<DisplayWindow>(); timer = new Timer(Main.SHOW, new TimerListener()); // should be laptop webcam webcam = Webcam.getDefault(); // the last view size is the largest. webcam.setViewSize(webcam.getViewSizes()[webcam.getViewSizes().length - 1]); } private void updateDisplays() { GraphicsDevice[] screenDevices = GraphicsEnvironment .getLocalGraphicsEnvironment() .getScreenDevices(); System.out.println("Screen devices length" + screenDevices.length); // we check to see if any monitors / displays have been added or removed // doesn't work if someone removes a display and then attaches another // but it's good enough if (screenDevices.length != displays.size()) { displays.clear(); System.out.println("Adding devices"); for (GraphicsDevice d : screenDevices) { System.out.println("sd length " + screenDevices.length + ". Display length " + displays.size()); displays.add(new DisplayWindow(d)); } } } private class DisplayWindow extends JWindow { private WebcamPanel wPanel; public DisplayWindow(GraphicsDevice gD) { buildGUI(gD.getDefaultConfiguration().getBounds()); } private void buildGUI(Rectangle bounds) { this.setLayout(new BorderLayout()); wPanel = new WebcamPanel(webcam, false); wPanel.setFitArea(true); final JButton shutdown = new JButton("SHUTDOWN"); shutdown.setPreferredSize(new Dimension((int) (bounds.getWidth() / 4), (int) bounds.getHeight())); shutdown.setForeground(Color.WHITE); shutdown.setBackground(Color.BLACK); shutdown.setBorderPainted(false); shutdown.addMouseListener(new MouseListener() { public void mouseClicked(MouseEvent e) { shutdown.setText("WE'RE GOING DOWN!"); Main.shutdown(); } public void mousePressed(MouseEvent e) { } public void mouseReleased(MouseEvent e) { } public void mouseEntered(MouseEvent e) { shutdown.setBackground(Color.DARK_GRAY); } public void mouseExited(MouseEvent e) { shutdown.setBackground(Color.BLACK); } }); this.getContentPane().add(wPanel, BorderLayout.CENTER); this.getContentPane().add(shutdown, BorderLayout.EAST); this.setLocation(bounds.x, bounds.y); this.setSize((int) bounds.getWidth(), (int) bounds.getHeight()); this.setAlwaysOnTop(true); } public void start() { wPanel.start(); } public void display() { this.setVisible(true); } public void stop() { wPanel.stop(); this.setVisible(false); } } private class InstantStart implements WebcamListener { public void start() { webcam.addWebcamListener(this); } public void webcamOpen(WebcamEvent webcamEvent) { } public void webcamClosed(WebcamEvent webcamEvent) { } public void webcamDisposed(WebcamEvent webcamEvent) { } public void webcamImageObtained(WebcamEvent webcamEvent) { for (DisplayWindow d : displays) { d.display(); } webcam.removeWebcamListener(this); } } private class TimerListener implements ActionListener { public void actionPerformed(ActionEvent e) { for (DisplayWindow d : displays) { d.stop(); } timer.stop(); } } }
JBarna/Reflection
Display.java
1,070
// should be laptop webcam
line_comment
en
false
907
5
1,070
6
1,136
5
1,070
6
1,335
6
false
false
false
false
false
true
106261_1
package frc.robot; import edu.wpi.first.wpilibj.Joystick; import edu.wpi.first.wpilibj.XboxController; import edu.wpi.first.wpilibj.buttons.JoystickButton; import frc.robot.commands.MoveCargoArm; import frc.robot.commands.MoveHatchArm; //Joytick and gamepad are defined here public final class OI { public final XboxController xbox = new XboxController(0); public final Joystick stick = new Joystick(1); // Buttons are called final JoystickButton buttonA = new JoystickButton(xbox, 1); final JoystickButton buttonX = new JoystickButton(xbox, 3); final JoystickButton buttonY = new JoystickButton(xbox, 4); final JoystickButton buttonB = new JoystickButton(xbox, 2 ); final JoystickButton buttonLB = new JoystickButton(xbox, 5); final JoystickButton buttonRB = new JoystickButton(xbox, 6); final JoystickButton buttonBack = new JoystickButton(xbox, 7); // getTriggerAxis public OI() { // Define what buttons do what buttonA.toggleWhenPressed(new MoveHatchArm(0)); buttonX.toggleWhenPressed(new MoveHatchArm(122)); buttonY.toggleWhenPressed(new MoveHatchArm(145)); buttonB.toggleWhenActive(new MoveHatchArm(109)); buttonLB.toggleWhenPressed(new MoveCargoArm(-52)); // down buttonRB.toggleWhenPressed(new MoveCargoArm(-90)); // up buttonBack.toggleWhenPressed(new MoveCargoArm(0)); } }
frc-team-7501/GoldenGears2019
OI.java
412
// Buttons are called
line_comment
en
false
367
5
412
5
398
5
412
5
478
6
false
false
false
false
false
true
106859_0
/* * ********************************************** * San Francisco State University * CSC 220 - Data Structures * File Name: Organization.java * Author: Duc Ta * Author: Arpita Misal * ********************************************** */ package assignment02PartB; // Please organize all the given files in 1 same package // Please make sure to read the provided "_ListOf-PleaseDoNotChange.txt" // // Please DO NOT CHANGE this file. // Please DO NOT CHANGE this file. // Please DO NOT CHANGE this file. // public sealed abstract class Organization permits Club, University, OwnerGroup { // // Data Fields // private String name; // Advanced OOP private String address; // Advanced OOP // // Constructors // protected Organization(){ } // // Abstract Methods // public abstract void displayAbout(); public abstract void displayMission(); } // // Please DO NOT CHANGE this file. // Please DO NOT CHANGE this file. // Please DO NOT CHANGE this file. //
arpitamisal/SF-Giants-Card-Generator
Organization.java
253
/* * ********************************************** * San Francisco State University * CSC 220 - Data Structures * File Name: Organization.java * Author: Duc Ta * Author: Arpita Misal * ********************************************** */
block_comment
en
false
218
47
253
56
292
61
253
56
332
70
false
false
false
false
false
true
106904_2
import java.io.File; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.io.OutputStream; import java.io.UnsupportedEncodingException; import java.net.MalformedURLException; import java.net.URL; import java.net.URLConnection; import jxl.Cell; import jxl.Sheet; import jxl.Workbook; import jxl.read.biff.BiffException; import jxl.write.Label; import jxl.write.Number; import jxl.write.WritableSheet; import jxl.write.WritableWorkbook; import jxl.write.WriteException; import jxl.write.biff.RowsExceededException; import org.apache.commons.codec.binary.Base64; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; import org.json.simple.parser.JSONParser; import org.json.simple.parser.ParseException; public class jsoncon { /** * @param args */ final static int n = 9;// enter number of merchants in the list final static int c = 3;// number of fields in the organisations json public static JSONObject getMerchantId(JSONObject json) throws JSONException { String urlString = "http://ratnakar.api.clinknow.com/m/organization/add"; String result = ""; String contentType = "application/json"; String charset = "UTF-8"; String name = "ratnakar"; String password = "banksecret"; String authString = name + ":" + password; System.out.println("auth string: " + authString); byte[] authEncBytes = Base64.encodeBase64(authString.getBytes()); String authStringEnc = new String(authEncBytes); System.out.println("Base64 encoded auth string: " + authStringEnc); URL url = null; URLConnection connection = null; OutputStream output = null; InputStream response = null; try { url = new URL(urlString); connection = url.openConnection(); connection.setRequestProperty("Authorization", "Basic " + authStringEnc); connection.setDoOutput(true); connection.setRequestProperty("Accept-Charset", charset); connection.setRequestProperty("Content-Type", contentType + ";charset=" + charset); // connection.setRequestProperty("username", username); // connection.setRequestProperty("password", password); output = connection.getOutputStream(); output.write(json.toString().getBytes()); response = connection.getInputStream(); BufferedReader br = new BufferedReader(new InputStreamReader( response)); StringBuilder sb = new StringBuilder(); String line = null; while ((line = br.readLine()) != null) { sb.append(line); } response.close(); result = sb.toString(); System.out.println("Result : \n" + result); } catch (MalformedURLException e) { System.out.println("Incorrect URL for Rest Services"); } catch (UnsupportedEncodingException e) { System.out.println("Unable to connect to Rest Services"); } catch (IOException e) { e.printStackTrace(); System.out.println("Unable to connect to Rest Services"); } return new JSONObject(result); } public static void main(String[] args) throws JSONException { // String[] details = new String[c]; String[] headings = new String[c]; String orgId = new String(); JSONObject jsonObj = new JSONObject(); JSONObject json = new JSONObject(); JSONParser parser = new JSONParser(); JSONObject addressOrg = new JSONObject(); addressOrg.put("line_1", "Dummy_line1"); addressOrg.put("line_2", "Dummy_line2"); addressOrg.put("city", "Dummy"); addressOrg.put("state", "Dummy State"); addressOrg.put("country", "India"); addressOrg.put("pincode", 500008); try { // Create a workbook object from the file at specified location. // Change the path of the file as per the location on your computer. Workbook wrk1 = Workbook.getWorkbook(new File( "F:/Organizations.xls")); // Obtain the reference to the first sheet in the workbook Sheet sheet1 = wrk1.getSheet(0); WritableWorkbook copy = Workbook.createWorkbook(new File( "F:/Organizations with ids.xls"), wrk1); WritableSheet sheet2 = copy.getSheet(0); for (int k = 0; k < c; k++) { Cell colArow = sheet1.getCell(k, 0); String str_colArow = colArow.getContents(); headings[k] = str_colArow; } Label label2 = new Label(c, 0, "organization_id"); sheet2.addCell(label2); for (int i = 1; i < n; i++) { for (int j = 0; j < c; j++) // Obtain reference to the Cell using getCell(int col, int row) // method of sheet { JSONArray campaignInfo = new JSONArray(); Cell colArow1 = sheet1.getCell(j, i); String str_colArow1 = colArow1.getContents(); if (headings[j].equals("address")) json.put(headings[j], addressOrg); else jsonObj.put(headings[j], str_colArow1); // System.out.println("Contents of cell Col" + jsonObj); // details[j]=str_colArow1; } System.out.println(jsonObj); JSONObject orgid = jsoncon.getMerchantId(jsonObj); System.out.println(orgid); Object obj = parser.parse(orgid.toString()); org.json.simple.JSONObject jsonp = (org.json.simple.JSONObject) obj; orgId = (String) jsonp.get("organization_id"); Label label1 = new Label(c, i, orgId); sheet2.addCell(label1); // System.out.println("org_id= " + // jsonp.get("Organization_id")); } // writing all orgId's into the excel sheet copy.write(); copy.close(); } catch (BiffException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } catch (ParseException e) { e.printStackTrace(); } catch (RowsExceededException e) { e.printStackTrace(); } catch (WriteException e) { e.printStackTrace(); } } }
prannoy/Clink
adding_organizations.java
1,672
// number of fields in the organisations json
line_comment
en
false
1,370
8
1,674
9
1,652
8
1,672
9
2,040
9
false
false
false
false
false
true
108322_2
package Numbers; public class mortgage { private double principal; private double rate; private int timePeriod; // in months i.e. no of months public double getPrincipal() { return principal; } /** * if principal is negative than return zero * @param principal */ private void setPrincipal(double principal) { if(principal >= 0) this.principal = principal; else this.principal = 0; // can't be a negative } public double getRate() { return rate; } /** * If rate is less then zero than return zero * @param rate */ private void setRate(double rate) { if(rate >= 0) this.rate = rate; else this.rate = 0; // can't be a negative } public int getTimePeriod() { return timePeriod; } /** * if timePeriod of payment is negative than return 0 * @param timePeriod */ private void setTimePeriod(int timePeriod) { if(timePeriod > 0) this.timePeriod = timePeriod; else this.timePeriod = 0; } /** * Calculate mortgage per month * @return */ public double calculateMortgage() { // M = P [ i(1 + i)^n ] / [ (1 + i)^n – 1] double temp = Math.pow( (1+rate), timePeriod); double x = temp* rate; double y = rate-1; return (this.principal * ( x ) ) / (y); } /** * constructor * @param principal * @param rate * @param timePeriod */ public mortgage (double principal, double rate, int timePeriod) { this.setPrincipal(principal); setRate(rate); setTimePeriod(timePeriod); } /** * Pretty Print form */ public void PrintPayment() { System.out.println("Principal : " + getPrincipal()); System.out.println("TimePeiod : " + getTimePeriod()); System.out.println("Rate : " + getRate()); System.out.println("Payement Per Month : " + calculateMortgage()); } }
Himanshu-Mishr/java
src/Numbers/mortgage.java
519
// can't be a negative
line_comment
en
false
508
6
519
6
584
7
519
6
629
7
false
false
false
false
false
true
108360_25
package src; import utils.*; public abstract class Property extends MonopolyCode { private int price; private int mortgageValue; private boolean mortgaged; private Player owner; // Constructor ======================================================================================================== // Zero Constructor public Property() {} // Default Constructor public Property(int id, String description, Terminal terminal, int price, boolean mortgaged ,int mortgageValue) { // Call the super constructor super(id, description, terminal); // Set rest of attributes this.price = price; this.mortgageValue = mortgageValue; this.mortgaged = mortgaged; this.owner = null; } // Public methods ===================================================================================================== public abstract int getPaymentForRent(); // Overriden toString() method @Override public String toString() { Translator trs = this.terminal.getTranslatorManager().getTranslator(); String output = trs.translate(" - Mortgaged: %s"); output = this.mortgaged ? String.format(output, trs.translate("Yes")) : String.format(output, trs.translate("No")); return super.toString() + "\n" + output; } // General method to do the buy operation public void doBuyOperation(Player p) { Translator trs = this.terminal.getTranslatorManager().getTranslator(); String output = trs.translate("Do you want to buy the property: %s for %d? (%s/%s)"); this.terminal.show(String.format(output, this.getDescription(), this.getPrice(), Constants.DEFAULT_APROVE_STRING, Constants.DEFAULT_CANCEL_STRING)); String answer = this.terminal.readStr(); this.terminal.show(""); if (answer.toLowerCase().equals(Constants.DEFAULT_APROVE_STRING)) { boolean maded = p.pay(this.getPrice(), false); if (maded) { this.setOwner(p); p.getOwnedProperties().add(this); } } } // Default doOperation() method public void doOperation(Player p) { Translator trs = this.terminal.getTranslatorManager().getTranslator(); String output; if (this.getOwner() == null) this.doBuyOperation(p); else if (this.getOwner() != p) { if (this.isMortgaged()) { output = trs.translate("You have landed on the property: %s, but it's mortgaged, you don't pay anything"); this.terminal.show(String.format(output, this.getDescription())); this.terminal.show(""); return; } // Calculate the cost int cost = this.getPaymentForRent(); // Show property info and cost output = trs.translate("You have landed on the property: %s, you must pay %d"); this.terminal.show(String.format(output, this.getDescription(), cost)); this.terminal.show(""); // Pay mandatory cost p.pay(cost, true); // Make operations depending on the player's status if (p.isBankrupt()) p.doBankruptcyTransference(this.getOwner()); else this.getOwner().receive(cost); } else this.doOwnerOperation(); } // Method to do owner operations with a default property (Override if needed) public void doOwnerOperation() { Translator trs = this.terminal.getTranslatorManager().getTranslator(); // Show the owner operation menu and get the answer int answer = this.showOwnerOperationMenu(); // Cancel operation if player wants to if (answer == 3) return; // Else, ask for confirmation String msg; msg = trs.translate("Do you want to make the operation? (%s/%s)"); this.terminal.show(String.format(msg, Constants.DEFAULT_APROVE_STRING, Constants.DEFAULT_CANCEL_STRING)); msg = this.terminal.readStr(); this.terminal.show(""); boolean aproval = msg.toLowerCase().equals(Constants.DEFAULT_APROVE_STRING); if (aproval) { switch (answer) { case 1 -> this.mortgage(); default -> this.unmortgage(); } } else this.terminal.show("The operation has been canceled..."); } // Method to show the owner operation menu for a default property (Override if needed) public int showOwnerOperationMenu() { Translator trs = this.terminal.getTranslatorManager().getTranslator(); String msg = ""; msg = trs.translate("What do you want to do with the property: %s?"); this.terminal.show(String.format(msg, this.getDescription())); msg = trs.translate("Mortgage"); this.terminal.show(String.format("1. %s", msg)); msg = trs.translate("Unmortgage"); this.terminal.show(String.format("2. %s", msg)); msg = trs.translate("Cancel"); this.terminal.show(String.format("3. %s", msg)); this.terminal.show(""); while (true) { int option = this.terminal.readInt(); this.terminal.show(""); if (option < 1 || option > 3) this.terminal.show("Invalid option"); else return option; } } // Method to mortgage a property public void mortgage() { if (this.isMortgaged()) { this.terminal.show("The property is already mortgaged"); this.terminal.show(""); return; } Translator trs = this.terminal.getTranslatorManager().getTranslator(); String output = trs.translate("Property mortgaged, you receive %d"); this.setMortgaged(true); Player owner = this.getOwner(); owner.setBalance(owner.getBalance() + this.getMortgageValue()); this.terminal.show(String.format(output, this.getMortgageValue())); this.terminal.show(""); // Show the mortgage summary this.showMortgageSummary(); } // Method to unmortgage a property public void unmortgage() { if (!this.isMortgaged()) { this.terminal.show("The property isn't mortgaged"); return; } String output; Translator trs = this.terminal.getTranslatorManager().getTranslator(); // Show the unmortgage value int unmortgageValue = Math.round(mortgageValue + (mortgageValue * 0.1f)); output = trs.translate("You must pay %d"); this.terminal.show(String.format(output, unmortgageValue)); this.terminal.show(""); // Ask for confirmation output = trs.translate("Do you want to pay %d? (%s/%s)"); this.terminal.show(String.format(output, unmortgageValue, Constants.DEFAULT_APROVE_STRING, Constants.DEFAULT_CANCEL_STRING)); String aproval = this.terminal.readStr(); this.terminal.show(""); // Cancel operation if player wants to if (!aproval.toLowerCase().equals(Constants.DEFAULT_APROVE_STRING)) return; // Else, get the owner and make the operation Player owner = this.getOwner(); // Check if the player has enough money if (owner.getBalance() < unmortgageValue) this.terminal.show("You don't have enough money"); else { this.setMortgaged(false); owner.setBalance(owner.getBalance() - unmortgageValue); this.terminal.show("Property unmortgaged"); } this.terminal.show(""); // Show the mortgage summary this.showMortgageSummary(); } // Method that returns if the property is owned or not public boolean isOwned() { return this.owner != null; } // Method used to show the mortgage operation summary public void showMortgageSummary() { Translator trs = this.terminal.getTranslatorManager().getTranslator(); String output = trs.translate("Property status: %s >> %s"); output = this.isMortgaged() ? String.format(output, this.getDescription(), trs.translate("Mortgaged")) : String.format(output, this.getDescription(), trs.translate("Unmortgaged")); this.terminal.show(output); this.terminal.show(""); } // Getters & setters ================================================================================================== public int getPrice() { return this.price; } public void setPrice(int price) { this.price = price; } public int getMortgageValue() { return this.mortgageValue; } public void setMortgageValue(int mortgageValue) { this.mortgageValue = mortgageValue; } public Player getOwner() { return this.owner; } public void setOwner(Player owner) { this.owner = owner; } public boolean isMortgaged() { return this.mortgaged; } public void setMortgaged(boolean mortgaged) { this.mortgaged = mortgaged; } }
CuB1z/MonopolyBank
src/Property.java
2,103
// Check if the player has enough money
line_comment
en
false
1,910
8
2,103
8
2,209
8
2,103
8
2,599
8
false
false
false
false
false
true
108409_3
public class MortgageAnalyzer { private double loanAmount; private double annualInterestRate; private int loanDurationInMonths; public void enterLoanDetails(double loanAmount, double annualInterestRate, int loanDurationInMonths) { this.loanAmount = loanAmount; this.annualInterestRate = annualInterestRate; this.loanDurationInMonths = loanDurationInMonths; } public boolean verifyLoanDetails() { // Perform verification checks on the entered loan details // Return true if the details are reasonable, otherwise false // Example verification: Check if loan amount, interest rate, and duration are valid // You can add your own validation logic here return (loanAmount > 0 && annualInterestRate >= 0 && loanDurationInMonths > 0); } public void correctLoanDetails() { // Allow the user to correct the input data // Example correction: Prompt the user to re-enter the loan details } public void calculateMortgageDetails() { double monthlyInterestRate = annualInterestRate / 12.0; int numberOfPayments = loanDurationInMonths; double monthlyPayment = (loanAmount * monthlyInterestRate * Math.pow(1 + monthlyInterestRate, numberOfPayments)) / (Math.pow(1 + monthlyInterestRate, numberOfPayments) - 1); double totalInterestPaid = (monthlyPayment * numberOfPayments) - loanAmount; System.out.println("Amount of Loan - $" + loanAmount); System.out.println("Annual Interest Rate - " + annualInterestRate + "%"); System.out.println("Duration of loan in months - " + loanDurationInMonths); System.out.println("Monthly payment - $" + monthlyPayment); System.out.println("Total interest paid - $" + totalInterestPaid); } // Other methods and logic can be added as needed } This is a separate unit test class to test the functionality of the MortgageAnalyzer class. Here's an example unit test using JUnit: java code import org.junit.Test; import static org.junit.Assert.*; public class MortgageAnalyzerTest { @Test public void testCalculateMortgageDetails() { MortgageAnalyzer mortgageAnalyzer = new MortgageAnalyzer(); // Set loan details for testing double loanAmount = 140000; double annualInterestRate = 8.00; int loanDurationInMonths = 360; mortgageAnalyzer.enterLoanDetails(loanAmount, annualInterestRate, loanDurationInMonths); // Verify loan details boolean isValid = mortgageAnalyzer.verifyLoanDetails(); assertTrue(isValid); // Calculate mortgage details mortgageAnalyzer.calculateMortgageDetails(); } }
ia-usgs/MortgageAnalyzer
src/MortgageAnalyzer.java
609
// You can add your own validation logic here
line_comment
en
false
578
9
609
9
635
9
609
9
776
9
false
false
false
false
false
true
108588_3
import java.util.Scanner; import java.util.*; import java.io.*; public class USACO{ public static int bronze(String filename){ try{ //set up local variables File file = new File(filename); Scanner scanner = new Scanner(file); int R = Integer.parseInt(scanner.next()); int C = Integer.parseInt(scanner.next()); int E = Integer.parseInt(scanner.next()); int N = Integer.parseInt(scanner.next()); // initialize lake int[][] lake = new int[R][C]; for (int x = 0; x < lake.length; x++){ for (int y = 0; y < lake[0].length; y++){ lake[x][y] = Integer.parseInt(scanner.next()); } } //instructions int[][] instr = new int[N][3]; for (int x = 0; x < instr.length; x++) { for (int y = 0; y < instr[x].length; y++) { instr[x][y] = scanner.nextInt(); } } //do the instructions... int biggest; for (int counter = 0; counter < instr.length; counter++){ biggest = lake[instr[counter][0]][instr[counter][1]]; //find biggest for (int x = instr[counter][0] - 1; x < instr[counter][0] + 2; x++) { for (int y = instr[counter][1] - 1; y < instr[counter][1] + 2; y++) { if (lake[x][y] > biggest) { biggest = lake[x][y]; } } } //set new lake elevations after stomp. int newbig = biggest - instr[counter][2]; for (int x = instr[counter][0] - 1; x < instr[counter][0] + 2; x++) { for (int y = instr[counter][1] - 1; y < instr[counter][1] + 2; y++) { if (lake[x][y] > newbig) { lake[x][y] = newbig; } } } } //calculate volume int depth = 0; for(int x = 0; x < R; x++){ for(int y = 0; y < C; y++){ if(lake[x][y] < E){ depth += E - lake[x][y]; } } } return 72 * 72 * depth; } catch(FileNotFoundException e){System.out.println("bad filename");return -100000;} } //helper for silver making old and new arrays equal private static void setEqual(int[][] first, int[][] second){ for (int x = 0; x < first.length; x++) { for (int y = 0; y < first[0].length; y++) { second[x][y] = first[x][y]; } } } public static int silver(String filename){ try{ //set up local variables File file = new File(filename); Scanner scanner = new Scanner(file); int N = Integer.parseInt(scanner.next()); int M = Integer.parseInt(scanner.next()); int T = Integer.parseInt(scanner.next()); //initialize pasture. String nextline = scanner.nextLine(); String[][] pasture = new String[N][M]; for (int x = 0; x < N; x++){ nextline = scanner.nextLine(); for (int y = 0; y < M; y++){ pasture[x][y] = nextline.substring(y, y + 1); } } //instructions. int[] instr = new int[4]; for (int x = 0; x < instr.length; x++) { instr[x] = scanner.nextInt(); } //do instructions. int[][] newpasture = new int[N][M]; int[][] oldpasture = new int[N][M]; for (int x = 0; x < N; x++){ for (int y = 0; y < M; y++){ if (pasture[x][y].equals("*")){ newpasture[x][y] = -1; oldpasture[x][y] = -1; }else{ newpasture[x][y] = 0; oldpasture[x][y] = 0; } } } //testing purposes /* for (int x = 0; x < N; x++){ for (int y = 0; y < M; y++){ System.out.print(newpasture[x][y]); } System.out.println(); }*/ newpasture[instr[0] - 1][instr[1] - 1] = 1; for (int time = 0; time < T; time++){ setEqual(newpasture, oldpasture); for (int x = 0; x < N; x++) { for (int y = 0; y < M; y++) { if (newpasture[x][y] != -1) { newpasture[x][y] = 0; if (y + 1 < M && newpasture[x][y + 1] >= 0) { newpasture[x][y] += oldpasture[x][y + 1]; } if (y - 1 >= 0 && newpasture[x][y - 1] >= 0) { newpasture[x][y] += oldpasture[x][y - 1]; } if (x - 1 >= 0 && newpasture[x - 1][y] >= 0) { newpasture[x][y] += oldpasture[x - 1][y]; } if (x + 1 < N && newpasture[x + 1][y] >= 0) { newpasture[x][y] += oldpasture[x + 1][y]; } } } } } return newpasture[instr[2] - 1][instr[3] - 1]; } catch(FileNotFoundException e) {System.out.println("bad filename");return -100000;} } public static void main(String[] args) { System.out.println("Bronze\n"); System.out.println(USACO.bronze("test1.txt")); System.out.println("should be 342144\n"); System.out.println(USACO.bronze("test2.txt")); System.out.println("should be 102762432\n"); System.out.println("Silver\n"); System.out.println(USACO.silver("silvertest1.txt")); System.out.println("answer is 1\n"); System.out.println(USACO.silver("silvertest2.txt")); System.out.println("answer is 74\n"); } }
bertw2002/MKS22X-USACO
USACO.java
1,685
//do the instructions...
line_comment
en
false
1,533
5
1,685
5
1,810
5
1,685
5
1,931
5
false
false
false
false
false
true
109260_3
// Modern, generics version. import java.util.*; class NewStyle { public static void main(String args[]) { // Now, list holds references of type String. ArrayList<String> list = new ArrayList<String>(); list.add("one"); list.add("two"); list.add("three"); list.add("four"); // Notice that Iterator is also generic. Iterator<String> itr = list.iterator(); // The following statement will now cause a compile-time error. // Iterator<Integer> itr = list.iterator(); // Error! while(itr.hasNext()) { String str = itr.next(); // no cast needed // Now, the following line is a compile-time, // rather than run-time, error. // Integer i = itr.next(); // this won't compile System.out.println(str + " is " + str.length() + " chars long."); } } }
Pnayaka/java-example-codes
NewStyle.java
235
// The following statement will now cause a compile-time error.
line_comment
en
false
198
13
235
14
248
13
235
14
286
13
false
false
false
false
false
true
109688_19
import org.jetbrains.annotations.NotNull; public class Country implements Comparable { private final String name; private Unit[] units; private Territory[] supplyCenters; private final Territory[] homeSCs; private boolean alive; private final int id; /** * @return name of the country as string */ public String getName() { return name; } /** * @param alive alive status to set (true = alive, false = not alive) */ public void setAlive(boolean alive) { this.alive = alive; } /** * @return array of units owned by this country */ public Unit[] getUnits() { return units; } /** * @return array of territories which are supply centers of this country */ public Territory[] getSupplyCenters() { return supplyCenters; } /** * @return array of home supply centers of the country */ public Territory[] getHomeSCs() { return homeSCs; } /** * @return are we alive? */ public boolean isAlive() { return alive; } /** * @return integer id of the country, this is a unique identifier for each country */ public int getId() { return id; } /** * Basic constructor for Countries * @param name String for its name * @param units Unit[] for the units that Country controls * @param supplyCenters Territory[] for the supply centers controlled * @param id int for the country id */ public Country(String name, @NotNull Unit[] units, @NotNull Territory[] supplyCenters, int id) { this.name = name; this.units = units; this.supplyCenters = supplyCenters; this.homeSCs = supplyCenters; this.alive = true; this.id = id; } /** * Actually useful constructor for Countries * @param name String for its name * @param supplyCenters Territory[] for the supply centers controlled * @param id int for the country id */ public Country(String name, Territory[] supplyCenters, int id) { this.name = name; this.units = null; this.supplyCenters = supplyCenters; this.homeSCs = supplyCenters; this.alive = true; this.id = id; } /** * Default Country constructor */ public Country(int cId){ name=""; units=null; supplyCenters =null; homeSCs = null; alive = false; id=cId; } /** * Set the country's units * @param units Unit[] for the country's new units */ public void setUnits(Unit[] units) { this.units = units; } /** * Add a new territory * @param newSC The new territory the country gains */ public void gainSupplyCenter(Territory newSC) { Territory[] newTerritories = new Territory[supplyCenters.length + 1]; System.arraycopy(supplyCenters, 0, newTerritories, 0, supplyCenters.length); newTerritories[supplyCenters.length] = newSC; newSC.setSupplyCenter(id); supplyCenters = newTerritories; } /** * Remove the supply center from the country's SCs * Requires that the country actually has goneSC * @param goneSC The supply center to be removed */ public void loseSupplyCenter(Territory goneSC) { Territory[] newTerritories = new Territory[supplyCenters.length - 1]; int idx = 0; for(Territory territory : supplyCenters) { if(!territory.equals(goneSC)){ newTerritories[idx] = territory; idx++; } } goneSC.setSupplyCenter(-1); supplyCenters = newTerritories; } /** * Check whether the country has the given supply center * @param scCheck The supply center to be checked * @return Whether or not the given supply center belongs to the country */ public boolean hasSupplyCenter(Territory scCheck) { boolean hasSC = false; for(Territory sc : supplyCenters) { if (sc.equals(scCheck)) { hasSC = true; break; } } return hasSC; } /** * Create a unit and add it to the list of units the country controls * @param sc The territory we are building the unit in * @param isFleet Whether the unit is a fleet or not * Requires canBuild(sc) */ public void build(Territory sc, boolean isFleet) { Unit unit = new Unit(this, isFleet, sc); Unit[] newUnits = new Unit[units.length + 1]; System.arraycopy(units, 0, newUnits, 0, units.length); newUnits[units.length] = unit; sc.setOccupied(id); units = newUnits; } /** * Remove the given unit from the list of units the country controls * @param unit The unit we want to disband */ public void disband(Unit unit) { Unit[] newUnits = new Unit[units.length - 1]; int idx = 0; for(Unit u : units) { if(u != unit){ newUnits[idx] = u; idx++; } } unit.getLocation().setOccupied(-1); units = newUnits; } /** * Calculate how many units a country needs to build or disband * Positive = disbands needed, negative = builds needed * @return see above */ public int numBuildsOrDisbands() { int diff = supplyCenters.length - units.length; if(diff <= 0) return diff; else { int numBuilds = 0; for(Territory sc : supplyCenters) if(canBuild(sc)) numBuilds++; return Math.min(numBuilds, diff); } } /** * Check whether the country can build in the given supply center * @param sc The given supply center * @return Whether or not sc is a country's home supply center and is empty */ public boolean canBuild(Territory sc) { for(Territory supplyCenter : supplyCenters) { if(sc.equals(supplyCenter) && sc.getOccupied() == -1) return true; } return false; } /** * Give country details * @return string with name, units, and supply centers of the country */ @Override public String toString() { String str = name; str += "\nUnits: "; for (Unit unit : units) str += unit.toString(); str += "\nSupply centers: "; for (Territory supplyCenter : supplyCenters) str += supplyCenter.toString() + " "; str += "\n----------\n"; return str; } /** * compareTo provides an ordering on countries * @param o The other country * @return -1 if o has a smaller id and 1 if o has a larger id */ @Override public int compareTo(Object o) { Country country2 = (Country)o; return country2.id - this.id; } /** * Check if two countries are equal * @param o - the other country * @return - are they equal? */ @Override public boolean equals(Object o) { return this.compareTo(o) == 0; } }
weibrian/diplomacy
src/Country.java
1,755
/** * compareTo provides an ordering on countries * @param o The other country * @return -1 if o has a smaller id and 1 if o has a larger id */
block_comment
en
false
1,690
43
1,755
41
1,895
44
1,755
41
2,095
45
false
false
false
false
false
true
109845_2
import java.awt.Color; /** * This class is a representation of a Piece * A piece has a color and a location on the board. * * A piece can move itself to another space. */ public class Piece { // attributes private Color _color; private Space _location; private Board _board; /** * Constructs a Piece with a color, location, and a reference to the board * @param color * @param location * @param theBoard that the piece is on */ public Piece(Color color, Space location, Board theBoard) { _color = color; _location = location; _board = theBoard; } /** * Moves the piece a certain number of spaces forward on the board * @param numSpaces the number of spaces to move forward on the board */ public void move(int numSpaces) { // if we are at not at the end of the board, move if (_location.getLocation() + numSpaces <= 31) _location = _board.findSpace(_location.getLocation() + numSpaces); // else move to the begining of the board else _location = _board.findSpace(_location.getLocation() + numSpaces - 32); } /** * Moves the piece to the desired space * @param space the space to move to */ public void moveTo(Space space) { _location = space; } /** * Returns the color of the piece * @return the color of the piece */ public Color getColor() { return _color; } /** * returns the location of the piece * @return the location of the piece */ public Space getLocation() { return _location; } }
bwalcott12/MonopolyJr
Piece.java
441
/** * Constructs a Piece with a color, location, and a reference to the board * @param color * @param location * @param theBoard that the piece is on */
block_comment
en
false
397
45
441
41
472
46
441
41
507
49
false
false
false
false
false
true
109855_6
/* class Fruit * * Credits for the Fruit icons go to: http://www.flaticon.com/free-icon/ */ /** * @author Patricia */ import java.util.ArrayList; import java.awt.Image; import javax.swing.ImageIcon; import javax.imageio.*; import java.io.*; public class Fruit extends Token { private ArrayList<String> soundColl = new ArrayList<String>(); //The collection of sounds which share a certain feature private String sortOfFruit; //can be used as argument for the loadFruitImage() method private String task; //display the task to be fulfilled /* * Default constructor */ public Fruit() { soundColl = new ArrayList<String>(); sortOfFruit = "no sort of fruit"; task = "no task"; } /* * Constructor that takes an ArrayList as an argument * @param aList - a list of sounds to be saved in soundColl */ public Fruit(ArrayList<String> aList) { soundColl.clear(); for(String item: aList) soundColl.add(item); } /* * Method to set the content of soundColl to the elements of ArrayList aList * @param aList - the ArrayList which contains the elements to be put into soundColl */ public void setSoundColl(ArrayList<String> aList) { soundColl.clear(); for(String item: aList) soundColl.add(item); } /* * Method to get the content of soundColl * @return soundColl - the instance variable ArrayList<String> soundColl */ public ArrayList<String> getSoundColl() { return soundColl; } /* * Set the sort of fruit to aSort * @param aSort - the sort of Fruit */ public void setSortOfFruit(String aSort) { sortOfFruit = aSort; } /* * Return the sort of fruit * @return the sortOfFruit */ public String getSortOfFruit() { return sortOfFruit; } /* * Set the task to aTask * @param aTask - the task to be fulfilled */ public void setTask(String aTask) { task = aTask; } /* * Return the task * @return the task */ public String getTask() { return task; } /* * Method to check whether a Sound object belongs to a certain sound collection * @return true if the sound is in the collection, false otherwise */ public boolean containsSound(Sound aSound) { if(aSound == null) return false; String aName = aSound.getSound(); return soundColl.contains(aName); } /* * Method for loading an image of a fruit to render it to the screen, and resize it as needed. * @Override Token.loadTokenImage() */ public void loadTokenImage() { ImageIcon image = new ImageIcon("Icons/Fruit/" + getSortOfFruit() + ".png"); tokenPic = image.getImage().getScaledInstance(Screen.GAME_COLUMN_WIDTH-(Screen.TOKEN_MARGINS*2), Screen.GAME_ROW_HEIGHT-(Screen.TOKEN_MARGINS*2), Image.SCALE_SMOOTH); } /** Static method for generating a random fruit * @param difficulty - Limits the selection based on current game difficulty * @return - The generated fruit */ public static Fruit randomFruit(GameState.Difficulty difficulty) { ArrayList<Fruit> allFruits = new ArrayList<Fruit>(); // Assemble list of possible fruits to choose from. // Fruits for EASY-MEDIUM-HARD allFruits.add(new Pear()); allFruits.add(new Pineapple()); allFruits.add(new Grape()); allFruits.add(new Tomato()); allFruits.add(new Watermelon()); allFruits.add(new Strawberry()); allFruits.add(new Cherry()); // Fruits for MEDIUM-HARD if (difficulty != GameState.Difficulty.EASY) { allFruits.add(new Apple()); allFruits.add(new Banana()); allFruits.add(new Orange()); allFruits.add(new Eggplant()); allFruits.add(new Lemon()); allFruits.add(new Mushroom()); allFruits.add(new Radish()); allFruits.add(new Broccoli()); } // Fruits for HARD if (difficulty == GameState.Difficulty.HARD) { allFruits.add(new Salad()); allFruits.add(new Pumpkin()); allFruits.add(new Carrot()); } // Randomly select a fruit from this list and return it int rVal = (int) Math.floor(Math.random()*allFruits.size()); System.out.println(Integer.toString(rVal)); allFruits.get(rVal).loadTokenImage(); return allFruits.get(rVal); } }
cgdilley/JavaGroupProject
Fruit.java
1,227
/* * Constructor that takes an ArrayList as an argument * @param aList - a list of sounds to be saved in soundColl */
block_comment
en
false
1,095
32
1,227
30
1,289
33
1,227
30
1,427
34
false
false
false
false
false
true
109872_2
import greenfoot.*; // (World, Actor, GreenfootImage, Greenfoot and MouseInfo) /** * Solid object in the world * * @author Eddie Zhuang * @version 2023.01.05 */ public abstract class Block extends GridItem { /** * Class constructor. * * @param cellX The x-position * @param cellY The y-position */ public Block(int cellX, int cellY) { super(cellX, cellY); } public void addedToWorld(World w) { super.addedToWorld(w); } /** * Attempts to move the item in a certain direction * * @param offsetX The number of cells to change the x position by * @param offsetY The number of cells to change the y position by * @return Whether the item was able to be pushed */ public abstract boolean push(int offsetX, int offsetY); }
edzhuang/ics4u-final-project
Block.java
229
/** * Class constructor. * * @param cellX The x-position * @param cellY The y-position */
block_comment
en
false
215
33
229
32
249
38
229
32
257
38
false
false
false
false
false
true
110674_3
import java.util.Arrays; public class Lab0 { private static int[] arr; // Used for mergeSort /** * Perform the insertion sort algorithm on the given array * @param array array to perform the insertion sort on * @return the sorted array */ public static int[] insertionSort(int[] array) { arr = array.clone(); int len = arr.length; if (len == 1) return arr; for (int i = 1; i < len; i++) { int key = arr[i]; int j = i -1; while (j >= 0 && arr[j] > key) { arr[j+1] = arr[j]; j--; } arr[j+1] = key; } return arr; } /** * Perform the merge sort algorithm on the given array * @param array array to sort * @return the sorted array */ public static int[] mergeSort(int[] array) { arr = array.clone(); merge(0, arr.length-1); return arr; } /** * Recursively split the arr array * @param l the left bound of the array * @param r the right bound of the array */ private static void merge(int l, int r) { if (l < r) { int mid = (l + r)/2; merge(l, mid); merge(mid+1, r); mergeSort(l, mid, r); } } /** * Merge the two arrays into one * @param l the left bound of the array * @param m the middle bound of the array * @param r the right bound of the array */ private static void mergeSort(int l, int m, int r) { int arr1Size = m - l + 1; int arr2Size = r - m; int[] arr1 = new int[arr1Size]; int[] arr2 = new int[arr2Size]; // Copying data into temp arrays for (int i = 0; i < arr1Size; i++) { arr1[i] = arr[l+i]; } for (int i = 0; i < arr2Size; i++) { arr2[i] = arr[m + i + 1]; } // Merge the data accordingly int first = 0; // Index for the first array int second = 0; // Index for the second array for (int index = l; index <= r; index++) { if (first == arr1Size) { arr[index] = arr2[second++]; } else if (second == arr2Size || arr1[first] < arr2[second]) { arr[index] = arr1[first++]; } else { arr[index] = arr2[second++]; } } } public static int[] radixSort(int[] array) { arr = array.clone(); int max = arr[0]; for (int i = 0; i < arr.length; i++) { if (max < arr[i]) { max = arr[i]; } } // Perform countSort starting from the least significant exponent for (int exp = 1; max/exp > 0; exp*=10) { countSort(exp); } return arr; } private static void countSort(int exp) { int size = arr.length; int output[] = new int[size]; // output array int count[] = new int[10]; int i; Arrays.fill(count, 0); // Initial occurences is 0 for each digit for (i = 0; i < size; i++) { int digit = (arr[i]/exp)%10; count[digit]++; } // Calculate the running-sum so c[i] = num elements <= i for (i = 1; i < 10; i++) { count[i] += count[i - 1]; } // Build the output array for (i = size - 1; i >= 0; i--) { int digit = (arr[i]/exp)%10; output[count[digit] - 1] = arr[i]; count[digit]--; } // Copy the output array to arr[], so that arr[] now // contains sorted numbers according to curent digit for (i = 0; i < size; i++) { arr[i] = output[i]; } } }
brucehow/cits3001-labs
Lab0.java
1,041
/** * Recursively split the arr array * @param l the left bound of the array * @param r the right bound of the array */
block_comment
en
false
1,025
36
1,041
33
1,174
38
1,041
33
1,209
39
false
false
false
false
false
true
111421_0
import java.awt.image.BufferedImage; public class Roberts { // kernels for x and y-axis's private final int[] dx = { 1, 0, 0, -1 }; private final int[] dy = { 0, -1, 1, 0 }; public BufferedImage robertsOperator(BufferedImage inputImage) { // convert the input image into two arrays, one for the input and output int[][] grayScaleArray = Util.bufferedImageToInt(Util.toGrayscale(inputImage)); long start = System.currentTimeMillis(); int width = grayScaleArray.length; int height = grayScaleArray[0].length; int[][] outputArray = new int[width][height]; // loop through each pixel for (int x = 0; x < width - 1; x++) { for (int y = 0; y < height - 1; y++) { int magnitude = Util.getMagnitude(x, y, dx, dy, grayScaleArray, "Roberts"); // apply magnitude outputArray[x][y] = magnitude; } } // return an image using the Util with the new pixel values System.out.println("TIME: "+(System.currentTimeMillis()-start)); return Util.intToBufferedImage(outputArray); } }
tom-n96/Edge-Detection-Analysis
Roberts.java
304
// kernels for x and y-axis's
line_comment
en
false
287
8
304
9
327
10
304
9
363
12
false
false
false
false
false
true
111428_3
package potluck.domain; import java.util.ArrayList; /* * an enum holding an arrayList of the possible users */ public enum UserDB { USER_DB; private ArrayList<LoginUser> userList = new ArrayList<LoginUser>(); /* * default constructor */ private UserDB() { userList.add(new LoginUser("Johan", "123456", false));// userList.add(new LoginUser("Jacob", "456789", false)); userList.add(new LoginUser("Robert", "789123",false)); userList.add(new LoginUser("Marie", "000000", true)); } /* * returns the arrayList of possible users */ public ArrayList<LoginUser> getUserList() { return userList; } }
mariehit/PotluckRecipes
UserDB.java
217
/* * returns the arrayList of possible users */
block_comment
en
false
177
12
217
12
209
13
217
12
232
14
false
false
false
false
false
true
112060_4
import java.util.*; /** * This class is the main class of the "World of Zuul" application. * "World of Zuul" is a very simple, text based adventure game. Users * can walk around some scenery. That's all. It should really be extended * to make it more interesting! * * To play this game, create an instance of this class and call the "play" * method. * * This main class creates and initialises all the others: it creates all * rooms, creates the parser and starts the game. It also evaluates and * executes the commands that the parser returns. * * @author Michael Kölling and David J. Barnes and Seyed Mohammad Reza Shahrestani. * @version 2019.11.26 */ public class Game { private Parser parser; private Room currentRoom; //private HashMap<String, Room> action; private Time time; private Scanner scan; private boolean finished = false; private int money; private int totalWeight; private int currentWeight; private int seconds = 0; private Room outsideBushHouse, outsideWaterloo, bLecture, wLecture, canteen, lab, office, waterloo, bushHouse, wParking,bParking; private Room previousRoom; private ArrayList<Item> inventory = new ArrayList<>(); private HashMap<String, Item> inventoryHashMap = new HashMap<>(); private HashMap<Item , Integer> hashWeight; private Stack<Room> roomStack; //to be changed private Command command; //to be changed /** * Create the game and initialise its internal map. */ public Game() { createRooms(); Time time = new Time(); parser = new Parser(); scan = new Scanner(System.in); previousRoom = currentRoom; money = 100; totalWeight = 0; currentWeight = 0; roomStack = new Stack<Room>(); hashWeight = new HashMap<>(); } /** * Create all the rooms and link their exits together. */ private void createRooms() { // create the rooms outsideBushHouse = new Room("outside the main entrance of the Bush House Building"); outsideWaterloo = new Room("outside the main entrance of Waterloo campus"); bLecture = new Room("in the Bush House lecture theater"); wLecture = new Room("in the Waterloo lecture theater"); canteen = new Room("in the Waterloo campus canteen"); lab = new Room("in the computing lab"); office = new Room("in the computing admin office"); // my own rooms: waterloo = new Room("The Waterloo campus"); bushHouse = new Room("The Bush House Building"); wParking = new Room("Waterloo campus parking"); bParking = new Room("Bush House Parking"); // initialise room exits outsideBushHouse.setExit("east", lab); outsideBushHouse.setExit("south", bLecture); outsideBushHouse.setExit("west", bLecture); outsideBushHouse.setExit("north", bParking); bParking.setExit("waterloo", wParking); //outsideBushHouse.setExit("Waterloo", outsideWaterloo); outsideWaterloo.setExit("east", wLecture); outsideWaterloo.setExit("south", canteen); outsideWaterloo.setExit("west", canteen); outsideWaterloo.setExit("north", wParking); wParking.setExit("bushHouse", bParking); //outsideWaterloo.setExit("BushHouse", outsideBushHouse); bLecture.setExit("east", outsideBushHouse); lab.setExit("west", outsideBushHouse); lab.setExit("south", office); office.setExit("north", lab); bParking.setExit("south", outsideBushHouse); wLecture.setExit("west", outsideWaterloo); canteen.setExit("east", outsideWaterloo); wParking.setExit("south", outsideWaterloo); currentRoom = outsideBushHouse; // start game outside } /** * Main play routine. Loops until end of play. */ public void play() { printWelcome(); if (scan.nextLine().equals("yes")) { Time time = new Time(); time.startTime(); System.out.println(currentRoom.getLongDescription()); // Enter the main command loop. Here we repeatedly read commands and // execute them until the game is over. //boolean finished = false; while (! finished ) { Command command = parser.getCommand(); finished = processCommand(command); } System.out.println("Thank you for playing. Good bye."); } else { System.out.println("Come back when you where ready!!!"); System.out.println("BYEEEEEEEEEEEEE"); } } /** * Print out the opening message for the player. */ private void printWelcome() { System.out.println(); System.out.println("Welcome to the World of Zuul!"); //System.out.println("World of Zuul is a new, incredibly boring adventure game."); System.out.println("Type 'help' if you need help."); System.out.println(); System.out.println("Type 'yes' if you are ready to start!!!"); System.out.println(); } /** * Given a command, process (that is: execute) the command. * @param command The command to be processed. * @return true If the command ends the game, false otherwise. */ private boolean processCommand(Command command) { String commandWord = command.getCommandWord(); boolean wantToQuit = false; if(command.isUnknown()) { System.out.println("I don't know what you mean..."); return false; } if (commandWord.equals("help")) { printHelp(); } else if (commandWord.equals("go")) { goRoom(command); } else if (commandWord.equals("quit")||commandWord.equals("bye")) { wantToQuit = quit(command); } else if (commandWord.equals("goWithCar")) { //car.withCar() = true; } else if (commandWord.equals("parkTheCar")) { //car.withCar() = false; } else if (commandWord.equals("timeLeft")) { time.timeLeft(); } else if (commandWord.equals("moneyLeft")) { System.out.println("you balance is £"+money); } else if (commandWord.equals("goBack")) { goBack(command); } else if (commandWord.equals("pick")) { pickItem(command); } else if (commandWord.equals("drop")) { } else if (commandWord.equals("inventory")) { printInventory(); } // else command not recognised. return wantToQuit; } /** * pickes the item and place it in inventory * and deletes is from the current room */ private void pickItem(Command command) { if(!command.hasSecondWord()) { // if there is no second word, we don't know what to get... System.out.println("Get what?"); return; } String item = command.getSecondWord(); Item newItem = currentRoom.getItems(item); if (newItem == null) { System.out.println("There is no such an item!"); } else { inventory.add(newItem); currentRoom.removeItems(item); System.out.println(item+ " has been picked up!"); } } /** * drops the item from myList * and places it in the current room */ private void dropItem(Command command) { if(!command.hasSecondWord()) { // if there is no second word, we don't know what to drop... System.out.println("drop what?"); return; } String item = command.getSecondWord(); Item newItem = null; int index = 0; for (int i = 0; i< inventory.size();i++) { if (inventory.get(i).getDescription().equals(item)) { newItem= inventory.get(i); index = i; } } if (newItem == null) { System.out.println("You're not carying such an item!"); } else { inventory.remove(index); currentRoom.setItems(new Item (item)); System.out.println(item+ " has been dropped!"); } } /** * */ private void printInventory() { String print = ""; for (int i=0; i<inventory.size(); i++) { print += inventory.get(i).getDescription() + ""; } System.out.println("You are carrying: "); System.out.println(print); } // implementations of user commands: /** * Print out some help information./ * Here we print some stupid, cryptic message and a list of the * command words. */ private void printHelp() { System.out.println("You are lost. You are alone. You wander"); System.out.println("around at the university."); System.out.println(); System.out.println("Your command words are:"); parser.showCommands(); } /** * Try to in to one direction. If there is an exit, enter the new * room, otherwise print an error message. */ private boolean goRoom(Command command) { if (!command.hasSecondWord()) { // if there is no second word, we don't know where to go... System.out.println("Go where?"); return false; } String direction = command.getSecondWord(); // Try to leave current room. Room nextRoom = currentRoom.getExit(direction); if (nextRoom == null) { System.out.println("There is no door!"); } else { previousRoom = currentRoom; currentRoom = nextRoom; System.out.println(currentRoom.getLongDescription()); } // you win if::: return false; } /** * */ private void goBaaack() { currentRoom = previousRoom; System.out.println(currentRoom.getLongDescription()); } /** * * */ private void goBack(Command command) { if(command.hasSecondWord()) { System.out.println("Back what?"); return; } if(previousRoom == null) { System.out.println("Sorry, cannot go back."); return; } roomStack.push(currentRoom); Room temp = currentRoom; currentRoom = previousRoom; previousRoom = temp; System.out.println("You have gone back to the previous room."); System.out.println(currentRoom.getLongDescription()); } /** * "Quit" was entered. Check the rest of the command to see * whether we really quit the game. * @return true, if this command quits the game, false otherwise. */ private boolean quit(Command command) { if(command.hasSecondWord()) { System.out.println("Quit what?"); return false; } else { return true; // signal that we want to quit } } /** * returns true to quit the game * this method is used in the Time class to finish the game when the time is over */ private boolean timeUp() { finished = true; return finished; } /** * not compleated * * */ private boolean goWithCar(Command command) { if(!command.hasSecondWord()) { // if there is no second word, we don't know where to go... System.out.println("How?"); return false; } String direction = command.getSecondWord(); // Try to leave current room. Room nextRoom = currentRoom.getExit(direction); if (nextRoom == null) { System.out.println("There is no door!"); } else { previousRoom = currentRoom; currentRoom = nextRoom; System.out.println(currentRoom.getLongDescription()); } // you win if::: return false; } }
smrshahrestani/First_Year_Java_2
save1/save1/Game.java
2,932
/** * Create the game and initialise its internal map. */
block_comment
en
false
2,696
14
2,932
14
3,213
16
2,932
14
3,527
17
false
false
false
false
false
true
112456_23
import javafx.event.ActionEvent; import javafx.fxml.FXML; import javafx.scene.control.Button; import javafx.scene.control.Label; import javafx.scene.control.TextField; import javafx.scene.input.KeyCode; import javafx.scene.input.KeyEvent; import java.util.Random; public class GameRound { private Player boris; private Player vadim; private Pile militaryGarbage; private Pile shelf; private Pile discard; private Pile setupAssist; public Player[] playerlist; private int turn=0; //tells you whose turn it is private int currStage=0; //tells you which stage program is at @FXML private Label health; @FXML private Label enemyHealth; @FXML private Label card1; @FXML private Label card2; @FXML private Label card3; @FXML private Label card4; @FXML private TextField inputBox; @FXML private Label messageBox; @FXML private Button deal_button; @FXML private Button end_turn; private Label[] cards; private String inputtext; private Card toDiscard; private void update_health(int new_health) { health.setText(String.valueOf(new_health)); //displays updated health } public void update_message(String message) { messageBox.setText(message); } @FXML public void initialize() { //Initialize Players boris = new Player("Boris", 20); vadim = new Player("Vadim", 20); //Initialize decks this.militaryGarbage = new Pile(true); this.shelf = new Pile(false); this.discard = new Pile(false); this.setupAssist = new Pile(false); int[] idxs = randCards(8); for (int i = 0; i < 8; i++){ int s = idxs[i] % 4; int n = (idxs[i] - s)/4; Card acqCard = new Card(n, s); Pile[] buffer; if (i < 4){ buffer = boris.receive_card(this.militaryGarbage, this.setupAssist, acqCard, i); }else{ buffer = vadim.receive_card(this.militaryGarbage, this.setupAssist, acqCard, i-4); } this.militaryGarbage = buffer[0]; this.setupAssist = buffer[1]; } cards = new Label[]{card1, card2, card3, card4}; //make array so you can access them by index playerlist = new Player[]{boris, vadim}; executeRound(); } /*@FXML protected void deal_hand(ActionEvent event) { update_hand(); int[] pdamage = executeRound(turn); deal_damage(pdamage); turn=(turn+1)%2; //inverts turn, if 0 becomes 1, 1 to 0, changes turn }*/ private void deal_damage(int[] pdamage) { if (pdamage[0] == 0) { boris.takeDamage(pdamage[1]); health.setText(String.valueOf(boris.get_health())); } else { vadim.takeDamage(pdamage[1]); enemyHealth.setText(String.valueOf(vadim.get_health())); } if (boris.get_health() <= 0) { messageBox.setText("Vadim Blyat has won."); } if (vadim.get_health() <= 0) { messageBox.setText("The slav king has won."); } } @FXML protected void endTurn(ActionEvent event) { if (end_turn.getText().equals("Start turn")) { Card[] currHand = playerlist[turn].get_hand(); for (int i=0; i<cards.length; i++) { cards[i].setText(currHand[i].toString()); } end_turn.setText("End turn"); executeRound(); } else { for (int i = 0; i < cards.length; i++) { cards[i].setText(""); } turn = (turn + 1) % 2; currStage=0; end_turn.setText("Start turn"); update_message("Waiting for Player" + turn); } } private boolean int_is_in(int x, int[] arr){ for (int i = 0; i < arr.length; i++){ if (x == arr[i]){ return true; } } return false; } /* private boolean card_is_in(Card ca, Pile pile){ Card[] cntnts = pile.getContents(); for (int i = 0; i < 52; i++){ if (cntnts[i].isEqual(ca)){ return true; } } return false; }*/ private static int randRange(int min, int max) { if (min >= max) { throw new IllegalArgumentException("max must be greater than min"); } Random r = new Random(); return r.nextInt((max - min) + 1) + min; } private Card randCardFromPile(Pile pile){; /* boolean success = false; int cno; Card tester = new Card(13,4); while (success == false) { cno = randRange(0,51)+4; int s = cno % 4; int n = (cno-s)/4; tester = new Card(n,s); if (card_is_in(tester, pile) == false){ return tester; } } return tester;*/ int idx = randRange(0, pile.length()); return pile.pop(idx); } private int[] randCards(int n){ //Generates n random numbers int[] ints = new int[n]; for (int i=0; i<n; i++) { int c=randRange(1,51); ints[i]=c; } return ints; } private boolean isValidCard(int cnum, int[] possibleCards){ for(int i = 0; i < 4; i++){ if(cnum == possibleCards[i]){ return true; } } return false; } private int[] removeCard(int cnum, int[] carray){ for(int i = 0; i < 4; i++){ if(carray[i] == cnum){ carray[i] = 20; } } return carray; } private boolean isKalashnikov(Card[] shand){ int sum = 0; for (int i = 0; i < 4; i++){ sum += shand[i].get_suit(); } if (sum % 4 == 0){ return true; } return false; } // returns 0 if none, 1 if kalashnikov, 2 if golden kalashnikov private int getGun(Player slav){ int[] cardNums = {0, 12, 3, 6}; Card[] slavHand = new Card[4]; slavHand = slav.get_hand(); int gunpoints = 0; for (int i = 0; i < 4; i++){ if (isValidCard(slavHand[i].get_number(), cardNums) == true){ cardNums = removeCard(slavHand[i].get_number(), cardNums); gunpoints++; } } if (gunpoints == 4){ if (isKalashnikov(slavHand) == true){ return 2; } return 1; } return 0; } private int damageDealt(int idx, Card[] hand, boolean isKalashnikov){ int[] snarray = new int[4]; int damage = 0; for (int i = 0; i < 4; i++){ snarray[i] = hand[i].get_number(); if (snarray[i] == 0){ snarray[i] = 20; } } for (int i = 0; i < 4; i++){ if (snarray[i] <= snarray[idx]){ damage++; } } if (isKalashnikov == true){ damage *= 2; } return damage; } /*private int getPlayerNo(Player p){ if (p.role == "Boris"){ return 1; } return 2; } private void printHand(Card[] shand){ for (int i = 0; i < 4; i++){ shand[i].disp(); } }*/ String tpile; @FXML //checks if enter key is pressed, if so get stuff from textbox protected void enterCheck(KeyEvent ke) { System.out.println(currStage); if (ke.getCode()==KeyCode.ENTER) { inputtext = inputBox.getText(); switch (currStage) { //checks if value of currStage == int value, better than a lot of if else case 0: update_message("Which card index do you pick?(0-3)"); case 1: //Kalashnikov Integer idx = Integer.valueOf(inputtext); executeGunLogic(idx); case 2: //Golden Kalashnikov Player otherPlayer = playerlist[(turn+1)%2]; if (inputtext=="y") { int[] pdamage = new int[2]; pdamage[0] = otherPlayer.get_player_id(); pdamage[1] = 8; deal_damage(pdamage); } case 3: Player currPlayer = playerlist[turn]; int rcno=Integer.valueOf(inputtext); toDiscard = currPlayer.get_hand().pop(rcno); update_message("Which pile should the card go to?(d)iscard/(s)helf"); break; case 4: tpile = inputtext; if (this.shelf.contents.length!=0) { update_message("Which pile do you want to draw from(m)ilitary/(s)helf"); } break; case 5: Card drawnCard; String opile = inputtext; if (opile.equals("military") | opile.equals("m")) { drawnCard = randCardFromPile(this.militaryGarbage); } else { try { drawnCard = randCardFromPile(this.shelf); } catch (NullPointerException e) { update_message("There is nothing in the shelf"); } } } currStage+=1; } } private void executeGunLogic(Integer idx) { //idx param needed to calc damage Player currPlayer = playerlist[turn]; Player otherPlayer = playerlist[(turn+1)%2]; Card[] hand2 = otherPlayer.get_hand(); //other player hand if (idx==null) { int gun = getGun(currPlayer);; boolean cont = true; if (gun == 1 && cont == true) { update_message("You have Kalashnikov, would you like to fire?(y/n) "); } else if (gun == 2 && cont == true) { update_message("You have Golden Kalashnikov, would you like to fire?(y/n) "); } else{ currStage+=2; //skip Kalashnikov if no gun } } else { int[] toReturn = new int[2]; int damage = damageDealt(idx, hand2, false); toReturn[0] = otherPlayer.get_player_id(); toReturn[1] = damage; deal_damage(toReturn); } } public void update_hand() { //takes a card, and the position of the card to replace Player currPlayer = playerlist[turn]; Card[] hand = currPlayer.get_hand(); if (currStage==2) { update_message("Which card would you like to replace(range 0-3)"); } for (int i=0;i<hand.length;i++) { cards[i].setText(hand[i].toString()); } currStage+=1; } // returns role code, damage taken of person of role code void executeRound(){ Player currPlayer = playerlist[turn]; Card[] hand1 = currPlayer.get_hand();; //kalashnikov and golden kalashnikov executeGunLogic(null); //pass in null the first time //player1 draws card Card drawnCard; update_hand(); } }
r2dev2/KalashnikovJava
src/GameRound.java
2,993
//player1 draws card
line_comment
en
false
2,768
5
2,993
6
3,233
5
2,993
6
3,539
6
false
false
false
false
false
true
112608_3
import Util.Branch; import java.sql.*; public class Clerk { private Connection con; private PreparedStatement rentVehicle; private PreparedStatement returnVehicle; private PreparedStatement getRentalId; private PreparedStatement getRentalTime; private PreparedStatement getRentalStartOdometer; private PreparedStatement getRentalType; private final String rentVehicleQuery = "INSERT INTO Rental" + "(rid, vid, dlicense, fromTimestamp, toTimestamp, odometer)" + "VALUES (?, ?, ?, ?, ?, ?)"; private final String returnVehicleQuery = "INSERT INTO RETURN" + "(rid, vid, stamp, VALUE)" + "VALUES (?, ?, ?, ?)"; private final String getRentalIdQuery = "SELECT rid FROM Rental WHERE vid = ?"; private final String getRentalTimeQuery = "SELECT fromtimestamp FROM Rental WHERE vid = ?"; private final String getRentalTypeQuery = "SELECT vtname FROM Vehicle WHERE vid = ?"; private final String getRentalStartOdometerQuery = "SELECT odometer FROM Rental WHERE vid = ?"; public Clerk(Connection con) { this.con = con; try { rentVehicle = con.prepareStatement(rentVehicleQuery); returnVehicle = con.prepareStatement(returnVehicleQuery); getRentalId = con.prepareStatement(getRentalIdQuery); getRentalTime = con.prepareStatement(getRentalTimeQuery); getRentalType = con.prepareStatement(getRentalTypeQuery); getRentalStartOdometer = con.prepareStatement(getRentalStartOdometerQuery); } catch (SQLException e) { e.printStackTrace(); } } long rentVehicle(long vid, String dlicense, Timestamp from, Timestamp to, long odometer) throws SQLException { long id = System.currentTimeMillis(); rentVehicle.setLong(1, id); rentVehicle.setLong(2, vid); rentVehicle.setString(3, dlicense); rentVehicle.setTimestamp(4, from); rentVehicle.setTimestamp(5, to); rentVehicle.setLong(6, odometer); rentVehicle.executeUpdate(); con.createStatement().executeUpdate("UPDATE VEHICLE SET STATUS = 1 WHERE VID = " + vid); // Set status of vehicle to rented return id; } void returnVehicle(long rid, long vid, Timestamp stamp, double value) throws SQLException { returnVehicle.setLong(1, rid); returnVehicle.setLong(2, vid); returnVehicle.setTimestamp(3, stamp); returnVehicle.setDouble(4, value); returnVehicle.executeUpdate(); con.createStatement().executeUpdate("UPDATE VEHICLE SET STATUS = 0 WHERE VID = " + vid); // Set status of vehicle to available to rent } Long getRentalId(Long vid) throws SQLException{ getRentalId.setLong(1, vid); ResultSet result = getRentalId.executeQuery(); result.next(); return result.getLong("rid"); } String getRentalType(Long vid) throws SQLException{ getRentalType.setLong(1, vid); ResultSet result = getRentalType.executeQuery(); result.next(); return result.getString("vtname"); } Timestamp getRentalTime(Long vid) throws SQLException{ getRentalTime.setLong(1, vid); ResultSet result = getRentalTime.executeQuery(); result.next(); return result.getTimestamp("fromTimestamp"); } Long getRentalOdometer(Long vid) throws SQLException{ getRentalStartOdometer.setLong(1, vid); ResultSet result = getRentalStartOdometer.executeQuery(); result.next(); return result.getLong("odometer"); } /** * Generates daily rentals report * @param br The branch specified. If null, will generate report for all branches * @param currentDate The currentDate. If null, get the currentDate. Format of currentDate should * be "YYYY-MM-DD" */ ResultSet[] generateDailyRentalsReport(Branch br, String currentDate) throws SQLException { StringBuilder query = new StringBuilder(); String date; if (currentDate == null) { date = new Date(System.currentTimeMillis()).toString(); } else { date = currentDate; } query.append(" FROM Vehicle v WHERE"); if (br != null) { query.append( " v.branch = '").append(br.getLoc()).append("' AND"); } query.append( " v.vid IN") .append(" (SELECT r.vid FROM Rental r WHERE TRUNC(CAST(r.fromTimestamp AS DATE)) = TO_DATE('") .append(date) .append("','YYYY-MM-DD'))"); ResultSet allVehiclesRentedOutToday = con.createStatement() .executeQuery("SELECT *" + query + " ORDER BY v.branch, v.vtname"); ResultSet numVehiclesPerCategory = con.createStatement() .executeQuery("SELECT v.vtname, COUNT(*)" + query + " GROUP BY v.vtname"); ResultSet numRentalsPerBranch = con.createStatement(). executeQuery("SELECT v.branch, COUNT(*)" + query + " GROUP BY v.branch"); ResultSet totalNumOfVehiclesRentedToday = con.createStatement(). executeQuery("SELECT COUNT(*)" + query); return new ResultSet[] {allVehiclesRentedOutToday, numVehiclesPerCategory, numRentalsPerBranch, totalNumOfVehiclesRentedToday}; } /** * Generates daily returns report * @param br The branch specified. If null, will generate report for all branches * @param currentDate The currentDate. If null, get the currentDate. Format of currentDate should * be "YYYY-MM-DD" */ ResultSet[] generateDailyReturnsReport(Branch br, String currentDate) throws SQLException { String date; if (currentDate == null) { date = new Date(System.currentTimeMillis()).toString(); } else { date = currentDate; } ResultSet allVehiclesReturnedToday = con.createStatement() .executeQuery(getallVehiclesReturnedTodayQS(br, date)); ResultSet numVehiclesPerCategory = con.createStatement() .executeQuery(numVehiclesPerCategory(br, date)); ResultSet revenuePerCategory = con.createStatement() .executeQuery(revenuePerCategory(br, date)); ResultSet subtotalsForVehicleAndRevenuePerBr = con.createStatement() .executeQuery(subtotalsForVehicleAndRevenuePerBr(br, date)); ResultSet grandTotals = con.createStatement() .executeQuery(grandTotals(br, date)); return new ResultSet[]{allVehiclesReturnedToday, numVehiclesPerCategory, revenuePerCategory, subtotalsForVehicleAndRevenuePerBr, grandTotals}; } private String getallVehiclesReturnedTodayQS(Branch br, String date) { String toRet = "SELECT * FROM Vehicle v WHERE"; if (br != null) { toRet += " v.branch = '" + br.getLoc() + "' AND"; } toRet += " v.vid IN (SELECT r.vid FROM Return r WHERE TRUNC(CAST(r.stamp AS DATE)) = TO_DATE('" + date + "','YYYY-MM-DD')) ORDER BY v.branch, v.vtname"; return toRet; } private String numVehiclesPerCategory(Branch br, String date) { String toRet = "SELECT v.vtname, COUNT(*) FROM Vehicle v WHERE"; if (br != null) { toRet += " v.branch = '" + br.getLoc() + "' AND"; } toRet += " v.vid IN (SELECT r.vid FROM Return r WHERE TRUNC(CAST(r.stamp AS DATE)) = TO_DATE('" + date + "','YYYY-MM-DD')) GROUP BY v.vtname"; return toRet; } private String revenuePerCategory(Branch br, String date) { String toRet = "SELECT v.vtname, SUM(r.value) FROM Return r, Vehicle v WHERE"; if (br != null) { toRet += " v.branch = '" + br.getLoc() + "' AND"; } toRet += " v.vid = r.vid AND TRUNC(CAST(r.stamp AS DATE)) = TO_DATE('" + date + "','YYYY-MM-DD') GROUP BY v.vtname"; return toRet; } private String subtotalsForVehicleAndRevenuePerBr(Branch br, String date) { String toRet = "SELECT v.branch, COUNT(v.vid), SUM(r.value) FROM Return r, Vehicle v WHERE"; if (br != null) { toRet += " v.branch = '" + br.getLoc() + "' AND"; } toRet += " v.vid = r.vid AND TRUNC(CAST(r.stamp AS DATE)) = TO_DATE('" + date + "','YYYY-MM-DD') GROUP BY v.branch"; return toRet; } private String grandTotals(Branch br, String date) { String toRet = "SELECT COUNT(v.vid), SUM(r.value) FROM Return r, Vehicle v WHERE"; if (br != null) { toRet += " v.branch = '" + br.getLoc() + "' AND"; } toRet += " v.vid = r.vid AND TRUNC(CAST(r.stamp AS DATE)) = TO_DATE('" + date + "','YYYY-MM-DD')"; return toRet; } public ResultSet getVehicleDetails(long targetVid) throws SQLException { return con.createStatement().executeQuery("SELECT * FROM Vehicle WHERE vid = " + targetVid); } }
michutrain/car-rental
src/Clerk.java
2,196
/** * Generates daily returns report * @param br The branch specified. If null, will generate report for all branches * @param currentDate The currentDate. If null, get the currentDate. Format of currentDate should * be "YYYY-MM-DD" */
block_comment
en
false
2,051
58
2,196
61
2,293
62
2,196
61
2,751
69
false
false
false
false
false
true
112612_16
package VideoRental; import java.util.ArrayList; import java.util.Scanner; public class Application { private static ArrayList<Customer> custs = new ArrayList<Customer>(); private static final Scanner sc = new Scanner(System.in); public ArrayList<Customer> getCustomers() { return custs; } public Customer getCustomer(String name) { for (int i=0; i<custs.size(); i++) if ( custs.get(i).getName().compareTo(name)==0) return custs.get(i); return null; } public static void main(String[] args) { // variables required to process user's menu selection String input; char selection = '\0'; // keep repeating the menu until the user chooses to exit do { // display menu options System.out.println("******* Video Rental System Menu *******"); System.out.println(""); System.out.println("A - Employee"); System.out.println("B - Customer"); System.out.println("X - Exit Program"); System.out.println(); // prompt the user to enter their selection System.out.print("Enter your selection: "); input = sc.nextLine(); System.out.println(); // check to see if the user failed to enter exactly one character // for their menu selection if (input.length() != 1) { System.out.println("Error - selection must be a single" + " character!"); } else { // extract the user's menu selection as a char value and // convert it to upper case so that the menu becomes // case-insensitive selection = Character.toUpperCase(input.charAt(0)); // process the user's selection switch (selection) { case 'A': // call addTour() helper method employeeMenu(); break; case 'B': // call displayTourSummary() helper method customerMenu(); break; case 'X': System.out.println("Video Rental system shutting down – goodbye!"); break; default: // default case - handles invalid selections System.out.println("Error - invalid selection!"); } } System.out.println(); } while (selection != 'X'); } private static final void employeeMenu() { String input; char selection = '\0'; // keep repeating the menu until the user chooses to exit do { // display menu options System.out.println("******* Employee Menu *******"); System.out.println(""); System.out.println("A - Add Movie"); System.out.println("B - Add Customer"); System.out.println("X - Exit Program"); System.out.println(); // prompt the user to enter their selection System.out.print("Enter your selection: "); input = sc.nextLine(); System.out.println(); // check to see if the user failed to enter exactly one character // for their menu selection if (input.length() != 1) { System.out.println("Error - selection must be a single" + " character!"); } else { // extract the user's menu selection as a char value and // convert it to upper case so that the menu becomes // case-insensitive selection = Character.toUpperCase(input.charAt(0)); // process the user's selection switch (selection) { case 'A': // call addTour() helper method addMovie(); break; case 'B': // call displayTourSummary() helper method addCustomer(); break; case 'X': System.out.println("Video Rental system shutting down – goodbye!"); break; default: // default case - handles invalid selections System.out.println("Error - invalid selection!"); } } System.out.println(); } while (selection != 'X'); } private static final void addMovie() { } private static final void addCustomer() { System.out.print("Enter customerID : "); String custID = sc.nextLine(); System.out.print("Enter customer name : "); String name = sc.nextLine(); System.out.print("Enter customer address : "); String address = sc.nextLine(); System.out.print("Enter customer email : "); String email = sc.nextLine(); System.out.print("Enter customer phone number : "); String phone = sc.nextLine(); System.out.print("Enter customer rating (Standard/Premium) : "); String rating = sc.nextLine(); // Stores the new tour details in an array Customer objt = new Customer(custID,name,address,email,phone,rating); custs.add(objt); System.out.print("Customer details stored successfully "); } private static final void customerMenu() { } }
rcohe001/SEF-Assignment
Application.java
1,211
// check to see if the user failed to enter exactly one character
line_comment
en
false
1,068
13
1,211
13
1,442
13
1,211
13
1,613
13
false
false
false
false
false
true
112651_1
package sol; import src.ITreeNode; public class Edge { public Object decision; public ITreeNode nextNode; public String attribute; /** * Edge Constructor * * @param decision, determined value associated with edge. * @param nextNode, the next node the edge points to going down the tree. */ public Edge(Object decision, ITreeNode nextNode, String attribute){ this.decision = decision; this.nextNode = nextNode; this.attribute = attribute; } /** * Helps print the tree with this edge, prepending a given string of lead space, and calling printNode on its * nextNode with sufficient lead space. * @param leadSpace the lead space to print before printing the tree (this is to help form * an indented tree structure) */ public void printEdge(String leadSpace){ //TODO: Implement System.out.println(leadSpace + attribute + ": " + decision); nextNode.printNode(leadSpace + " "); } }
brown-cs18-summer-2021/recommender-jgoshu-liamoconno
sol/Edge.java
234
/** * Helps print the tree with this edge, prepending a given string of lead space, and calling printNode on its * nextNode with sufficient lead space. * @param leadSpace the lead space to print before printing the tree (this is to help form * an indented tree structure) */
block_comment
en
false
222
69
234
68
255
71
234
68
270
74
false
false
false
false
false
true
112725_1
/** * Models a Leave Class that extends from Event, * used to simulate the LEAVE event. */ public class Leave extends Event { /** * Build constructor for Leave class. * @param time the time of the event. * @param eventNum the number of the event. * @param customer the customer of the event. */ public Leave(double time, int eventNum, Customer customer) { super(time, eventNum, customer); } @Override Pair<Event, ImList<Server>> updateStatus(ImList<Server> servers, int numOfServers) { return new Pair<>(this, servers); } @Override int updateLeft(int leftCustomer) { return leftCustomer + 1; } @Override public String toString() { return String.format("%.3f " + getCustomer().getCustomerNum() + " leaves", getTime()); } }
nafisazizir/checkout-simulator
Leave.java
204
/** * Build constructor for Leave class. * @param time the time of the event. * @param eventNum the number of the event. * @param customer the customer of the event. */
block_comment
en
false
195
45
204
45
221
50
204
45
242
51
false
false
false
false
false
true
113186_6
// SPDX-License-Identifier: 0BSD // SPDX-FileCopyrightText: The XZ for Java authors and contributors // SPDX-FileContributor: Lasse Collin <[email protected]> import java.io.*; import org.tukaani.xz.*; /** * Decompresses .lzma files to standard output. If no arguments are given, * reads from standard input. * * NOTE: For most purposes, .lzma is a legacy format and usually you should * use .xz instead. */ class LZMADecDemo { public static void main(String[] args) { byte[] buf = new byte[8192]; String name = null; try { if (args.length == 0) { name = "standard input"; // No need to use BufferedInputStream with System.in which // seems to be fast with one-byte reads. InputStream in = new LZMAInputStream(System.in); int size; while ((size = in.read(buf)) != -1) System.out.write(buf, 0, size); } else { // Read from files given on the command line. for (int i = 0; i < args.length; ++i) { name = args[i]; InputStream in = new FileInputStream(name); try { // In contrast to other classes in org.tukaani.xz, // LZMAInputStream doesn't do buffering internally // and reads one byte at a time. BufferedInputStream // gives a huge performance improvement here but even // then it's slower than the other input streams from // org.tukaani.xz. in = new BufferedInputStream(in); in = new LZMAInputStream(in); int size; while ((size = in.read(buf)) != -1) System.out.write(buf, 0, size); } finally { // Close FileInputStream (directly or indirectly // via LZMAInputStream, it doesn't matter). in.close(); } } } } catch (FileNotFoundException e) { System.err.println("LZMADecDemo: Cannot open " + name + ": " + e.getMessage()); System.exit(1); } catch (EOFException e) { System.err.println("LZMADecDemo: Unexpected end of input on " + name); System.exit(1); } catch (IOException e) { System.err.println("LZMADecDemo: Error decompressing from " + name + ": " + e.getMessage()); System.exit(1); } } }
tukaani-project/xz-java
src/LZMADecDemo.java
602
// Read from files given on the command line.
line_comment
en
false
556
10
602
10
643
10
602
10
720
10
false
false
false
false
false
true
114255_3
package View; import javax.swing.*; import javax.swing.border.EmptyBorder; import java.awt.*; import java.awt.event.ActionListener; import java.util.List; public class JobSeekerView extends JFrame { public JList<String> jobsList; private JButton searchButton; private JTextArea jobOpportunitiesTextArea; private JButton applyButton; // New Apply button public JTextField locationTextField; public JTextField fieldOfInterestTextField; public JobSeekerView() { setTitle("Job Opportunities"); //setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); setBounds(100, 100, 600, 400); JPanel contentPane = new JPanel() { @Override protected void paintComponent(Graphics g) { super.paintComponent(g); /*Image backgroundImage = new ImageIcon("bg.jpg").getImage(); // Change "bg.jpg" to your image file g.drawImage(backgroundImage, 0, 0, getWidth(), getHeight(), this);*/ } }; contentPane.setBorder(new EmptyBorder(5, 5, 5, 5)); setContentPane(contentPane); JPanel panel = new JPanel(new GridLayout(2, 1)); contentPane.add(panel, BorderLayout.CENTER); // Panel for input fields contentPane.setBorder(new EmptyBorder(5, 5, 5, 5)); setContentPane(contentPane); contentPane.setLayout(null); JLabel lblLocation = new JLabel("Location:"); lblLocation.setFont(new Font("Tahoma", Font.PLAIN, 15)); lblLocation.setBounds(29, 23, 75, 23); contentPane.add(lblLocation); locationTextField = new JTextField(); locationTextField.setBounds(110, 23, 200, 23); contentPane.add(locationTextField); JLabel lblFieldOfInterest = new JLabel("Field of Interest:"); lblFieldOfInterest.setFont(new Font("Tahoma", Font.PLAIN, 15)); lblFieldOfInterest.setBounds(320, 23, 120, 23); contentPane.add(lblFieldOfInterest); fieldOfInterestTextField = new JTextField(); fieldOfInterestTextField.setBounds(450, 23, 200, 23); contentPane.add(fieldOfInterestTextField); searchButton = new JButton("Search"); searchButton.setBounds(29, 60, 100, 23); contentPane.add(searchButton); // Scroll pane for job opportunities text area JScrollPane jobOpportunitiesScrollPane = new JScrollPane(); jobOpportunitiesScrollPane.setBounds(29, 100, 540, 250); contentPane.add(jobOpportunitiesScrollPane); // Job opportunities text area jobOpportunitiesTextArea = new JTextArea(); jobOpportunitiesScrollPane.setViewportView(jobOpportunitiesTextArea); // Apply button applyButton = new JButton("Apply"); applyButton.setBounds(29, 60, 100, 23); contentPane.add(applyButton); } public String getLocationText() { return locationTextField.getText(); } public String getFieldOfInterestText() { return fieldOfInterestTextField.getText(); } public void setSearchButtonListener(ActionListener listener) { searchButton.addActionListener(listener); } public void setJobOpportunities(List<String> jobOpportunities) { StringBuilder sb = new StringBuilder(); for (String opportunity : jobOpportunities) { sb.append(opportunity).append("\n\n"); } jobOpportunitiesTextArea.setText(sb.toString()); } public void addApplyButtonListener(ActionListener listener) { applyButton.addActionListener(listener); } }
rhian9843/SmartCity
View/JobSeekerView.java
905
// Panel for input fields
line_comment
en
false
796
6
904
6
956
6
905
6
1,133
7
false
false
false
false
false
true
114363_0
import java.util.Scanner; /** * Class that will handle taking a string input from the command line, * checking the input, and returning an appropriate response back to the * main driver. */ public abstract class Driver { /** * Prompt to show in command line. */ public abstract void showPrompt(); /** * Handle input from the Scanner appropriately. * Optional arguments are also acceptable by this function. * Returns the next driver to use. */ public abstract Driver handleInput(Scanner scan, Object... args); }
PiJoules/bug-free-palm-tree
Driver.java
122
/** * Class that will handle taking a string input from the command line, * checking the input, and returning an appropriate response back to the * main driver. */
block_comment
en
false
112
34
122
37
131
37
122
37
138
37
false
false
false
false
false
true
114652_5
/* Project Title: Enigma * Description: This emulates the rotor component. * * Created by: Isaac Newell * Date: 04/22/2017 */ public class Rotor { // Output of the rotor private final String out; // Reverse output of the rotor (useful for coming back through rotors) private final String revOut; // Location of turnover notch(es) private final String notches; // Actual wirings of rotors I-VIII public static final Rotor I = new Rotor("EKMFLGDQVZNTOWYHXUSPAIBRCJ", "R"); public static final Rotor II = new Rotor("AJDKSIRUXBLHWTMCQGZNPYFVOE", "F"); public static final Rotor III = new Rotor("BDFHJLCPRTXVZNYEIWGAKMUSQO", "W"); public static final Rotor IV = new Rotor("ESOVPZJAYQUIRHXLNFTGKDCMWB", "K"); public static final Rotor V = new Rotor("VZBRGITYUPSDNHLXAWMJQOFECK", "A"); public static final Rotor VI = new Rotor("JPGVOUMFYQBENHZRDKASXLICTW", "AN"); public static final Rotor VII = new Rotor("NZJHGRCXMYSWBOUFAIVLPEKQDT", "AN"); public static final Rotor VIII = new Rotor("FKQHTLXOCBJSPDZRAMEWNIUYGV", "AN"); public Rotor(String out, String notches) { this.out = out; this.notches = notches; // Create the reverse mapping, so as to not have to do it every time // Traversing the rotors in the reverse direction char[] revList = new char[26]; for (int i = 0; i < out.length(); i++) { revList[(int)out.charAt(i)-65] = (char)(i+65); } String ro = ""; for (char c : revList) ro += String.valueOf(c); revOut = ro; } public String getNotches() { return notches; } public String out() { return out; } // Returns whether or not c is one of the turnover notches public boolean isNotch(char c) { for (int i = 0; i < notches.length(); i++) { if (notches.charAt(i) == c) return true; } return false; } // Useful for the Enigma class, offsets a char in a circular fashion by a // specified amount. i.e. offset('A', 2) = 'C' and offset('Z', 3) = 'C' public static char offset(char start, int shift) { if (shift > 0) { if ((start+shift) > 90) return (char)(65 + shift - (90-start) - 1); else return (char)(start+shift); } else { if ((start+shift) < 65) return (char)(90 + (shift + (start-65)) + 1); else return (char)(start+shift); } } // Output of the rotor givin its ringSetting public char output(char in, int ringSetting) { char alphChar = offset(in, -(ringSetting-1)); int offset = out.charAt((int)(alphChar)-65)-alphChar; return offset(in, offset); } // Same as above, but for traversing in reverse direction public char revOutput(char in, int ringSetting) { char alphChar = offset(in, -(ringSetting-1)); int offset = revOut.charAt((int)(alphChar)-65)-alphChar; return offset(in, offset); } }
inewell/enigma
Rotor.java
941
// Create the reverse mapping, so as to not have to do it every time
line_comment
en
false
918
16
941
16
965
16
941
16
1,069
16
false
false
false
false
false
true
116888_9
import processing.core.PApplet; import processing.core.PImage; public class ChristmasInvaders extends PApplet { /** * Enemy Variables */ int[][][] Enemies; // 2D array to store enemies' int Wave = 1; int enemyKilled = 0; int numCols = 15; // Number of columns int numRows = 5; // Number of rows int enemyRadius = 10; // Radius of enemies int spacingX = 50; // Horizontal spacing between enemies int spacingY = 50; // Vertical spacing between enemies /** * Player Variables */ int playerX; // X position of the player int playerY; // Y position of the player int playerSpeed = 5; // Speed of the player /** * Projectile Variables */ int[][] projectiles; // Array to store projectile positions int maxProjectiles = 0; // Maximum number of projectiles int projectileSpeed = 8; // Speed of the projectiles int projectileSize = 10; // Size of the projectiles int nextProjectileIndex = 0; // Index to track the next available slot in the projectiles array boolean keySpace = false; boolean gameOver = false; // Checks if the game is over PImage projectile; PImage player; public void settings() { size(1200, 675); } public void setup() { frameRate(60); initializeEnemies(); initializePlayer(); player = loadImage("Player.png"); player.resize(72, 39); projectile = loadImage("Projectile.png"); } public void draw() { if (!gameOver) { background(255); drawEnemies(); storeProjectiles(); moveProjectiles(); drawPlayer(); if (enemyKilled % 75 == 0) { storeEnemies(); } fill (0); text(enemyKilled, width / 2, height / 2); } else { displayGameOver(); } } public void drawEnemies() { for (int i = 0; i < numCols; i++) { for (int j = 0; j < numRows; j++) { ellipse(Enemies[i][j][0], Enemies[i][j][1], enemyRadius * 2, enemyRadius * 2); } } // Move enemies down every few frames if (frameCount % (60 * 2) == 0) { moveEnemiesDown(); } } public void storeEnemies() { // Create a new temporary array for the new set of enemies int[][][] newEnemies = new int[numCols][numRows][2]; // Initialize enemies' positions in a grid for (int i = 0; i < numCols; i++) { for (int j = 0; j < numRows; j++) { int x = i * spacingX + enemyRadius * 10; int y = j * spacingY + enemyRadius; newEnemies[i][j][0] = x; newEnemies[i][j][1] = y; } } // Update enemies to point to the new array Enemies = newEnemies; } public void moveEnemiesDown() { // Move enemies down in their rows for (int j = 0; j < numRows; j++) { for (int k = 0; k < numCols; k++) { Enemies[k][j][1] += 50; if (Enemies[k][j][1] + enemyRadius >= height - enemyRadius) { gameOver = true; break; // Exit the function if game-over } } } } private void displayGameOver() { textAlign(CENTER, CENTER); textSize(32); fill(255, 0, 0); text("Game Over", width / 2, height / 2); } public void initializeEnemies() { Enemies = new int[numCols][numRows][2]; // Initialize enemies' positions in a grid for (int i = 0; i < numCols; i++) { for (int j = 0; j < numRows; j++) { int x = i * spacingX + enemyRadius * 10; // Adjust the starting X position int y = j * spacingY + enemyRadius; // Adjust the starting Y position Enemies[i][j][0] = x; Enemies[i][j][1] = y; } } } public void initializePlayer() { // Initialize player position playerX = width / 2; playerY = height - 48; } public void drawPlayer() { // Draw player image(player, playerX, playerY); } public void storeProjectiles() { // Create a new temporary array with increased capacity int[][] newProjectiles = new int[nextProjectileIndex + 15][2]; // Copy existing projectiles to the new array for (int i = 0; i < nextProjectileIndex; i++) { newProjectiles[i][0] = projectiles[i][0]; newProjectiles[i][1] = projectiles[i][1]; } // Update projectiles to point to the new array projectiles = newProjectiles; // Update maxProjectiles to the new capacity maxProjectiles = nextProjectileIndex + 15; } public void keyPressed() { // Move the player left or right on key press if (keyCode == LEFT && playerX - player.width / 2 > 0) { playerX -= playerSpeed * 5; } else if (keyCode == RIGHT && playerX + player.width / 2 < width) { playerX += playerSpeed * 5; } else if (key == ' ' && keySpace == false) { // Shoot a projectile when the spacebar is pressed if (nextProjectileIndex < maxProjectiles) { projectiles[nextProjectileIndex][0] = playerX + player.width / 2; projectiles[nextProjectileIndex][1] = playerY; nextProjectileIndex++; keySpace = true; } } } public void keyReleased() { if (key == ' ') { keySpace = false; } } private void moveProjectiles() { for (int i = 0; i < nextProjectileIndex; i++) { image(projectile, projectiles[i][0], projectiles[i][1]); projectiles[i][1] -= projectileSpeed; // Check for collision with enemies for (int j = 0; j < numCols; j++) { for (int k = 0; k < numRows; k++) { float d = dist(projectiles[i][0], projectiles[i][1], Enemies[j][k][0] - 10, Enemies[j][k][1]); if (d < enemyRadius + projectileSize / 2) { // Reset projectile position on collision to off screen, different coordinates to not affect collision projectiles[i][0] = -200; projectiles[i][1] = -200; Enemies[j][k][0] = -100; Enemies[j][k][1] = -100; enemyKilled++; } } } } } }
SACHSTech/JP-Games-Christmas-Invaders
ChristmasInvaders.java
1,718
// Y position of the player
line_comment
en
false
1,643
6
1,718
6
1,844
6
1,718
6
2,012
6
false
false
false
false
false
true
116997_2
/* ====================================================== * JFinance : a class library for financial applications; * ====================================================== * Version 0.2.0; * Written by David Gilbert; * (C) Copyright 2000, Simba Management Limited; * * Simba Management Limited is registered in England, number 3136023. * * 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 2 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, write to the Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, * MA 02111-1307, USA. * * For information regarding updates to the JFinance library, please visit our website * (http://www.jrefinery.com) or e-mail David Gilbert ([email protected]); */ package com.jrefinery.finance; /** * The base class for exceptions that can occur when handling an Abstraction object. */ public class AbstractionException extends Exception { /** * Standard constructor - builds an exception with the specified message. * @param message A message describing the exception; */ public AbstractionException(String message) { super(message); } }
Payment-Factory/opensource
AbstractionException.java
395
/** * Standard constructor - builds an exception with the specified message. * @param message A message describing the exception; */
block_comment
en
false
353
27
395
27
394
30
395
27
445
30
false
false
false
false
false
true
117527_2
// Copyright 2018 by George Mason University // Licensed under the Apache 2.0 License package flow; /** Nil is a Unit which does nothing. Its frequencies and amplitudes are all zero. The sole purpose of Nil objects is to indicate that the input to a Unit has not been filled by another Unit (Nil basically serves the purpose of null). <p>Nil instances do not register themselves with Sounds. You will never see a ModPanel which represents Nil. <p>There is a canonical Nil object available: Unit.NIL. However other Nil instances can and will be created, and they should all be treated as equivalent. **/ public class Nil extends Unit { private static final long serialVersionUID = 1; public Nil() { super(null); } public String toString() { return "<NIL>"; } }
eclab/flow
flow/Nil.java
197
/** Nil is a Unit which does nothing. Its frequencies and amplitudes are all zero. The sole purpose of Nil objects is to indicate that the input to a Unit has not been filled by another Unit (Nil basically serves the purpose of null). <p>Nil instances do not register themselves with Sounds. You will never see a ModPanel which represents Nil. <p>There is a canonical Nil object available: Unit.NIL. However other Nil instances can and will be created, and they should all be treated as equivalent. **/
block_comment
en
false
193
124
197
120
211
128
197
120
225
132
false
false
false
false
false
true
117745_1
import java.io.IOException; public class Client { public static void main(String[] args) { Client client = new Client(); client.run(); } protected Client() { keyboard = new KeyboardReader(); connServ = new ConnectionToServer(getIpAddr(), getPortNumb()); } protected void run() { userdata = connServ.run(); GraphFrame frame = new GraphFrame(userdata); } /** * */ private UserData userdata; private KeyboardReader keyboard; private ConnectionToServer connServ; /** * Prints an error message saying that something went wrong and * that the program will force shutdown then it * shuts down the program. */ private void forceShutdown() { System.err.println("Something went wrong!" + "\n" + "Forcing a Shutdown!!!"); System.exit(1); } /** * Asks the user to type in the ip address and * then returns the input in the form of a string. */ private String getIpAddr() { System.out.println("Type in the ip address to the server"); String ipAddr = ""; try { ipAddr = keyboard.stringLine(); } catch (IOException e) { forceShutdown(); } return ipAddr; } /** * Asks the user to type in the port number and * then returns the input in the form of a integer. */ private int getPortNumb() { System.out.println("Type in the port number to the server"); int portNumb = 0; try { portNumb = Integer.parseInt(keyboard.stringLine()); } catch (IOException e) { forceShutdown(); } return portNumb; } }
SmartShoppingTeam/SmartShopping
Client.java
438
/** * Prints an error message saying that something went wrong and * that the program will force shutdown then it * shuts down the program. */
block_comment
en
false
387
34
438
33
463
37
438
33
536
40
false
false
false
false
false
true
119491_6
/** * The Headphones class represents a specific type of device, namely headphones, * implementing the Device interface. */ public class Headphones implements Device { private String category; private String name; private double price; private int quantity; /** * Constructs a new Headphones object with the specified name, price, and * quantity. * Time complexity: O(1) * * @param name The name of the headphones. * @param price The price of the headphones. * @param quantity The quantity of the headphones. */ public Headphones(String name, double price, int quantity) { this.category = "Headphones"; this.name = name; this.price = price; this.quantity = quantity; } /** * Retrieves the category of the headphones. * Time complexity: O(1) * * @return The category of the headphones. * */ @Override public String getCategory() { return category; } /** * Retrieves the name of the headphones. * Time complexity: O(1) * * @return The name of the headphones. */ @Override public String getName() { return name; } /** * Sets the name of the headphones. * Time complexity: O(1) * * @param name The new name of the headphones. */ @Override public void setName(String name) { this.name = name; } /** * Retrieves the price of the headphones. * Time complexity: O(1) * * @return The price of the headphones. * */ @Override public double getPrice() { return price; } /** * Sets the price of the headphones. * Time complexity: O(1) * * @param price The new price of the headphones. * */ @Override public void setPrice(double price) { this.price = price; } /** * Retrieves the quantity of the headphones. * Time complexity: O(1) * * @return The quantity of the headphones. * */ @Override public int getQuantity() { return quantity; } /** * Sets the quantity of the headphones. * Time complexity: O(1) * * @param quantity The new quantity of the headphones. */ @Override public void setQuantity(int quantity) { this.quantity = quantity; } }
enespatir07/Data-Structures-and-Algorithms
hw3/Headphones.java
575
/** * Sets the price of the headphones. * Time complexity: O(1) * * @param price The new price of the headphones. * */
block_comment
en
false
554
39
575
39
677
45
575
39
748
51
false
false
false
false
false
true
120975_6
/* * Solution to Project Euler problem 79 * by Project Nayuki * * http://www.nayuki.io/page/project-euler-solutions * https://github.com/nayuki/Project-Euler-solutions */ public final class p079 implements EulerSolution { public static void main(String[] args) { System.out.println(new p079().run()); } private static String[] SUBSEQS = {"319", "680", "180", "690", "129", "620", "762", "689", "762", "318", "368", "710", "720", "710", "629", "168", "160", "689", "716", "731", "736", "729", "316", "729", "729", "710", "769", "290", "719", "680", "318", "389", "162", "289", "162", "718", "729", "319", "790", "680", "890", "362", "319", "760", "316", "729", "380", "319", "728", "716"}; private char[] packedSubseqs; public String run() { // Preprocessing packedSubseqs = new char[SUBSEQS.length * 3]; for (int i = 0; i < packedSubseqs.length; i++) packedSubseqs[i] = SUBSEQS[i / 3].charAt(i % 3); // Try ascending lengths for (int len = 3; len <= 10; len++) { int end = Library.pow(10, len); for (int guess = 0; guess < end; guess++) { char[] guessChars = toChars(guess, len); if (isConsistent(guessChars)) return new String(guessChars); } } throw new RuntimeException("Not found"); } private boolean isConsistent(char[] guess) { // For each string 's' in SUBSEQS, test if 's' is a subsequence of 'guess' for (int i = 0; i < packedSubseqs.length; i += 3) { int j = 0; // Index in 's' for (int k = 0; k < guess.length && j < 3; k++) { // Index in 'guess' if (guess[k] == packedSubseqs[i + j]) j++; } if (j < 3) // Not all characters consumed, fail return false; } return true; } // Converts integer to string with zero padding, in little endian. // Since we're trying all combinations, the order doesn't matter. private static char[] toChars(int n, int len) { char[] result = new char[len]; int i = 0; for (; i < result.length; i++, n /= 10) result[i] = (char)('0' + (n % 10)); if (n != 0) throw new IllegalArgumentException(); for (; i < result.length; i++) result[i] = '0'; return result; } }
dweis/Project-Euler-solutions
java/p079.java
877
// Not all characters consumed, fail
line_comment
en
false
812
7
877
7
897
7
877
7
1,012
8
false
false
false
false
false
true
122969_0
public class FibonacciIterative { public static long calculateFibonacci(int n) { if (n <= 1) { return n; } long fibNMinus2 = 0; long fibNMinus1 = 1; long fibN = 0; for (int i = 2; i <= n; i++) { fibN = fibNMinus1 + fibNMinus2; fibNMinus2 = fibNMinus1; fibNMinus1 = fibN; } return fibN; } public static void main(String[] args) { int n = 10; // Calculate the 10th Fibonacci number long startTime = System.nanoTime(); long result = calculateFibonacci(n); long endTime = System.nanoTime(); System.out.println("Fibonacci(" + n + ") = " + result); System.out.println("Time taken: " + (endTime - startTime) + " nanoseconds"); } }
sahil-gidwani/DAA
1i.java
226
// Calculate the 10th Fibonacci number
line_comment
en
false
215
9
226
11
243
9
226
11
278
13
false
false
false
false
false
true
123086_0
/* Main class for launching the game */ import java.util.Scanner; class Game { static World world = new World(); static Context context = new Context(world.getEntry()); static Command fallback = new CommandUnknown(); static Registry registry = new Registry(context, fallback); static Scanner scanner = new Scanner(System.in); private static void initRegistry () { Command cmdExit = new CommandExit(); registry.register("exit", cmdExit); registry.register("quit", cmdExit); registry.register("bye", cmdExit); registry.register("go", new CommandGo()); registry.register("help", new CommandHelp(registry)); registry.register("get", new CommandInventory()); registry.register("displayI", new CommandDisplay()); } public static void main (String args[]) { System.out.println("Velkommen til World of evacuation!"); System.out.println("Advarsel dette spil simulerer skoleskyderi, hvis du har PTSD eller traumatiske oplevelser med ligne burde du lukke spillet"); initRegistry(); context.getCurrent().welcome(); while (context.isDone()==false) { System.out.print("> "); String line = scanner.nextLine(); registry.dispatch(line); } System.out.println("Game Over 😥"); } }
Bsen1ka/1SemesterProjekt
Game.java
322
/* Main class for launching the game */
block_comment
en
false
280
9
322
10
334
9
322
10
372
10
false
false
false
false
false
true
123515_2
package a1; /** * NetId: bas358, ha292. Time spent: 4 hours, 25 minutes. <br> * What I thought about this assignment: We thought it was a good introductory * assignment as it got us familiar with Eclipse and the different methods in * Java. <br> * An instance maintains info about tan Elephant. */ public class Elephant { /** Name given to this Elephant, a String of length > 0. */ private String nickName; /** Birth year of Elephant, int must be >= 2000 */ private int birthYear; /** month this elephant was born. In 1..12, with 1 meaning January, etc. */ private int birthMonth; /** Gender of Elephant 'F' means female and 'M' means male. */ private char gen; /** Mother of this elephant—null if unknown */ private Elephant mother; /** Mother of this elephant—null if unknown */ private Elephant father; /** Number of known children of this Elephant */ private int numChildren; /** * Constructor: an instance with nickname n, gender g, birth year y, and birth * month m. Its parents are unknown, and it has no children. <br> * Precondition: n has at least 1 character, y >= 2000, m is in 1..12, and g is * 'F' for female or 'M' for male. */ public Elephant(String n, char g, int y, int m) { assert n.length() > 0; assert g == 'M' || g == 'F'; assert y >= 2000; assert m >= 1 && m <= 12; nickName = n; gen = g; birthYear = y; birthMonth = m; mother = null; father = null; numChildren = 0; } /** * Constructor: an elephant with nickname n, gender g, birth year y, birth month * m, mother ma, and father pa. <br> * Precondition: n has at least 1 character, y >= 2000, g is 'F' for female or * 'M' for male, m is in 1..12, ma is a female, and pa is a male. */ public Elephant(String n, char g, int y, int m, Elephant ma, Elephant pa) { this(n, g, y, m); assert ma != null; assert pa != null; this.addMom(ma); this.addDad(pa); } /** * This elephant's nickname */ public String name() { return nickName; } /** * the value of "this elephant is a female" */ public boolean isFemale() { return gen == 'F'; } /** * the date of birth of this elephant. In the form "month/year", with no blanks, * e.g. "6/2007" */ public String date() { return Integer.toString(birthMonth) + "/" + Integer.toString(birthYear); } /** * this elephant's mother (null if unknown) */ public Elephant mom() { return mother; } /** * this elephant's father (null if unknown) */ public Elephant dad() { return father; } /** * the number of children of this elephant */ public int children() { return numChildren; } /** * Add e as this elephant's mother. Precondition: this elephant’s mother is * unknown and e is female. */ public void addMom(Elephant e) { assert this.mother == null && e.isFemale(); this.mother = e; e.numChildren++; } /** * Add e as this elephant's father. Precondition: This elephant's father is * unknown and e is male. */ public void addDad(Elephant e) { assert this.father == null && !e.isFemale(); this.father = e; e.numChildren++; } /** * Return value of "this elephant is older than e." <br> * Precondition: e is not null. */ public boolean isOlder(Elephant e) { assert e != null; return this.birthYear < e.birthYear || (this.birthYear == e.birthYear && this.birthMonth < e.birthMonth); } /** * Return value of "this elephant and e are siblings." (note: if e is null they * can't be siblings, so false is returned). */ public boolean areSibs(Elephant e) { assert this != e; return e != null && ((this.mom() != null && this.mother == e.mother) || (this.dad() != null && this.father == e.father)); } }
HAklilu/Classes-and-Objects-
Elephant.java
1,295
/** Birth year of Elephant, int must be >= 2000 */
block_comment
en
false
1,084
16
1,295
20
1,234
16
1,295
20
1,408
19
false
false
false
false
false
true
124783_4
/* Neil Patel CoE 1501; Algorithms Spring 2018 Semester GitHub: neilpatel */ // Import Statements import java.util.ArrayList; public class Node{ String currentWord; Node sibling = null; Node child = null; Node nextSibling = null; Node nextChild = null; //String prediction; char character; public Node () {} // Use Array List to keep track of all the predictions that are being stored. public ArrayList<String> predictionsGenerator() { ArrayList<String> prediction = new ArrayList<String>(); //Check if the sentinel variable has the been triggered. if (character == '*') { prediction.add(currentWord); } // Conditional to check if the child node is equal to null if (child != null) { prediction.addAll(child.predictionsGenerator()); } // Conditional to check if the sibling node is equal to null if (sibling != null) { prediction.addAll(sibling.predictionsGenerator()); } return prediction; // return the prediction } // Establish a way to keep track of the currentWord and also eliminate the next line character public Node(char ch, String currentWord) { character = ch; int currentWordSub1 = currentWord.length() - 1; this.currentWord = currentWord.substring(0, currentWordSub1); } } // End of DLBNode Class // Neil Patel
neilpatel/AutoComplete
Node.java
372
//Check if the sentinel variable has the been triggered.
line_comment
en
false
327
12
372
12
381
12
372
12
444
14
false
false
false
false
false
true