file_id
stringlengths
4
9
content
stringlengths
41
35k
repo
stringlengths
7
113
path
stringlengths
5
90
token_length
int64
15
4.07k
original_comment
stringlengths
3
9.88k
comment_type
stringclasses
2 values
detected_lang
stringclasses
1 value
excluded
bool
2 classes
230318_0
public class Fraction { private int denominator, numerator; public Fraction(int num, int denom) { numerator = num; denominator = denom; } public int getNumerator() { return numerator; } public int getDenominator() { return denominator; } public Fraction add(Fraction inp) { int lcd = lcd(denominator, inp.getDenominator()); Fraction answer = new Fraction(1, 1); if (numerator > inp.getNumerator()) { answer = new Fraction((inp.getNumerator() * lcd) + (numerator), lcd); } else if (numerator <= inp.getNumerator()) { answer = new Fraction((inp.getNumerator()) + (numerator * lcd), lcd); } // answer = answer.reduce(answer); return answer; } public Fraction subtract(Fraction inp) { int lcd = lcd(inp.getNumerator(), inp.getDenominator()); Fraction answer = new Fraction((inp.getNumerator() * lcd) - (numerator * lcd), inp.getDenominator() * lcd); answer = answer.reduce(answer); return answer; } public Fraction multiply(Fraction inp) { Fraction answer = new Fraction(numerator * inp.getNumerator(), denominator * inp.getDenominator()); answer = reduce(answer); return answer; } public Fraction divide(Fraction inp) { Fraction answer = new Fraction(numerator / inp.getNumerator(), denominator / inp.getDenominator()); answer = reduce(answer); return answer; } public Fraction reduce() { int gcd = gcd(numerator, denominator); Fraction answer = new Fraction(numerator / gcd, denominator / gcd); return answer; } public String toString() { return numerator + "/" + denominator; } public int toDecimal() { int answer = numerator / denominator; return answer; } public Fraction toRecip() { Fraction answer = new Fraction(denominator, numerator); return answer; } private int gcd(int a, int b) { if (b == 0) { return a; } else { return gcd(b, a % b); } } private int lcd(int a, int b) { for (int c = 1; c < b; c++) { if (c * a % b == 0) { return c * a; } } return a * b; } }
t94j0/flaming-sansa
Fraction.java
638
// answer = answer.reduce(answer);
line_comment
en
true
230693_0
import java.util.*; class Player { private int id; private String name; private int level; private int money; private ArrayList<Character> characters = new ArrayList<Character>(); public static int playerCount=0; public Player(String name){ this.name = name; this.money = 10; this.level = 1; this.id = playerCount; playerCount++; } public int getId(){ return this.id; } public String getName(){ return this.name; } public void setName(String name){ this.name = name; } public int getLevel(){ return this.level; } public int getMoney(){ return this.money; } /*public void adventure(Character character){ if(characters.size() ==0){ System.out.println("You do not own any character"); } else{ if(characters.contains(character)){ level += 5; money +=10; character.increaseLevel(5); } else{ System.out.println("You do not own this character"); } } }*/ public void adventure(Character character){ if(characters.size() == 0){ System.out.println("You do not own any character"); } else{ boolean check =false; for(int i=0; i<characters.size(); i++){ if(characters.get(i) == character){ check = true; level += 5; money += 10; character.increaseLevel(5); break; } } if(check == false){ System.out.println("You do not own this character"); } } } public void buyCharacter(Character character){ if(character.getRank()==3){ if(this.money >=15 && this.level>=3){ characters.add(character); this.money -= 15; } else{ System.out.println("You do not have enough money"); } } else if(character.getRank()==2){ if(this.money >=10 && this.level>=2){ characters.add(character); this.money -= 10; } else{ System.out.println("You do not have enough money"); } } else if(character.getRank()==1 && this.level>=1){ if(this.money >=5){ characters.add(character); this.money -= 5; } else{ System.out.println("You do not have enough money"); } } else{ System.out.println("The rank of this character are not supported"); } } public void getAllCharacter(){ for(Character s : characters){ System.out.println(s.getName()); } } } abstract class Character { private String name; private int level; private int rank; public Character(String name,int rank){ this.name = name; this.rank = rank; this.level = 1; } public String getName(){ return this.name; } public void setName(String name){ this.name = name; } public int getLevel(){ return this.level; } public int getRank(){ return this.rank; } public void increaseLevel(int level){ this.level +=level; } } class Geo extends Character{ public Geo(String name,int rank){ super(name, rank); } public void stoneStatue(Enemy enemy){ double elctro = ((this.getLevel()*0.1)+(this.getRank()*2)+5); double result =enemy.getHealthPoint()-elctro; enemy.setHealthPoint(result); if(enemy.getHealthPoint()<=0){ System.out.println("You defeated an enemy"); this.increaseLevel(1); } } } class Anemo extends Character{ public Anemo(String name,int rank){ super(name, rank); } public void windFlow(Enemy enemy){ double elctro = ((this.getLevel()*0.1)+(this.getRank()*2)+5); double result =enemy.getHealthPoint()-elctro; enemy.setHealthPoint(result); if(enemy.getHealthPoint()<=0){ System.out.println("You defeated an enemy"); this.increaseLevel(1); } } } class Electro extends Character{ public Electro(String name,int rank){ super(name, rank); } public void electricCurrent(Enemy enemy){ double elctro = ((this.getLevel()*0.1)+(this.getRank()*2)+5); double result =enemy.getHealthPoint()-elctro; enemy.setHealthPoint(result); if(enemy.getHealthPoint()<=0){ System.out.println("You defeated an enemy"); this.increaseLevel(1); } } } class Enemy{ private double healthPoint; public Enemy(double healthpoint){ this.healthPoint = healthpoint; } public double getHealthPoint(){ return this.healthPoint; } public void setHealthPoint(double health){ this.healthPoint = health; } } class AdventureGame { public static void main(String[] args) { Player p1 = new Player("Float"); Player p2 = new Player("BABA"); System.out.println("--------------------------------"); System.out.println("Player: "+p1.getName()); System.out.println("Player Id: "+p1.getId()); System.out.println("Level: "+p1.getLevel() + " Money: " + p1.getMoney()); System.out.println("--------------------------------"); System.out.println("Player: "+p2.getName()); System.out.println("Player Id: "+p2.getId()); System.out.println("Level: "+p2.getLevel() + " Money: " + p2.getMoney()); System.out.println("--------------------------------"); Geo ZhongLi = new Geo("Zhong Li", 3); Anemo Venti = new Anemo("Venti", 2); Electro RaidenShogun = new Electro("Raiden Shogun", 3); Electro Beidou = new Electro("Beidou", 1); p1.adventure(Beidou); p1.buyCharacter(RaidenShogun); p1.buyCharacter(Beidou); System.out.println("--------------------------------"); System.out.println("Player: "+p1.getName()); System.out.println("Player Id: "+p1.getId()); System.out.println("Level: "+p1.getLevel() + " Money: " + p1.getMoney()); System.out.println("--------------------------------"); System.out.println("Character: "+ Beidou.getName() + " Level: " +Beidou.getLevel()); p1.adventure(Beidou); System.out.println("--------------------------------"); System.out.println("Player: "+p1.getName()); System.out.println("Player Id: "+p1.getId()); System.out.println("Level: "+p1.getLevel() + " Money: " + p1.getMoney()); System.out.println("--------------------------------"); Enemy e1 = new Enemy(10); System.out.println(e1.getHealthPoint()); Beidou.electricCurrent(e1); System.out.println(e1.getHealthPoint()); Beidou.electricCurrent(e1); System.out.println("--------------------------------"); p1.adventure(RaidenShogun); p1.buyCharacter(ZhongLi); p1.getAllCharacter(); p1.adventure(ZhongLi); p1.adventure(ZhongLi); p1.buyCharacter(RaidenShogun); System.out.println("--------------------------------"); Enemy e2 = new Enemy(5); System.out.println("Enemy Health: "+e2.getHealthPoint()); System.out.println("Character: "+ ZhongLi.getName() + " Level: " +ZhongLi.getLevel()); ZhongLi.stoneStatue(e2); System.out.println("Character: "+ ZhongLi.getName() + " Level: " +ZhongLi.getLevel()); System.out.println("--------------------------------"); Anemo RiceShower = new Anemo("Rice Shower",500); p1.buyCharacter(RiceShower); } }
jigneng1/csc102-cscms
Quiz4/Q2.java
2,010
/*public void adventure(Character character){ if(characters.size() ==0){ System.out.println("You do not own any character"); } else{ if(characters.contains(character)){ level += 5; money +=10; character.increaseLevel(5); } else{ System.out.println("You do not own this character"); } } }*/
block_comment
en
true
230735_2
package AdventureModel; import java.io.Serializable; import java.util.ArrayList; /** * This class keeps track of the progress * of the player in the game. */ public class Player implements Serializable { /** * The current room that the player is located in. */ private Room currentRoom; /** * The list of items that the player is carrying at the moment. */ public ArrayList<AdventureObject> inventory; /** * Adventure Game Player Constructor */ public Player(Room currentRoom) { this.inventory = new ArrayList<AdventureObject>(); this.currentRoom = currentRoom; } /** * This method adds an object into players inventory if the object is present in * the room and returns true. If the object is not present in the room, the method * returns false. * * @param object name of the object to pick up * @return true if picked up, false otherwise */ public boolean takeObject(String object){ if(this.currentRoom.checkIfObjectInRoom(object)){ AdventureObject object1 = this.currentRoom.getObject(object); this.currentRoom.removeGameObject(object1); this.addToInventory(object1); return true; } else { return false; } } /** * checkIfObjectInInventory * __________________________ * This method checks to see if an object is in a player's inventory. * * @param s the name of the object * @return true if object is in inventory, false otherwise */ public boolean checkIfObjectInInventory(String s) { for(int i = 0; i<this.inventory.size();i++){ if(this.inventory.get(i).getName().equals(s)) return true; } return false; } /** * This method drops an object in the players inventory and adds it to the room. * If the object is not in the inventory, the method does nothing. * * @param s name of the object to drop */ public void dropObject(String s) { for(int i = 0; i<this.inventory.size();i++){ if(this.inventory.get(i).getName().equals(s)) { this.currentRoom.addGameObject(this.inventory.get(i)); this.inventory.remove(i); } } } /** * Setter method for the current room attribute. * * @param currentRoom The location of the player in the game. */ public void setCurrentRoom(Room currentRoom) { this.currentRoom = currentRoom; } /** * This method adds an object to the inventory of the player. * * @param object Prop or object to be added to the inventory. */ public void addToInventory(AdventureObject object) { this.inventory.add(object); } /** * Getter method for the current room attribute. * * @return current room of the player. */ public Room getCurrentRoom() { return this.currentRoom; } /** * Getter method for string representation of inventory. * * @return ArrayList of names of items that the player has. */ public ArrayList<String> getInventory() { ArrayList<String> objects = new ArrayList<>(); for(int i=0;i<this.inventory.size();i++){ objects.add(this.inventory.get(i).getName()); } return objects; } }
IbraTech04/AdventureEditorPro
AdventureModel/Player.java
788
/** * The list of items that the player is carrying at the moment. */
block_comment
en
false
230779_0
package src; import o1.adventure.ui.AdventureGUI; /** * Created by Toni on 4.12.2014. */ public class Main { public static void main(String[] args) { System.out.println("Java main wrapper"); AdventureGUI.main(args); } }
jtoikka/textadventure
src/Main.java
81
/** * Created by Toni on 4.12.2014. */
block_comment
en
true
230782_1
/** * Location for text adventure game. * @author Sean Stern * @version 1.0 */ public interface Location{ /** * Gets the name of the location in the text adventure game. * Every location in a {@link Game} should have a unique name so that an * {@link Engine} can properly track the state of the game. * * @return a unique identifier for each level */ public String getName(); /** * Causes the {@link Player} to enter the location and returns * the name of the next game location. * * @param p the {@link Player} entering the location * @return the name of the next location * @throws InterruptedException if the game is paused and gets interrupted */ public String enter(Player p) throws InterruptedException; }
bujars/text-adventure-origin-jumpworks
Location.java
182
/** * Gets the name of the location in the text adventure game. * Every location in a {@link Game} should have a unique name so that an * {@link Engine} can properly track the state of the game. * * @return a unique identifier for each level */
block_comment
en
false
230945_15
// Buying Watches // Description // Mr. Ghanshyam & Ms. Richa have decided to purchase watches from ABC corporations such that ABC corporations is used to have different pricing components customer wise. // The mandatory components are- cost price, profit percentage & GST // For women citizen they are offering discount of 2% on total bill amount and // For senior citizen (of 60 years or more) they are offering discount of 3% // The ABC Corporation has two types of watched with pricing structure as follow Watch Type: // Titan // cost price = 7999 // profit percentage = 12.5 // GST = 7.5 // Watch Type: Rolex // cost price = 10999 // profit percentage = 13.5 // GST = 12.5 // For example, consider the following examples // Sample input-1 // Enter age 25 // Enter gender female // Enter watch type (Titan/Rolex): Titan // Output // The total bill amount is 9406.82 // Sample input-2 // Enter age 65 // Enter gender male // Enter watch type (Titan/Rolex): Rolex // Output // The total bill amount is 13442.98 // Sample input-3 // Enter age 61 // Enter gender female // Enter watch type (Titan/Rolex): Rolex // Output // The total bill amount is 13165.80 // Sample input-4 // Enter age 25 // Enter gender male // Enter watch type (Titan/Rolex): Titan // Output // The total bill amount is 9598.80 // There is no need to take the input or the output. Just complete the class as mentioned in the problem statement above // Input // There is no need to take the input or the output. Just complete the class as mentioned in the problem statement above // Output // There is no need to take the input or the output. Just complete the class as mentioned in the problem statement above // Sample Input 1 // NA // Sample Output 1 // NA class WatchPriceCalculator { double getWatchPrice(String watchType, int age, String gender) { int discount = 0; if (age >= 60) { discount += 3; } if (gender == "female") { discount += 2; } if (watchType == "Rolex") { double amt = 10999 * 1.26; double fp = ((double) (100 - discount) / 100) * amt; return Math.round(fp * 100.0) / 100.0; } else { double amt = 7999 * 1.2; double fp = ((double) (100 - discount) / 100) * amt; return Math.round(fp * 100.0) / 100.0; } } } // ============================When return wants in String Format============================= class WatchPriceCalculator { String getWatchPrice(String watchType, int age, String gender) { int discount = 0; if (age >= 60) { discount += 3; } if (gender == "female") { discount += 2; } if (watchType == "Rolex") { double amt = 10999 * 1.26; double fp = ((double) (100 - discount) / 100) * amt; return "The total bill amount is " + String.format("%.2f", fp); } else { double amt = 7999 * 1.2; double fp = ((double) (100 - discount) / 100) * amt; return "The total bill amount is " + String.format("%.2f", fp); } } }
hoshiyarjyani/Masai-School-Assignments
dsa401/conceptofjava/BuyingWatch.java
970
// For example, consider the following examples
line_comment
en
true
230957_4
import java.awt.EventQueue; import javax.swing.*; import java.awt.Color; import java.awt.Font; import java.awt.Component; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.awt.event.MouseAdapter; import java.awt.event.MouseEvent; import java.awt.Toolkit; import com.toedter.calendar.JCalendar; import java.awt.Button; import java.awt.font.TextAttribute; import java.beans.PropertyChangeEvent; import java.beans.PropertyChangeListener; import java.sql.Connection; import java.sql.DriverManager; import java.sql.ResultSet; import java.sql.Statement; import java.util.Map; import com.toedter.calendar.JDayChooser; import com.toedter.calendar.JMonthChooser; import com.toedter.calendar.JYearChooser; public class MemberAttendance implements PropertyChangeListener, ActionListener{ JFrame frmCrossconnect2; JCalendar calendar; JEditorPane infoPane; public static String username = ""; public static String userid = ""; /** * Launch the application. */ public static void main(String[] args) { if(args.length > 0) { userid = args[0]; username = args[1]; } EventQueue.invokeLater(new Runnable() { public void run() { try { MemberAttendance window = new MemberAttendance(); window.frmCrossconnect2.setVisible(true); //window.frmCrossconnect.setVisible(true); } catch (Exception e) { e.printStackTrace(); } } }); } /** * Create the application. * @wbp.parser.entryPoint */ public MemberAttendance() { initialize(); } /** * Initialize the contents of the frame. */ private void initialize() { frmCrossconnect2 = new JFrame(); frmCrossconnect2.setIconImage(Toolkit.getDefaultToolkit().getImage("C:\\Users\\amina\\Documents\\crossconnect-Recovered.png")); frmCrossconnect2.setBackground(new Color(255, 255, 255)); frmCrossconnect2.getContentPane().setForeground(Color.BLUE); frmCrossconnect2.getContentPane().setBackground(Color.WHITE); frmCrossconnect2.setTitle("CROSSCONNECT"); frmCrossconnect2.setBounds(100, 100, 768, 600); frmCrossconnect2.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); frmCrossconnect2.getContentPane().setLayout(null); JLabel lblMember = new JLabel(" MEMBER ATTENDANCE"); lblMember.setVerticalAlignment(SwingConstants.TOP); lblMember.setHorizontalAlignment(SwingConstants.LEFT); lblMember.setForeground(new Color(105, 105, 105)); lblMember.setBackground(new Color(0, 0, 139)); lblMember.setFont(new Font("Tahoma", Font.PLAIN, 16)); lblMember.setBounds(0, 0, 752, 17); frmCrossconnect2.getContentPane().add(lblMember); JLabel lblWelcomeToThe = new JLabel("WELCOME TO THE TEMPLE OF PENTECOST"); lblWelcomeToThe.setForeground(new Color(0, 0, 139)); lblWelcomeToThe.setBackground(Color.CYAN); lblWelcomeToThe.setFont(new Font("Tahoma", Font.BOLD, 18)); lblWelcomeToThe.setHorizontalAlignment(SwingConstants.CENTER); lblWelcomeToThe.setBounds(0, 24, 752, 14); frmCrossconnect2.getContentPane().add(lblWelcomeToThe); JLabel lblMemId = new JLabel("Member ID: " + userid); lblMemId.setFont(new Font("Tahoma", Font.BOLD, 11)); lblMemId.setForeground(new Color(30, 144, 255)); lblMemId.setBounds(370, 52, 120, 14); frmCrossconnect2.getContentPane().add(lblMemId); JLabel lblName = new JLabel("Name: " + username); lblName.setFont(new Font("Tahoma", Font.BOLD, 11)); lblName.setForeground(new Color(30, 144, 255)); lblName.setBackground(Color.LIGHT_GRAY); lblName.setBounds(224, 52, 100, 14); frmCrossconnect2.getContentPane().add(lblName); JLabel lblMemInfo = new JLabel("Member Information"); lblMemInfo.setFont(new Font("Tahoma", Font.BOLD, 12)); lblMemInfo.setForeground(new Color(30, 144, 255)); lblMemInfo.setBackground(Color.WHITE); lblMemInfo.setBounds(24, 49, 144, 20); lblMemInfo.addMouseListener(new MouseAdapter() { Font original; @Override public void mouseClicked(MouseEvent e) { String[] args = {userid, username}; Member.main(args); frmCrossconnect2.dispose(); } @Override public void mouseEntered(MouseEvent e) { original = e.getComponent().getFont(); Map attributes = original.getAttributes(); attributes.put(TextAttribute.UNDERLINE, TextAttribute.UNDERLINE_ON); e.getComponent().setFont(original.deriveFont(attributes)); } @Override public void mouseExited(MouseEvent e) { e.getComponent().setFont(original); } }); frmCrossconnect2.getContentPane().add(lblMemInfo); JLabel lblAttendance = new JLabel("Contributions"); lblAttendance.setFont(new Font("Tahoma", Font.BOLD, 12)); lblAttendance.setForeground(new Color(30, 144, 255)); lblAttendance.setBackground(Color.WHITE); lblAttendance.setBounds(24, 74, 144, 20); lblAttendance.addMouseListener(new MouseAdapter() { Font original; @Override public void mouseClicked(MouseEvent e) { String[] args = {userid, username}; MemberContribution.main(args); frmCrossconnect2.dispose(); } @Override public void mouseEntered(MouseEvent e) { original = e.getComponent().getFont(); Map attributes = original.getAttributes(); attributes.put(TextAttribute.UNDERLINE, TextAttribute.UNDERLINE_ON); e.getComponent().setFont(original.deriveFont(attributes)); } @Override public void mouseExited(MouseEvent e) { e.getComponent().setFont(original); } }); frmCrossconnect2.getContentPane().add(lblAttendance); JLabel lblEventCal = new JLabel("Event Calendar"); lblEventCal.setFont(new Font("Tahoma", Font.BOLD, 12)); lblEventCal.setForeground(new Color(30, 144, 255)); lblEventCal.setBackground(Color.WHITE); lblEventCal.setBounds(24, 99, 144, 20); lblEventCal.addMouseListener(new MouseAdapter() { Font original; @Override public void mouseClicked(MouseEvent e) { String[] args = {userid, username}; EventSchedule.main(args); frmCrossconnect2.dispose(); } @Override public void mouseEntered(MouseEvent e) { original = e.getComponent().getFont(); Map attributes = original.getAttributes(); attributes.put(TextAttribute.UNDERLINE, TextAttribute.UNDERLINE_ON); e.getComponent().setFont(original.deriveFont(attributes)); } @Override public void mouseExited(MouseEvent e) { e.getComponent().setFont(original); } }); frmCrossconnect2.getContentPane().add(lblEventCal); JLabel lblContribution = new JLabel("Ministries"); lblContribution.setFont(new Font("Tahoma", Font.BOLD, 12)); lblContribution.setForeground(new Color(30, 144, 255)); lblContribution.setBackground(Color.WHITE); lblContribution.setBounds(24, 124, 144, 20); lblContribution.addMouseListener(new MouseAdapter() { Font original; @Override public void mouseClicked(MouseEvent e) { String[] args = {userid, username}; ministries.main(args); frmCrossconnect2.dispose(); } @Override public void mouseEntered(MouseEvent e) { original = e.getComponent().getFont(); Map attributes = original.getAttributes(); attributes.put(TextAttribute.UNDERLINE, TextAttribute.UNDERLINE_ON); e.getComponent().setFont(original.deriveFont(attributes)); } @Override public void mouseExited(MouseEvent e) { e.getComponent().setFont(original); } }); frmCrossconnect2.getContentPane().add(lblContribution); JLabel lblChurchDir = new JLabel("Church Directory"); lblChurchDir.setFont(new Font("Tahoma", Font.BOLD, 12)); lblChurchDir.setForeground(new Color(30, 144, 255)); lblChurchDir.setBackground(Color.WHITE); lblChurchDir.setBounds(24, 149, 144, 20); lblChurchDir.addMouseListener(new MouseAdapter() { Font original; @Override public void mouseClicked(MouseEvent e) { String[] args = {userid, username}; ChurchDirectory.main(args); frmCrossconnect2.dispose(); } @Override public void mouseEntered(MouseEvent e) { original = e.getComponent().getFont(); Map attributes = original.getAttributes(); attributes.put(TextAttribute.UNDERLINE, TextAttribute.UNDERLINE_ON); e.getComponent().setFont(original.deriveFont(attributes)); } @Override public void mouseExited(MouseEvent e) { e.getComponent().setFont(original); } }); frmCrossconnect2.getContentPane().add(lblChurchDir); JLabel lblSelectAYear = new JLabel("Make a Selection"); lblSelectAYear.setBounds(224, 102, 103, 14); frmCrossconnect2.getContentPane().add(lblSelectAYear); calendar = new JCalendar(); calendar.setBounds(274, 127, 198, 153); frmCrossconnect2.getContentPane().add(calendar); JDayChooser getD = calendar.getDayChooser(); JMonthChooser getM = calendar.getMonthChooser(); JYearChooser getY = calendar.getYearChooser(); getD.addPropertyChangeListener(this); getM.addPropertyChangeListener(this); getY.addPropertyChangeListener(this); JButton btnExit = new JButton("EXIT"); btnExit.setForeground(new Color(0, 0, 0)); btnExit.setBackground(new Color(30, 144, 255)); btnExit.setBounds(370, 480, 70, 22); btnExit.setActionCommand("EXIT"); frmCrossconnect2.getContentPane().add(btnExit); btnExit.addActionListener(this); /* JLabel lblSelectAYear_1 = new JLabel("Select a year for full year attendance record"); lblSelectAYear_1.setBounds(509, 102, 233, 14); frmCrossconnect2.getContentPane().add(lblSelectAYear_1); JYearChooser yearChooser = new JYearChooser(); yearChooser.setBounds(659, 127, 67, 20); frmCrossconnect2.getContentPane().add(yearChooser); */ infoPane = new JEditorPane(); infoPane.setFont(new Font("Tahoma", Font.BOLD, 12)); infoPane.setForeground(new Color(30, 144, 255)); infoPane.setBackground(Color.WHITE); infoPane.setText(""); infoPane.setEditable(false); JScrollPane scrollPane = new JScrollPane(infoPane); scrollPane.setBounds(145, 280, 510, 170); frmCrossconnect2.getContentPane().add(scrollPane); } public void propertyChange(PropertyChangeEvent e) { JDayChooser dc = calendar.getDayChooser(); JMonthChooser mc = calendar.getMonthChooser(); JYearChooser yc = calendar.getYearChooser(); String date = ""; date = date + yc.getYear() + "-"; if(mc.getMonth() < 9) { date = date + "0" + (mc.getMonth()+1) + "-"; } else { date = date + (mc.getMonth()+1) + "-"; } if(dc.getDay() < 10) { date = date +"0" + dc.getDay(); } else { date = date + dc.getDay(); } try { Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver"); Connection con= DriverManager.getConnection("jdbc:sqlserver://zfa6f4giy6.database.windows.net:1433;database=TOP_CC;user=CC_Admin@zfa6f4giy6;password={Cross_Connect};encrypt=true;trustServerCertificate=false;hostNameInCertificate=*.database.windows.net;loginTimeout=30"); Statement s=con.createStatement(); //use s.executeQuery("SQL statement"); to execute statements on the database String query = "SELECT * FROM Event"; ResultSet rs = s.executeQuery(query); String datetime = ""; String obtainedDate = ""; String obtainedTime = ""; String infoMessage = ""; boolean hasEvent = false; infoPane.setText(""); while(rs.next()) { datetime = rs.getString("Start_Date_Time"); obtainedDate = datetime.substring(0, 10); obtainedTime = datetime.substring(11,16); if(obtainedDate.equals(date)) { hasEvent = true; infoMessage = infoMessage + rs.getString("Event_Name") + " at " + obtainedTime + "\n\tNumber of attendees: "; if(rs.getString("Attendance")== null) { infoMessage = infoMessage + "N/A \n\tNumber of guests: " ; } else { infoMessage = infoMessage + rs.getString("Attendance") + "\n\tNumber of guests: "; } if(rs.getString("Num_Guests")==null) { infoMessage = infoMessage + "N/A\n\tTotal tithes: "; } else { infoMessage = infoMessage + rs.getString("Num_Guests") + "\n\tTotal tithes: "; } if(rs.getString("Total_Tithe")==null) { infoMessage = infoMessage + "N/A\n\tTotal offerings: "; } else { String tithe = rs.getString("Total_Tithe"); infoMessage = infoMessage + tithe.substring(0, tithe.length() - 2) + "\n\tTotal offerings: "; } if(rs.getString("Total_Offering")==null) { infoMessage = infoMessage + "N/A\n"; } else { String tithe = rs.getString("Total_Offering"); infoMessage = infoMessage + tithe.substring(0, tithe.length()-2) + "\n"; } } } if(hasEvent == false) { infoMessage = "No events planned on this day"; } infoPane.setText(infoMessage); } catch (Exception ex) { // TODO Auto-generated catch block ex.printStackTrace(); } } public void actionPerformed(ActionEvent e) { if("EXIT".equals(e.getActionCommand())) { System.exit(0); } } private static void addPopup(Component component, final JPopupMenu popup) { component.addMouseListener(new MouseAdapter() { public void mousePressed(MouseEvent e) { if (e.isPopupTrigger()) { showMenu(e); } } public void mouseReleased(MouseEvent e) { if (e.isPopupTrigger()) { showMenu(e); } } private void showMenu(MouseEvent e) { popup.show(e.getComponent(), e.getX(), e.getY()); } }); } }
amasood1/Capstone-Project
MemberAttendance.java
3,896
/* JLabel lblSelectAYear_1 = new JLabel("Select a year for full year attendance record"); lblSelectAYear_1.setBounds(509, 102, 233, 14); frmCrossconnect2.getContentPane().add(lblSelectAYear_1); JYearChooser yearChooser = new JYearChooser(); yearChooser.setBounds(659, 127, 67, 20); frmCrossconnect2.getContentPane().add(yearChooser); */
block_comment
en
true
230985_1
package rmi.server; public abstract class RMIServer<T> extends Thread { /** * The remote interface type */ protected Class<T> service; /** * Actual object offering serivce to client */ protected T serviceImpl; protected RMIServer() {} protected RMIServer(Class<T> c, T server) { this.service = c; this.serviceImpl = server; } }
StrikeW/15-440_S12_P1_RMI
rmi/server/RMIServer.java
102
/** * Actual object offering serivce to client */
block_comment
en
true
231279_0
class Solution{ //Function to find the leaders in the array. static ArrayList<Integer> leaders(int arr[], int n){ // Your code here ArrayList<Integer> leaders = new ArrayList<>(); int maxRight = Integer.MIN_VALUE; for (int i = arr.length - 1; i >= 0; i--) { if (arr[i] >= maxRight) { maxRight = arr[i]; leaders.add(maxRight); } } Collections.reverse(leaders); return leaders; } }
NKSharathChandra/GFG_Solutions
August/18-08-23.java
131
//Function to find the leaders in the array.
line_comment
en
true
231317_6
package servlet; import java.io.IOException; import javax.servlet.RequestDispatcher; import javax.servlet.ServletException; import javax.servlet.annotation.WebServlet; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import service.PosterService; import serviceimp.PosterServiceImp; import vo.Poster; /** * Servlet implementation class PosterServlet */ @WebServlet("/PosterServlet") public class PosterServlet extends HttpServlet { private static final long serialVersionUID = 1L; /** * @see HttpServlet#HttpServlet() */ public PosterServlet() { super(); // TODO Auto-generated constructor stub } /** * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response) */ protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { request.setCharacterEncoding("utf-8"); String movieName=request.getParameter("movieName"); String picturename=request.getParameter("picturename"); String image_address=request.getParameter("image_address"); //System.out.println(movieName); if(!movieName.equals("")) { PosterService ms=new PosterServiceImp(); Poster poster=new Poster(); poster.setImage_address(image_address); poster.setMovieName(movieName); poster.setPicturename(picturename); int a=ms.addPoster(poster); if(a>0) { RequestDispatcher rd=request.getRequestDispatcher("showposter.jsp"); rd.forward(request, response); } else { RequestDispatcher rd=request.getRequestDispatcher("addposter.jsp"); rd.forward(request, response); } } else { RequestDispatcher rd=request.getRequestDispatcher("addposter.jsp"); rd.forward(request, response); } } /** * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response) */ protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { // TODO Auto-generated method stub doGet(request, response); } }
QiliangFan/DouDou
src/servlet/PosterServlet.java
539
// TODO Auto-generated method stub
line_comment
en
true
231385_1
// Miriam Mai Watanabe package Posters; import processing.core.*; import Posters.Utilities.Letter; import geomerative.*; public class Poster12 extends Poster{ PVector gravity = new PVector(); String [] letters = new String [1]; int shapeColor=0; int pathSimplification = 0; float pathSampleFactor = 0.1f; RFont font; Letter f; Letter a; Letter l1; Letter l2; Letter i; Letter n; Letter g; Letter[] ls; Letter aa; Letter ll; Letter ii; Letter gg; Letter nn; public Poster12(PApplet parent, boolean DEBUG) { super(parent, DEBUG); p.noFill(); p.strokeWeight(1.5f); p.textAlign( p.CENTER); gravity.set(0, 25); RG.init(p); font = new RFont("Poster12/NotoSans-Bold.ttf", (600* p.height)/1920, RFont.LEFT); f = new Letter(p, font, "f", ( p.width*60f)/1215f, ( p.height*290)/1080f, 6.0f/7.0f); a = new Letter(p, font,"a", ( p.width*200f)/1215f, ( p.height*350)/1080f, 5.0f/7.0f); l1 = new Letter(p, font,"l", ( p.width*430f)/1215f, ( p.height*480)/1080f, 4.0f/7.0f); l2 = new Letter(p, font,"l", ( p.width*255f)/1215f, ( p.height*680)/1080f, 3.0f/7.0f); i = new Letter(p, font,"i", ( p.width*69f)/1215f, ( p.height*680)/1080f, 2.0f/7.0f); n = new Letter(p, font,"n", ( p.width*69f)/1215f, ( p.height*960)/1080f, 1.0f/7.0f); g = new Letter(p, font,"g", ( p.width*370f)/1215f, ( p.height*860)/1080f, 0.7f/7.0f); aa = new Letter(p, font,"a", ( p.width*602f)/1215f, (600* p.height)/1080f, 6.0f/7.0f); ll = new Letter(p, font,"l", ( p.width*752.5f)/1215f, (600* p.height)/1080f, 5.0f/7.0f); ii = new Letter(p, font,"i", ( p.width*800f)/1215f, (600* p.height)/1080f, 4.0f/7.0f); gg = new Letter(p, font,"g", ( p.width*855f)/1215f, (600* p.height)/1080f, 3.0f/7.0f); nn = new Letter(p, font,"n", ( p.width*1019f)/1215f, (600* p.height)/1080f, 2.0f/7.0f); p.rectMode(p.CORNER); } void animateLetter(Letter myLetter, float newX) { float ribbonWidth = p.map(myLetter.movement, 0, p.height, 1, 150); myLetter.drawLetter((float)((int)(myLetter.movement))/p.width, ribbonWidth); if (newX > myLetter.animationStart) { myLetter.y= p.min(p.height + 300, myLetter.y + 6); } else if (myLetter.y > myLetter.startY && newX < myLetter.animationStart) { myLetter.y= myLetter.y - 6; } myLetter.movement= myLetter.y - myLetter.startY; }; void animateLetterH(Letter myLetter, float newX) { float ribbonWidth = p.map(myLetter.movement, 0, p.height, 1, 150); myLetter.drawLetter((float)((int)(myLetter.movement))/p.width, ribbonWidth); if (newX > myLetter.animationStart) { myLetter.x= p.min(p.width + 300, myLetter.x + 6); } else if (myLetter.x > myLetter.startX && newX < myLetter.animationStart) { myLetter.x = myLetter.x - 6; } myLetter.movement= myLetter.x - myLetter.startX; }; public void draw(PVector Pos) { p.fill(206,41,41); p.rect(0, 0, p.width/2, p.height); p.fill(255); p.rect(p.width/2, 0, p.width/2, p.height); // screen split line p.line(p.width/2, 0, p.width/2, p.height); p.noFill(); p.stroke(255); animateLetter(f, Pos.x); animateLetter(a, Pos.x); animateLetter(l1, Pos.x); animateLetter(l2, Pos.x); animateLetter(n, Pos.x); animateLetter(i, Pos.x); animateLetter(g, Pos.x); p.stroke(206,41,41); animateLetterH(aa, 1-Pos.x); animateLetterH(ll, 1-Pos.x); animateLetterH(ii, 1-Pos.x); animateLetterH(gg, 1-Pos.x); animateLetterH(nn, 1-Pos.x); } }
IAD-ZHDK/Moving-Posters-2019
src/Posters/Poster12.java
1,554
// screen split line
line_comment
en
true
231419_0
package org.hl7.v3; import java.util.ArrayList; import java.util.List; import javax.xml.bind.annotation.XmlAccessType; import javax.xml.bind.annotation.XmlAccessorType; import javax.xml.bind.annotation.XmlAttribute; import javax.xml.bind.annotation.XmlType; /** * Note: because this type is defined as an extension of SXCM_T, * all of the attributes and elements accepted for T are also * accepted by this definition. However, they are NOT allowed * by the normative description of this type. Unfortunately, * we cannot write a general purpose schematron contraints to * provide that extra validation, thus applications must be * aware that instance (fragments) that pass validation with * this might might still not be legal. * * <p>Java class for PIVL_TS complex type. * * <p>The following schema fragment specifies the expected content contained within this class. * * <pre> * &lt;complexType name="PIVL_TS"> * &lt;complexContent> * &lt;extension base="{urn:hl7-org:v3}SXCM_TS"> * &lt;sequence> * &lt;element name="phase" type="{urn:hl7-org:v3}IVL_TS" minOccurs="0"/> * &lt;element name="period" type="{urn:hl7-org:v3}PQ" minOccurs="0"/> * &lt;/sequence> * &lt;attribute name="alignment" type="{urn:hl7-org:v3}CalendarCycle" /> * &lt;attribute name="institutionSpecified" type="{urn:hl7-org:v3}bl" default="false" /> * &lt;/extension> * &lt;/complexContent> * &lt;/complexType> * </pre> * * */ @XmlAccessorType(XmlAccessType.FIELD) @XmlType(name = "PIVL_TS", propOrder = { "phase", "period" }) public class PIVLTS extends SXCMTS { protected IVLTS phase; protected PQ period; @XmlAttribute(name = "alignment") protected List<String> alignment; @XmlAttribute(name = "institutionSpecified") protected Boolean institutionSpecified; /** * Gets the value of the phase property. * * @return * possible object is * {@link IVLTS } * */ public IVLTS getPhase() { return phase; } /** * Sets the value of the phase property. * * @param value * allowed object is * {@link IVLTS } * */ public void setPhase(IVLTS value) { this.phase = value; } /** * Gets the value of the period property. * * @return * possible object is * {@link PQ } * */ public PQ getPeriod() { return period; } /** * Sets the value of the period property. * * @param value * allowed object is * {@link PQ } * */ public void setPeriod(PQ value) { this.period = value; } /** * Gets the value of the alignment property. * * <p> * This accessor method returns a reference to the live list, * not a snapshot. Therefore any modification you make to the * returned list will be present inside the JAXB object. * This is why there is not a <CODE>set</CODE> method for the alignment property. * * <p> * For example, to add a new item, do as follows: * <pre> * getAlignment().add(newItem); * </pre> * * * <p> * Objects of the following type(s) are allowed in the list * {@link String } * * */ public List<String> getAlignment() { if (alignment == null) { alignment = new ArrayList<String>(); } return this.alignment; } /** * Gets the value of the institutionSpecified property. * * @return * possible object is * {@link Boolean } * */ public boolean isInstitutionSpecified() { if (institutionSpecified == null) { return false; } else { return institutionSpecified; } } /** * Sets the value of the institutionSpecified property. * * @param value * allowed object is * {@link Boolean } * */ public void setInstitutionSpecified(Boolean value) { this.institutionSpecified = value; } }
KRMAssociatesInc/eHMP
lib/mvi/org/hl7/v3/PIVLTS.java
1,114
/** * Note: because this type is defined as an extension of SXCM_T, * all of the attributes and elements accepted for T are also * accepted by this definition. However, they are NOT allowed * by the normative description of this type. Unfortunately, * we cannot write a general purpose schematron contraints to * provide that extra validation, thus applications must be * aware that instance (fragments) that pass validation with * this might might still not be legal. * * <p>Java class for PIVL_TS complex type. * * <p>The following schema fragment specifies the expected content contained within this class. * * <pre> * &lt;complexType name="PIVL_TS"> * &lt;complexContent> * &lt;extension base="{urn:hl7-org:v3}SXCM_TS"> * &lt;sequence> * &lt;element name="phase" type="{urn:hl7-org:v3}IVL_TS" minOccurs="0"/> * &lt;element name="period" type="{urn:hl7-org:v3}PQ" minOccurs="0"/> * &lt;/sequence> * &lt;attribute name="alignment" type="{urn:hl7-org:v3}CalendarCycle" /> * &lt;attribute name="institutionSpecified" type="{urn:hl7-org:v3}bl" default="false" /> * &lt;/extension> * &lt;/complexContent> * &lt;/complexType> * </pre> * * */
block_comment
en
true
231531_13
package loanassistant; import java.awt.Color; import java.awt.Dimension; import java.awt.Font; import java.awt.GridBagConstraints; import java.awt.GridBagLayout; import java.awt.HeadlessException; import java.awt.Insets; import java.awt.Toolkit; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.awt.event.WindowAdapter; import java.awt.event.WindowEvent; import java.text.DecimalFormat; import javax.swing.BorderFactory; import javax.swing.JButton; import javax.swing.JFrame; import javax.swing.JLabel; import javax.swing.JOptionPane; import javax.swing.JTextArea; import javax.swing.JTextField; import javax.swing.SwingConstants; public class LoanAssistant extends JFrame { JLabel balanceLabel = new JLabel(); JTextField balanceTextField = new JTextField(); JLabel interestLabel = new JLabel(); JTextField interestTextField = new JTextField(); JLabel monthsLabel = new JLabel(); JTextField monthsTextField = new JTextField(); JLabel paymentLabel = new JLabel(); JTextField paymentTextField = new JTextField(); JButton computeButton = new JButton(); JButton newLoanButton = new JButton(); JButton monthsButton = new JButton(); JButton paymentButton = new JButton(); JLabel analysisLabel = new JLabel(); JTextArea analysisTextArea = new JTextArea(); JButton exitButton = new JButton(); Font myFont = new Font("Arial", Font.PLAIN, 16); Color lightYellow = new Color(255, 255, 128); boolean computePayment; public static void main(String args[]) /* Complete Project Code */ { // create frame new LoanAssistant().show(); } public LoanAssistant() { // frame constructor setTitle("Loan Assistant"); setResizable(false); addWindowListener(new WindowAdapter() { public void windowClosing(WindowEvent evt) { exitForm(evt); } }); getContentPane().setLayout(new GridBagLayout()); GridBagConstraints gridConstraints; balanceLabel.setText("Loan Balance"); balanceLabel.setFont(myFont); gridConstraints = new GridBagConstraints(); gridConstraints.gridx = 0; gridConstraints.gridy = 0; gridConstraints.anchor = GridBagConstraints.WEST; gridConstraints.insets = new Insets(10, 10, 0, 0); getContentPane().add(balanceLabel, gridConstraints); balanceTextField.setPreferredSize(new Dimension(100, 25)); balanceTextField.setHorizontalAlignment(SwingConstants.RIGHT); balanceTextField.setFont(myFont); gridConstraints = new GridBagConstraints(); gridConstraints.gridx = 1; gridConstraints.gridy = 0; gridConstraints.insets = new Insets(10, 10, 0, 10); getContentPane().add(balanceTextField, gridConstraints); balanceTextField.addActionListener(new ActionListener () { public void actionPerformed(ActionEvent e) { balanceTextFieldActionPerformed(e); } }); interestLabel.setText("Interest Rate"); interestLabel.setFont(myFont); gridConstraints = new GridBagConstraints(); gridConstraints.gridx = 0; gridConstraints.gridy = 1; gridConstraints.anchor = GridBagConstraints.WEST; gridConstraints.insets = new Insets(10, 10, 0, 0); getContentPane().add(interestLabel, gridConstraints); interestTextField.setPreferredSize(new Dimension(100, 25)); interestTextField.setHorizontalAlignment(SwingConstants.RIGHT); interestTextField.setFont(myFont); gridConstraints = new GridBagConstraints(); gridConstraints.gridx = 1; gridConstraints.gridy = 1; gridConstraints.insets = new Insets(10, 10, 0, 10); getContentPane().add(interestTextField, gridConstraints); interestTextField.addActionListener(new ActionListener () { public void actionPerformed(ActionEvent e) { interestTextFieldActionPerformed(e); } }); monthsLabel.setText("Number of Payments"); monthsLabel.setFont(myFont); gridConstraints = new GridBagConstraints(); gridConstraints.gridx = 0; gridConstraints.gridy = 2; gridConstraints.anchor = GridBagConstraints.WEST; gridConstraints.insets = new Insets(10, 10, 0, 0); getContentPane().add(monthsLabel, gridConstraints); monthsTextField.setPreferredSize(new Dimension(100, 25)); monthsTextField.setHorizontalAlignment(SwingConstants.RIGHT); monthsTextField.setFont(myFont); gridConstraints = new GridBagConstraints(); gridConstraints.gridx = 1; gridConstraints.gridy = 2; gridConstraints.insets = new Insets(10, 10, 0, 10); getContentPane().add(monthsTextField, gridConstraints); monthsTextField.addActionListener(new ActionListener () { public void actionPerformed(ActionEvent e) { monthsTextFieldActionPerformed(e); } }); paymentLabel.setText("Monthly Payment"); paymentLabel.setFont(myFont); gridConstraints = new GridBagConstraints(); gridConstraints.gridx = 0; gridConstraints.gridy = 3; gridConstraints.anchor = GridBagConstraints.WEST; gridConstraints.insets = new Insets(10, 10, 0, 0); getContentPane().add(paymentLabel, gridConstraints); paymentTextField.setPreferredSize(new Dimension(100, 25)); paymentTextField.setHorizontalAlignment(SwingConstants.RIGHT); paymentTextField.setFont(myFont); gridConstraints = new GridBagConstraints(); gridConstraints.gridx = 1; gridConstraints.gridy = 3; gridConstraints.insets = new Insets(10, 10, 0, 10); getContentPane().add(paymentTextField, gridConstraints); paymentTextField.addActionListener(new ActionListener () { public void actionPerformed(ActionEvent e) { paymentTextFieldActionPerformed(e); } }); computeButton.setText("Compute Monthly Payment"); gridConstraints = new GridBagConstraints(); gridConstraints.gridx = 0; gridConstraints.gridy = 4; gridConstraints.gridwidth = 2; gridConstraints.insets = new Insets(10, 0, 0, 0); getContentPane().add(computeButton, gridConstraints); computeButton.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { computeButtonActionPerformed(e); } }); newLoanButton.setText("New Loan Analysis"); newLoanButton.setEnabled(false); gridConstraints = new GridBagConstraints(); gridConstraints.gridx = 0; gridConstraints.gridy = 5; gridConstraints.gridwidth = 2; gridConstraints.insets = new Insets(10, 0, 10, 0); getContentPane().add(newLoanButton, gridConstraints); newLoanButton.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { newLoanButtonActionPerformed(e); } }); monthsButton.setText("X"); monthsButton.setFocusable(false); gridConstraints = new GridBagConstraints(); gridConstraints.gridx = 2; gridConstraints.gridy = 2; gridConstraints.insets = new Insets(10, 0, 0, 0); getContentPane().add(monthsButton, gridConstraints); monthsButton.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { monthsButtonActionPerformed(e); } }); paymentButton.setText("X"); paymentButton.setFocusable(false); gridConstraints = new GridBagConstraints(); gridConstraints.gridx = 2; gridConstraints.gridy = 3; gridConstraints.insets = new Insets(10, 0, 0, 0); getContentPane().add(paymentButton, gridConstraints); paymentButton.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { paymentButtonActionPerformed(e); } }); analysisLabel.setText("Loan Analysis:"); analysisLabel.setFont(myFont); gridConstraints = new GridBagConstraints(); gridConstraints.gridx = 3; gridConstraints.gridy = 0; gridConstraints.anchor = GridBagConstraints.WEST; gridConstraints.insets = new Insets(0, 10, 0, 0); getContentPane().add(analysisLabel, gridConstraints); analysisTextArea.setPreferredSize(new Dimension(250, 150)); analysisTextArea.setFocusable(false); analysisTextArea.setBorder(BorderFactory.createLineBorder(Color.BLACK)); analysisTextArea.setFont(new Font("Courier New", Font.PLAIN, 14)); analysisTextArea.setEditable(false); analysisTextArea.setBackground(Color.WHITE); gridConstraints = new GridBagConstraints(); gridConstraints.gridx = 3; gridConstraints.gridy = 1; gridConstraints.gridheight = 4; gridConstraints.insets = new Insets(0, 10, 0, 10); getContentPane().add(analysisTextArea, gridConstraints); exitButton.setText("Exit"); exitButton.setFocusable(false); gridConstraints = new GridBagConstraints(); gridConstraints.gridx = 3; gridConstraints.gridy = 5; getContentPane().add(exitButton, gridConstraints); exitButton.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { exitButtonActionPerformed(e); } }); pack(); Dimension screenSize = Toolkit.getDefaultToolkit().getScreenSize(); setBounds((int) (0.5 * (screenSize.width - getWidth())), (int) (0.5 * (screenSize.height - getHeight())), getWidth(), getHeight()); paymentButton.doClick(); } private void exitForm(WindowEvent evt) { System.exit(0); } private void computeButtonActionPerformed(ActionEvent e) { double balance, interest, payment; int months; double monthlyInterest, multiplier; double loanBalance, finalPayment; if (validateDecimalNumber(balanceTextField)) { balance = Double.valueOf(balanceTextField.getText()).doubleValue(); } else { JOptionPane.showConfirmDialog(null, "Invalid or empty Loan Balance entry.\nPlease correct.", "Balance Input Error", JOptionPane.DEFAULT_OPTION,JOptionPane.INFORMATION_MESSAGE); return; } if (validateDecimalNumber(interestTextField)) { interest = Double.valueOf(interestTextField.getText()).doubleValue(); } else { JOptionPane.showConfirmDialog(null, "Invalid or empty Interest Rate entry.\nPlease correct.", "Interest Input Error", JOptionPane.DEFAULT_OPTION,JOptionPane.INFORMATION_MESSAGE); return; } monthlyInterest = interest / 1200; if (computePayment) { // Compute loan payment if (validateDecimalNumber(monthsTextField)) { months = Integer.valueOf(monthsTextField.getText()).intValue(); } else { JOptionPane.showConfirmDialog(null, "Invalid or empty Number of Payments entry.\nPlease correct.", "Number of Payments Input Error",JOptionPane.DEFAULT_OPTION, JOptionPane.INFORMATION_MESSAGE); return; } if (interest == 0) { payment = balance / months; } else { multiplier = Math.pow(1 + monthlyInterest, months); payment = balance * monthlyInterest * multiplier / (multiplier - 1); } paymentTextField.setText(new DecimalFormat("0.00").format(payment)); } else { // Compute number of payments if (validateDecimalNumber(paymentTextField)) { payment = Double.valueOf(paymentTextField.getText()).doubleValue(); if (payment <= (balance * monthlyInterest + 1.0)) { if (JOptionPane.showConfirmDialog(null, "Minimum payment must be $" + new DecimalFormat("0.00").format((int)(balance * monthlyInterest + 1.0)) + "\n" + "Do you want to use the minimum payment?", "Input Error", JOptionPane.YES_NO_OPTION, JOptionPane.QUESTION_MESSAGE) == JOptionPane.YES_OPTION) { paymentTextField.setText(new DecimalFormat("0.00").format((int)(balance * monthlyInterest + 1.0))); payment = Double.valueOf(paymentTextField.getText()).doubleValue(); } else { paymentTextField.requestFocus(); return; } } } else { JOptionPane.showConfirmDialog(null, "Invalid or empty Monthly Payment entry.\nPlease correct.", "Payment Input Error", JOptionPane.DEFAULT_OPTION, JOptionPane.INFORMATION_MESSAGE); return; } if (interest == 0) { months = (int)(balance / payment); } else{ months = (int)((Math.log(payment) - Math.log(payment - balance * monthlyInterest)) / Math.log(1 + monthlyInterest)); } monthsTextField.setText(String.valueOf(months)); } // reset payment prior to analysis to fix at two decimals payment = Double.valueOf(paymentTextField.getText()).doubleValue(); // show analysis analysisTextArea.setText("Loan Balance: $" + new DecimalFormat("0.00").format(balance)); analysisTextArea.append("\n" + "Interest Rate: " + new DecimalFormat("0.00").format(interest) + "%"); // process all but last payment loanBalance = balance; for (int paymentNumber = 1; paymentNumber <= months - 1; paymentNumber++) { loanBalance += loanBalance * monthlyInterest - payment; } // find final payment finalPayment = loanBalance; if (finalPayment > payment) { // apply one more payment loanBalance += loanBalance * monthlyInterest - payment; finalPayment = loanBalance; months++; monthsTextField.setText(String.valueOf(months)); } analysisTextArea.append("\n\n" + String.valueOf(months - 1) + " Payments of $" + new DecimalFormat("0.00").format(payment)); analysisTextArea.append("\n" + "Final Payment of: $" + new DecimalFormat("0.00").format(finalPayment)); analysisTextArea.append("\n" + "Total Payments: $" + new DecimalFormat("0.00").format((months - 1) * payment + finalPayment)); analysisTextArea.append("\n" + "Interest Paid $" + new DecimalFormat("0.00").format((months - 1) * payment + finalPayment - balance)); computeButton.setEnabled(false); newLoanButton.setEnabled(true); newLoanButton.requestFocus(); } private void newLoanButtonActionPerformed(ActionEvent e) { // clear computed value and analysis if (computePayment) { paymentTextField.setText(""); } else { monthsTextField.setText(""); } analysisTextArea.setText(""); computeButton.setEnabled(true); newLoanButton.setEnabled(false); balanceTextField.requestFocus(); } private void monthsButtonActionPerformed(ActionEvent e) { // will compute months computePayment = false; paymentButton.setVisible(true); monthsButton.setVisible(false); monthsTextField.setText(""); monthsTextField.setEditable(false); monthsTextField.setBackground(lightYellow); monthsTextField.setFocusable(false); paymentTextField.setEditable(true); paymentTextField.setBackground(Color.WHITE); paymentTextField.setFocusable(true); computeButton.setText("Compute Number of Payments"); balanceTextField.requestFocus(); } private void paymentButtonActionPerformed(ActionEvent e) { // will compute payment computePayment = true; paymentButton.setVisible(false); monthsButton.setVisible(true); monthsTextField.setEditable(true); monthsTextField.setBackground(Color.WHITE); monthsTextField.setFocusable(true); paymentTextField.setText(""); paymentTextField.setEditable(false); paymentTextField.setBackground(lightYellow); paymentTextField.setFocusable(false); computeButton.setText("Compute Monthly Payment"); balanceTextField.requestFocus(); } private void exitButtonActionPerformed(ActionEvent e) { System.exit(0); } private void balanceTextFieldActionPerformed(ActionEvent e) { balanceTextField.transferFocus(); } private void interestTextFieldActionPerformed(ActionEvent e) { interestTextField.transferFocus(); } private void monthsTextFieldActionPerformed(ActionEvent e) { monthsTextField.transferFocus(); } private void paymentTextFieldActionPerformed(ActionEvent e) { paymentTextField.transferFocus(); } private boolean validateDecimalNumber(JTextField tf) { // checks to see if text field contains // valid decimal number with only digits and a single decimal point String s = tf.getText().trim(); boolean hasDecimal = false; boolean valid = true; if (s.length() == 0) { valid = false; } else { for (int i = 0; i < s.length(); i++) { char c = s.charAt(i); if (c >= '0' && c <= '9') { continue; } else if (c == '.' && !hasDecimal) { hasDecimal = true; } else { // invalid character found valid = false; } } } tf.setText(s); if (!valid) { tf.requestFocus(); } return (valid); } }
Akanks-cell/SUVEN-CONSULTANTS-PVT-LIMITED
LoanAssiatnt.java
3,957
// checks to see if text field contains
line_comment
en
true
231533_1
import java.io.FileInputStream; import java.io.FileNotFoundException; import java.util.Scanner; /** * <h3>COMP90041, Sem2, 2022: Final Project</h3> * <p>Class HRAssistant is used to take in command flags from running HRAssistant. Run the approriate type of menu, functionalities and * display welcome messages. * @author Gia Han Ly */ public class HRAssistant { public static void main(String[] args){ // Read command line option Command command = new Command(); command.readCommand(args); String appFile = command.getApplicationsFile(); String jobsFile = command.getJobsFile(); // Go to HR menu if role flag is set to hr if(command.getRole().equals("hr")){ displayWelcomeMessage("hr"); HRmenu hrMenu = new HRmenu(jobsFile, appFile); hrMenu.getInput(); System.out.println(); } // Go to applicant menu if role flag is set to applicant else if(command.getRole().equals("applicant")){ displayWelcomeMessage("applicant"); ApplicantMenu menu = new ApplicantMenu(jobsFile, appFile); menu.getInput(); System.out.println(); } else if (command.getRole().equals("audit")){ Audit audit = new Audit(jobsFile, appFile); audit.printStatistics(); } } /** * Display welcome messages depends on role input * @param role */ private static void displayWelcomeMessage(String role) { Scanner inputStream = null; String filename = null; if(role.equals("hr")){ filename = "welcome_hr.ascii"; } else if(role.equals("applicant")){ filename = "welcome_applicant.ascii"; } try{ inputStream = new Scanner(new FileInputStream(filename)); } catch (FileNotFoundException e) { System.out.println("Welcome File not found."); } while(inputStream.hasNextLine()) { System.out.println(inputStream.nextLine()); } } }
amybok/COMP90041-2022Sem2Final
HRAssistant.java
479
// Read command line option
line_comment
en
false
231575_0
//This class is our model for storing Charge Of public class ChargeOf { private int residentId; private int assistantId; public ChargeOf(int residentId, int assistantId) { this.residentId = residentId; this.assistantId = assistantId; } public int getResidentId() { return residentId; } public void setResidentId(int residentId) { this.residentId = residentId; } public int getAssistantId() { return assistantId; } public void setAssistantId(int assistantId) { this.assistantId = assistantId; } public Object getByName(String attributeName) { switch(attributeName) { case "residentId" : return residentId; case "assistantId" : return assistantId; default : return null; } } @Override public String toString() { return "ChargeOf [residentId=" + residentId + ", assistantId=" + assistantId + "]"; } }
alperenoztas/JDBC-MVC
src/ChargeOf.java
264
//This class is our model for storing Charge Of
line_comment
en
true
231856_16
/ Java program to print BFS traversal from a given source vertex. // BFS(int s) traverses vertices reachable from s. import java.io.*; import java.util.*; // This class represents a directed graph using adjacency list // representation class Graph { private int V; // No. of vertices private LinkedList<Integer> adj[]; //Adjacency Lists // Constructor Graph(int v) { V = v; adj = new LinkedList[v]; for (int i=0; i<v; ++i) adj[i] = new LinkedList(); } // Function to add an edge into the graph void addEdge(int v,int w) { adj[v].add(w); } // prints BFS traversal from a given source s void BFS(int s) { // Mark all the vertices as not visited(By default // set as false) boolean visited[] = new boolean[V]; // Create a queue for BFS LinkedList<Integer> queue = new LinkedList<Integer>(); // Mark the current node as visited and enqueue it visited[s]=true; queue.add(s); while (queue.size() != 0) { // Dequeue a vertex from queue and print it s = queue.poll(); System.out.print(s+" "); // Get all adjacent vertices of the dequeued vertex s // If a adjacent has not been visited, then mark it // visited and enqueue it Iterator<Integer> i = adj[s].listIterator(); while (i.hasNext()) { int n = i.next(); if (!visited[n]) { visited[n] = true; queue.add(n); } } } } // Driver method to public static void main(String args[]) { Graph g = new Graph(4); g.addEdge(0, 1); g.addEdge(0, 2); g.addEdge(1, 2); g.addEdge(2, 0); g.addEdge(2, 3); g.addEdge(3, 3); System.out.println("Following is Breadth First Traversal "+ "(starting from vertex 2)"); g.BFS(2); } }
TitanVaibhav/ByldSession
bfs.java
528
// Driver method to
line_comment
en
false
231957_0
package uk.ac.gla.dcs.anc; import java.util.HashMap; import java.util.Map; import java.util.Set; public class Node { private int nodeId; public Map<Node,CostAndNextNode> routingTable; public Map<Node,Integer> neighbours; public Node(int nodeId) { this.nodeId = nodeId; this.routingTable = new HashMap<Node, CostAndNextNode>(); this.neighbours = new HashMap<Node,Integer>(); routingTable.put(this, new CostAndNextNode(0, this)); } public String name() { return "N" + nodeId; } public boolean updateConnectionIfBetter(Node node, int newCost, Node nextNode, Set<Node> tracedNode) { int baseCost = neighbours.get(nextNode); // System.out.println(name() + ": Receiving " + nextNode.name() + "'s advertisement towards " + node.name() + " with baseCost " + baseCost); boolean toReturn = false; if(!this.routingTable.containsKey(node) || (baseCost + newCost) < this.routingTable.get(node).cost) { toReturn = true; if(tracedNode != null && tracedNode.contains(this)) { System.out.println(name() + "=>" + node.name() + ": Swapping " + (this.routingTable.containsKey(node) ? this.routingTable.get(node).cost : "null") + " for " + (baseCost + newCost)); } this.routingTable.put(node, new CostAndNextNode(newCost + baseCost, nextNode)); } return toReturn; } public Map<Node,Integer> getAdvertisement(boolean splitHorizon, Node forWhom) { HashMap<Node,Integer> toReturn = new HashMap<Node,Integer>(); for(Node key : routingTable.keySet()) { CostAndNextNode currentCostAndNextNode = routingTable.get(key); if(!splitHorizon || (splitHorizon && !currentCostAndNextNode.nextNode.equals(forWhom))) { toReturn.put(key, currentCostAndNextNode.cost); } else { toReturn.put(key, Integer.MAX_VALUE); } } return toReturn; } public boolean receiveAdvertisement(Node from, Map<Node,Integer> advertisement, Set<Node> tracedNode) { boolean toReturn = false; for(Node node : advertisement.keySet()) { Integer newCost = advertisement.get(node); toReturn = updateConnectionIfBetter(node, newCost, from, tracedNode); } return toReturn; } @Override public String toString() { StringBuilder a = new StringBuilder(); a.append("\nNode: " + name()); for(Node node : routingTable.keySet()) { CostAndNextNode costAndNextNode = routingTable.get(node); a.append("\n" + node.name() + ": " + costAndNextNode.cost + " via " + costAndNextNode.nextNode.name()); } return a.toString(); } public int getId() { return this.nodeId; } }
akoss/uog-anc-ae
src/uk/ac/gla/dcs/anc/Node.java
809
// System.out.println(name() + ": Receiving " + nextNode.name() + "'s advertisement towards " + node.name() + " with baseCost " + baseCost);
line_comment
en
true
232233_0
/* * Copyright (C) 2012 The Android Open Source Project * * 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 com.wly.net; public class Ipsum { static String[] Headlines = { "Article One", "Article Two" }; static String[] Articles = { "Article One\n\nExcepteur pour-over occaecat squid biodiesel umami gastropub, nulla laborum salvia dreamcatcher fanny pack. Ullamco culpa retro ea, trust fund excepteur eiusmod direct trade banksy nisi lo-fi cray messenger bag. Nesciunt esse carles selvage put a bird on it gluten-free, wes anderson ut trust fund twee occupy viral. Laboris small batch scenester pork belly, leggings ut farm-to-table aliquip yr nostrud iphone viral next level. Craft beer dreamcatcher pinterest truffaut ethnic, authentic brunch. Esse single-origin coffee banksy do next level tempor. Velit synth dreamcatcher, magna shoreditch in american apparel messenger bag narwhal PBR ennui farm-to-table.", "Article Two\n\nVinyl williamsburg non velit, master cleanse four loko banh mi. Enim kogi keytar trust fund pop-up portland gentrify. Non ea typewriter dolore deserunt Austin. Ad magna ethical kogi mixtape next level. Aliqua pork belly thundercats, ut pop-up tattooed dreamcatcher kogi accusamus photo booth irony portland. Semiotics brunch ut locavore irure, enim etsy laborum stumptown carles gentrify post-ironic cray. Butcher 3 wolf moon blog synth, vegan carles odd future." }; }
sum1nil/Android-Port-Scanner-JNI
src/com/wly/net/Ipsum.java
551
/* * Copyright (C) 2012 The Android Open Source Project * * 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. */
block_comment
en
true
232283_7
package view.edges; import javafx.scene.Group; import javafx.scene.paint.Color; import javafx.scene.shape.Circle; import javafx.scene.shape.Line; import javafx.scene.text.Text; import model.edges.AbstractEdge; import model.edges.MessageEdge; import util.Constants; import view.nodes.AbstractNodeView; import java.beans.PropertyChangeEvent; import java.util.ArrayList; /** * The Graphical Representation of a AssociationEdge. */ public class MessageEdgeView extends AbstractEdgeView { private AbstractNodeView startNode; private AbstractNodeView endNode; private ArrayList<Line> arrowHeadLines = new ArrayList<>(); private Double startX; private Double startY; private Circle circleHandle; private Group arrowHead; private Text title = new Text(); //TODO these constructors are a mess. public MessageEdgeView(MessageEdge edge, Double pStartX, Double pStartY, AbstractNodeView startNode, AbstractNodeView endNode) { super(edge, startNode, endNode); arrowHead = new Group(); this.getChildren().add(arrowHead); startX = pStartX; startY = pStartY; this.startNode = startNode; this.endNode = endNode; this.setStrokeWidth(super.STROKE_WIDTH); this.setStroke(Color.BLACK); setPosition(); draw(); this.getChildren().add(title); } public MessageEdgeView(MessageEdge edge, Double pStartX, Double pStartY, AbstractNodeView endNode) { super(edge, null, endNode); arrowHead = new Group(); this.getChildren().add(arrowHead); startX = pStartX; startY = pStartY; this.startNode = null; this.endNode = endNode; this.setStrokeWidth(super.STROKE_WIDTH); this.setStroke(Color.BLACK); setPosition(); drawCircleHandle(); draw(); this.getChildren().add(title); } @Override protected void draw() { AbstractEdge.Direction direction = refEdge.getDirection(); //Draw arrows. switch(direction) { case NO_DIRECTION: break; case START_TO_END: drawArrowHead(startLine.getEndX(), startLine.getEndY(), startLine.getStartX(), startLine.getStartY()); break; case END_TO_START: drawArrowHead(startLine.getStartX(), startLine.getStartY(), startLine.getEndX(), startLine.getEndY()); break; } } private void drawTitle(String titleStr){ title.setText(titleStr); title.setX((startLine.getStartX() + endNode.getX())/2); title.setY(startLine.getStartY() - 5); title.toFront(); } @Override protected void setPosition() { if(startNode != null){ setPosition2();//WithStartNode(); } else { setPositionNoStartNode(); } //setPositionNoStartNode(); drawTitle(title.getText()); } private void setPosition2(){ //If end node is to the right of startPos: if (startX <= endNode.getTranslateX()) { startLine.setStartX(startNode.getTranslateX() + (startNode.getWidth()/2)); startLine.setStartY(startY); startLine.setEndX(endNode.getTranslateX() + (endNode.getWidth()/2)); startLine.setEndY(startY); position = Position.RIGHT; } //If end node is to the left of startPos: else if (startX > endNode.getTranslateX() + endNode.getWidth()) { startLine.setStartX(startNode.getTranslateX() + (startNode.getWidth()/2)); startLine.setStartY(startY); startLine.setEndX(endNode.getTranslateX() + (endNode.getWidth()/2)); startLine.setEndY(startY); position = Position.LEFT; } //TODO Handle when the nodes are overlapping. } private void setPositionWithStartNode(){ //If end node is to the right of startNode: AbstractNodeView lowestNodeView; if(startNode.getTranslateY() <= endNode.getTranslateY()){ lowestNodeView = endNode; } else { lowestNodeView = startNode; } if (startNode.getTranslateX() + startNode.getWidth() <= endNode.getTranslateX()) { startLine.setStartX(startNode.getTranslateX() + (startNode.getWidth()/2)); startLine.setStartY(lowestNodeView.getTranslateY() + lowestNodeView.getHeight() + 20); startLine.setEndX(endNode.getTranslateX() + (endNode.getWidth()/2)); startLine.setEndY(lowestNodeView.getTranslateY() + lowestNodeView.getHeight() + 20); position = Position.RIGHT; } //If end node is to the left of startNode: else if (startNode.getTranslateX() > endNode.getTranslateX() + endNode.getWidth()) { startLine.setStartX(startNode.getTranslateX() + (startNode.getWidth()/2)); startLine.setStartY(lowestNodeView.getTranslateY() + lowestNodeView.getHeight() + 20); startLine.setEndX(endNode.getTranslateX() + (endNode.getWidth()/2)); startLine.setEndY(lowestNodeView.getTranslateY() + lowestNodeView.getHeight() + 20); position = Position.LEFT; } } private void setPositionNoStartNode(){ //If end node is to the right of startPos: if (startX <= endNode.getTranslateX()) { startLine.setStartX(startX); startLine.setStartY(startY); startLine.setEndX(endNode.getTranslateX() + (endNode.getWidth()/2)); startLine.setEndY(startY); position = Position.RIGHT; } //If end node is to the left of startPos: else if (startX > endNode.getTranslateX() + endNode.getWidth()) { startLine.setStartX(startX); startLine.setStartY(startY); startLine.setEndX(endNode.getTranslateX() + (endNode.getWidth()/2)); startLine.setEndY(startY); position = Position.LEFT; } //TODO Handle when the nodes are overlapping. } private void drawCircleHandle(){ circleHandle = new Circle(10); circleHandle.centerXProperty().bind(startLine.startXProperty()); circleHandle.centerYProperty().bind(startLine.startYProperty()); this.getChildren().add(circleHandle); } public void setSelected(boolean selected){ super.setSelected(selected); Color color; if(selected){ color = Constants.selected_color; } else { color = Color.BLACK; } for(Line l : arrowHeadLines){ l.setStroke(color); } title.setFill(color); if(circleHandle != null){ circleHandle.setFill(color); } } /** * Draws an ArrowHead and returns it in a group. * Based on code from http://www.coderanch.com/t/340443/GUI/java/Draw-arrow-head-line * @param startX * @param startY * @param endX * @param endY * @return Group. */ private void drawArrowHead(double startX, double startY, double endX, double endY) { arrowHead.getChildren().clear(); double phi = Math.toRadians(30); int barb = 15; double dy = startY - endY; double dx = startX - endX; double theta = Math.atan2(dy, dx); double x, y, rho = theta + phi; for (int j = 0; j < 2; j++) { x = startX - barb * Math.cos(rho); y = startY - barb * Math.sin(rho); Line arrowHeadLine = new Line(startX, startY, x, y); arrowHeadLine.setStrokeWidth(super.STROKE_WIDTH); arrowHeadLines.add(arrowHeadLine); if(super.isSelected()){ arrowHeadLine.setStroke(Constants.selected_color); } arrowHead.getChildren().add(arrowHeadLine); rho = theta - phi; } } public void propertyChange(PropertyChangeEvent evt){ super.propertyChange(evt); String propertyName = evt.getPropertyName(); if(propertyName.equals(Constants.changeNodeTranslateX) || propertyName.equals(Constants.changeNodeTranslateY) || propertyName.equals(Constants.changeEdgeDirection)) { draw(); } else if (propertyName.equals(Constants.changeMessageStartX) ){ startX = (Double)evt.getNewValue(); setPositionNoStartNode(); drawTitle(title.getText()); draw(); } else if (propertyName.equals(Constants.changeMessageStartY)){ startY = (Double)evt.getNewValue(); if(startNode != null){ setPosition2(); } else { setPositionNoStartNode(); } drawTitle(title.getText()); draw(); } else if (propertyName.equals(Constants.changeMessageTitle)){ drawTitle((String)evt.getNewValue()); } else if (propertyName.equals(Constants.changeMessageType)){ if(evt.getNewValue() == MessageEdge.MessageType.RESPONSE){ startLine.getStrokeDashArray().addAll(15d, 10d); } else { startLine.getStrokeDashArray().clear(); } } else if (evt.getPropertyName().equals(Constants.changeNodeTranslateX) || evt.getPropertyName().equals(Constants.changeNodeTranslateY)){ } } public Circle getCircleHandle(){ return circleHandle; } }
Imarcus/OctoUML
src/view/edges/MessageEdgeView.java
2,344
//TODO Handle when the nodes are overlapping.
line_comment
en
true
232323_3
import java.awt.*; import java.awt.event.*; import javax.swing.*; import javax.swing.border.LineBorder; import java.sql.*; import java.time.format.DateTimeFormatter; import java.time.*; import java.security.*; public class CallLogs extends PhonePresetWithNoWallpaper implements ActionListener, KeyListener{ // Clear Call log button private JButton homeBtn = new JButton(); JButton clearBtn = new JButton(); private SecureRandom randomNumbers = new SecureRandom(); // object for random numbers // Panel to hold contacts private JPanel contactListPanel = new JPanel(); private String today; private String yesterday; // Control how events are added; make sure listeners are added only once private boolean eventsAdded = false; private JPanel allPanel = new JPanel(); private JLabel allLabel = new JLabel("All"); private JPanel missedPanel = new JPanel(); private JLabel missedLabel = new JLabel("Missed"); // Constructor --> public CallLogs(){ setLayout(null); DateTimeFormatter dateFormat = DateTimeFormatter.ofPattern("E, MMM d yyyy"); LocalDateTime now = LocalDateTime.now(); today = dateFormat.format(now); LocalDate yestee = (LocalDate.now()).minusDays(1); yesterday = dateFormat.format(yestee); showAllCalls(); // Add event listeners to nav buttons if(!eventsAdded){ missedLabel.addMouseListener(new MouseAdapter() { @Override public void mouseClicked(MouseEvent e) { showMissedCalls(); // System.out.println("Missed Label pressed"); missedLabel.setForeground(Color.WHITE); missedPanel.setBackground(SystemColor.controlDkShadow); allPanel.setBackground(Color.BLACK); } }); allLabel.addMouseListener(new MouseAdapter() { @Override public void mouseClicked(MouseEvent e) { showAllCalls(); // System.out.println("All Label pressed"); allLabel.setForeground(Color.WHITE); allPanel.setBackground(SystemColor.controlDkShadow); missedPanel.setBackground(Color.BLACK); } }); homeBtn.addActionListener(this); clearBtn.addActionListener(this); eventsAdded = true; } addInnerJPanel(); }// <-- end Constructor // add panel on which list wil be written public void addInnerJPanel(){ // Add scroll pane to inner panel JScrollPane scrollPane = new JScrollPane(contactListPanel, ScrollPaneConstants.VERTICAL_SCROLLBAR_AS_NEEDED, ScrollPaneConstants.HORIZONTAL_SCROLLBAR_NEVER); scrollPane.setBounds( 20, 90, 247, 380 ); scrollPane.setPreferredSize(new Dimension(160, 200)); scrollPane.setBorder(null); scrollPane.getVerticalScrollBar().setUnitIncrement(10); contactListPanel.setLayout(null); contactListPanel.setBackground(Color.WHITE); add(scrollPane); showNavigationButtons(); } //RECENT AND CONTACTS TAB CODES public void addRecAndConTab() { JLabel dialLabel = new JLabel("New label"); dialLabel.setBounds(62, 489, 34, 34); dialLabel.setIcon(new ImageIcon(getClass().getResource("/images/icons/dialpad.png"))); dialLabel.setVerticalAlignment(SwingConstants.BOTTOM); dialLabel.addMouseListener(new MouseAdapter() { public void mouseClicked(MouseEvent arg0) { changeCurrentPage("dial"); } }); add(dialLabel); JLabel contactsLabel = new JLabel("New label"); contactsLabel.setBounds(185, 489, 34, 34); contactsLabel.setIcon(new ImageIcon(getClass().getResource("/images/icons/contac.png"))); contactsLabel.setVerticalAlignment(SwingConstants.BOTTOM); contactsLabel.addMouseListener(new MouseAdapter() { public void mouseClicked(MouseEvent arg0) { changeCurrentPage("contacts"); } }); add(contactsLabel); // Home Button Icon homebar = new ImageIcon(getClass().getResource("./images/homebar.png")); homeBtn.setIcon(homebar); homeBtn.setForeground(Color.BLUE); homeBtn.setBounds(75, 532, 131, 10); homeBtn.setHorizontalAlignment(SwingConstants.CENTER); super.makeButtonTransparent(homeBtn, false); homeBtn.setFocusable(false); add(homeBtn); } private void showNavigationButtons(){ Icon addIcon = new ImageIcon(getClass().getResource("./images/icons/delete.png")); clearBtn.setBounds(223, 50, 50, 30); clearBtn.setIcon(addIcon); super.makeButtonTransparent(clearBtn, false); clearBtn.setFocusable(false); add(clearBtn); // Show top nav JPanel topNav = new JPanel(); topNav.setLayout(null); topNav.setBorder(new LineBorder(new Color(169, 169, 169), 3, true)); topNav.setBackground(Color.WHITE); topNav.setBounds(77, 50, 125, 30); add(topNav); allPanel.setLayout(null); allPanel.setBackground(SystemColor.controlDkShadow); allPanel.setBounds(0, 0, 62, 30); topNav.add(allPanel); allLabel.setHorizontalAlignment(SwingConstants.CENTER); allLabel.setForeground(Color.WHITE); allLabel.setFont(new Font("Raleway", Font.PLAIN, 15)); allLabel.setBounds(3, 5, 56, 16); allPanel.add(allLabel); missedPanel.setBackground(Color.BLACK); missedPanel.setBounds(62, 0, 62, 30); topNav.add(missedPanel); missedLabel.setHorizontalAlignment(SwingConstants.CENTER); missedLabel.setForeground(Color.WHITE); missedLabel.setFont(new Font("Raleway", Font.PLAIN, 15)); missedPanel.add(missedLabel); // System.out.println("all label mouse listeners count : "+allLabel.getMouseListeners().length); // System.out.println("missed label mouse listeners count : "+missedLabel.getMouseListeners().length); // Show bottom nav addRecAndConTab(); } // display missed calls public void showMissedCalls(){ contactListPanel.removeAll(); contactListPanel.revalidate(); contactListPanel.repaint(); // System.out.println("Missed Calls"); MyDatabaseManager db = new MyDatabaseManager(); displayCallLogs(db.fetchSpecificCallLog("missed")); // Resize scroll bar int count = db.countNumOfRowsFrom( db.fetchSpecificCallLog("missed")); contactListPanel.setPreferredSize(new Dimension(247, (count*65))); contactListPanel.repaint(); // show changes made } // display all calls public void showAllCalls() { contactListPanel.removeAll(); contactListPanel.revalidate(); contactListPanel.repaint(); // System.out.println("All Calls"); MyDatabaseManager db = new MyDatabaseManager(); displayCallLogs(db.fetchAllCallLog()); // Resize scroll bar int count = db.countNumOfRowsFrom( db.fetchAllCallLog()); contactListPanel.setPreferredSize(new Dimension(247, (count*65))); contactListPanel.repaint(); // show changes made } // display call logs function public void displayCallLogs(ResultSet logsList){ // starting values int x = 10, y = 5, w = 200, h = 60; // Display all call logs if it is not empty try{ // Display contact list now if(logsList.next()){ do{ String phone = logsList.getString("log_phone"); String time = logsList.getString("time"); String date = logsList.getString("date"); String category = logsList.getString("category"); String categoryIconUrl = ""; String name = logsList.getString("name"); name = (name == null || name.contentEquals("")) ? phone : name; if(category.contentEquals("missed")){ categoryIconUrl = "./images/icons/missedCall.png"; } else if(category.contentEquals("dialed")){ categoryIconUrl = "./images/icons/callout.png"; } int num = 1 + randomNumbers.nextInt(6); String defaultImageUrl = "./images/icons/contacts/contacts-"+num+".png"; Icon contactImage = new ImageIcon(getClass().getResource(defaultImageUrl)); // System.out.printf("%10s%10s%10s%n", phone, time, category); Icon categoryIcon = new ImageIcon(ContactsPage.class.getResource(categoryIconUrl)); // making the line under the Calendar label JSeparator separator = new JSeparator(); separator.setBackground(Color.LIGHT_GRAY); separator.setBounds(x , y, w, 2); contactListPanel.add(separator); y += 4; // outer label for name/phone JLabel contactLog = new JLabel(); contactLog.setText(String.format("%s",name)); contactLog.setIcon(contactImage); contactLog.setForeground(Color.DARK_GRAY); contactLog.setFont(new Font("Raleway", Font.PLAIN, 18)); contactLog.setHorizontalAlignment(SwingConstants.LEFT); contactLog.setVerticalAlignment(SwingConstants.TOP); contactLog.setHorizontalTextPosition(SwingConstants.RIGHT); contactLog.setVerticalTextPosition(SwingConstants.TOP); contactLog.setIconTextGap(22); contactLog.setBounds(x, y, w, h); contactLog.setLayout(null); // inner label for icon and time String day = date; String innerStr = String.format("<html>%s<br>%s</html>", day, time); if(today.compareTo(date) == 0){ innerStr = String.format("Today, %s", time); } else if(yesterday.compareTo(date) == 0){ innerStr = String.format("Yesterday, %s", time);; } // inner label JButton inner = new JButton(innerStr, categoryIcon); super.makeButtonTransparent(inner, false); inner.setBounds(40, 26, 180, 30); inner.setFocusable(false); inner.setFont(new Font("Raleway", Font.PLAIN, 12)); inner.setHorizontalAlignment(SwingConstants.LEFT); contactLog.add(inner); contactListPanel.add(contactLog); y = y+h+1; // add an action listener contactLog.addMouseListener(new MouseAdapter() { public void mouseClicked(MouseEvent e) { makeCall(phone); } }); }while(logsList.next());// end do while loop }else{ JLabel nothingFound = new JLabel("Nothing Found!"); nothingFound.setForeground(Color.GRAY); nothingFound.setHorizontalAlignment(SwingConstants.CENTER); nothingFound.setVerticalAlignment(SwingConstants.CENTER); nothingFound.setFont(new Font("Raleway", Font.PLAIN, 14)); nothingFound.setBounds(5, 110, 235, 45); contactListPanel.add(nothingFound); } }catch(SQLException ex){ System.out.println(ex.getMessage()); System.out.println(ex.getSQLState()); System.out.println("VendorError: " + ex.getErrorCode()); } } // make a call public void makeCall(String contactNumber){ // System.out.println("dialing "+contactName+"..."); PhoneDial panel = new PhoneDial(); panel.setTextFieldText(contactNumber); NewWindowFrame frame = new NewWindowFrame(panel); frame.setVisible(true); ((JFrame) SwingUtilities.getWindowAncestor(this)).dispose(); } // Handle ActionListener events public void actionPerformed(ActionEvent e){ if( e.getSource() == homeBtn ){ // Go to home screen HomeScreen panel = new HomeScreen(); NewWindowFrame frame = new NewWindowFrame(panel); frame.setVisible(true); ((JFrame) SwingUtilities.getWindowAncestor(this)).dispose(); } if( e.getSource() == clearBtn ){ // Go to home screen MyDatabaseManager db = new MyDatabaseManager(); if(db.clearCallLog()){ // refresh page CallLogs panel = new CallLogs(); NewWindowFrame frame = new NewWindowFrame(panel); frame.setVisible(true); ((JFrame) SwingUtilities.getWindowAncestor(this)).dispose(); } } }// <-- end actionPerformed // Handle KeyListener events public void keyTyped(KeyEvent e){ // code... }// <-- end keyTyped public void keyPressed(KeyEvent e){ // code... }// <-- end keyPressed public void keyReleased(KeyEvent e){ // code... }// <-- end keyReleased // Change current page public void changeCurrentPage(String target){ if(target == "dial"){ // go to dial page PhoneDial panel = new PhoneDial(); NewWindowFrame frame = new NewWindowFrame(panel); frame.setVisible(true); ((JFrame) SwingUtilities.getWindowAncestor(this)).dispose(); } else if(target == "contacts"){ // go to contacts page ContactsPage panel = new ContactsPage(); NewWindowFrame frame = new NewWindowFrame(panel); frame.setVisible(true); ((JFrame) SwingUtilities.getWindowAncestor(this)).dispose(); } else if(target == "logs"){ // go to call logs page CallLogs panel = new CallLogs(); NewWindowFrame frame = new NewWindowFrame(panel); frame.setVisible(true); ((JFrame) SwingUtilities.getWindowAncestor(this)).dispose(); } } }
theLivin/phone-simulator
CallLogs.java
3,233
// Control how events are added; make sure listeners are added only once
line_comment
en
false
232776_0
public class Bmi { public static void main(String[] args) { double massInKg = 81.2; double heightInM = 1.78; double bmiIndex = (massInKg) / (heightInM * heightInM); System.out.println("BMI: " + bmiIndex); // Print the Body mass index (BMI) based on these values } }
green-fox-academy/ronai22
week-01/day-04/workshop/src/Bmi.java
96
// Print the Body mass index (BMI) based on these values
line_comment
en
true
232875_3
package com.fiskkit; import java.io.BufferedWriter; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; import java.io.OutputStreamWriter; import java.io.Writer; import java.util.ArrayList; import java.util.List; import com.fiskkit.Fetcher; import opennlp.tools.sentdetect.SentenceModel; import opennlp.tools.sentdetect.SentenceDetectorME; public class ParseSentences { public static final String ENCODING = "utf-8"; SentenceDetectorME sentenceDetector; public ParseSentences() { // Find the pre-trained model file in our classpath // We don't want or need to load this every time we parse a paragraph. try (InputStream modelIn = ParseSentences.class.getClassLoader().getResourceAsStream("en-sent.bin")) { // Moving this block is mostly a philosophical change. Which can be discussed. SentenceModel model = new SentenceModel(modelIn); sentenceDetector = new SentenceDetectorME(model); } catch (IOException e) { e.printStackTrace(); } } /** * Create the sentence detector and fetch the url. * This is then written to a file with writeToFile(); * * @param url the website url we will fetch our article from * @param filename the name of the file */ public void doParse(String url, String filename) { System.out.println("Parsing " + url + ", writing to " + filename); List<String> paragraphs; paragraphs = Fetcher.pullAndExtract(url); writeToFile(paragraphs, sentenceDetector, filename); } /** * Parses the paragraphs into sentences and writes them to a file. * This method overwrites whichever file it is writing to. * * @param paragraphs the List of paragraph strings, obtained with * @param sentenceDetector the detector we use to parse the paragraphs * @param filename where the strings will be written to */ public void writeToFile(List<String> paragraphs, SentenceDetectorME sentenceDetector, String filename) { String sentences[] = null; String line = null; // Index that keeps count throughout all of the paragraphs, not just one int lineIndex = 0; // Use BufferedWriter instead of Writer for newLine() try (BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(filename), ENCODING))) { for (String p : paragraphs) { sentences = sentenceDetector.sentDetect(p); for (String s : sentences) { lineIndex++; line = String.format("[%d] --> \"%s\"", lineIndex, s); // System.out.println(line); writer.write(line); writer.newLine(); } } } catch (IOException e) { e.printStackTrace(); } } public static void main(String[] argv) { ParseSentences parser = new ParseSentences(); // Sample articles we can parse parser.doParse("http://www.weeklystandard.com/blogs/intel-chief-blasts-obama_802242.html", "intel.txt"); parser.doParse("http://www.thedailybeast.com/articles/2014/08/21/swat-lobby-takes-a-shot-at-congress.html", "swat.txt"); parser.doParse("http://www.thedailybeast.com/articles/2014/08/12/russia-s-suspicious-humanitarian-aid-for-ukraine-separatists.html", "russia.txt"); } }
bryangarza/ParseSentences
ParseSentences.java
862
/** * Create the sentence detector and fetch the url. * This is then written to a file with writeToFile(); * * @param url the website url we will fetch our article from * @param filename the name of the file */
block_comment
en
true
232972_1
/* Dishes Easy Time Limit: 2 sec Memory Limit: 128000 kB Problem Statement Sheldon and Leonard are gone for lunch but none of them have money so they decided to wash dishes. In total, they washed T dishes from which N dishes are washed by Leonard. Now Leonard wants to know the number of dishes Sheldon washed. Help him to find it. Input The first line of the input contains N and T Constraints:- 1 <= N <= T <= 1000 Output Return the number of dishes Sheldon washed. Example Sample Input:- 3 6 Sample Output:- 3 Sample Input:- 2 4 Sample Output:- 2 */ import java.io.*; // for handling input/output import java.util.*; // contains Collections framework // don't change the name of this class // you can add inner classes if needed class Main { public static void main (String[] args) { Scanner sc = new Scanner(System.in); int a = sc.nextInt(); int b = sc.nextInt(); System.out.println(b-a); // Your code here } }
Shubham-Jaiswal-838/Newton-School-Questions-with-Solution
Dishes.java
303
// for handling input/output
line_comment
en
true
232975_13
package org.jfree.data; import static org.junit.Assert.*; import org.jfree.data.Range; import org.junit.*; public class RangeTest { private Range exampleRange; @BeforeClass public static void setUpBeforeClass() throws Exception { } @Before public void setUp() throws Exception { exampleRange = new Range(-1, 1); } @Test public void centralValueShouldBeZero() { assertEquals("The central value of -1 and 1 should be 0", 0, exampleRange.getCentralValue(), .000000001d); } @Test public void getLengthShouldBeTwo() { // fail("Not yet implemented"); assertEquals("The length should be 2", 2, exampleRange.getLength(), .000000001d); } @Test public void getLowerBoundShouldBeNegOne() { //fail("Not yet implemented"); assertEquals("The lower bound should be -1",-1,exampleRange.getLowerBound(), .000000001d); } @Test public void getUpperBoundShouldBeOne() { //fail("Not yet implemented"); assertEquals("The upperbound should be 1", 1, exampleRange.getUpperBound(), .000000001d); } @Test public void intersectsShouldBeTrueALessThanLower() { //fail("Not yet implemented"); Range exampleRange2 = new Range(-2, 2); assertTrue(exampleRange.intersects(exampleRange2)); } @Test public void intersectsShouldBeFalseAGreaterThanUpper() { //fail("Not yet implemented"); Range exampleRange2 = new Range(3, 4); assertFalse(exampleRange.intersects(exampleRange2)); } @Test public void intersectsShouldBeTrueABetweenBounds() { //fail("Not yet implemented"); Range exampleRange2 = new Range(0, 4); assertTrue(exampleRange.intersects(exampleRange2)); } //BVT @Test public void intersectsShouldBeTrueAEqualLower() { //fail("Not yet implemented"); Range exampleRange2 = new Range(-1, 2); assertTrue(exampleRange.intersects(exampleRange2)); } @Test public void intersectsShouldBeTrueAEqualUpper() { //fail("Not yet implemented"); Range exampleRange2 = new Range(1, 2); assertTrue(exampleRange.intersects(exampleRange2)); } //Robustness @Test public void intersectsShouldBeTrueABLB() { //fail("Not yet implemented"); Range exampleRange2 = new Range(-1.01, 2); assertTrue(exampleRange.intersects(exampleRange2)); } @Test public void intersectsShouldBeFalseAAUB() { //fail("Not yet implemented"); Range exampleRange2 = new Range(1.01, 2); assertFalse(exampleRange.intersects(exampleRange2)); } @Test(expected = IllegalArgumentException.class) public void rangeCtorLowerGreaterThanUpper() throws Exception { //fail("Not yet implemented"); Range exampleRange2 = new Range(4, 2); } @Test(expected = IllegalArgumentException.class) public void rangeCtorInvalidArgument() throws Exception{ //fail("Not yet implemented"); Range exampleRange2 = new Range('L',3); } @Test public void rangeCtorValidArgument() throws Exception{ //fail("Not yet implemented"); Range exampleRange2 = new Range(1,3); } //BVT @Test public void rangeCtorAEqualB() { Range exampleRange2 = new Range(1,1); } //Robustness @Test public void rangeCtorABLB(){ Range exampleRange2 = new Range(.9999,1); } @Test (expected = IllegalArgumentException.class) public void rangeCtorAAUB() throws Exception{ Range exampleRange2 = new Range(1.1111,1); } ////////////////////////////////////////////////// @Test public void lessThanLowerGreaterThanLarger() { //fail("Not yet implemented"); Range exampleRange2 = new Range(-1, 4); assertTrue(exampleRange.intersects(exampleRange2)); } @Test public void lessThanSmallerLargerGreater() { //fail("Not yet implemented"); Range exampleRange2 = new Range(0, 4); assertTrue(exampleRange.intersects(exampleRange2)); } @Test public void falseEqualBounds() { //fail("Not yet implemented"); Range exampleRange2 = new Range(-1, -1); assertFalse(exampleRange.intersects(exampleRange2)); } ///////////////////////////////////////////////////////// @After public void tearDown() throws Exception { } @AfterClass public static void tearDownAfterClass() throws Exception { } //-------------------------------TEST MUTATION------------------------------------// //test message mutation @Test public void rangeCtorLowerGreaterThanUpperTestMessage() throws Exception { //fail("Not yet implemented"); try { Range exampleRange2 = new Range(4, 2); } catch(IllegalArgumentException e) { assertEquals("Message of Range ctor", "Range(double, double): require lower (" + 4d + ") <= upper (" + 2d + ").", e.getMessage()); } } //test ctor bounds mutation @Test public void RangeCtorCorrectLowerValue() { //fail("Not yet implemented"); Range exampleRange2 = new Range(1.01, 2); assertEquals("Lower bounds incorrect", 1.01, exampleRange2.getLowerBound(), .000000001d); } //test ctor bounds mutation @Test public void RangeCtorCorrectUpperValue() { //fail("Not yet implemented"); Range exampleRange2 = new Range(1.01, 2); assertEquals("Upper bounds incorrect", 2, exampleRange2.getUpperBound(), .000000001d); } //test centralValue change value mutation @Test public void centralValueShouldBeNonZero() { Range exampleRange2 = new Range(1, 2); assertEquals("The central value of -1 and 1 should be 1.5", 1.5, exampleRange2.getCentralValue(), .000000001d); } //test negated lower field mutation @Test public void intersectsFalseAllPositiveValues() { Range exampleRange2 = new Range(1, 2); Range exampleRange3 = new Range(3, 4); assertFalse("Should not intersect", exampleRange3.intersects(exampleRange2)); } //test != mutation @Test public void intersectsFalse() { Range exampleRange2 = new Range(1, 2); Range exampleRange3 = new Range(3, 4); assertFalse("Should not intersect", exampleRange2.intersects(exampleRange3)); } //test contains @Test public void containsTrue() { Range exampleRange2 = new Range(1, 2); assertTrue("Should contain", exampleRange2.contains(1.5)); } //test contains @Test public void containsTrueUB() { Range exampleRange2 = new Range(1, 2); assertTrue("Should contain", exampleRange2.contains(2)); } //test contains @Test public void containsTrueLB() { Range exampleRange2 = new Range(1, 2); assertTrue("Should contain", exampleRange2.contains(1)); } //test contains @Test public void containsFalse() { Range exampleRange2 = new Range(1, 2); assertFalse("Should not contain", exampleRange2.contains(0.5)); } //test contains @Test public void containsFalseBLB() { Range exampleRange2 = new Range(1, 2); assertFalse("Should contain", exampleRange2.contains(0.99995)); } //test contains @Test public void containsFalseAUB() { Range exampleRange2 = new Range(1, 2); assertFalse("Should contain", exampleRange2.contains(2.0001)); } //test constrain @Test public void constrainBLB() { Range exampleRange2 = new Range(1, 2); assertEquals("Should not constrain to 1", 1.0, exampleRange2.constrain(0.99995), .000000001d); } //test constrain @Test public void constrainAUB() { Range exampleRange2 = new Range(1, 2); assertEquals("Should constrain to 2", 2.0, exampleRange2.constrain(2.0005), .000000001d); } //test constrain @Test public void constrainInside() { Range exampleRange2 = new Range(1, 2); assertEquals("Should constrain to 1.5", 1.5, exampleRange2.constrain(1.5), .000000001d); } //test combine @Test public void combineBothNull() { assertNull("combine should return null",Range.combine(null, null)); } //test combine @Test public void combineR1null() { Range exampleRange2 = new Range(1, 2); assertEquals("combine should return range 1-2", exampleRange2, Range.combine(null, exampleRange2)); } //test combine @Test public void combineR2null() { Range exampleRange2 = new Range(1, 2); assertEquals("combine should return range 1-2", exampleRange2, Range.combine(exampleRange2, null)); } //test combine @Test public void combineIntersects() { Range exampleRange2 = new Range(.5, 2); assertEquals("combine should return range -1-2", new Range(-1,2), Range.combine(exampleRange2, exampleRange)); } //test combine @Test public void combineNotIntersects() { Range exampleRange2 = new Range(2, 3); assertEquals("combine should return range -1-3", new Range(-1,3), Range.combine(exampleRange2, exampleRange)); } //test combine @Test public void combineInside() { Range exampleRange2 = new Range(-.5, .5); assertEquals("combine should return range -1-1", new Range(-1,1), Range.combine(exampleRange2, exampleRange)); } //test shift @Test public void shiftByHalf() { Range exampleRange2 = new Range(-.5, .5); assertEquals("shift should return 1 to 0", new Range(0,1), Range.shift(exampleRange2, .5)); } //test shift @Test (expected = IllegalArgumentException.class) public void shiftWithNull() { //Range exampleRange2 = new Range(-.5, .5); Range.shift(null, 20); } //test shift @Test public void shiftByNegative() { Range exampleRange2 = new Range(-.5, .5); assertEquals("shift should return -1 to 0", new Range(-1,0), Range.shift(exampleRange2, -.5)); } //test shift @Test public void shiftBeyondZero() { Range exampleRange2 = new Range(-.5, .5); assertEquals("shift should return -2.5 to 0", new Range(-2.5,0), Range.shift(exampleRange2, -2)); } }
seng438-winter-2022/seng438-a4-bjaron
RangeTest.java
2,785
//fail("Not yet implemented");
line_comment
en
true
232983_12
import javax.imageio.ImageIO; import java.awt.*; import java.awt.geom.Line2D; import java.awt.geom.Point2D; import java.awt.image.BufferedImage; import java.io.File; import java.io.IOException; import java.util.ArrayList; import java.util.Random; /** * Created by jason on 1/20/2016. */ public class Ball { private GameBoard mGameBoard; private Paddle mPaddle; private ArrayList<BrickItem> mBricks; private int posnX, posnY; private int ballRadius; private int frameWidth, frameHeight; private Color ballColor; private boolean randomAngleInit = true; private double vectorLengthSq; private BufferedImage mBallImage; private int dx = 0; private int dy = 0; public Ball(GameBoard gameBoard, Paddle paddle, Color color) { mGameBoard = gameBoard; mPaddle = paddle; frameHeight = mGameBoard.getHeight(); frameWidth = mGameBoard.getWidth(); ballColor = color; mBricks = mGameBoard.getBricks().getBricks(); try { mBallImage = ImageIO.read(new File("src/ball-hd.png")); } catch (IOException ex) { System.err.println(ex.getMessage()); } } protected void setInitPosition(){ dx = 0; dy = 0; Double x = mPaddle.getCenterTopPoint().getX() - ballRadius; posnX = x.intValue(); Double y = mPaddle.getCenterTopPoint().getY() - ballRadius*2; posnY = y.intValue(); } protected void move(){ Line2D topBorder = new Line2D.Double(0, 0, frameWidth, 0); //topBorder.setLine(0, 0, frameWidth, 0); Line2D leftBorder = new Line2D.Double(0, 0, 0, frameHeight); //leftBorder.setLine(0, 0, 0, frameHeight); Line2D rightBorder = new Line2D.Double(frameWidth, 0, frameWidth, frameHeight); //rightBorder.setLine(frameWidth, 0, frameWidth, frameHeight); Line2D bottomBorder = new Line2D.Double(0, frameHeight, frameWidth, frameHeight); //bottomBorder.setLine(0, frameHeight, frameWidth, frameHeight); Line2D paddleTop = mPaddle.getTopBorder(); int speedFactor = mGameBoard.getSpeedFactor(); Point2D ball2D = new Point2D.Double(posnX + ballRadius, posnY + ballRadius); //= new Point2D(posnX + ballRadius, posnY + ballRadius); // check collision if (dx == 0 && dy == 0) { if(randomAngleInit){ dx = (new Random().nextInt(8) - 3); } System.out.println("dx is " + dx); dy = -4; vectorLengthSq = dx*dx + dy*dy; } else if(bottomBorder.ptLineDist(ball2D) <= ballRadius || posnY > bottomBorder.getY1()){ mGameBoard.lostLive(); mGameBoard.stop(); } else if(topBorder.ptLineDist(ball2D) <= ballRadius || posnY < topBorder.getY1()) { dy = dy * -1; } else if(leftBorder.ptLineDist(ball2D) <= ballRadius || posnX < leftBorder.getX1() || rightBorder.ptLineDist(ball2D) <= ballRadius || posnX > rightBorder.getX1()) { dx = dx * -1; } else if (posnY + 2 * ballRadius > paddleTop.getY1() && mPaddle.getUpperLeftPoint().getX() - 2*ballRadius < posnX && mPaddle.getUpperRightPoint().getX() > posnX) { if (posnX + ballRadius < mPaddle.getLeftMostX()){ int tmp = dx; dx = -1 * dy; dy = -1 * tmp; } else if (posnX + ballRadius < mPaddle.getFirstPointX()){ try { if (Math.abs(dx) / Math.abs(dy) >= 4 || Math.abs(dy) / Math.abs(dx) >= 4) { dy = dy * -1; } else { dx = dx * 2; dy = dy * -1; } } catch (Exception e){ } } else if (posnX + ballRadius < mPaddle.getThirdPointX()){ dy = dy * -1; } else if (posnX + ballRadius < mPaddle.getRightMostx()){ if(Math.abs(dx)/Math.abs(dy) >= 4){ dy = dy * -1; } else { dx = dx * 2; dy = dy * -1; } } else{ int tmp = dx; dx = dy; dy = tmp; } if(dy >= 0){ dy = -1; } } // check for bricks collision for(BrickItem mBrick : mBricks){ if (!mBrick.isExist()){ continue; } else if (posnX + ballRadius > mBrick.getLeftBorder().getX1() && posnX + ballRadius < mBrick.getRightBorder().getX1() && posnY + 2*ballRadius > mBrick.getTopBorder().getY1() && posnY < mBrick.getBottomBorder().getY1()) { System.out.println("collision!: up down now dx dy: " + dx + " " + dy); dy = dy * -1; System.out.println(" changed to dx dy: " + dx + " " + dy); mBrick.gone(); double z = Math.sqrt(vectorLengthSq/(dy*dy + dx*dx)); if(mBrick.getTopBorder().ptLineDist(ball2D) < mBrick.getBottomBorder().ptLineDist(ball2D)){ Double tmp = mBrick.getTopBorder().getY1() - ballRadius*2; posnY = tmp.intValue(); } else{ Double tmp = (mBrick.getBottomBorder().getY1()); posnY = tmp.intValue(); } return; //break; } else if (posnY + ballRadius > mBrick.getTopBorder().getY1() && posnY + ballRadius < mBrick.getBottomBorder().getY1() && posnX + 2*ballRadius > mBrick.getLeftBorder().getX1() && posnX < mBrick.getRightBorder().getX1()) { System.out.println("collision!: left right now dx dy: " + dx + " " + dy); dx = dx * -1; System.out.println(" changed to dx dy: " + dx + " " + dy); mBrick.gone(); double z = Math.sqrt(vectorLengthSq/(dy*dy + dx*dx)); if(mBrick.getLeftBorder().ptLineDist(ball2D) < mBrick.getRightBorder().ptLineDist(ball2D)){ Double tmp = (mBrick.getLeftBorder().getX1() - ballRadius*2); posnX = tmp.intValue(); } else{ Double tmp = (mBrick.getRightBorder().getX1()); posnX = tmp.intValue(); } return; } else if ((mBrick.getTopBorder().ptLineDist(ball2D) < ballRadius && mBrick.getRightBorder().ptLineDist(ball2D) < ballRadius && posnX + ballRadius > mBrick.getRightBorder().getX1() && posnY + ballRadius < mBrick.getTopBorder().getY1())){ // if hit top-right corner System.out.println("collision!: corners now dx dy: " + dx + " " + dy); int tmp = dx; dx = dy; dy = tmp; System.out.println(" changed to dx dy: " + dx + " " + dy); mBrick.gone(); break; } else if ((mBrick.getTopBorder().ptLineDist(ball2D) < ballRadius && mBrick.getLeftBorder().ptLineDist(ball2D) < ballRadius && posnX + ballRadius < mBrick.getLeftBorder().getX1() && posnY + ballRadius < mBrick.getTopBorder().getY1())){ // if hit top-left corner System.out.println("collision!: corners now dx dy: " + dx + " " + dy); int tmp = dx; dx = dy; dy = tmp; System.out.println(" changed to dx dy: " + dx + " " + dy); mBrick.gone(); break; } else if((mBrick.getBottomBorder().ptLineDist(ball2D) < ballRadius && mBrick.getLeftBorder().ptLineDist(ball2D) < ballRadius && posnX + ballRadius < mBrick.getLeftBorder().getX1() && posnY + ballRadius > mBrick.getBottomBorder().getY1())){ // if hit bottom-left corner System.out.println("collision!: corners now dx dy: " + dx + " " + dy); int tmp = dx; dx = dy; dy = tmp; System.out.println(" changed to dx dy: " + dx + " " + dy); mBrick.gone(); break; } else if((mBrick.getBottomBorder().ptLineDist(ball2D) < ballRadius && mBrick.getRightBorder().ptLineDist(ball2D) < ballRadius && posnX + ballRadius > mBrick.getRightBorder().getX1() && posnY + ballRadius > mBrick.getBottomBorder().getY1())){ // if hit bottom-right corner System.out.println("collision!: corners now dx dy: " + dx + " " + dy); int tmp = dx; dx = dy; dy = tmp; System.out.println(" changed to dx dy: " + dx + " " + dy); mBrick.gone(); break; } } if(dy >= 17){ dy = 1; } //System.out.println("********************changed to dx dy: " + dx + " " + dy); // update position double z = Math.sqrt(vectorLengthSq/(dy*dy + dx*dx)); posnX += z*dx*speedFactor; posnY += z*dy*speedFactor; } protected void paintComponent(Graphics2D g2, int width, int height) { ballRadius = frameWidth / 100; frameWidth = width; frameHeight = height; g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON); g2.setStroke(new BasicStroke(5)); // 32 pixels wide g2.setColor(ballColor); if(!mGameBoard.isStarted()){ setInitPosition(); } Line2D paddleTop = mPaddle.getTopBorder(); Double x1 = mPaddle.getUpperLeftPoint().getX(); Double y1 = mPaddle.getUpperLeftPoint().getY(); Double x2 = mPaddle.getUpperRightPoint().getX(); Double y2 = mPaddle.getUpperRightPoint().getY(); g2.drawImage(mBallImage, posnX, posnY, ballRadius*2, ballRadius*2, null); Toolkit.getDefaultToolkit().sync(); //g2.fillOval(posnX, posnY, ballRadius*2, ballRadius*2); //Toolkit.getDefaultToolkit().sync(); } protected int getBallPosnX(){ return posnX; } protected int getBallPosnY(){ return posnY; } protected void setBallPosn(int x, int y){ posnX = x; posnY = y; } protected int getFrameWidth(){ return frameWidth; } protected int getFrameHeight(){ return frameHeight; } }
IYCI/Breakout
src/Ball.java
2,895
// if hit bottom-right corner
line_comment
en
true
233046_0
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; public class LifExp { static { //You should put your codes in this section Like 'Liferay_Windows_payload.txt' } }
thelostworldFree/CVE-2020-7961-payloads
LifExp.java
64
//You should put your codes in this section Like 'Liferay_Windows_payload.txt'
line_comment
en
true
233109_23
package vrml.node; import java.util.Hashtable; import vrml.*; // // This is the general Script class, to be subclassed by all scripts. // Note that the provided methods allow the script author to explicitly // throw tailored exceptions in case something goes wrong in the // script. // public abstract class Script extends vrml.BaseNode { Hashtable fields; Hashtable fieldkinds; Hashtable fieldtypes; public Script() { fields = new Hashtable(); fieldkinds = new Hashtable(); fieldtypes = new Hashtable(); } public void add_field(String kind, String type, String name, Field f) { fields.put(name,f); fieldkinds.put(name,kind); fieldtypes.put(name,type); } public String get_field_type(String name) { return (String)fieldtypes.get(name); } // This method is called before any event is generated public void initialize() { } // Get a Field by name. // Throws an InvalidFieldException if fieldName isn't a valid // field name for a node of this type. protected final Field getField(String fieldName) { return (Field)fields.get(fieldName); } // Get an EventOut by name. // Throws an InvalidEventOutException if eventOutName isn't a valid // eventOut name for a node of this type. // spec: protected public final Field getEventOut(String eventOutName) { return (Field)fields.get(eventOutName); } // Get an EventIn by name. // Throws an InvalidEventInException if eventInName isn't a valid // eventIn name for a node of this type. protected final Field getEventIn(String eventInName) { return (Field)fields.get(eventInName); } // processEvents() is called automatically when the script receives // some set of events. It shall not be called directly except by its subclass. // count indicates the number of events delivered. public void processEvents(int count, Event events[]) { } // processEvent() is called automatically when the script receives // an event. public void processEvent(Event event) { } // eventsProcessed() is called after every invocation of processEvents(). public void eventsProcessed() { } // shutdown() is called when this Script node is deleted. public void shutdown() { } public String toString() { return ""; } // This overrides a method in Object }
gitpan/FreeWRL
java/Script.java
578
// shutdown() is called when this Script node is deleted.
line_comment
en
false
233176_0
package qns; import java.util.List; /** * In LeetCode Store, there are some kinds of items to sell. Each item has a price. * <p> * However, there are some special offers, and a special offer consists of one or more different * kinds of items with a sale price. * <p> * You are given the each item's price, a set of special offers, and the number we need to buy for * each item. The job is to output the lowest price you have to pay for exactly certain items as given, * where you could make optimal use of the special offers. * <p> * Each special offer is represented in the form of an array, the last number represents the price * you need to pay for this special offer, other numbers represents how many specific items you could * get if you buy this offer. * <p> * You could use any of special offers as many times as you want. * <p> * Example 1: * Input: [2,5], [[3,0,5],[1,2,10]], [3,2] * Output: 14 * Explanation: * There are two kinds of items, A and B. Their prices are $2 and $5 respectively. * In special offer 1, you can pay $5 for 3A and 0B * In special offer 2, you can pay $10 for 1A and 2B. * You need to buy 3A and 2B, so you may pay $10 for 1A and 2B (special offer #2), and $4 for 2A. * Example 2: * Input: [2,3,4], [[1,1,0,4],[2,2,1,9]], [1,2,1] * Output: 11 * Explanation: * The price of A is $2, and $3 for B, $4 for C. * You may pay $4 for 1A and 1B, and $9 for 2A ,2B and 1C. * You need to buy 1A ,2B and 1C, so you may pay $4 for 1A and 1B (special offer #1), and $3 for 1B, $4 for 1C. * You cannot add more items, though only $9 for 2A ,2B and 1C. * Note: * There are at most 6 kinds of items, 100 special offers. * For each item, you need to buy at most 6 of them. * You are not allowed to buy more items than you want, even if that would lower the overall price. */ public class Q638 { public int shoppingOffers(List<Integer> price, List<List<Integer>> special, List<Integer> needs) { return 0; } }
ttyrueiwoqp/LeetCode
src/qns/Q638.java
668
/** * In LeetCode Store, there are some kinds of items to sell. Each item has a price. * <p> * However, there are some special offers, and a special offer consists of one or more different * kinds of items with a sale price. * <p> * You are given the each item's price, a set of special offers, and the number we need to buy for * each item. The job is to output the lowest price you have to pay for exactly certain items as given, * where you could make optimal use of the special offers. * <p> * Each special offer is represented in the form of an array, the last number represents the price * you need to pay for this special offer, other numbers represents how many specific items you could * get if you buy this offer. * <p> * You could use any of special offers as many times as you want. * <p> * Example 1: * Input: [2,5], [[3,0,5],[1,2,10]], [3,2] * Output: 14 * Explanation: * There are two kinds of items, A and B. Their prices are $2 and $5 respectively. * In special offer 1, you can pay $5 for 3A and 0B * In special offer 2, you can pay $10 for 1A and 2B. * You need to buy 3A and 2B, so you may pay $10 for 1A and 2B (special offer #2), and $4 for 2A. * Example 2: * Input: [2,3,4], [[1,1,0,4],[2,2,1,9]], [1,2,1] * Output: 11 * Explanation: * The price of A is $2, and $3 for B, $4 for C. * You may pay $4 for 1A and 1B, and $9 for 2A ,2B and 1C. * You need to buy 1A ,2B and 1C, so you may pay $4 for 1A and 1B (special offer #1), and $3 for 1B, $4 for 1C. * You cannot add more items, though only $9 for 2A ,2B and 1C. * Note: * There are at most 6 kinds of items, 100 special offers. * For each item, you need to buy at most 6 of them. * You are not allowed to buy more items than you want, even if that would lower the overall price. */
block_comment
en
true
233299_0
import java.util.*; public class Stringy { public static void main(String[] args) { String s = "seattle-java-401d6"; HashMap<Character, Integer> counts = new HashMap<>(); char mostFreq = s.charAt(0); // silly: splitting that into an array of single characters // less silly: just iterating through each character for (int i = 0; i < s.length(); i++) { char current = s.charAt(i); int times = 1; if(counts.containsKey(current)) { times += counts.get(current); } counts.put(current, times); if(times > counts.get(mostFreq)) { mostFreq = current; } } System.out.println(mostFreq); } }
codefellows/seattle-java-401d6
class-35/Stringy.java
190
// silly: splitting that into an array of single characters
line_comment
en
true
233527_1
/* * 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 Rating_800; import java.util.Scanner; /** * * @author Acer */ public class GoldenPlate { public static void main(String[] args) { Scanner sc = new Scanner(System.in); int w = sc.nextInt(); int h = sc.nextInt(); int k = sc.nextInt(); int ans = 0; while(h > 0 && w > 0 && k > 0){ ans+=((w*2)+((h-2)*2)); w-=4; h-=4; k--; } System.out.println(ans); } }
meheedihasaan/Codeforces-Problem-Solution
GoldenPlate.java
195
/** * * @author Acer */
block_comment
en
true
234087_1
import java.util.ArrayList; public class Lighting { //direction that the light faces. public Vector3 lightDirection; //how bright should the illuminated side of meshes be? public double lightIntensity; //how dark should the unilluminated side of meshes be? public double shadowIntensity; public Lighting(Vector3 lightDirectionIn, double lightIntensityIn, double shadowIntensityIn) { lightDirection = lightDirectionIn; lightIntensity = lightIntensityIn; shadowIntensity = shadowIntensityIn; } //goes through the specified meshes and updates all their lighting's public void update(ArrayList<Mesh> meshes) { for (int i = 0; i < meshes.size(); i++) meshes.get(i).calculateLighting(this); } }
trrt-good/FlightSimulator
Lighting.java
179
//how bright should the illuminated side of meshes be?
line_comment
en
false
234105_5
import java.awt.event.KeyEvent; import javax.media.opengl.GL2; import javax.media.opengl.glu.GLU; import com.jogamp.opengl.util.gl2.GLUT; import framework.JOGLFrame; import framework.Scene; import framework.ShaderProgram; /** * Display a simple scene to demonstrate OpenGL. * * @author Robert C. Duvall */ public class Shader extends Scene { private static final String SHADERS_DIR = "/shaders/"; private static final String[] SHADERS = { "fixed", "diffuse", "gouraud", "gooch", "pulse" }; private float[] myLightPos = { 0, 1, 1, 1 }; // animation state private float myTime; private float myAngle; private boolean isShaderOn; private String myShaderFile; private ShaderProgram myShader; /** * Create the scene with the given arguments. */ public Shader (String[] args) { super("Shader example"); myTime = 0; myAngle = 0; isShaderOn = true; myShaderFile = args.length > 0 ? args[0] : "fixed"; } /** * Initialize general OpenGL values once (in place of constructor). */ @Override public void init (GL2 gl, GLU glu, GLUT glut) { // load shaders from disk ONCE myShader = makeShader(gl, myShaderFile); } /** * Draw all of the objects to display. */ @Override public void display (GL2 gl, GLU glu, GLUT glut) { // usually not necessary myShader = makeShader(gl, myShaderFile); gl.glRotatef(myAngle, 0, 1, 0); if (isShaderOn) { myShader.bind(gl); { glut.glutSolidTeapot(1); } myShader.unbind(gl); } else { gl.glColor3d(1, 0, 1); glut.glutSolidTeapot(1); } } /** * Set the camera's view of the scene. */ @Override public void setCamera (GL2 gl, GLU glu, GLUT glut) { glu.gluLookAt(0, 1, 5, // from position 0, 0, 0, // to position 0, 1, 0); // up direction } /** * Establish the lights in the scene. */ public void setLighting (GL2 gl, GLU glu, GLUT glut) { gl.glEnable(GL2.GL_LIGHTING); gl.glEnable(GL2.GL_LIGHT0); gl.glShadeModel(GL2.GL_SMOOTH); gl.glEnable(GL2.GL_COLOR_MATERIAL); // position light and make it a spotlight gl.glLightfv(GL2.GL_LIGHT0, GL2.GL_POSITION, myLightPos, 0); } /** * Animate the scene by changing its state slightly. */ @Override public void animate (GL2 gl, GLU glu, GLUT glut) { myAngle += 4; myTime += 1.0f / JOGLFrame.FPS; myShader.bind(gl); { // animate shader values if (myShaderFile == "pulse") { myShader.setUniform(gl, "time", new float[] { myTime }, 1); } } myShader.unbind(gl); } /** * Called when any key is pressed within the canvas. */ @Override public void keyReleased (int keyCode) { switch (keyCode) { // turn light on/off case KeyEvent.VK_S: isShaderOn = ! isShaderOn; break; case KeyEvent.VK_1: case KeyEvent.VK_2: case KeyEvent.VK_3: case KeyEvent.VK_4: case KeyEvent.VK_5: myShaderFile = SHADERS[keyCode - KeyEvent.VK_1]; break; } } // create a program from the corresponding vertex and fragment shaders private ShaderProgram makeShader (GL2 gl, String filename) { ShaderProgram result = new ShaderProgram(); result.attachVertexShader(gl, SHADERS_DIR+filename+".vert"); result.attachFragmentShader(gl, SHADERS_DIR+filename+".frag"); result.link(gl); return result; } // allow program to be run from here public static void main (String[] args) { new JOGLFrame(new Shader(args)); } }
duke-compsci344-spring2015/lab_opengl
src/Shader.java
1,101
/** * Draw all of the objects to display. */
block_comment
en
false
234116_1
public class Floor extends Thing { private double floorHeight; private Color dark, bright; private Color specularLight; public Floor(Color dark, Color bright, double floorHeight, Color specularLight) { this.dark = dark; this.bright = bright; this.floorHeight = floorHeight; this.specularLight = specularLight; } public boolean hasLighting() { return true; } public Color getSpecularWeight() {// what does specular light need to be? return specularLight; } public void makeColorProportional(double size) { // keeps the original colors proportional to what you chose, // and prepares them for recieving diffuse lighting and shadows dark.changeColor(dark.getRed() * size, dark.getGreen() * size, dark.getBlue() * size); bright.changeColor(bright.getRed() * size, bright.getGreen() * size, bright.getBlue() * size); } public Point getNormal(Point spot) { return new Point(0.0, 1.0, 0.0); } public Color getAmbient(Point p) { double cD = 4; double x = p.getX(); double z = p.getZ(); x = x % cD; z = z % cD; if (z > -1 && z <= 2) { if (x >= 0 && x <= 2) { return dark; } if (x >= 2 && x < 4) { return bright; } if (x < 0 && x >= -2) { return bright; } if (x <= -2 && x > -4) { return dark; } } if (z >= 2 && z < 4) { if (x >= 0 && x <= 2) { return bright; } if (x >= 2 && x < 4) { return dark; } if (x < 0 && x >= -2) { return dark; } if (x <= -2 && x > -4) { return bright; } } return new Color(255, 25, 25);// you should never see this color } public Intersection getIntersection(Point start, Point end) { double distance = (floorHeight - start.getY()) / (end.getY() - start.getY()); if (Math.abs(end.getX() - start.getY()) < this.MIN) { return new Intersection(60 + 1, null, null); } if (distance < MIN) { return new Intersection(60 + 1, null, null); } double x = start.getX() * (1.0 - distance) + end.getX() * distance; double y = floorHeight; double z = start.getZ() * (1.0 - distance) + end.getZ() * distance; return new Intersection(distance, new Point(x, y, z), this); } public boolean hasDiffuse() { return true; } public Color getDiffuse(Point p) { return getAmbient(p); } }
edgartheunready/raytracer
Floor.java
727
// keeps the original colors proportional to what you chose,
line_comment
en
false
234120_27
package edu.mit.blocks.codeblockutil; import java.awt.AlphaComposite; import java.awt.Color; import java.awt.Cursor; import java.awt.Dimension; import java.awt.Font; import java.awt.FontMetrics; import java.awt.GradientPaint; import java.awt.Graphics; import java.awt.Graphics2D; import java.awt.Insets; import java.awt.RenderingHints; import java.awt.Transparency; import java.awt.event.MouseEvent; import java.awt.event.MouseListener; import java.awt.geom.Rectangle2D; import java.awt.geom.RoundRectangle2D; import java.awt.image.BufferedImage; import java.awt.image.ConvolveOp; import java.awt.image.Kernel; import javax.swing.JButton; import javax.swing.SwingUtilities; /** * A CButton is a swing-compatible widget that allows clients * to display an oval button with an optional text. * * To add a particular action to this widget, users should invoke * this.addCButtonListener( new CButtonListener()); */ public class CButton extends JButton implements MouseListener { private static final long serialVersionUID = 328149080228L; /** blur lighting of this button */ static float[] BLUR = {0.10f, 0.10f, 0.10f, 0.10f, 0.30f, 0.10f, 0.10f, 0.10f, 0.10f}; /** the inset of this button */ static final int INSET = 3; /** The highlighting inset */ static final int HIGHLIGHT_INSET = 2; /** Focus Flag: true iff mouse is hovering over button */ boolean focus = false; /** Press Flag: true iff button was pressed but has not been released */ boolean pressed = false; /** Selected Flag: true iff button was toggled to selected */ boolean selected = false; /** Color of this button when not pressed */ Color buttonColor; /** Color of this button when pressed */ Color selectedColor; /** Color of the foreground when not hovered */ Color foregroundColor = Color.white; /** Color of the foreground whe hovered */ Color hoveredColor = Color.red; /** * Creates a button with text and black buttonColor, and * white slectedColor * @param text */ public CButton(String text) { this(new Color(30, 30, 30), Color.gray, text); } /** * Create a button with text; * @param buttonColor - color when not pressed down * @param selectedColor - color when pressed down but not released yet * @param text - textual label of this * * @requires buttonColor, selectedColor, text != null * @effects constructs new CButton */ public CButton(Color buttonColor, Color selectedColor, String text) { super(); this.setOpaque(false); this.buttonColor = buttonColor; this.selectedColor = selectedColor; this.setText(text); this.setFont(new Font("Ariel", Font.BOLD, 16)); this.addMouseListener(this); this.setPreferredSize(new Dimension(80, 25)); this.setCursor(new Cursor(Cursor.HAND_CURSOR)); } /** * Dynamically changes the coloring of the buttons when * pressed or not pressed. * * @param buttonColor * @param selectedColor * * @requires buttonColor, selectedColor != null * @modifies this.buttonColor && this.seletedColor * @effects change button coloring to match to inputs */ public void setLighting(Color buttonColor, Color selectedColor) { this.buttonColor = buttonColor; this.selectedColor = selectedColor; } public void setTextLighting(Color foregroundColor, Color hoveredColor) { this.foregroundColor = foregroundColor; this.hoveredColor = hoveredColor; } /** * @modifies this.selected * @effects toggles selcted flag to valeu of selected */ public void toggleSelected(boolean selected) { this.selected = selected; this.repaint(); } ///////////////////////////////////////////////////////////////////////// //Methods below this line should not be //modified or overriden and affects the Rendering of this button. /////////////////////// /** * Prevents textual label from display out of the bounds * of the this oval shaped button's edges */ @Override public Insets getInsets() { //top, left, bottom, right return new Insets(0, this.getHeight() / 2, 0, this.getHeight() / 2); } /** * re paints this */ @Override public void paint(Graphics g) { //super.paint(g); //selected color Color backgroundColor; if (this.pressed || this.selected) { backgroundColor = this.selectedColor; } else { backgroundColor = this.buttonColor; } // Set up graphics and buffer Graphics2D g2 = (Graphics2D) g; g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON); BufferedImage buffer = GraphicsManager.gc.createCompatibleImage(this.getWidth(), this.getHeight(), Transparency.TRANSLUCENT); Graphics2D gb = buffer.createGraphics(); gb.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON); // Set up first layer int buttonHeight = this.getHeight() - (INSET * 2); int buttonWidth = this.getWidth() - (INSET * 2); int arc = buttonHeight; Color topColoring = backgroundColor.darker(); Color bottomColoring = backgroundColor.darker(); gb.setPaint(new GradientPaint(0, INSET, topColoring, 0, buttonHeight, bottomColoring, false)); // Paint the first layer gb.fillRoundRect(INSET, INSET, buttonWidth, buttonHeight, arc, arc); gb.setColor(Color.darkGray); gb.drawRoundRect(INSET, INSET, buttonWidth, buttonHeight, arc, arc); // set up paint data fields for second layer int highlightHeight = buttonHeight - (HIGHLIGHT_INSET * 2); int highlightWidth = buttonWidth - (HIGHLIGHT_INSET * 2); int highlightArc = highlightHeight; topColoring = backgroundColor.brighter().brighter().brighter().brighter(); bottomColoring = backgroundColor.brighter().brighter().brighter().brighter(); // Paint the second layer gb.setComposite(AlphaComposite.getInstance(AlphaComposite.SRC_OVER, .8f)); gb.setPaint(new GradientPaint(0, INSET + HIGHLIGHT_INSET, topColoring, 0, INSET + HIGHLIGHT_INSET + (highlightHeight / 2), backgroundColor.brighter(), false)); gb.setClip(new RoundRectangle2D.Float(INSET + HIGHLIGHT_INSET, INSET + HIGHLIGHT_INSET, highlightWidth, highlightHeight / 2, highlightHeight / 3, highlightHeight / 3)); gb.fillRoundRect(INSET + HIGHLIGHT_INSET, INSET + HIGHLIGHT_INSET, highlightWidth, highlightHeight, highlightArc, highlightArc); // Blur ConvolveOp blurOp = new ConvolveOp(new Kernel(3, 3, BLUR)); BufferedImage blurredImage = blurOp.filter(buffer, null); // Draw button g2.drawImage(blurredImage, 0, 0, null); // Draw the text (if any) if (this.getText() != null) { if (this.focus) { g2.setColor(hoveredColor); } else { g2.setColor(foregroundColor); } Font font = g2.getFont().deriveFont((float) (((float) buttonHeight) * .6)); g2.setFont(font); FontMetrics metrics = g2.getFontMetrics(); Rectangle2D textBounds = metrics.getStringBounds(this.getText(), g2); float x = (float) ((this.getWidth() / 2) - (textBounds.getWidth() / 2)); float y = (float) ((this.getHeight() / 2) + (textBounds.getHeight() / 2)) - metrics.getDescent(); g2.drawString(this.getText(), x, y); } } ////////////////////// //Mouse Listeners ////////////////////// @Override public void addMouseListener(MouseListener l) { super.addMouseListener(l); } @Override public void mouseEntered(MouseEvent e) { this.focus = true; repaint(); } @Override public void mouseExited(MouseEvent e) { this.focus = false; repaint(); } @Override public void mousePressed(MouseEvent e) { if (SwingUtilities.isLeftMouseButton(e)) { this.pressed = true; } repaint(); } @Override public void mouseReleased(MouseEvent e) { this.pressed = false; repaint(); } @Override public void mouseClicked(MouseEvent e) { } }
laurentschall/openblocks
src/main/java/edu/mit/blocks/codeblockutil/CButton.java
2,198
// set up paint data fields for second layer
line_comment
en
false
234123_4
import java.awt.Toolkit; /** * Write a description of class Vertex here. * * @author (your name) * @version (a version number or a date) */ public class Vertex { private int r, g, b, normalsAdded, lightingScale; private double x, y, z, s, depthScale, twoDX, twoDY, lightingScaleConstant, st1, st2; private Point normal; private static final double WIDTH = Toolkit.getDefaultToolkit().getScreenSize().getWidth() * 0.5; public Vertex(double x, double y, double z, double s, int r, int g, int b) { this.x = x; this.y = y; this.z = z; this.s = s; this.r = r; this.g = g; this.b = b; this.depthScale = s * WIDTH / (10 + z); this.twoDX = (this.depthScale * x); this.twoDY = (this.depthScale * y); this.normal = new Point(0, 0, 0); } public Vertex(double x, double y, double z, int r, int g, int b) { this(x, y, z, 1.0, r, g, b); } public void addNormal(Point normal) { this.normal = new Point((this.normal.getX() * normalsAdded + normal.getX()) / (normalsAdded + 1), (this.normal.getY() * normalsAdded + normal.getY()) / (normalsAdded + 1), (this.normal.getZ() * normalsAdded + normal.getZ()) / (normalsAdded + 1)); normalsAdded += 1; //double mag = Math.sqrt(Math.pow(this.normal.getX(), 2) + Math.pow(this.normal.getY(), 2) + Math.pow(this.normal.getZ(), 2)); //System.out.println(this.normal.getX()+ " " + this.normal.getY() + " " + this.normal.getZ() + " " + mag); //this.normal = new Point(this.normal.getX() / mag, this.normal.getY() / mag, this.normal.getZ() / mag); this.lightingScaleConstant = 0.7 / (0.3266667 * Math.sqrt(Math.pow(this.normal.getX(), 2) + Math.pow(this.normal.getY(), 2) + Math.pow(this.normal.getZ(), 2))); } public void transform(double[] transformationMatrix) { double newX = x * transformationMatrix[0] + y * transformationMatrix[1] + z * transformationMatrix[2] + s * transformationMatrix[3]; double newY = x * transformationMatrix[4] + y * transformationMatrix[5] + z * transformationMatrix[6] + s * transformationMatrix[7]; double newZ = x * transformationMatrix[8] + y * transformationMatrix[9] + z * transformationMatrix[10] + s * transformationMatrix[11]; double newS = x * transformationMatrix[12] + y * transformationMatrix[13] + z * transformationMatrix[14] + s * transformationMatrix[15]; x = newX; y = newY; z = newZ; s = newS; depthScale = s * WIDTH / (10 + z); twoDX = (depthScale * x); twoDY = (depthScale * y); } public void transformNormal(double[] transformationMatrix) { normal.transform(transformationMatrix); } public void calculateNewlightingScale(double gravityX, double gravityY, double gravityZ) { lightingScale = 30 + (int) (140 * Math.max((gravityX * normal.getX() + gravityY * normal.getY() + gravityZ * normal.getZ()) * lightingScaleConstant, -0.4)); } public void setST(double st1, double st2) { this.st1 = st1 * 1500; this.st2 = -st2 * 1500; //System.out.println(st1 + " " + st2); } public void setRGB(int r, int g, int b) { this.r = r; this.g = g; this.b = b; } public int getLightingScale() { return this.lightingScale; } public Point getNormal() { return normal; } public double getST1() { return this.st1; } public double getST2() { return this.st2; } public int getR() { return r; } public int getG() { return g; } public int getB() { return b; } public double get2Dx() { return twoDX; } public double get2Dy() { return twoDY; } public double getX() { return x; } public double getY() { return y; } public double getZ() { return z; } }
ThanatchaPanpairoj/aircraft-simulator
src/Vertex.java
1,200
//System.out.println(st1 + " " + st2);
line_comment
en
true
234268_0
//Solution 1 greedy ban solution class Solution { public String predictPartyVictory(String senate) { Queue<Integer> q1 = new LinkedList<Integer>(), q2 = new LinkedList<Integer>(); int n = senate.length(); for(int i = 0; i<n; i++){ if(senate.charAt(i) == 'R')q1.add(i); else q2.add(i); } while(!q1.isEmpty() && !q2.isEmpty()){ int r_index = q1.poll(), d_index = q2.poll(); if(r_index < d_index)q1.add(r_index + n); else q2.add(d_index + n); } return (q2.size() == 0)? "Radiant" : "Dire"; } }
YouwangDeng/Leetcode
Greedy/0649-Dota2 Senate.java
198
//Solution 1 greedy ban solution
line_comment
en
true
234391_0
import java.util.Scanner; /** * Created by User on 15.01.2017. */ public class Funny { public static void main(String[] args) { Funny solution = new Funny(); solution.solve(); } private void solve() { Scanner scanner = new Scanner(System.in); int queries = Integer.parseInt(scanner.nextLine()); for (int q = 0; q < queries ; q++) { String S = scanner.nextLine(); char[] s = S.toCharArray(); String R = new StringBuilder(S).reverse().toString(); char[] r = R.toCharArray(); int flag = 0; for (int i = 1; i < s.length; i ++) { if (Math.abs(s[i] - s[i - 1]) != Math.abs(r[i] - r[i - 1])) { System.out.println("Not Funny"); flag = 1; break; } } if (flag == 0) System.out.println("Funny"); } } }
yuriihd/hackerrank-algoritms
Funny.java
258
/** * Created by User on 15.01.2017. */
block_comment
en
true
234401_1
import java.util.ArrayList; import java.util.Scanner; public class Funny_String { public static void main(String[] args) { // TODO Auto-generated method stub Scanner sc=new Scanner(System.in); int n=sc.nextInt(); ArrayList<Character>list=new ArrayList<Character>(); for(int i=0;i<n;i++) { String str=sc.next(); check(str); } } public static void check(String str) { int len=str.length(); String rev=""; int a[]=new int[len]; int b[]=new int[len]; for(int i=0;i<str.length();i++) { a[i]=(int) str.charAt(i); } for(int i1=len-1;i1>=0;i1--) // Reverse a string { rev=rev+str.charAt(i1); } for(int i=0;i<rev.length();i++) { b[i]=(int) rev.charAt(i); } if(true==array(a,b)) System.out.println("Funny"); else System.out.println("Not Funny"); } public static boolean array (int a[],int b[] ) { ArrayList<Integer>alist=new ArrayList<Integer>(); ArrayList<Integer>blist=new ArrayList<Integer>(); for(int i=0;i<a.length-1;i++) { alist.add(Math.abs(a[i]-a[i+1])); } for(int i=0;i<b.length-1;i++) { blist.add(Math.abs(b[i]-b[i+1])); } if(true==alist.equals(blist)) return true; else return false; } }
sandipan08/HackerRank_ProblemSolving
src/Funny_String.java
497
// Reverse a string
line_comment
en
true
234459_6
package Model; /** * * @author Jonathan */ public class Review { private String idReview; private int useful; private int Funny; private int Rating; private String Comment; private String Status; private String ReportDetails; private String reviewer; private String images; private String review; public Review() { } public Review(String idReview, int useful, int Funny, int Rating, String Comment, String Status, String ReportDetails) { this.idReview = idReview; this.useful = useful; this.Funny = Funny; this.Rating = Rating; this.Comment = Comment; this.Status = Status; this.ReportDetails = ReportDetails; } /** * @return the idReview */ public String getIdReview() { return idReview; } /** * @param idReview the idReview to set */ public void setIdReview(String idReview) { this.idReview = idReview; } /** * @return the useful */ public int getUseful() { return useful; } /** * @param useful the useful to set */ public void setUseful(int useful) { this.useful = useful; } /** * @return the Funny */ public int getFunny() { return Funny; } /** * @param Funny the Funny to set */ public void setFunny(int Funny) { this.Funny = Funny; } /** * @return the Rating */ public int getRating() { return Rating; } /** * @param Rating the Rating to set */ public void setRating(int Rating) { this.Rating = Rating; } /** * @return the Comment */ public String getComment() { return Comment; } /** * @param Comment the Comment to set */ public void setComment(String Comment) { this.Comment = Comment; } /** * @return the Status */ public String getStatus() { return Status; } /** * @param Status the Status to set */ public void setStatus(String Status) { this.Status = Status; } /** * @return the ReportDetails */ public String getReportDetails() { return ReportDetails; } /** * @param ReportDetails the ReportDetails to set */ public void setReportDetails(String ReportDetails) { this.ReportDetails = ReportDetails; } /** * @return the reviewer */ public String getReviewer() { return reviewer; } /** * @param reviewer the reviewer to set */ public void setReviewer(String reviewer) { this.reviewer = reviewer; } /** * @return the images */ public String getImages() { return images; } /** * @param images the images to set */ public void setImages(String images) { this.images = images; } /** * @return the review */ public String getReview() { return review; } /** * @param review the review to set */ public void setReview(String review) { this.review = review; } }
getEat/getEatCode
GetEat/Review.java
749
/** * @param Funny the Funny to set */
block_comment
en
false
234481_0
package CodeBasics; class App { public static String makeItFunny(String str, int n) { // BEGIN (write your solution here) var i = 0; var result = ""; while (i < str.length()) { var current = str.charAt(i); if ((i + 1) % n == 0) { result = result + Character.toUpperCase(current); } else { result = result + current; } i++; } return result; // END } }
INTERFEJS/Chistyakov-V-A-First-course
2 sem/CodeBasics/60.java
120
// BEGIN (write your solution here)
line_comment
en
true
234768_21
import java.util.*; public class City { //Determine the City Grid based on the size of the Plotter public static final int WIDTH = 80; public static final int HEIGHT = 80; //Different names, same result public static final int MAX_COL = WIDTH; public static final int MAX_ROW = HEIGHT; // The Grid World for your reference // // (x) // columns // 0 1 2 3 4 5 ... WIDTH (MAX_COL) // .----------------... // (y)r 0| ,--column (x) // o 1| * (1,3) // w 2| ^ // 3| '-row (y) // .| // .| // .| //HEIGHT : //MAX_ROW: // //IMPORTANT! The grid world is a torus. Whenn a a point goes off //an edge, it wrapps around to the other side. So with a width of //of 80, a point at (79,5) would move to (0,5) next if it moved //one space down. Similarly, with a height of 80, a point //at (5,0) would move to (5,79) if it moved one space left. //------------------------------------- //The simulation's Data Structures // private List<Creature> creatures; //list of all creatues //Map of GridPoint to a list of cratures whose location is that grid point private HashMap<GridPoint,List<Creature>> creatureGrid; private Queue<Creature> rmQueue; //creatures that are staged for removal private Queue<Creature> addQueue; //creatures taht are staged to be added //... YES! you must use all of these collections. //... YES! you may add others if you need, but you MUST use these too! //Random instance private Random rand; //Note, for Level 4, you may need to change this constructors arguments. public City(Random rand, int numMice, int numCats, int numZombieCats, int numCheeseCreatures) { this.rand = rand; //TODO complete this constructor this.creatures = new LinkedList<Creature>(); this.rmQueue = new LinkedList<Creature>(); this.addQueue = new LinkedList<Creature>(); this.creatureGrid = new HashMap<GridPoint, List<Creature>>(); for (int i = 1; i <= MAX_ROW; i++) { for (int j = 1; j <= MAX_COL; j++) { creatureGrid.put(new GridPoint(i,j), new LinkedList<Creature>()); } } for(int i = 0; i < numMice; i++) { addMice(); } for (int i = 0; i < numCats; i++) { addCats(); } for (int i = 0; i < numZombieCats; i++) { addZombieCats(); } for (int i = 0; i < numCheeseCreatures; i++) { addCheeseCreature(); } } //Return the current number of creatures in the simulation public int numCreatures(){ return creatures.size(); } // Because we'll be iterating of the Creature List we can't remove // items from the list until after that iteration is // complete. Instead, we will queue (or stage) removals and // additions. // // I gave yout the two methods for adding, but you'll need to // implementing the clearing. //stage a create to be removed public void queueRmCreature(Creature c){ //DO NOT EDIT rmQueue.add(c); } //Stage a creature to be added public void queueAddCreature(Creature c){ //DO NOT EDIT addQueue.add(c); } //Clear the queue of creatures staged for removal and addition public void clearQueue(){ //TODO //Clear the queues by either adding creatures to the //simulation or removing them. while(!rmQueue.isEmpty()) { Creature newC = rmQueue.remove(); this.creatures.remove(newC); if(this.creatureGrid.get(newC.getGridPoint()) != null) { this.creatureGrid.get(newC.getGridPoint()).remove(newC); } } rmQueue.clear(); while(!addQueue.isEmpty()) { Creature addC = this.addQueue.remove(); // addQueue.add(addC); this.creatures.add(addC); if(this.creatureGrid.get(addC.getGridPoint()) == null) { this.creatureGrid.put(addC.getGridPoint(), new LinkedList<Creature>()); } this.creatureGrid.get(addC.getGridPoint()).add(addC); } addQueue.clear(); } //TODO -- there are a number of other member methods you'll want //to write here to interact with creatures. This is a good thing //to think about when putting together your UML diagram public List<Creature> getCreatures() { return creatures; } public HashMap<GridPoint, List<Creature>> getCreatureGrid() { return creatureGrid; } public List<Creature> getCreaturesAtLoc(GridPoint p) { return creatureGrid.get(p); } public Queue<Creature> getrmQueue() { return rmQueue; } public Queue<Creature> getaddQueue() { return addQueue; } public void addMice() { Mice mouse = new Mice(rand.nextInt(HEIGHT), rand.nextInt(WIDTH), this, rand); queueAddCreature(mouse); } public void addCats() { Cat cat = new Cat(rand.nextInt(HEIGHT), rand.nextInt(WIDTH), this, rand); queueAddCreature(cat); } public void addZombieCats() { ZombieCat zCat = new ZombieCat(rand.nextInt(HEIGHT), rand.nextInt(WIDTH), this, rand); queueAddCreature(zCat); } public void addCheeseCreature() { CheeseCreature cc = new CheeseCreature(rand.nextInt(HEIGHT), rand.nextInt(WIDTH), this, rand); queueAddCreature(cc); } // This is the simulate method that is called in Simulator.java // //You need to realize in your Creature class (and decendents) this //functionality so that they work properly. Read through these //comments so it's clear you understand. public void simulate() { //DO NOT EDIT! //You get this one for free, but you need to review this to //understand how to implement your various creatures //First, for all creatures ... for(Creature c : creatures){ //check to see if any creature should die if(c.die()){ queueRmCreature(c); //stage that creature for removal continue; } //for all remaining creatures take a step //this could involve chasing another creature //or running away from a creature c.step(); } //Clear queue of any removes or adds of creatures due to creature death clearQueue(); //For every creature determine if an action should be taken // such as, procreating (mice), eating (cats, zombiecats), or // some new action that you'll add to the system. for(Creature c : creatures){ c.takeAction(); } //Clear queue of any removes or adds following actions, such //as a mouse that was eaten or a cat that was was removed due //to being turned into a zombie cat. clearQueue(); //Output all the locations of the creatures. for(Creature c : creatures){ System.out.println(c); } } }
ralphp34/Software-Projects
project-2-ralphp34-main/City.java
1,834
//one space down. Similarly, with a height of 80, a point
line_comment
en
true
235025_2
/* * Copyright (C) 2014 Alfons Wirtz * website www.freerouting.net * * 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 at <http://www.gnu.org/licenses/> * for more details. */ package board; import geometry.planar.TileShape; import java.util.Set; /** * * Functionality required for items, which can be * electrical connected to other items. * * @author Alfons Wirtz */ public interface Connectable { /** * Returns true if this item belongs to the net with number p_net_no. */ public boolean contains_net(int p_net_no); /** * Returns true if the net number array of this and p_net_no_arr have a common * number. */ public boolean shares_net_no(int [] p_net_no_arr); /** * Returns a list of all connectable items overlapping * and sharing a net with this item. */ Set<Item> get_all_contacts(); /** * Returns a list of all connectable items overlapping with * this item on the input layer and sharing a net with this item. */ Set<Item> get_all_contacts(int p_layer ); /** * Returns the list of all contacts of a connectable item * located at defined connection points. * Connection points of traces are there endpoints, connection * points of drill_items there center points, and connection * points of conduction areas are points on there border. */ Set<Item> get_normal_contacts(); /** * Returns all connectable items of the net with number p_net_no, which can be reached recursively * from this item via normal contacts. * if (p_net_no <= 0, the net number is ignored. */ Set<Item> get_connected_set(int p_net_no); /** * Returns for each convex shape of a connectable item * the subshape of points, where traces can be connected to that item. */ TileShape get_trace_connection_shape(ShapeSearchTree p_tree, int p_index); }
nikropht/FreeRouting
board/Connectable.java
620
/** * Returns true if this item belongs to the net with number p_net_no. */
block_comment
en
false
235074_7
//Dynamic Host Configuration and Name Generation Protocol (DHCNGP) // //Copyright (C) 2012, Delft University of Technology, Faculty of Electrical Engineering, Mathematics and Computer Science, Network Architectures and Services, Niels van Adrichem // // This file is part of DHCNGP. // // DHCNGP is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License version 3 as published by // the Free Software Foundation. // // DHCNGP 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 DHCNGP. If not, see <http://www.gnu.org/licenses/>. import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.io.IOException; import java.io.ObjectInputStream; import java.io.ObjectOutputStream; public class Serializer { public static byte[] serialize(Object obj) throws IOException { ByteArrayOutputStream b = new ByteArrayOutputStream(); ObjectOutputStream o = new ObjectOutputStream(b); o.writeObject(obj); return b.toByteArray(); } public static Object deserialize(byte[] bytes) throws IOException, ClassNotFoundException { ByteArrayInputStream b = new ByteArrayInputStream(bytes); ObjectInputStream o = new ObjectInputStream(b); return o.readObject(); } }
TUDelftNAS/CCNx-DHCNGP
src/Serializer.java
373
// it under the terms of the GNU General Public License version 3 as published by
line_comment
en
true
235157_3
// Pyramid.java import java.util.Scanner; public class Pyramid extends Shape implements Volume { private double baseLength; private double baseWidth; private double height; @Override public double calculateShape() { // Surface area of a pyramid return baseLength * baseWidth + 0.5 * baseLength * Math.sqrt(Math.pow(baseWidth / 2, 2) + Math.pow(height, 2)) + 0.5 * baseWidth * Math.sqrt(Math.pow(baseLength / 2, 2) + Math.pow(height, 2)); } @Override public double calculatePerimeter() { // Perimeter calculation for a 3D shape is not applicable return 0; } @Override public double calculateVolume() { return (1.0 / 3.0) * baseLength * baseWidth * height; } // Function to get input from the user public void getInput() { Scanner scanner = new Scanner(System.in); System.out.print("Enter the base length of the pyramid: "); this.baseLength = scanner.nextDouble(); System.out.print("Enter the base width of the pyramid: "); this.baseWidth = scanner.nextDouble(); System.out.print("Enter the height of the pyramid: "); this.height = scanner.nextDouble(); } }
samisafk/PIJ
Assignment 5/Pyramid.java
320
// Function to get input from the user
line_comment
en
false
235601_13
/* Copyright 2008-2023 E-Hentai.org https://forums.e-hentai.org/ tenboro@e-hentai.org This file is part of Hentai@Home GUI. Hentai@Home GUI 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. Hentai@Home GUI 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 Hentai@Home GUI. If not, see <http://www.gnu.org/licenses/>. */ package hath.gui; import hath.base.*; import java.awt.*; import java.awt.event.*; import javax.swing.*; public class HentaiAtHomeClientGUI extends JFrame implements HathGUI, ActionListener, WindowListener, MouseListener, Runnable { private HentaiAtHomeClient client; private HHControlPane controlPane; private HHLogPane logPane; private Thread myThread; private JMenuItem refresh_settings, suspend_resume, suspend_5min, suspend_15min, suspend_30min, suspend_1hr, suspend_2hr, suspend_4hr, suspend_8hr; private SystemTray tray; private TrayIcon trayIcon; private boolean trayFirstMinimize; private long lastSettingRefresh = 0; public HentaiAtHomeClientGUI(String[] args) { String mainjar = "HentaiAtHome.jar"; if(! (new java.io.File(mainjar)).canRead()) { Out.error("Required JAR file " + mainjar + " could not be found. Please re-download Hentai@Home."); System.exit(-1); } try { UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName()); } catch(Exception e) { e.printStackTrace(); System.exit(-1); } Image icon16 = Toolkit.getDefaultToolkit().getImage(getClass().getResource("/src/hath/gui/icon16.png")); Image icon32 = Toolkit.getDefaultToolkit().getImage(getClass().getResource("/src/hath/gui/icon32.png")); setTitle("Hentai@Home " + Settings.CLIENT_VERSION + " (Build " + Settings.CLIENT_BUILD + ")"); setIconImage(icon32); setSize(1000, 550); setResizable(true); setDefaultCloseOperation(EXIT_ON_CLOSE); addWindowListener(this); // set up the menu bar JMenuBar mb = new JMenuBar(); JMenu program = new JMenu("Program"); JMenu suspend = new JMenu("Suspend"); // set up the program menu refresh_settings = new JMenuItem("Refresh Settings"); refresh_settings.addActionListener(this); refresh_settings.setEnabled(false); program.add(refresh_settings); program.add(new JSeparator()); JMenuItem program_exit = new JMenuItem("Shutdown H@H"); program_exit.addActionListener(this); program.add(program_exit); // set up the suspend menu suspend_resume = new JMenuItem("Resume"); suspend_resume.setEnabled(false); suspend_5min = new JMenuItem("Suspend for 5 Minutes"); suspend_15min = new JMenuItem("Suspend for 15 Minutes"); suspend_30min = new JMenuItem("Suspend for 30 Minutes"); suspend_1hr = new JMenuItem("Suspend for 1 Hour"); suspend_2hr = new JMenuItem("Suspend for 2 Hours"); suspend_4hr = new JMenuItem("Suspend for 4 Hours"); suspend_8hr = new JMenuItem("Suspend for 8 Hours"); suspend_resume.addActionListener(this); suspend_5min.addActionListener(this); suspend_15min.addActionListener(this); suspend_30min.addActionListener(this); suspend_1hr.addActionListener(this); suspend_2hr.addActionListener(this); suspend_4hr.addActionListener(this); suspend_8hr.addActionListener(this); suspend.add(suspend_resume); suspend.add(new JSeparator()); suspend.add(suspend_5min); suspend.add(suspend_15min); suspend.add(suspend_30min); suspend.add(suspend_1hr); suspend.add(suspend_2hr); suspend.add(suspend_4hr); setResumeEnabled(false); setSuspendEnabled(false); mb.add(program); mb.add(suspend); setJMenuBar(mb); // initialize the panes getContentPane().setLayout(new BorderLayout()); controlPane = new HHControlPane(this); getContentPane().add(controlPane, BorderLayout.PAGE_START); logPane = new HHLogPane(); getContentPane().add(logPane, BorderLayout.CENTER); // create the systray if(SystemTray.isSupported()) { trayFirstMinimize = true; // popup the "still running" box the first time the client is minimized to the systray this run setDefaultCloseOperation(DO_NOTHING_ON_CLOSE); // we'll handle this with the WindowListener tray = SystemTray.getSystemTray(); PopupMenu trayMenu = new PopupMenu(); //MenuItem test = new MenuItem("test"); //test.addActionListener(this); //trayMenu.add(test); trayIcon = new TrayIcon(icon16, "Hentai@Home", trayMenu); trayIcon.addMouseListener(this); try { tray.add(trayIcon); } catch(AWTException e) { e.printStackTrace(); } } boolean startVisible = true; for(String s : args) { if(s.equalsIgnoreCase("--silentstart")) { if(SystemTray.isSupported()) { startVisible = false; } } } pack(); setVisible(startVisible); lastSettingRefresh = System.currentTimeMillis(); myThread = new Thread(this); myThread.start(); try { Thread.currentThread().sleep(startVisible ? 2000 : 60000); } catch(Exception e) {} Settings.setActiveGUI(this); Stats.trackBytesSentHistory(); client = new HentaiAtHomeClient(new InputQueryHandlerGUI(this), args); setSuspendEnabled(true); } public void run() { while(true) { try { myThread.sleep(500); } catch(Exception e) {} if(!Stats.isClientSuspended() && suspend_resume.isEnabled()) { setResumeEnabled(false); setSuspendEnabled(true); } if(!refresh_settings.isEnabled() && lastSettingRefresh < System.currentTimeMillis() - 60000) { refresh_settings.setEnabled(true); } controlPane.updateData(); logPane.checkRebuildLogDisplay(); } } public void notifyWarning(String title, String text) { JOptionPane.showMessageDialog(this, text, title, JOptionPane.WARNING_MESSAGE); } public void notifyError(String reason) { JOptionPane.showMessageDialog(this, reason + "\n\nFor more information, look in the log files found in the data directory.", "Hentai@Home has encountered an error", JOptionPane.ERROR_MESSAGE); } // ActionListener for the JMenuBar public void actionPerformed(ActionEvent e) { String cmd = e.getActionCommand(); if(cmd.equals("Refresh Settings")) { refresh_settings.setEnabled(false); client.getClientAPI().refreshSettings(); } else if(cmd.equals("Shutdown H@H")) { if(client != null) { new GUIThreaded(client, GUIThreaded.ACTION_SHUTDOWN); } else { System.exit(0); } } else if(cmd.equals("Resume")) { clientResume(); } else if(cmd.equals("Suspend for 5 Minutes")) { clientSuspend(60 * 5); } else if(cmd.equals("Suspend for 15 Minutes")) { clientSuspend(60 * 15); } else if(cmd.equals("Suspend for 30 Minutes")) { clientSuspend(60 * 30); } else if(cmd.equals("Suspend for 1 Hour")) { clientSuspend(60 * 60); } else if(cmd.equals("Suspend for 2 Hours")) { clientSuspend(60 * 120); } else if(cmd.equals("Suspend for 4 Hours")) { clientSuspend(60 * 240); } else if(cmd.equals("Suspend for 8 Hours")) { clientSuspend(60 * 480); } } // WindowListener for the JFrame public void windowActivated(WindowEvent e) {} public void windowClosed(WindowEvent e) {} public void windowClosing(WindowEvent e) { setVisible(false); if(trayFirstMinimize) { trayFirstMinimize = false; trayIcon.displayMessage("Hentai@Home is still running", "Click here when you wish to show the Hentai@Home Client", TrayIcon.MessageType.INFO); } } public void windowDeactivated(WindowEvent e) {} public void windowDeiconified(WindowEvent e) {} public void windowIconified(WindowEvent e) {} public void windowOpened(WindowEvent e) {} // MouseListener for the SystemTray public void mouseClicked(MouseEvent e) { setVisible(true); } public void mouseEntered(MouseEvent e) {} public void mouseExited(MouseEvent e) {} public void mousePressed(MouseEvent e) {} public void mouseReleased(MouseEvent e) {} private void clientSuspend(int suspendTimeSeconds) { if(client != null && client.getClientAPI() != null) { if(client.getClientAPI().clientSuspend(suspendTimeSeconds).getResultText().equals("OK")) { setSuspendEnabled(false); setResumeEnabled(true); } else { Out.error("Failed to suspend"); } } else { Out.error("The client is not started, cannot suspend."); } } private void clientResume() { if(client != null && client.getClientAPI() != null) { if(client.getClientAPI().clientResume().getResultText().equals("OK")) { setSuspendEnabled(true); setResumeEnabled(false); } else { Out.error("Failed to resume"); } } else { Out.error("The client is not started, cannot resume."); } } private void setResumeEnabled(boolean enabled) { suspend_resume.setEnabled(enabled); } private void setSuspendEnabled(boolean enabled) { suspend_5min.setEnabled(enabled); suspend_15min.setEnabled(enabled); suspend_30min.setEnabled(enabled); suspend_1hr.setEnabled(enabled); suspend_2hr.setEnabled(enabled); suspend_4hr.setEnabled(enabled); suspend_8hr.setEnabled(enabled); } public static void main(String[] args) { new HentaiAtHomeClientGUI(args); } }
simon300000/hentaiathome
src/hath/gui/HentaiAtHomeClientGUI.java
2,886
// MouseListener for the SystemTray
line_comment
en
true
235613_36
package me.devsaki.hentoid.enums; import androidx.annotation.NonNull; import androidx.annotation.Nullable; import java.util.HashSet; import java.util.Set; import io.objectbox.converter.PropertyConverter; import me.devsaki.hentoid.R; import me.devsaki.hentoid.json.core.JsonSiteSettings; import me.devsaki.hentoid.util.network.HttpHelperKt; import timber.log.Timber; /** * Site enumerator */ public enum Site { // NOTE : to maintain compatiblity with saved JSON files and prefs, do _not_ edit either existing names or codes FAKKU(0, "Fakku", "https://www.fakku.net", R.drawable.ic_site_fakku), // Legacy support for old fakku archives PURURIN(1, "Pururin", "https://pururin.to", R.drawable.ic_site_pururin), HITOMI(2, "hitomi", "https://hitomi.la", R.drawable.ic_site_hitomi), NHENTAI(3, "nhentai", "https://nhentai.net", R.drawable.ic_site_nhentai), TSUMINO(4, "tsumino", "https://www.tsumino.com", R.drawable.ic_site_tsumino), HENTAICAFE(5, "hentaicafe", "https://hentai.cafe", R.drawable.ic_site_hentaicafe), ASMHENTAI(6, "asmhentai", "https://asmhentai.com", R.drawable.ic_site_asmhentai), ASMHENTAI_COMICS(7, "asmhentai comics", "https://comics.asmhentai.com", R.drawable.ic_site_asmcomics), EHENTAI(8, "e-hentai", "https://e-hentai.org", R.drawable.ic_site_ehentai), FAKKU2(9, "Fakku", "https://www.fakku.net", R.drawable.ic_site_fakku), NEXUS(10, "Hentai Nexus", "https://hentainexus.com", R.drawable.ic_site_nexus), MUSES(11, "8Muses", "https://www.8muses.com", R.drawable.ic_site_8muses), DOUJINS(12, "doujins.com", "https://doujins.com/", R.drawable.ic_site_doujins), LUSCIOUS(13, "luscious.net", "https://members.luscious.net/manga/", R.drawable.ic_site_luscious), EXHENTAI(14, "exhentai", "https://exhentai.org", R.drawable.ic_site_exhentai), PORNCOMIX(15, "porncomixonline", "https://www.porncomixonline.net/", R.drawable.ic_site_porncomix), HBROWSE(16, "Hbrowse", "https://www.hbrowse.com/", R.drawable.ic_site_hbrowse), HENTAI2READ(17, "Hentai2Read", "https://hentai2read.com/", R.drawable.ic_site_hentai2read), HENTAIFOX(18, "Hentaifox", "https://hentaifox.com", R.drawable.ic_site_hentaifox), MRM(19, "MyReadingManga", "https://myreadingmanga.info/", R.drawable.ic_site_mrm), MANHWA(20, "ManwhaHentai", "https://manhwahentai.me/", R.drawable.ic_site_manhwa), IMHENTAI(21, "Imhentai", "https://imhentai.xxx", R.drawable.ic_site_imhentai), TOONILY(22, "Toonily", "https://toonily.com/", R.drawable.ic_site_toonily), ALLPORNCOMIC(23, "Allporncomic", "https://allporncomic.com/", R.drawable.ic_site_allporncomic), PIXIV(24, "Pixiv", "https://www.pixiv.net/", R.drawable.ic_site_pixiv), MANHWA18(25, "Manhwa18", "https://manhwa18.com/", R.drawable.ic_site_manhwa18), MULTPORN(26, "Multporn", "https://multporn.net/", R.drawable.ic_site_multporn), SIMPLY(27, "Simply Hentai", "https://www.simply-hentai.com/", R.drawable.ic_site_simply), HDPORNCOMICS(28, "HD Porn Comics", "https://hdporncomics.com/", R.drawable.ic_site_hdporncomics), EDOUJIN(29, "Edoujin", "https://ehentaimanga.com/", R.drawable.ic_site_edoujin), KSK(30, "Koushoku", "https://ksk.moe", R.drawable.ic_site_ksk), ANCHIRA(31, "Anchira", "https://anchira.to", R.drawable.ic_site_anchira), DEVIANTART(32, "DeviantArt", "https://www.deviantart.com/", R.drawable.ic_site_deviantart), MANGAGO(33, "Mangago", "https://www.mangago.me/", R.drawable.ic_site_mangago), NONE(98, "none", "", R.drawable.ic_attribute_source), // External library; fallback site PANDA(99, "panda", "https://www.mangapanda.com", R.drawable.ic_site_panda); // Safe-for-work/wife/gf option; not used anymore and kept here for retrocompatibility private static final Site[] INVISIBLE_SITES = { NEXUS, // Dead HBROWSE, // Dead HENTAICAFE, // Dead KSK, // Dead ANCHIRA, // Dead FAKKU, // Old Fakku; kept for retrocompatibility FAKKU2, // Dropped after Fakku decided to flag downloading accounts and IPs ASMHENTAI_COMICS, // Does not work directly PANDA, // Dropped; kept for retrocompatibility NONE // Technical fallback }; private final int code; private final String description; private final String url; private final int ico; // Default values overridden in sites.json private boolean useMobileAgent = true; private boolean useHentoidAgent = false; private boolean useWebviewAgent = true; // Download behaviour control private boolean hasBackupURLs = false; private boolean hasCoverBasedPageUpdates = false; private boolean useCloudflare = false; private boolean hasUniqueBookId = false; private int requestsCapPerSecond = -1; private int parallelDownloadCap = 0; // Controls for "Mark downloaded/merged" in browser private int bookCardDepth = 2; private Set<String> bookCardExcludedParentClasses = new HashSet<>(); // Controls for "Mark books with blocked tags" in browser private int galleryHeight = -1; // Determine which Jsoup output to use when rewriting the HTML // 0 : html; 1 : xml private int jsoupOutputSyntax = 0; Site(int code, String description, String url, int ico) { this.code = code; this.description = description; this.url = url; this.ico = ico; } public static Site searchByCode(long code) { for (Site s : values()) if (s.getCode() == code) return s; return NONE; } // Same as ValueOf with a fallback to NONE // (vital for forward compatibility) public static Site searchByName(String name) { for (Site s : values()) if (s.name().equalsIgnoreCase(name)) return s; return NONE; } @Nullable public static Site searchByUrl(String url) { if (null == url || url.isEmpty()) { Timber.w("Invalid url"); return null; } for (Site s : Site.values()) if (s.code > 0 && HttpHelperKt.getDomainFromUri(url).equalsIgnoreCase(HttpHelperKt.getDomainFromUri(s.url))) return s; return Site.NONE; } public int getCode() { return code; } public String getDescription() { return description; } public String getUrl() { return url; } public int getIco() { return ico; } public boolean useMobileAgent() { return useMobileAgent; } public boolean useHentoidAgent() { return useHentoidAgent; } public boolean useWebviewAgent() { return useWebviewAgent; } public boolean hasBackupURLs() { return hasBackupURLs; } public boolean hasCoverBasedPageUpdates() { return hasCoverBasedPageUpdates; } public boolean isUseCloudflare() { return useCloudflare; } public boolean hasUniqueBookId() { return hasUniqueBookId; } public int getRequestsCapPerSecond() { return requestsCapPerSecond; } public int getParallelDownloadCap() { return parallelDownloadCap; } public int getBookCardDepth() { return bookCardDepth; } public Set<String> getBookCardExcludedParentClasses() { return bookCardExcludedParentClasses; } public int getGalleryHeight() { return galleryHeight; } public int getJsoupOutputSyntax() { return jsoupOutputSyntax; } public boolean isVisible() { for (Site s : INVISIBLE_SITES) if (s.equals(this)) return false; return true; } public String getFolder() { if (this == FAKKU) return "Downloads"; else return description; } public String getUserAgent() { if (useMobileAgent()) return HttpHelperKt.getMobileUserAgent(useHentoidAgent(), useWebviewAgent()); else return HttpHelperKt.getDesktopUserAgent(useHentoidAgent(), useWebviewAgent()); } public void updateFrom(@NonNull final JsonSiteSettings.JsonSite jsonSite) { if (jsonSite.getUseMobileAgent() != null) useMobileAgent = jsonSite.getUseMobileAgent(); if (jsonSite.getUseHentoidAgent() != null) useHentoidAgent = jsonSite.getUseHentoidAgent(); if (jsonSite.getUseWebviewAgent() != null) useWebviewAgent = jsonSite.getUseWebviewAgent(); if (jsonSite.getHasBackupURLs() != null) hasBackupURLs = jsonSite.getHasBackupURLs(); if (jsonSite.getHasCoverBasedPageUpdates() != null) hasCoverBasedPageUpdates = jsonSite.getHasCoverBasedPageUpdates(); if (jsonSite.getUseCloudflare() != null) useCloudflare = jsonSite.getUseCloudflare(); if (jsonSite.getHasUniqueBookId() != null) hasUniqueBookId = jsonSite.getHasUniqueBookId(); if (jsonSite.getParallelDownloadCap() != null) parallelDownloadCap = jsonSite.getParallelDownloadCap(); if (jsonSite.getRequestsCapPerSecond() != null) requestsCapPerSecond = jsonSite.getRequestsCapPerSecond(); if (jsonSite.getBookCardDepth() != null) bookCardDepth = jsonSite.getBookCardDepth(); if (jsonSite.getBookCardExcludedParentClasses() != null) bookCardExcludedParentClasses = new HashSet<>(jsonSite.getBookCardExcludedParentClasses()); if (jsonSite.getGalleryHeight() != null) galleryHeight = jsonSite.getGalleryHeight(); if (jsonSite.getJsoupOutputSyntax() != null) jsoupOutputSyntax = jsonSite.getJsoupOutputSyntax(); } public static class SiteConverter implements PropertyConverter<Site, Long> { @Override public Site convertToEntityProperty(Long databaseValue) { if (databaseValue == null) { return Site.NONE; } for (Site site : Site.values()) { if (site.getCode() == databaseValue) { return site; } } return Site.NONE; } @Override public Long convertToDatabaseValue(Site entityProperty) { return entityProperty == null ? null : (long) entityProperty.getCode(); } } }
avluis/Hentoid
app/src/main/java/me/devsaki/hentoid/enums/Site.java
3,035
// External library; fallback site
line_comment
en
true
235616_4
//jDownloader - Downloadmanager //Copyright (C) 2008 JD-Team support@jdownloader.org // //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 jd.plugins.decrypter; import java.util.ArrayList; import java.util.regex.Pattern; import jd.PluginWrapper; import jd.controlling.AccountController; import jd.controlling.ProgressController; import jd.http.Request; import jd.nutils.encoding.Encoding; import jd.parser.Regex; import jd.plugins.Account; import jd.plugins.CryptedLink; import jd.plugins.DecrypterPlugin; import jd.plugins.DownloadLink; import jd.plugins.FilePackage; import jd.plugins.PluginException; import jd.plugins.PluginForDecrypt; import jd.plugins.PluginForHost; import jd.utils.JDUtilities; import org.jdownloader.controlling.filter.CompiledFiletypeFilter; @DecrypterPlugin(revision = "$Revision$", interfaceVersion = 3, names = { "hentai-foundry.com" }, urls = { "https?://(?:www\\.)?hentai-foundry\\.com/pictures/user/[A-Za-z0-9\\-_]+(?:/scraps)?(?:/\\d+)?|https?://(?:www\\.)?hentai-foundry\\.com/user/[A-Za-z0-9\\-_]+/(profile|faves/pictures)" }) public class HentaiFoundryComGallery extends PluginForDecrypt { public HentaiFoundryComGallery(PluginWrapper wrapper) { super(wrapper); } public ArrayList<DownloadLink> decryptIt(CryptedLink param, ProgressController progress) throws Exception { final ArrayList<DownloadLink> decryptedLinks = new ArrayList<DownloadLink>(); getUserLogin(false); br.setReadTimeout(3 * 60 * 1000); br.setFollowRedirects(true); String parameter = param.toString(); if (new Regex(parameter, Pattern.compile(".+/user/[A-Za-z0-9\\-_]+/profile", Pattern.CASE_INSENSITIVE)).matches()) { final String userID = new Regex(parameter, Pattern.compile(".+/user/([A-Za-z0-9\\-_]+)", Pattern.CASE_INSENSITIVE)).getMatch(0); decryptedLinks.add(createDownloadlink("http://www.hentai-foundry.com/pictures/user/" + userID)); decryptedLinks.add(createDownloadlink("http://www.hentai-foundry.com/pictures/user/" + userID + "/scraps")); decryptedLinks.add(createDownloadlink("http://www.hentai-foundry.com/stories/user/" + userID)); return decryptedLinks; } if (new Regex(parameter, Pattern.compile(".+/pictures/user/[A-Za-z0-9\\-_]+/\\d+", Pattern.CASE_INSENSITIVE)).matches()) { decryptedLinks.add(createDownloadlink(parameter)); return decryptedLinks; } br.getPage(parameter + "?enterAgree=1&size=0"); if (br.getHttpConnection().getResponseCode() == 404) { decryptedLinks.add(this.createOfflinelink(parameter)); return decryptedLinks; } else if (br.containsHTML("class=\"empty\"")) { /* User has not uploaded any content */ decryptedLinks.add(this.createOfflinelink(parameter)); return decryptedLinks; } final String fpName = new Regex(parameter, "/user/(.+)").getMatch(0); int page = 1; String next = null; final FilePackage fp = FilePackage.getInstance(); fp.setName(Encoding.htmlDecode(fpName.trim())); do { if (this.isAbort()) { logger.info("Decryption aborted by user: " + parameter); return decryptedLinks; } logger.info("Decrypting page " + page); if (page > 1) { br.getPage(next); } String[] links = br.getRegex("<[^<>]+class='thumb_square'.*?</").getColumn(-1); if (links == null || links.length == 0) { return null; } for (String link : links) { String title = new Regex(link, "thumbTitle\"><[^<>]*?>([^<>]+)<").getMatch(0); final String url = new Regex(link, "\"(/pictures/user/[A-Za-z0-9\\-_]+/\\d+[^<>\"]*?)\"").getMatch(0); if (url == null) { logger.warning("Decrypter broken for link: " + parameter); logger.info("link: " + link); logger.info("title: " + title + "url: " + url); return null; } final String pic_id = jd.plugins.hoster.HentaiFoundryCom.getFID(url); if (title != null) { title = pic_id + "_" + Encoding.htmlDecode(title).trim(); title = encodeUnicode(title); } else { title = pic_id; } final DownloadLink dl = createDownloadlink(Request.getLocation(url, br.getRequest())); dl.setName(title); dl.setMimeHint(CompiledFiletypeFilter.ImageExtensions.BMP); dl.setAvailable(true); decryptedLinks.add(dl); fp.add(dl); distribute(dl); } next = br.getRegex("class=\"next\"><a href=\"(/pictures/user/.*?/page/\\d+)\">Next").getMatch(0); if (next == null) { next = br.getRegex("class=\"next\"><a href=\"(/user/.*?/page/\\d+)\">Next").getMatch(0); } page++; } while (next != null); return decryptedLinks; } /** Log in the account of the hostplugin */ @SuppressWarnings("deprecation") private boolean getUserLogin(final boolean force) throws Exception { final PluginForHost hostPlugin = JDUtilities.getPluginForHost(this.getHost()); final Account aa = AccountController.getInstance().getValidAccount(hostPlugin); if (aa == null) { logger.warning("There is no account available, continuing without logging in (if possible)"); return false; } try { jd.plugins.hoster.HentaiFoundryCom.login(br, aa, force); } catch (final PluginException e) { logger.warning("Login failed - continuing without login"); aa.setValid(false); return false; } logger.info("Logged in successfully"); return true; } }
5l1v3r1/jdownloader
src/jd/plugins/decrypter/HentaiFoundryComGallery.java
1,715
//it under the terms of the GNU General Public License as published by
line_comment
en
true
235622_0
package cn.org.hentai.dns.stat; import cn.org.hentai.dns.util.IPUtils; /** * Created by matrixy on 2019/5/9. */ public class IPStat { public int ip; public int queryCount; public IPStat(int ip, int count) { this.ip = ip; this.queryCount = count; } public String getIP() { return IPUtils.fromInteger(ip); } public int getQueryCount() { return this.queryCount; } }
glaciall/dns-cheater
src/main/java/cn/org/hentai/dns/stat/IPStat.java
142
/** * Created by matrixy on 2019/5/9. */
block_comment
en
true
235628_8
/* Copyright 2008-2020 E-Hentai.org https://forums.e-hentai.org/ ehentai@gmail.com This file is part of Hentai@Home GUI. Hentai@Home GUI 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. Hentai@Home GUI 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 Hentai@Home GUI. If not, see <http://www.gnu.org/licenses/>. */ package hath.gui; import hath.base.*; import java.awt.*; import java.awt.event.*; import javax.swing.*; public class HentaiAtHomeClientGUI extends JFrame implements HathGUI, ActionListener, WindowListener, MouseListener, Runnable { private HentaiAtHomeClient client; private HHControlPane controlPane; private HHLogPane logPane; private Thread myThread; private JMenuItem refresh_settings, suspend_resume, suspend_5min, suspend_15min, suspend_30min, suspend_1hr, suspend_2hr, suspend_4hr, suspend_8hr; private SystemTray tray; private TrayIcon trayIcon; private boolean trayFirstMinimize; private long lastSettingRefresh = 0; public HentaiAtHomeClientGUI(String[] args) { String mainjar = "HentaiAtHome.jar"; if(! (new java.io.File(mainjar)).canRead()) { Out.error("Required JAR file " + mainjar + " could not be found. Please re-download Hentai@Home."); System.exit(-1); } try { UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName()); } catch(Exception e) { e.printStackTrace(); System.exit(-1); } Image icon16 = Toolkit.getDefaultToolkit().getImage(getClass().getResource("/src/hath/gui/icon16.png")); Image icon32 = Toolkit.getDefaultToolkit().getImage(getClass().getResource("/src/hath/gui/icon32.png")); setTitle("Hentai@Home " + Settings.CLIENT_VERSION + " (Build " + Settings.CLIENT_BUILD + ")"); setIconImage(icon32); setSize(1000, 550); setResizable(true); setDefaultCloseOperation(EXIT_ON_CLOSE); addWindowListener(this); // set up the menu bar JMenuBar mb = new JMenuBar(); JMenu program = new JMenu("Program"); JMenu suspend = new JMenu("Suspend"); // set up the program menu refresh_settings = new JMenuItem("Refresh Settings"); refresh_settings.addActionListener(this); refresh_settings.setEnabled(false); program.add(refresh_settings); program.add(new JSeparator()); JMenuItem program_exit = new JMenuItem("Shutdown H@H"); program_exit.addActionListener(this); program.add(program_exit); // set up the suspend menu suspend_resume = new JMenuItem("Resume"); suspend_resume.setEnabled(false); suspend_5min = new JMenuItem("Suspend for 5 Minutes"); suspend_15min = new JMenuItem("Suspend for 15 Minutes"); suspend_30min = new JMenuItem("Suspend for 30 Minutes"); suspend_1hr = new JMenuItem("Suspend for 1 Hour"); suspend_2hr = new JMenuItem("Suspend for 2 Hours"); suspend_4hr = new JMenuItem("Suspend for 4 Hours"); suspend_8hr = new JMenuItem("Suspend for 8 Hours"); suspend_resume.addActionListener(this); suspend_5min.addActionListener(this); suspend_15min.addActionListener(this); suspend_30min.addActionListener(this); suspend_1hr.addActionListener(this); suspend_2hr.addActionListener(this); suspend_4hr.addActionListener(this); suspend_8hr.addActionListener(this); suspend.add(suspend_resume); suspend.add(new JSeparator()); suspend.add(suspend_5min); suspend.add(suspend_15min); suspend.add(suspend_30min); suspend.add(suspend_1hr); suspend.add(suspend_2hr); suspend.add(suspend_4hr); setResumeEnabled(false); setSuspendEnabled(false); mb.add(program); mb.add(suspend); setJMenuBar(mb); // initialize the panes getContentPane().setLayout(new BorderLayout()); controlPane = new HHControlPane(this); getContentPane().add(controlPane, BorderLayout.PAGE_START); logPane = new HHLogPane(); getContentPane().add(logPane, BorderLayout.CENTER); // create the systray if(SystemTray.isSupported()) { trayFirstMinimize = true; // popup the "still running" box the first time the client is minimized to the systray this run setDefaultCloseOperation(DO_NOTHING_ON_CLOSE); // we'll handle this with the WindowListener tray = SystemTray.getSystemTray(); PopupMenu trayMenu = new PopupMenu(); //MenuItem test = new MenuItem("test"); //test.addActionListener(this); //trayMenu.add(test); trayIcon = new TrayIcon(icon16, "Hentai@Home", trayMenu); trayIcon.addMouseListener(this); try { tray.add(trayIcon); } catch(AWTException e) { e.printStackTrace(); } } boolean startVisible = true; for(String s : args) { if(s.equalsIgnoreCase("--silentstart")) { if(SystemTray.isSupported()) { startVisible = false; } } } pack(); setVisible(startVisible); lastSettingRefresh = System.currentTimeMillis(); myThread = new Thread(this); myThread.start(); try { Thread.sleep(startVisible ? 2000 : 60000); } catch(Exception e) {} Settings.setActiveGUI(this); Stats.trackBytesSentHistory(); client = new HentaiAtHomeClient(new InputQueryHandlerGUI(this), args); setSuspendEnabled(true); } public void run() { while(true) { try { myThread.sleep(500); } catch(Exception e) {} if(!Stats.isClientSuspended() && suspend_resume.isEnabled()) { setResumeEnabled(false); setSuspendEnabled(true); } if(!refresh_settings.isEnabled() && lastSettingRefresh < System.currentTimeMillis() - 60000) { refresh_settings.setEnabled(true); } controlPane.updateData(); logPane.checkRebuildLogDisplay(); } } public void notifyWarning(String title, String text) { JOptionPane.showMessageDialog(this, text, title, JOptionPane.WARNING_MESSAGE); } public void notifyError(String reason) { JOptionPane.showMessageDialog(this, reason + "\n\nFor more information, look in the log files found in the data directory.", "Hentai@Home has encountered an error", JOptionPane.ERROR_MESSAGE); } // ActionListener for the JMenuBar public void actionPerformed(ActionEvent e) { String cmd = e.getActionCommand(); if(cmd.equals("Refresh Settings")) { refresh_settings.setEnabled(false); client.getClientAPI().refreshSettings(); } else if(cmd.equals("Shutdown H@H")) { if(client != null) { new GUIThreaded(client, GUIThreaded.ACTION_SHUTDOWN); } else { System.exit(0); } } else if(cmd.equals("Resume")) { clientResume(); } else if(cmd.equals("Suspend for 5 Minutes")) { clientSuspend(60 * 5); } else if(cmd.equals("Suspend for 15 Minutes")) { clientSuspend(60 * 15); } else if(cmd.equals("Suspend for 30 Minutes")) { clientSuspend(60 * 30); } else if(cmd.equals("Suspend for 1 Hour")) { clientSuspend(60 * 60); } else if(cmd.equals("Suspend for 2 Hours")) { clientSuspend(60 * 120); } else if(cmd.equals("Suspend for 4 Hours")) { clientSuspend(60 * 240); } else if(cmd.equals("Suspend for 8 Hours")) { clientSuspend(60 * 480); } } // WindowListener for the JFrame public void windowActivated(WindowEvent e) {} public void windowClosed(WindowEvent e) {} public void windowClosing(WindowEvent e) { setVisible(false); if(trayFirstMinimize) { trayFirstMinimize = false; trayIcon.displayMessage("Hentai@Home is still running", "Click here when you wish to show the Hentai@Home Client", TrayIcon.MessageType.INFO); } } public void windowDeactivated(WindowEvent e) {} public void windowDeiconified(WindowEvent e) {} public void windowIconified(WindowEvent e) {} public void windowOpened(WindowEvent e) {} // MouseListener for the SystemTray public void mouseClicked(MouseEvent e) { setVisible(true); } public void mouseEntered(MouseEvent e) {} public void mouseExited(MouseEvent e) {} public void mousePressed(MouseEvent e) {} public void mouseReleased(MouseEvent e) {} private void clientSuspend(int suspendTimeSeconds) { if(client != null && client.getClientAPI() != null) { if(client.getClientAPI().clientSuspend(suspendTimeSeconds).getResultText().equals("OK")) { setSuspendEnabled(false); setResumeEnabled(true); } else { Out.error("Failed to suspend"); } } else { Out.error("The client is not started, cannot suspend."); } } private void clientResume() { if(client != null && client.getClientAPI() != null) { if(client.getClientAPI().clientResume().getResultText().equals("OK")) { setSuspendEnabled(true); setResumeEnabled(false); } else { Out.error("Failed to resume"); } } else { Out.error("The client is not started, cannot resume."); } } private void setResumeEnabled(boolean enabled) { suspend_resume.setEnabled(enabled); } private void setSuspendEnabled(boolean enabled) { suspend_5min.setEnabled(enabled); suspend_15min.setEnabled(enabled); suspend_30min.setEnabled(enabled); suspend_1hr.setEnabled(enabled); suspend_2hr.setEnabled(enabled); suspend_4hr.setEnabled(enabled); suspend_8hr.setEnabled(enabled); } public static void main(String[] args) { new HentaiAtHomeClientGUI(args); } }
HeXis-YS/HentaiAtHome
src/hath/gui/HentaiAtHomeClientGUI.java
2,880
//MenuItem test = new MenuItem("test");
line_comment
en
true
235890_0
/** * Theatre class holds all database information * initialize on programming start up * * Singleton design to ensure only instance */ import java.util.*; public class Theatre { private static Theatre theatre; //showtime has time/name/screen private List<Movie> movies = new ArrayList<Movie>(); //order has orderid/ticketid/movie name/seat number/showtime time private List<Order> orders = new ArrayList<Order>(); private List<DiscountCode> discounts = new ArrayList<DiscountCode>(); private UserController loginserver; /** *deafult ctor */ public Theatre() { } /** * add items to run time arrays */ public void addMovie(Movie newMovie) {movies.add(newMovie);} public void addOrder(Order newOrder) {orders.add(newOrder);} public void addDiscount(DiscountCode newDiscount) {discounts.add(newDiscount);} /** *remove items from dynamic arrays */ public void removeOrder(int orderID) { for(int i = 0; i < orders.size(); i++) { if(orderID == orders.get(i).getOrderID()) { updateSeatmap(orders.get(i)); orders.remove(i); } } } public void removeDiscount(int discountCode) { for(int i = 0; i < discounts.size(); i++) { if(discountCode == discounts.get(i).getCode()) { discounts.remove(i); } } } /** * find items in dynamic arrays */ public Order findOrder(int orderID, String email) { for(int i = 0; i < orders.size(); i++) { if(orderID == orders.get(i).getOrderID() && email == orders.get(i).getEmail()) { return orders.get(i); } } return null; } public DiscountCode findDiscount(int discountCode) { for(int i = 0; i < discounts.size(); i++) { if(discountCode == discounts.get(i).getCode()) { return discounts.get(i); } } return null; } public Showtime findShowTime(int ID) { for(int i = 0; i < movies.size(); i++) { Movie checkMovie = movies.get(i); for(int j = 0; j < checkMovie.getShowtimes().size(); j++) { Showtime checkShowtime = checkMovie.getShowtime(j); if(checkShowtime.getID() == ID) { return checkShowtime; } } } return null; } /** *Singleton ctor */ private Theatre(int testIntRemoveLater) { MovieDatabase theatredb = new MovieDatabase(); movies = theatredb.readMovies(); orders = theatredb.readOrders(); discounts = theatredb.readDiscountCodes(); theatredb.setMaxOrderID(); theatredb.setMaxTicketID(); theatredb.setMaxShowtimeID(); theatredb.setMaxCodeCounter(); loginserver = UserController.getLoginInstance(); } //getters public static Theatre getTheatre() { if (theatre == null) { theatre = new Theatre(); } return theatre; } public List<Movie> getReleasedMovies(){ ArrayList<Movie> released = new ArrayList<Movie>(); for (Movie m : this.movies){ if(m.isReleased()){ released.add(m); } } return released; } public List<Movie> getEarlyMovies(){ ArrayList<Movie> early = new ArrayList<Movie>(); for(Movie m : this.movies){ if(m.isEarly()){ early.add(m); } } return early; } /** * Updated seatmap after order cancellation * */ public void updateSeatmap(Order order){ Movie movie = null; Showtime st = null; for(int i = 0; i < movies.size(); i++){ if(movies.get(i).getTitle().equals(order.getTickets().get(0).getMovieName())){ movie = movies.get(i); break; } } for(int i = 0; i < movie.getShowtimes().size(); i++){ if(order.getTickets().get(0).getshowtimeID() == movie.getShowtime(i).getID()){ st = movie.getShowtime(i); break; } } for(int i = 0; i < order.getTickets().size(); i++){ st.getSeats().cancelSeats(order.getTickets().get(i).getSeatColumn(), order.getTickets().get(i).getSeatRow()); } } }
Jgerbrandt/ENSF-480-Final-Project
Theatre.java
1,223
/** * Theatre class holds all database information * initialize on programming start up * * Singleton design to ensure only instance */
block_comment
en
false
235970_0
import javax.swing.*; import java.awt.event.ActionListener; import java.awt.event.ActionEvent; import java.awt.*; public class Addmovie implements ActionListener { JFrame frame = new JFrame(); JLabel movie_name = new JLabel("Movie Name:"); JTextField movie_name_text = new JTextField(); JLabel theatre = new JLabel("Theatre:"); JTextField theatre_text = new JTextField(); JLabel seats = new JLabel("Seats:"); JTextField seats_text = new JTextField(); JLabel date = new JLabel("Date:"); JTextField date_text = new JTextField(); JLabel time = new JLabel("Time:"); JTextField time_text = new JTextField(); // JLabel price = new JLabel("Price:"); // JTextField price_text = new JTextField(); JLabel movie_des = new JLabel("About:"); // JLabel id = new JLabel("ID:"); // JTextField id_text = new JTextField(); JTextArea movie_description = new JTextArea(); JButton add_movie = new JButton("Add Movie"); JButton back = new JButton("Back"); public Addmovie() { frame.setContentPane(new JLabel(new ImageIcon( new ImageIcon(".\\Images\\moviereel.jpg").getImage().getScaledInstance(1000, 650, Image.SCALE_DEFAULT)))); frame.setTitle("Operations Page"); back.setBounds(850, 50, 75, 30); back.addActionListener(this); movie_name.setBounds(450, 100, 100, 30); movie_name.setForeground(Color.BLACK); movie_name_text.setBounds(550, 100, 200, 30); movie_name_text.setForeground(Color.BLACK); theatre.setBounds(450, 150, 100, 30); theatre.setForeground(Color.BLACK); theatre_text.setBounds(550, 150, 200, 30); theatre_text.setForeground(Color.BLACK); seats.setBounds(450, 200, 100, 30); seats.setForeground(Color.BLACK); seats_text.setBounds(550, 200, 200, 30); seats_text.setForeground(Color.BLACK); movie_des.setBounds(450, 250, 100, 30); movie_des.setForeground(Color.BLACK); movie_description.setBounds(550, 250, 200, 200); movie_description.setForeground(Color.BLACK); date.setBounds(450, 500, 100, 30); date.setForeground(Color.BLACK); date_text.setBounds(550, 500, 200, 30); date_text.setForeground(Color.BLACK); time.setBounds(450, 550, 100, 30); time.setForeground(Color.BLACK); time_text.setBounds(550, 550, 100, 30); time_text.setForeground(Color.BLACK); add_movie.setBounds(825, 550, 100, 30); add_movie.addActionListener(this); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); frame.setLayout(null); frame.setBackground(new Color(135, 206, 235)); frame.setSize(1000, 650); frame.add(movie_name); frame.add(movie_name_text); frame.add(theatre); frame.add(theatre_text); frame.add(seats); frame.add(seats_text); frame.add(movie_des); frame.add(movie_description); // frame.add(price); // frame.add(price_text); frame.add(add_movie); // frame.add(id); // frame.add(id_text); frame.add(date); frame.add(date_text); frame.add(time); frame.add(time_text); frame.add(back); frame.setLocationRelativeTo(null); frame.setVisible(true); } @Override public void actionPerformed(ActionEvent e) { // System.out.println("Addmovie"); if (e.getSource() == add_movie) { System.out.println("Addmovie"); SingleDatabase obj = SingleDatabase.getInstance(); int success = obj.addMovie(movie_name_text.getText(), movie_description.getText(), theatre_text.getText(), seats_text.getText(), date_text.getText(), time_text.getText()); if (success == 1) JOptionPane.showMessageDialog(null, "Movie Added"); else JOptionPane.showMessageDialog(null, "Another Movie already scheduled for that time"); } if (e.getSource() == back) { frame.dispose(); new ManagerView(); } } } // java -cp "E:\pes1ug19cs095_sem6\final project 1\Login // system\postgresql-42.3.4.jar;E:\pes1ug19cs095_sem6\final project 1\Login // system\Manager" Addmovie
ASHWINK07/Movie-Ticket-Booking-System
model/Addmovie.java
1,282
// JLabel price = new JLabel("Price:");
line_comment
en
true
236099_19
/* * A program for filtering variants based on their overlap with a list of regions. */ import java.io.File; import java.io.FileInputStream; import java.io.PrintWriter; import java.util.ArrayList; import java.util.Collections; import java.util.HashMap; import java.util.HashSet; import java.util.Scanner; import java.util.TreeSet; public class Overlap { static String vcfFn = ""; static String bedFn = ""; static String ofn = ""; static String FILTER_MODE = "CONTAINED_IN_REGION"; static String REPORT_MODE = "REMOVE"; static String reportInfo = ""; static ChrNameNormalization chrNorm; static void parseArgs(String[] args) { for(String arg : args) { int equalsIdx = arg.indexOf('='); if(equalsIdx == -1) { } else { String key = arg.substring(0, equalsIdx); String val = arg.substring(1 + equalsIdx); if(key.equalsIgnoreCase("vcf_file")) { vcfFn = val; } else if(key.equalsIgnoreCase("bed_file")) { bedFn = val; } else if(key.equalsIgnoreCase("out_file")) { ofn = val; } else if(key.equalsIgnoreCase("info_report")) { reportInfo = val; } } } if(reportInfo.length() > 0) { REPORT_MODE = "INFO"; } if(vcfFn.length() == 0 || bedFn.length() == 0 || ofn.length() == 0) { usage(); System.exit(0); } } static void usage() { System.out.println(); System.out.println("Jasmine Overlapping"); System.out.println("Usage: overlap_jasmine [args]"); System.out.println(" Example: overlap_jasmine vcf_file=merged.vcf bed_file=regions.bed out_fie=filtered.vcf"); System.out.println(); System.out.println("Required args:"); System.out.println(" vcf_file (String) - the VCF file with merged SVs"); System.out.println(" bed_file (String) - a BED file with regions of interest"); System.out.println(" out_file (String) - the name of the output VCF filtered by regions of interest"); System.out.println(); System.out.println("Optional args:"); System.out.println(" info_report (String) [] - the INFO field to indicate presence in regions instead of removing non-overlapping variants"); System.out.println(); } public static void main(String[] args) throws Exception { parseArgs(args); Settings.DEFAULT_CHR_NORM = true; chrNorm = new ChrNameNormalization(); filterVcf(); } static ArrayList<Event> getBedEvents() throws Exception { Scanner input = new Scanner(new FileInputStream(new File(bedFn))); ArrayList<Event> events = new ArrayList<Event>(); int idNum = 0; while(input.hasNext()) { String line = input.nextLine(); if(line.startsWith("#")) { continue; } String[] tokens = line.split("\t"); String chr = tokens[0]; chr = chrNorm.normalize(chr); int start = Integer.parseInt(tokens[1]); int end = Integer.parseInt(tokens[2]); idNum++; events.add(new Event(chr, start, 1, idNum + "")); events.add(new Event(chr, end, -1, idNum + "")); } input.close(); Collections.sort(events); return events; } /* * Gets the start and end events for variants * Translocations are a special case and are broken up into two event pairs, one for each breakpoint */ static ArrayList<Event> getVcfEvents() throws Exception { Scanner input = new Scanner(new FileInputStream(new File(vcfFn))); ArrayList<Event> events = new ArrayList<Event>(); while(input.hasNext()) { String line = input.nextLine(); if(line.startsWith("#")) { continue; } VcfEntry entry = VcfEntry.fromLine(line); String chr = entry.getChromosome(); chr = chrNorm.normalize(chr); int start = (int)(entry.getPos()); int end = (int)(entry.getEnd()); String id = entry.getId(); if(entry.getNormalizedType().equals("TRA")) { events.add(new Event(chr, start, 1, id + "_breakpoint1")); events.add(new Event(chr, start+1, -1, id + "_breakpoint1")); String chr2 = entry.getChr2(); if(chr2.length() != 0) { events.add(new Event(chr2, end, 1, id + "_breakpoint2")); events.add(new Event(chr2, end + 1, -1, id + "_breakpoint2")); } } else { events.add(new Event(chr, start, 1, id)); events.add(new Event(chr, end + 1, -1, id)); } } input.close(); Collections.sort(events); return events; } /* * Gets a list of overlaps based on variant and region start and end events * For each variant, it outputs a list of the IDs of regions with which it overlaps */ static HashMap<String, HashSet<String>> getOverlaps(ArrayList<Event> regions, ArrayList<Event> variants) { // The next region and variant events to consider int regionIdx = 0, variantIdx = 0; // As we do the plane sweep, the list of regions we are currently inside, if any TreeSet<String> openRegions = new TreeSet<String>(); // The list of variant intervals we are currently inside TreeSet<String> openVariants = new TreeSet<String>(); HashMap<String, HashSet<String>> overlaps = new HashMap<String, HashSet<String>>(); // Plane sweep time! while(true) { // Stop when there are no more events if(regionIdx == regions.size() && variantIdx == variants.size()) { break; } // Whether or not the next event to process is a region event (as opposed to a variant) boolean nextEventRegion = false; // If we are out of regions, take a variant event if(regionIdx == regions.size()) { nextEventRegion = false; } // If we are out of variants, take a region event else if(variantIdx == variants.size()) { nextEventRegion = true; } // If we have both left, compare positions and choose according to overlap scheme else { Event nextRegion = regions.get(regionIdx); Event nextVariant = variants.get(variantIdx); // If region is on earlier chromosome, take that if(nextRegion.chr.compareTo(nextVariant.chr) < 0) { nextEventRegion = true; } // If region is on later chromosome, take variant else if(nextRegion.chr.compareTo(nextVariant.chr) > 0) { nextEventRegion = false; } // If region is at earlier position on same chromosome, take it else if(nextRegion.pos < nextVariant.pos) { nextEventRegion = true; } // If region is at later position on same chromosome, take variant else if(nextRegion.pos > nextVariant.pos) { nextEventRegion = false; } // Now the case where positions are the same - tie handling depends on overlap mode else if(FILTER_MODE.equalsIgnoreCase("CONTAINED_IN_REGION")) { // Order of priority is variant end, region end, region start, variant start if(nextVariant.type == 1) { nextEventRegion = false; } else { nextEventRegion = true; } } } // After deciding what kind of event to use, process it! // Case where next event is a region breakpoint if(nextEventRegion) { Event next = regions.get(regionIdx); // Start of region if(next.type == 1) { // Add to list of open regions openRegions.add(next.id); } // End of region else { // Remove from list of open regions openRegions.remove(next.id); for(String openVariant : openVariants) { if(overlaps.get(openVariant).contains(next.id)) { overlaps.get(openVariant).remove(next.id); } } } regionIdx++; } // Case where next event is a variant breakpoint else { Event next = variants.get(variantIdx); // Start of variant if(next.type == 1) { // Add to list of open variants openVariants.add(next.id); // Initialize list of overlaps to all open regions overlaps.put(next.id, new HashSet<String>()); for(String openRegion : openRegions) { overlaps.get(next.id).add(openRegion); } } // End of variant else { // Remove from list of open variants openVariants.remove(next.id); // If all overlapping regions were removed, take this out of overlap list if(overlaps.get(next.id).size() == 0) { overlaps.remove(next.id); } } variantIdx++; } } return overlaps; } static void filterVcf() throws Exception { System.err.println("Getting regions"); ArrayList<Event> bedEvents = getBedEvents(); System.err.println("Found " + bedEvents.size() + " region breakpoints"); System.err.println("Getting variants"); ArrayList<Event> vcfEvents = getVcfEvents(); System.err.println("Found " + vcfEvents.size() + " variant breakpoints"); System.err.println("Finding overlaps"); HashMap<String, HashSet<String>> overlaps = getOverlaps(bedEvents, vcfEvents); System.err.println("Found " + overlaps.size() + " variants with at least one overlap"); System.err.println("Filtering variants"); Scanner input = new Scanner(new FileInputStream(new File(vcfFn))); PrintWriter out = new PrintWriter(new File(ofn)); VcfHeader header = new VcfHeader(); boolean printedHeader = false; while(input.hasNext()) { String line = input.nextLine(); if(line.length() == 0) { continue; } if(line.startsWith("#")) { header.addLine(line); } else { if(!printedHeader) { if(REPORT_MODE.equalsIgnoreCase("INFO")) { header.addInfoField(reportInfo, "1", "String", "Whether or not the variant is in the regions of interest listed in " + bedFn); } header.print(out); printedHeader = true; } VcfEntry entry = VcfEntry.fromLine(line); String id = entry.getId(); HashSet<String> curOverlaps = overlaps.getOrDefault(id, null); boolean hasOverlap = curOverlaps != null; if(entry.getNormalizedType().equals("TRA")) { String id1 = id + "_breakpoint1", id2 = id + "_breakpoint2"; HashSet<String> firstOverlap = overlaps.getOrDefault(id1, null); HashSet<String> secondOverlap = overlaps.getOrDefault(id2, null); hasOverlap = firstOverlap != null && secondOverlap != null; } if(REPORT_MODE.equalsIgnoreCase("REMOVE")) { if(hasOverlap) { out.println(entry); } } if(REPORT_MODE.equalsIgnoreCase("INFO")) { if(hasOverlap) { entry.setInfo(reportInfo, "1"); } else { entry.setInfo(reportInfo, "0"); } out.println(entry); } } } input.close(); out.close(); } static class Event implements Comparable<Event> { String chr; int pos; int type; String id; Event(String chr, int pos, int type, String id) { this.chr = chr; this.pos = pos; this.type = type; this.id = id; } @Override public int compareTo(Event o) { if(!chr.equals(o.chr)) { return chr.compareTo(o.chr); } if(pos != o.pos) return pos - o.pos; return type - o.type; // Do ends before starts } } }
mkirsche/Jasmine
src/Overlap.java
3,355
// Case where next event is a region breakpoint
line_comment
en
false
236108_0
/* * If we took coin with value n earlier, we shall not take coin with more than n. * This is to prevent looping through the same combination again * as the sequence doesn't matter here. * The 100,50,50 is same with 50,50,100. * * * aka DFS with branch cutting. */ public class euler { public static int [] coinType={1,2,5,10,20,50,100,200}; public static int dfs (int sum, int lastPut) { if (sum==0) { return 1; } else { int count=0; for (int i=coinType.length-1;i>=0;i--) { if (lastPut>=i && sum>=coinType[i]) { count+=dfs(sum-coinType[i],i); } } return count; } } public static void main (String [] abc) { System.out.println(dfs(200,coinType.length-1)); } }
PuzzlesLab/ProjectEuler
King/031_DFS.java
276
/* * If we took coin with value n earlier, we shall not take coin with more than n. * This is to prevent looping through the same combination again * as the sequence doesn't matter here. * The 100,50,50 is same with 50,50,100. * * * aka DFS with branch cutting. */
block_comment
en
true
236191_0
/******************************************************************************* * @author Reika Kalseki * * Copyright 2013 * * All rights reserved. * Distribution of the software in any form is only allowed with * explicit, prior permission from the owner. ******************************************************************************/ package Reika.RotaryCraft.Registry; import Reika.DragonAPI.Exception.RegistrationException; import Reika.RotaryCraft.RotaryCraft; public enum Manufacturers { BEDROCKBREAKER(""), DCENGINE(""), WINDENGINE(""), STEAMENGINE(""), GASENGINE(""), ACENGINE(""), PERFENGINE(""), HYDROENGINE(""), MICROENGINE(""), JETENGINE(""); public static final Manufacturers[] list = Manufacturers.values(); private String makerName; private String desc; private Manufacturers(String n) { makerName = n; //desc = RotaryDescriptions.getPartDesc(this.ordinal()); } public static boolean hasSubMakers(MachineRegistry m) { if (m == MachineRegistry.ENGINE) return true; if (m == MachineRegistry.ADVANCEDGEARS) return true; return false; } public static Manufacturers getSpecificMaker(MachineRegistry m, int offset) { if (!hasSubMakers(m)) throw new RegistrationException(RotaryCraft.instance, "Machine "+m.getName()+" does not have sub-makers!"); if (m == MachineRegistry.ENGINE) return getEngineName(m, offset); if (m == MachineRegistry.ADVANCEDGEARS) return getAdvGearName(m, offset); return null; } private static Manufacturers getAdvGearName(MachineRegistry m, int offset) { return null; } private static Manufacturers getEngineName(MachineRegistry m, int offset) { return null; } public static Manufacturers getMaker(MachineRegistry m) { if (hasSubMakers(m)) return getSpecificMaker(m, 0); return null; } public String getName() { return makerName; } public String getPartDesc() { return desc; } }
Baughn/RotaryCraft
Registry/Manufacturers.java
544
/******************************************************************************* * @author Reika Kalseki * * Copyright 2013 * * All rights reserved. * Distribution of the software in any form is only allowed with * explicit, prior permission from the owner. ******************************************************************************/
block_comment
en
true
236195_1
/* * Copyright (C) 2015 Brian Wernick * * 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 com.devbrackets.android.exomedia.util; import android.os.Build; /** * A Utility class to help determine characteristics about the device */ public class EMDeviceUtil { private static final String[] NON_CTS_COMPLIANT_MANUFACTURERS; private static final String[] NON_CTS_COMPLIANT_DEVICES; static { NON_CTS_COMPLIANT_MANUFACTURERS = new String[] { "Amazon" }; NON_CTS_COMPLIANT_DEVICES = new String[] { }; } /** * Determines if the current device has passed the Android Compatibility Test * Suite (CTS). This will indicate if we can trust the exoPlayer to run correctly * on this device. * * @return True if the device is CTS compliant. */ public static boolean isDeviceCTSCompliant() { //Until we can find a better way to do this, we will just list the devices and manufacturers known to not follow compliance for (String manufacturer: NON_CTS_COMPLIANT_MANUFACTURERS) { if (Build.MANUFACTURER.equalsIgnoreCase(manufacturer)) { return false; } } for (String device: NON_CTS_COMPLIANT_DEVICES) { if (Build.MANUFACTURER.equalsIgnoreCase(device)) { return false; } } return true; } }
daimajia/ExoMedia
library/src/main/java/com/devbrackets/android/exomedia/util/EMDeviceUtil.java
485
/** * A Utility class to help determine characteristics about the device */
block_comment
en
true
236243_4
package sample.company; import sample.products.BasketItem; import sample.products.Item; import sample.products.OtherProducts; import sample.products.clothing.Footwear; import sample.products.clothing.Pants; import sample.products.clothing.Tshirt; import sample.products.electronics.Computer; import sample.products.electronics.Phone; import sample.products.electronics.Television; import sample.utility.Address; import sample.utility.Position; import sample.utility.Receipt; import java.io.*; import java.util.ArrayList; public class Database { //Create a company private static Company CYGCOMPANY; public Database() throws IOException { setCYGCOMPANY(new Company(2124137544, "info@cyg.com", new Address("izmir", "buca", "Atatürk Mah"))); addShops(); addEmployees(); addManufacturers(); addProducts(); loadProducts(); loadReceipt(); // //Create a item // Item item1 = new Item("Apple", "Iphone 6", 2800, manufacturer1); // Item item2 = new Item("Samsung", "S7", 2500, manufacturer2); // Item item3 = new Item("Xiaomi", "Redmi 8", 3000, manufacturer3); // Item item4 = new Item("Huawei", "P20 PRO", 2900, manufacturer3); // Item item5 = new Item("CAT", "S35", 500, manufacturer1); // // // //Items Assign to manufacturers and shops // manufacturer1.addNewItem(item1, 10); // shop1.addNewItem(item1, 10); // manufacturer2.addNewItem(item2, 5); // shop1.addNewItem(item2, 5); // manufacturer3.addNewItem(item3, 8); // shop1.addNewItem(item3, 8); // manufacturer3.addNewItem(item4, 7); // shop1.addNewItem(item4, 8); // manufacturer1.addNewItem(item5, 20); // shop1.addNewItem(item5, 20); } public static Company getCYGCOMPANY() { return CYGCOMPANY; } public static void setCYGCOMPANY(Company CYGCOMPANY) { Database.CYGCOMPANY = CYGCOMPANY; } public void addShops() throws IOException { File file = new File("src/sample/database/shop.txt"); BufferedReader br = new BufferedReader(new FileReader(file)); String st; System.out.println("-----------------SHOPS--------------------"); while ((st = br.readLine()) != null) { String[] data = st.split(","); System.out.println("------------------------------------------"); System.out.println("Name: " + data[0]); System.out.println("Phone number: " + data[1]); System.out.println("Email: " + data[2]); System.out.println("City: " + data[3]); System.out.println("Town: " + data[4]); System.out.println("Street: " + data[5]); // Creating Shop and adding into Company Shop shop = new Shop(data[0], data[1], data[2], new Address(data[3], data[4], data[5])); getCYGCOMPANY().addShop(shop); System.out.println(data[0] + " shop is added to Company"); } System.out.println("-------------SHOPS ARE ADDED--------------"); System.out.println("------------------------------------------"); } public void addEmployees() throws IOException { File file = new File("src/sample/database/employee.txt"); BufferedReader br = new BufferedReader(new FileReader(file)); String st; System.out.println("----------------EMPLOYEES-----------------"); while ((st = br.readLine()) != null) { String[] data = st.split(","); System.out.println("------------------------------------------"); System.out.println("Name: " + data[0]); System.out.println("City: " + data[1]); System.out.println("Town: " + data[2]); System.out.println("Street: " + data[3]); System.out.println("Phone number: " + data[4]); System.out.println("Weekly Work Hours: " + data[5]); System.out.println("Position Name: " + data[6]); System.out.println("Base Wage: " + data[7]); System.out.println("Shop ID: " + data[8]); System.out.println("Username: " + data[9]); System.out.println("Password: " + data[10]); System.out.println("Weekly Wage Bonus: " + data[11]); Employee employee = new Employee(data[0], new Address(data[1], data[2], data[3]), data[4], Integer.parseInt(data[5]), new Position(data[6], Integer.parseInt(data[7])), Integer.parseInt(data[8]), data[9], data[10], Integer.parseInt(data[11])); getCYGCOMPANY().addEmployee(employee); } System.out.println("----------EMPLOYEES ARE ADDED------------"); System.out.println("------------------------------------------"); } public void addManufacturers() throws IOException { File file = new File("src/sample/database/manufacturer.txt"); BufferedReader br = new BufferedReader(new FileReader(file)); String st; System.out.println("-------------MANUFACTURERS----------------"); while ((st = br.readLine()) != null) { String[] data = st.split(","); System.out.println("------------------------------------------"); System.out.println("Name: " + data[0]); System.out.println("City: " + data[1]); System.out.println("Town: " + data[2]); System.out.println("Street: " + data[3]); System.out.println("Phone number: " + data[4]); Manufacturer manufacturer = new Manufacturer(data[0], new Address(data[1], data[2], data[3]), data[4]); getCYGCOMPANY().getManufacturerArraylist().add(manufacturer); System.out.println(" Manufacturer " + data[0] + " is added to Database"); } System.out.println("--------MANUFACTURERS ARE ADDED---------"); System.out.println("------------------------------------------"); } public void addProducts() throws IOException { File file = new File("src/sample/database/product.txt"); BufferedReader br = new BufferedReader(new FileReader(file)); String st; System.out.println("---------------PRODUCTS-------------------"); while ((st = br.readLine()) != null) { String[] data = st.split(","); System.out.println("------------------------------------------"); Manufacturer manufacturer = getCYGCOMPANY().getManufacturerArraylist().get(Integer.parseInt(data[4])); switch (data[0]) { case "Footwear": Footwear footwear = new Footwear(data[1], data[2], Double.parseDouble(data[3]), manufacturer, data[5], data[6], Double.parseDouble(data[7])); getCYGCOMPANY().addItemToManufacturer(footwear, Integer.parseInt(data[4])); System.out.println(footwear.getName() + " is added to Manufacturer-" + manufacturer.getManufacturerID()); break; case "Pants": Pants pants = new Pants(data[1], data[2], Double.parseDouble(data[3]), manufacturer, data[5], data[6], Integer.parseInt(data[7]), Integer.parseInt(data[8])); getCYGCOMPANY().addItemToManufacturer(pants, Integer.parseInt(data[4])); System.out.println(pants.getName() + " is added to Manufacturer-" + manufacturer.getManufacturerID()); break; case "Tshirt": Tshirt tshirt = new Tshirt(data[1], data[2], Double.parseDouble(data[3]), manufacturer, data[5], data[6], data[7]); getCYGCOMPANY().addItemToManufacturer(tshirt, Integer.parseInt(data[4])); System.out.println(tshirt.getName() + " is added to Manufacturer-" + manufacturer.getManufacturerID()); break; case "Computer": Computer computer = new Computer(data[1], data[2], Double.parseDouble(data[3]), manufacturer, Double.parseDouble(data[5]), data[6], data[7], data[8]); getCYGCOMPANY().addItemToManufacturer(computer, Integer.parseInt(data[4])); System.out.println(computer.getName() + " is added to Manufacturer-" + manufacturer.getManufacturerID()); break; case "Phone": Phone phone = new Phone(data[1], data[2], Double.parseDouble(data[3]), manufacturer, Double.parseDouble(data[5]), data[6], data[7], data[8]); getCYGCOMPANY().addItemToManufacturer(phone, Integer.parseInt(data[4])); System.out.println(phone.getName() + " is added to Manufacturer-" + manufacturer.getManufacturerID()); break; case "Television": Television television = new Television(data[1], data[2], Double.parseDouble(data[3]), manufacturer, Double.parseDouble(data[5]), data[6], data[7]); getCYGCOMPANY().addItemToManufacturer(television, Integer.parseInt(data[4])); System.out.println(television.getName() + " is added to Manufacturer-" + manufacturer.getManufacturerID()); break; case "Misc": OtherProducts misc = new OtherProducts(data[1], data[2], Double.parseDouble(data[3]), manufacturer, data[5]); getCYGCOMPANY().addItemToManufacturer(misc, Integer.parseInt(data[4])); System.out.println(misc.getName() + " is added to Manufacturer-" + manufacturer.getManufacturerID()); break; } } System.out.println("----------PRODUCTS ARE ADDED------------"); System.out.println("------------------------------------------"); } public void loadProducts() throws IOException { File file = new File("src/sample/database/productInShop.txt"); BufferedReader br = new BufferedReader(new FileReader(file)); String st; while ((st = br.readLine()) != null) { String[] data = st.split(","); Item tempItem = getCYGCOMPANY().getManufacturerArraylist().get(Integer.parseInt(data[0])).getItemBag().get(Integer.parseInt(data[2])); getCYGCOMPANY().getShopList().get(Integer.parseInt(data[1])).addNewItem(tempItem, Integer.parseInt(data[3])); System.out.println(tempItem.getName()); } System.out.println("----------PRODUCTS ARE READED------------"); System.out.println("------------------------------------------"); } public void saveProducts() throws IOException { FileWriter file = new FileWriter("src/sample/database/productInShop.txt"); String data = ""; for (Shop shop : CYGCOMPANY.getShopList()) { for (Item item : shop.getItemBag().values()) { data += item.getManufacturer().getManufacturerID() + "," + shop.getShopID() + "," + item.getItemID() + "," + shop.getItemQuantity().get(item.getItemID()) + "\n"; } } file.write(data); file.close(); System.out.println("----------PRODUCTS ARE SAVED------------"); System.out.println("------------------------------------------"); } public void saveManufacturers() throws IOException { FileWriter file = new FileWriter("src/sample/database/manufacturer.txt"); String data = ""; for (Manufacturer manufacturer : CYGCOMPANY.getManufacturerArraylist()) { data += manufacturer.getName() + "," + manufacturer.getAddress().getCity() + "," + manufacturer.getAddress().getTown() + "," + manufacturer.getAddress().getStreet() + "," + manufacturer.getPhoneNumber() + "\n"; } file.write(data); file.close(); System.out.println("----------MANUFACTURERS ARE SAVED------------"); System.out.println("------------------------------------------"); } public void saveEmployee() throws IOException { FileWriter file = new FileWriter("src/sample/database/employee.txt"); String data = ""; for (Employee employee : CYGCOMPANY.getEmployeeList()) { data += employee.getName() + "," + employee.getAddress().getCity() + "," + employee.getAddress().getTown() + "," + employee.getAddress().getStreet() + "," + employee.getPhoneNumber() + "," + employee.getWeeklyWorkHours() + "," + employee.getPosition().getPositionName() + "," + employee.getPosition().getBaseWage() + "," + employee.getShopID() + "," + employee.getUsername() + "," + employee.getPassword() + "," + employee.getWeeklyWageBonus() + "\n"; } file.write(data); file.close(); System.out.println("----------EMPLOYEE ARE SAVED------------"); System.out.println("------------------------------------------"); } public void saveShop() throws IOException { FileWriter file = new FileWriter("src/sample/database/shop.txt"); String data = ""; for (Shop shop : CYGCOMPANY.getShopList()) { data += shop.getName() + "," + shop.getPhoneNumber() + "," + shop.getEmailAddress() + "," + shop.getAddress().getCity() + "," + shop.getAddress().getTown() + "," + shop.getAddress().getStreet() + "\n"; } file.write(data); file.close(); System.out.println("----------SHOP ARE SAVED------------"); System.out.println("------------------------------------------"); } public void saveReceipt() throws IOException { FileWriter file = new FileWriter("src/sample/database/receipt.txt"); String data = ""; String dataBasketItems = ""; for (Shop shop : CYGCOMPANY.getShopList()) { int n = shop.getReceiptHashMap().size(); for (int i = 0; i < n; i++) { Receipt receipt = shop.getReceiptHashMap().get(i); for (int j = 0; j < receipt.getCart().size(); j++) { if (j == receipt.getCart().size() - 1) { dataBasketItems += receipt.getCart().get(j).getItemID() + "-" + receipt.getCart().get(j).getName() + "-" + receipt.getCart().get(j).getQuantity() + "-" + receipt.getCart().get(j).getPrice() + "-" + receipt.getCart().get(j).getTotal(); } else { dataBasketItems += receipt.getCart().get(j).getItemID() + "-" + receipt.getCart().get(j).getName() + "-" + receipt.getCart().get(j).getQuantity() + "-" + receipt.getCart().get(j).getPrice() + "-" + receipt.getCart().get(j).getTotal() + ":"; } } data += i + "," + shop.getShopID() + "," + receipt.getDate() + "," + receipt.getTotalPrice() + "," + receipt.getCashier().getEmployeeID() + "," + dataBasketItems + "\n"; dataBasketItems =""; } } file.write(data); file.close(); System.out.println("----------RECEIPT ARE SAVED------------"); System.out.println("------------------------------------------"); } public void loadReceipt() throws IOException { File file = new File("src/sample/database/receipt.txt"); BufferedReader br = new BufferedReader(new FileReader(file)); String st; ArrayList<BasketItem> basketItems = new ArrayList<>(); while ((st = br.readLine()) != null) { String[] data = st.split(","); Shop shop = CYGCOMPANY.getShopList().get(Integer.parseInt(data[1])); basketItems.clear(); for (String tempBasketItem : data[5].split(":")) { String[] temp = tempBasketItem.split("-"); basketItems.add(new BasketItem(Integer.parseInt(temp[0]), temp[1], Integer.parseInt(temp[2]), Double.parseDouble(temp[3]), Double.parseDouble(temp[4]))); } //ArrayList<BasketItem> items, double totalPrice, Employee employee shop.sellItem(basketItems, CYGCOMPANY.getEmployeeList().get(Integer.parseInt(data[4]))); } System.out.println("----------RECEIPT ARE READED------------"); System.out.println("------------------------------------------"); } }
gokselelpeze/Retail-Management-System
src/sample/company/Database.java
3,986
// Item item3 = new Item("Xiaomi", "Redmi 8", 3000, manufacturer3);
line_comment
en
true
236425_0
package classical; /** * @author Kunal * */ import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.io.PrintWriter; import java.util.Arrays; import java.util.StringTokenizer; public class AGGRCOW { public static void main(String[] args) { InputReader in = new InputReader(); PrintWriter out = new PrintWriter(System.out); final long start = System.currentTimeMillis(); Task1 solver = new Task1(); solver.solve(in, out); @SuppressWarnings("unused") final long duration = System.currentTimeMillis() - start; out.close(); } static class Task1 { public void solve(InputReader in, PrintWriter out) { int t = in.nextInt(); while(t-->0){ int n = in.nextInt(), c = in.nextInt(); int[] stalls = new int[n]; for(int i=0; i<n; i++){ stalls[i] = in.nextInt(); } Arrays.sort(stalls); int lo = stalls[0], hi = stalls[n-1], mid = 0; while(lo<=hi){ mid = lo+(hi-lo)/2; //out.println(lo+" "+mid+" "+hi); int curr = 0, stock = c-1; for(int i=0; i<n && stock>0; i++){ if(stalls[i]-stalls[curr] >= mid){ curr = i; stock--; } } if(stock==0){ lo = mid+1; } else { hi = mid-1; } } out.println(hi); } } } static class InputReader { public BufferedReader reader; public StringTokenizer tokenizer; public InputReader() { reader = new BufferedReader(new InputStreamReader(System.in)); tokenizer = null; } public String next() { while (tokenizer == null || !tokenizer.hasMoreTokens()) { try { tokenizer = new StringTokenizer(reader.readLine()); } catch (IOException e) { throw new RuntimeException(e); } } return tokenizer.nextToken(); } public int nextInt() { return Integer.parseInt(next()); } public long nextLong() { return Long.parseLong(next()); } public double nextDouble() { return Double.parseDouble(next()); } } }
kc596/eclipse-java
SPOJ/src/classical/AGGRCOW.java
647
/** * @author Kunal * */
block_comment
en
true
236444_0
package Classical; import java.io.PrintWriter; import java.io.File; import java.io.FileReader; import java.io.FileNotFoundException; import java.io.InputStream; import java.io.InputStreamReader; import java.io.IOException; import java.io.OutputStream; import java.io.Writer; import java.io.BufferedReader; import java.util.StringTokenizer; import java.util.ArrayList; import java.util.Collections; /** * * @author sagarjauhari@gmail.com * */ class AE1B { String PROB_NAME = ""; String TEST_NAME = "input00.txt"; InputScanner i_scan; OutputWriter o_writ; Boolean is_debug = false; long start_time = 0; long end_time = 0; public static void main(String[] args) { AE1B program = new AE1B(args); program.begin(); program.end(); } public void begin() { int n = i_scan.nextInt(); int k = i_scan.nextInt(); int s = i_scan.nextInt(); int target_screws = k*s; int screws_so_far = 0; ArrayList<Integer> list = new ArrayList<Integer>(); for (int cases = 0; cases < n; cases++){ list.add(i_scan.nextInt()); } Collections.sort(list); Collections.reverse(list); int i = 0; for(; i<list.size(); i++){ if(screws_so_far>=target_screws) break; screws_so_far+=list.get(i); } o_writ.printLine(i); } public AE1B(String[] args) { if (args.length > 0 && args[0].equals("Test")) { i_scan = new InputScanner(new File( "/home/sagar/code_arena/Eclipse Workspace/InterviewStr/inputs/" + PROB_NAME + "/"+TEST_NAME)); } else { i_scan = new InputScanner(System.in); } o_writ = new OutputWriter(System.out); if (is_debug) { start_time = System.currentTimeMillis(); } } public void end() { if (is_debug) { end_time = System.currentTimeMillis(); o_writ.printLine("Time (milisec): " + (end_time - start_time)); } o_writ.close(); } class InputScanner { private final BufferedReader br; StringTokenizer tokenizer; public InputScanner(InputStream stream) { br = new BufferedReader(new InputStreamReader(stream)); } public InputScanner(File file) { try { br = new BufferedReader(new FileReader(file)); } catch (FileNotFoundException e) { throw new RuntimeException(e); } } public String next() { while (tokenizer == null || !tokenizer.hasMoreTokens()) { try { tokenizer = new StringTokenizer(br.readLine()); } catch (IOException e) { throw new RuntimeException(e); } } return tokenizer.nextToken(); } public int nextInt() { int num; try { num = Integer.parseInt(next()); } catch (NumberFormatException e) { throw new RuntimeException(e); } return num; } public float nextFloat(){ float num; try{ num = Float.parseFloat(next()); }catch(NumberFormatException e){ throw new RuntimeException(e); } return num; } public String nextLine() { while (tokenizer == null || !tokenizer.hasMoreTokens()) { try { tokenizer = new StringTokenizer(br.readLine()); } catch (IOException e) { throw new RuntimeException(e); } } return tokenizer.nextToken("\n").trim(); } } class OutputWriter { private final PrintWriter pw; public OutputWriter(OutputStream op) { pw = new PrintWriter(op); } public OutputWriter(Writer writer) { pw = new PrintWriter(writer); } public void print(Object... objects) { for (int i = 0; i < objects.length; i++) { if (i != 0) pw.print(' '); pw.print(objects[i]); } } public void printLine(Object... objects) { print(objects); pw.println(); } public void close() { pw.close(); } } }
sagarjauhari/spoj
src/Classical/AE1B.java
1,056
/** * * @author sagarjauhari@gmail.com * */
block_comment
en
true
237509_19
package Replica2; import java.text.SimpleDateFormat; import java.util.Date; import java.util.Scanner; /** * author: Team 22 */ public class Constant { public static final String SERVER_ATWATER = "ATWATER"; public static final String SERVER_VERDUN = "VERDUN"; public static final String SERVER_OUTREMONT = "OUTREMONT"; public static final int USER_TYPE_CUSTOMER = 1; public static final int USER_TYPE_ADMIN = 2; public static final String MOVIE_AVTAR = "Avtar"; public static final String MOVIE_AVENGER = "Avenger"; public static final String MOVIE_TITANIC = "Titanic"; public static final int ATWATER_REGISTRY_PORT = 2964; public static final int VERDUN_REGISTRY_PORT = 2965; public static final int OUTREMONT_REGISTRY_PORT = 2966; public static final int ATWATER_SERVER_PORT = 8888; public static final int VERDUN_SERVER_PORT = 7777; public static final int OUTREMONT_SERVER_PORT = 6666; public static final String MOVIE_MANAGEMENT_REGISTERED_NAME= "MovieS"; public static final int CUSTOMER_BOOK_MOVIE = 1; public static final int CUSTOMER_GET_BOOKING_SCHEDULE = 2; public static final int CUSTOMER_CANCEL_MOVIE = 3; public static final int CUSTOMER_EXCHANGE_TICKET = 4; public static final int CUSTOMER_LOGOUT = 5; public static final int ADMIN_ADD_MOVIE = 1; public static final int ADMIN_REMOVE_MOVIE = 2; public static final int ADMIN_LIST_MOVIE_AVAILABILITY = 3; public static final int ADMIN_BOOK_MOVIE = 4; public static final int ADMIN_GET_BOOKING_SCHEDULE = 5; public static final int ADMIN_CANCEL_MOVIE = 6; public static final int ADMIN_LOGOUT = 8; public static final int ADMIN_EXCHANGE_TICKET = 7; public static final int SHUTDOWN =0; public static final String SHOW_TIME_MORNING = "Morning"; public static final String SHOW_TIME_AFTERNOON = "Afternoon"; public static final String SHOW_TIME_EVENING = "Evening"; public static final int SHOW_FULL_FLAG = -1; public static final int ALREADY_BOOKED_FLAG = 0; public static final int ADD_SUCCESS_FLAG = 1; public static final int LOG_TYPE_SERVER = 1; public static final int LOG_TYPE_CLIENT = 0; /** * * @param movieID * @return */ public static String detectServer(String movieID) { if (movieID.substring(0, 3).equalsIgnoreCase("ATW")) { return SERVER_ATWATER; } else if (movieID.substring(0, 3).equalsIgnoreCase("VER")) { //return MovieManagement.THEATER_SERVER_VERDUN; return SERVER_VERDUN; } else { return SERVER_OUTREMONT; //return MovieManagement.THEATER_SERVER_OUTREMONT; } } /** * * @param movieID * @return */ public static String identifyMovieTimeSlot(String movieID) { if (movieID.substring(3, 4).equalsIgnoreCase("M")) { return SHOW_TIME_MORNING; } else if (movieID.substring(3, 4).equalsIgnoreCase("A")) { return SHOW_TIME_AFTERNOON; } else { return SHOW_TIME_EVENING; } } /** * * @param movieID * @return */ public static String identifyMovieDate(String movieID) { return movieID.substring(4, 6) + "/" + movieID.substring(6, 8) + "/20" + movieID.substring(8, 10); } /** * * @param branchAcronym * @return */ public static int getServerPort(String branchAcronym) { if (branchAcronym.equalsIgnoreCase("ATW")) { return ATWATER_REGISTRY_PORT; } else if (branchAcronym.equalsIgnoreCase("VER")) { return VERDUN_REGISTRY_PORT; } else if (branchAcronym.equalsIgnoreCase("OUT")) { return OUTREMONT_REGISTRY_PORT; } return 1; } /** * * @param movieID * @return */ public static int getUDPServerPort(String movieID) { if (movieID.equalsIgnoreCase("ATW")) { return ATWATER_SERVER_PORT; } else if (movieID.equalsIgnoreCase("VER")) { return VERDUN_SERVER_PORT; } else if (movieID.equalsIgnoreCase("OUT")) { return OUTREMONT_SERVER_PORT; } return 1; } /** * * @param movieDate * @return */ public static boolean isMovieDateWithinOneWeek(String movieDate) { try { String d = movieDate.substring(0,2) + "/"+movieDate.substring(2,4)+"/"+movieDate.substring(4); Date movieDateObj = new SimpleDateFormat("dd/MM/yy").parse(d); Date currentDate = new Date(); long diff = movieDateObj.getTime() - currentDate.getTime(); long diffDays = diff / (24 * 60 * 60 * 1000); return diffDays < 7 & diffDays>=0 ? true : false; } catch (Exception e) { //System.out.println("Exception in isMovieDateWithinOneWeek: " + e.getMessage()); return false; } } /** * * @param userID * @return */ public static int checkUserType(String userID) { if (userID.length() == 8) { if (userID.substring(0, 3).equalsIgnoreCase("ATW") || userID.substring(0, 3).equalsIgnoreCase("VER") || userID.substring(0, 3).equalsIgnoreCase("OUT")) { if (userID.substring(3, 4).equalsIgnoreCase("C")) { return USER_TYPE_CUSTOMER; } else if (userID.substring(3, 4).equalsIgnoreCase("A")) { return USER_TYPE_ADMIN; } } } return 0; } /** * * @param branchAcronym * @param sc * @return */ public static String askForCustomerIDFromManager(String branchAcronym,Scanner sc) { System.out.println("Please enter a customerID(Within " + branchAcronym + " Server):"); String userID = sc.next().trim().toUpperCase(); if (checkUserType(userID) != USER_TYPE_CUSTOMER || !userID.substring(0, 3).equals(branchAcronym)) { return askForCustomerIDFromManager(branchAcronym,sc); } else { return userID; } } /** * * @param userType */ public static void printMenu(int userType) { System.out.println("*************************************"); System.out.println("Please choose an option below:"); if (userType == USER_TYPE_CUSTOMER) { System.out.println("1.Book Movie Show"); System.out.println("2.Get Booking Schedule"); System.out.println("3.Cancel Movie Show"); System.out.println("4.Exchange MovieTicket"); System.out.println("5.Logout"); System.out.println("0.Shut Down of CORBA"); } else if (userType == USER_TYPE_ADMIN) { System.out.println("1.Add Movie Slot"); System.out.println("2.Remove Movie Slot"); System.out.println("3.List Movie Shows Availability"); System.out.println("4.Book Movie Show"); System.out.println("5.Get Booking Schedule"); System.out.println("6.Cancel Movie Show"); System.out.println("7.Exchange MovieTicket"); System.out.println("8.Logout"); System.out.println("0.Shut Down of CORBA"); } } /** * * @param sc * @return */ public static String promptForMovieName(Scanner sc) { System.out.println("*************************************"); System.out.println("Please choose an Movie Name below:"); System.out.println("1.Avtar"); System.out.println("2.Avenger"); System.out.println("3.Titanic"); switch (sc.next()) { case "1": return MOVIE_AVTAR; case "2": return MOVIE_AVENGER; case "3": return MOVIE_TITANIC; default: System.out.println("Invalid Choice"); } return promptForMovieName(sc); } /** * * @param sc * @return */ public static String promptForMovieID(Scanner sc) { System.out.println("*************************************"); System.out.println("Please enter the MovieID in valid format (e.g ATWM130223)"); String movieID = sc.next().trim().toUpperCase(); if (movieID.length() == 10) { if (movieID.substring(0, 3).equalsIgnoreCase("ATW") || movieID.substring(0, 3).equalsIgnoreCase("VER") || movieID.substring(0, 3).equalsIgnoreCase("OUT")) { if (movieID.substring(3, 4).equalsIgnoreCase("M") || movieID.substring(3, 4).equalsIgnoreCase("A") || movieID.substring(3, 4).equalsIgnoreCase("E")) { return movieID; } } } return promptForMovieID(sc); } /** * * @param userID * @return */ public static String getServerID(String userID) { String branchAcronym = userID.substring(0, 3); if (branchAcronym.equalsIgnoreCase("ATW")) { return branchAcronym; } else if (branchAcronym.equalsIgnoreCase("VER")) { return branchAcronym; } else if (branchAcronym.equalsIgnoreCase("OUT")) { return branchAcronym; } return "1"; } /** * * @param sc * @return */ public static int promptForCapacity(Scanner sc) { System.out.println("*************************************"); System.out.println("Please enter the booking capacity:"); return sc.nextInt(); } /** * * @param sc * @return */ public static int promptForTicketsCount(Scanner sc) { System.out.println("*************************************"); System.out.println("Please enter the number of Tickets:"); return sc.nextInt(); } /** * * @param newMovieDate * @param movieID * @return */ public static boolean onTheSameWeek(String newMovieDate, String movieID) { if (movieID.substring(6, 8).equals(newMovieDate.substring(2, 4)) && movieID.substring(8, 10).equals(newMovieDate.substring(4, 6))) { int week1 = Integer.parseInt(movieID.substring(4, 6)) / 7; int week2 = Integer.parseInt(newMovieDate.substring(0, 2)) / 7; // int diff = Math.abs(day2 - day1); return week1 == week2; } else { return false; } } }
zadfiya/DistributedTheaterHA-SCR
src/Replica2/Constant.java
2,727
// int diff = Math.abs(day2 - day1);
line_comment
en
true
237688_0
import java.util.Scanner; public class Nuclear{ public static boolean no_decay(double chance_of_decay){ return ( Math.random() > chance_of_decay); //This method will return "true" if the isotope survives and "false if it decays. //Decay occurs if the random number 0 to 1 is greater than chance. //The input "chance" is the probability of decay per iteration } public static void main(String[] args){ Scanner scan = new Scanner(System.in); int N; //set the initial number of atoms System.out.println( "input N, the initial number of atoms."); N = scan.nextInt(); int survive; // this is a temporary variable to count the number of survivors per iteration double prob; // this is the chance of decay process happening for an atom each iteration System.out.println( "input P, the probability of decay."); prob = scan.nextDouble(); int steps=0; StdDraw.setXscale( 0. , 8.0 / prob); StdDraw.setYscale(0. , (float) N ); while(N>0){ System.out.print( N + " "); StdDraw.point((double) steps , (float) N ); survive = 0; steps++; for(int i=0; i<N; i++){ if( no_decay( prob) ){ survive++; } } StdDraw.line( steps -1,N,steps,survive); N=survive; } System.out.print( "0"+ "\nThe number of time steps was " + steps + "\n"); } }
TaeyoungLeeJack/decay_sim
Nuclear.java
393
//This method will return "true" if the isotope survives and "false if it decays.
line_comment
en
false
237739_0
package ic2.api; import java.lang.reflect.Field; public class IC2Reactor { private static Field energyGeneratorNuclear; public static int getEUOutput() { try { if (energyGeneratorNuclear == null) energyGeneratorNuclear = Class.forName(getPackage() + ".core.IC2").getDeclaredField("energyGeneratorNuclear"); return energyGeneratorNuclear.getInt(null); } catch (Throwable e) { throw new RuntimeException(e); } } /** * Get the base IC2 package name, used internally. * * @return IC2 package name, if unable to be determined defaults to ic2 */ private static String getPackage() { Package pkg = IC2Reactor.class.getPackage(); if (pkg != null) return pkg.getName().substring(0, pkg.getName().lastIndexOf('.')); else return "ic2"; } }
stevebest/OpenCCSensors
src/ic2/api/IC2Reactor.java
221
/** * Get the base IC2 package name, used internally. * * @return IC2 package name, if unable to be determined defaults to ic2 */
block_comment
en
true
237820_5
package Server; /** * Server/TaxesPOA.java . * Generated by the IDL-to-Java compiler (portable), version "3.2" * from Taxes.idl * Sunday, April 26, 2020 4:23:58 PM EDT */ public abstract class TaxesPOA extends org.omg.PortableServer.Servant implements Server.TaxesOperations, org.omg.CORBA.portable.InvokeHandler { // Constructors private static java.util.Hashtable _methods = new java.util.Hashtable (); static { _methods.put ("calculateTax", new java.lang.Integer (0)); _methods.put ("shutdown", new java.lang.Integer (1)); } public org.omg.CORBA.portable.OutputStream _invoke (String $method, org.omg.CORBA.portable.InputStream in, org.omg.CORBA.portable.ResponseHandler $rh) { org.omg.CORBA.portable.OutputStream out = null; java.lang.Integer __method = (java.lang.Integer)_methods.get ($method); if (__method == null) throw new org.omg.CORBA.BAD_OPERATION (0, org.omg.CORBA.CompletionStatus.COMPLETED_MAYBE); switch (__method.intValue ()) { case 0: // Server/Taxes/calculateTax { double salary = in.read_double (); double taxRate = in.read_double (); String $result = null; $result = this.calculateTax (salary, taxRate); out = $rh.createReply(); out.write_string ($result); break; } case 1: // Server/Taxes/shutdown { this.shutdown (); out = $rh.createReply(); break; } default: throw new org.omg.CORBA.BAD_OPERATION (0, org.omg.CORBA.CompletionStatus.COMPLETED_MAYBE); } return out; } // _invoke // Type-specific CORBA::Object operations private static String[] __ids = { "IDL:Server/Taxes:1.0"}; public String[] _all_interfaces (org.omg.PortableServer.POA poa, byte[] objectId) { return (String[])__ids.clone (); } public Taxes _this() { return TaxesHelper.narrow( super._this_object()); } public Taxes _this(org.omg.CORBA.ORB orb) { return TaxesHelper.narrow( super._this_object(orb)); } } // class TaxesPOA
jacobcoughenour/Project2-Corba
src/Server/TaxesPOA.java
614
// Type-specific CORBA::Object operations
line_comment
en
true
237878_0
package cp213; import java.awt.Font; import java.math.*; import java.awt.Graphics; import java.awt.Graphics2D; import java.awt.print.PageFormat; import java.awt.print.Printable; import java.awt.print.PrinterException; import java.math.BigDecimal; import java.util.HashMap; import java.util.Map; /** * Stores a HashMap of MenuItem objects and the quantity of each MenuItem * ordered. Each MenuItem may appear only once in the HashMap. * * @author Vicky Sekhon * @author Abdul-Rahman Mawlood-Yunis * @author David Brown * @version 2023-09-06 */ public class Order implements Printable { public static final BigDecimal TAX_RATE = new BigDecimal(0.13); private static final String itemFormat = "%-20s %s @ $ %.2f = $ %.2f %n"; // your code here // create hash map (holds item and quantity) HashMap<MenuItem, Integer> items = new HashMap<>(); /** * Increments the quantity of a particular MenuItem in an Order with a new * quantity. If the MenuItem is not in the order, it is added. * * @param item The MenuItem to purchase - the HashMap key. * @param quantity The number of the MenuItem to purchase - the HashMap value. */ public void add(final MenuItem item, final int quantity) { // your code here // check if item already exists in order if (items.containsKey(item)) { this.update(item, quantity); } else { // quantity is greater than 0 if (quantity > 0) { items.put(item, quantity); // quantity is 0 } else { items.remove(item); } } } /** * Removes an item from an order entirely. * * @param item The MenuItem to completely remove. */ public void removeAll(final MenuItem item) { items.remove(item); } /** * Calculates the total value of all MenuItems and their quantities in the * HashMap. * * @return the total price for the MenuItems ordered. */ public BigDecimal getSubTotal() { // your code here BigDecimal subTotal = BigDecimal.ZERO; // iterate through the hash map for (Map.Entry<MenuItem, Integer> entry : items.entrySet()) { // run "get" to find the item name and based on that, do menuitem.getPrice() BigDecimal itemPrice = entry.getKey().getPrice(); // run "get" to find the item quantity int quantity = entry.getValue(); // multiply price x quantity and add it the running total subTotal = subTotal.add(itemPrice.multiply(BigDecimal.valueOf(quantity))); } return subTotal; } /** * Calculates and returns the total taxes to apply to the subtotal of all * MenuItems in the order. Tax rate is TAX_RATE. * * @return total taxes on all MenuItems */ public BigDecimal getTaxes() { // your code here BigDecimal tax = BigDecimal.ZERO; MathContext m = new MathContext(2); tax = this.getSubTotal().multiply(TAX_RATE).round(m); return tax; } /** * Calculates and returns the total price of all MenuItems order, including tax. * * @return total price */ public BigDecimal getTotal() { // your code here BigDecimal subTot = BigDecimal.ZERO; subTot = this.getSubTotal().add(this.getTaxes()); return subTot; } /* * Implements the Printable interface print method. Prints lines to a Graphics2D * object using the drawString method. Prints the current contents of the Order. */ @Override public int print(final Graphics graphics, final PageFormat pageFormat, final int pageIndex) throws PrinterException { int result = PAGE_EXISTS; if (pageIndex == 0) { final Graphics2D g2d = (Graphics2D) graphics; g2d.setFont(new Font("MONOSPACED", Font.PLAIN, 12)); g2d.translate(pageFormat.getImageableX(), pageFormat.getImageableY()); // Now we perform our rendering final String[] lines = this.toString().split("\n"); int y = 100; final int inc = 12; for (final String line : lines) { g2d.drawString(line, 100, y); y += inc; } } else { result = NO_SUCH_PAGE; } return result; } /** * Returns a String version of a receipt for all the MenuItems in the order. */ @Override public String toString() { // your code here String format = ""; for (Map.Entry<MenuItem, Integer> entry : items.entrySet()) { MenuItem menuItem = entry.getKey(); int quantity = entry.getValue(); String name = entry.getKey().getName(); BigDecimal price = entry.getKey().getPrice(); BigDecimal totalPrice = menuItem.getPrice().multiply(BigDecimal.valueOf(quantity)); // return formatted output containing details about customer order format += String.format(itemFormat, name, quantity, price, totalPrice); } // create payment section format += String.format("Subtotal: $%6.2f %n", this.getSubTotal()); format += String.format("Taxes: $%6.2f %n", this.getTaxes()); format += String.format("Total: $%6.2f %n", this.getTotal()); return format; } /** * Replaces the quantity of a particular MenuItem in an Order with a new * quantity. If the MenuItem is not in the order, it is added. If quantity is 0 * or negative, the MenuItem is removed from the Order. * * @param item The MenuItem to update * @param quantity The quantity to apply to item */ public void update(final MenuItem item, final int quantity) { // your code here if (quantity > 0) { int currentItemQuantity = items.get(item); // update quantity items.put(item, currentItemQuantity+quantity); } else { // remove item from hashmap items.remove(item); } } }
VickySekhon/cp213
GUI/Order.java
1,531
/** * Stores a HashMap of MenuItem objects and the quantity of each MenuItem * ordered. Each MenuItem may appear only once in the HashMap. * * @author Vicky Sekhon * @author Abdul-Rahman Mawlood-Yunis * @author David Brown * @version 2023-09-06 */
block_comment
en
false
238107_0
import java.io.*; import java.sql.CallableStatement; import java.sql.Connection; import java.sql.DriverManager; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; import java.sql.Statement; import java.util.Scanner; import java.util.concurrent.Callable; public class CriminalData { Connection connection; public CriminalData(Connection connection){ this.connection = connection; } private void display(){ System.out.println("1. Add criminal Record "); System.out.println("2. Fetch Information of criminal"); System.out.println("3. Go back to main dashboard"); } private void fetchCriminalRecord(String cid){ // fetch information from table using connection try{ Statement stmt = connection.createStatement(); System.out.println("Fetching records with condition..."); String sql = "SELECT * FROM criminal WHERE criminal_id = '" + cid + "'"; ResultSet rs = stmt.executeQuery(sql); rs = stmt.executeQuery(sql); while(rs.next()){ //Display values System.out.print("ID: " + rs.getString("criminal_id")); System.out.print(", First Name: " + rs.getString("first_name")); System.out.print(", Last Name: " + rs.getString("last_name")); System.out.print(", Gender: " + rs.getString("gender")); System.out.print(", Age: " + rs.getString("age")); System.out.print(", Address: " + rs.getString("criminal_address")); System.out.println(", District: " + rs.getString("district")); } rs.close(); } catch(SQLException e){ System.err.println(e.getMessage()); } return; } private void addCriminalRecord(){ // add criminal Information in Criminal Table using Connection // add case information in Cases Table // use attributes for taking input Scanner sc = new Scanner(System.in); System.out.println("Enter Criminal ID :"); String criminal_id = sc.nextLine(); System.out.println("Enter First name :"); String first_name = sc.nextLine(); System.out.println("Enter Last name :"); String last_name = sc.nextLine(); System.out.println("Enter gender (M/F) :"); String gender = sc.nextLine(); System.out.println("Enter age :"); int age = sc.nextInt(); sc.nextLine(); System.out.println("Enter Criminal Address :"); String criminal_address = sc.nextLine(); System.out.println("Enter District :"); String district = sc.nextLine(); System.out.println("Enter Jail ID :"); int jailid = sc.nextInt(); System.out.println("Enter Case ID :"); int caseid = sc.nextInt(); System.out.println("Enter the suspect ID :"); int suspect_id = sc.nextInt(); try{ System.out.println("Inserting records into the table..."); String sql = "{CALL add_criminal(?,?,?,?,?,?,?,?,?)}"; CallableStatement cs = connection.prepareCall(sql); cs.setString(1, criminal_id); cs.setString(2, first_name); cs.setString(3, last_name); cs.setString(4, gender); cs.setInt(5, age); cs.setString(6, criminal_address); cs.setString(7, district); cs.setInt(8, caseid); cs.setInt(9, suspect_id); cs.execute(); sql = "{CALL add_jailLog(?,?)}"; cs = connection.prepareCall(sql); cs.setInt(1, jailid); cs.setString(2, criminal_id); cs.execute(); System.out.println("Inserted record into the table..."); } catch(SQLException e){ System.err.println(e.getMessage()); } // sc.close(); return; // officer-in-charge must exist // case must be filed already // verdict in courtHearing must be } public void runClass(){ Scanner cin = new Scanner(System.in); while(true){ display(); int option = cin.nextInt(); cin.nextLine(); if(option == 1){ addCriminalRecord(); }else if(option == 2){ System.out.println("Enter criminal id : "); // cin.nextLine(); String criminal_id = cin.nextLine(); fetchCriminalRecord(criminal_id); }else if(option == 3){ System.out.println("Going back to Main dashboard!!"); break; }else{ System.out.println("Wrong option selected"); } } // cin.close(); } }
AdiG-iitrpr/CriminalRecordManagementSystem
java/src/CriminalData.java
1,149
// fetch information from table using connection
line_comment
en
false
238121_0
package game.utils; import com.badlogic.gdx.Gdx; import com.badlogic.gdx.graphics.Color; import com.badlogic.gdx.graphics.Texture; import com.badlogic.gdx.graphics.g2d.BitmapFont; import com.badlogic.gdx.graphics.g2d.GlyphLayout; import com.badlogic.gdx.graphics.g2d.freetype.FreeTypeFontGenerator; import com.badlogic.gdx.graphics.g2d.freetype.FreeTypeFontGenerator.FreeTypeFontParameter; import static game.systems.render.world.RenderingSystem.SCALE; public class Fonts { public static final BitmapFont WHITE_FONT; public static final BitmapFont WHITE_FONT_WITH_BORDER; public static final BitmapFont CONSOLE_FONT; public static final BitmapFont GM_NAME_FONT; public static final BitmapFont NEWBIE_NAME_FONT; public static final BitmapFont CITIZEN_NAME_FONT; public static final BitmapFont CRIMINAL_NAME_FONT; public static final BitmapFont DIALOG_FONT; public static final BitmapFont MAGIC_FONT; public static final BitmapFont ENERGY_FONT; public static final BitmapFont WRITING_FONT; public static final BitmapFont STAB_FONT; public static final BitmapFont COMBAT_FONT; public static final BitmapFont MAGIC_COMBAT_FONT; public static final BitmapFont CLAN_FONT; public static final GlyphLayout layout = new GlyphLayout(); public static final GlyphLayout dialogLayout = new GlyphLayout(); private static final String COMMODORE_FONT = "Commodore Rounded v1.2.ttf"; private static final String FIRA_FONT = "FuraMono-Bold Powerline.otf"; static { WHITE_FONT = gui(Color.WHITE, 5, Color.BLACK, 0, 0, 0, COMMODORE_FONT); WHITE_FONT_WITH_BORDER = gui(Color.WHITE, 6, Color.BLACK, 0, 1, 0, COMMODORE_FONT); CONSOLE_FONT = gui(Color.WHITE, 8, Color.BLACK, 0, 0, 0, COMMODORE_FONT); GM_NAME_FONT = generate(Colors.GM, 9, Color.BLACK, 0, 1, -1, COMMODORE_FONT); NEWBIE_NAME_FONT = generate(Colors.NEWBIE, 9, Color.BLACK, 0, 1, -1, COMMODORE_FONT); CITIZEN_NAME_FONT = generate(Colors.CITIZEN, 9, Color.BLACK, 0, 1, -1, COMMODORE_FONT); CRIMINAL_NAME_FONT = generate(Colors.CRIMINAL, 9, Color.BLACK, 0, 1, -1, COMMODORE_FONT); CLAN_FONT = generate(Colors.GREY, 9, Color.BLACK, 0, 1, -1, COMMODORE_FONT); DIALOG_FONT = generate(Color.WHITE, 9, Color.BLACK, 0, 1, -1, COMMODORE_FONT); MAGIC_FONT = generate(Colors.MANA, 9, Color.BLACK, 0, 1, -1, COMMODORE_FONT); ENERGY_FONT = generate(Colors.YELLOW, 9, Color.BLACK, 0, 1, -1, COMMODORE_FONT); WRITING_FONT = generate(Color.BLACK, 6, Color.WHITE, 1, 0, -2, COMMODORE_FONT); COMBAT_FONT = generate(Colors.COMBAT, 9, Color.BLACK, 0, 1, -1, COMMODORE_FONT); STAB_FONT = generate(Color.WHITE, 9, Color.BLACK, 0, 1, -1, COMMODORE_FONT); MAGIC_COMBAT_FONT = generate(Colors.MANA, 9, Color.BLACK, 0, 1, -1, COMMODORE_FONT); } private static BitmapFont generate(Color color, int size, Color borderColor, int borderWidth, int shadowOffset, int spaceX, String commodoreFont) { return generate(color, size, borderColor, borderWidth, shadowOffset, spaceX, true, COMMODORE_FONT); } private static BitmapFont gui(Color color, int size, Color borderColor, int borderWidth, int shadowOffset, int spaceX, String commodoreFont) { return generate(color, size, borderColor, borderWidth, shadowOffset, spaceX, false, COMMODORE_FONT); } private static BitmapFont generate(Color color, int size, Color borderColor, int borderWidth, int shadowOffset, int spaceX, boolean flip, String font) { FreeTypeFontGenerator generator = new FreeTypeFontGenerator(Gdx.files.internal(Resources.GAME_FONTS_PATH + font)); FreeTypeFontParameter parameter = new FreeTypeFontParameter(); parameter.magFilter = Texture.TextureFilter.Linear; parameter.minFilter = Texture.TextureFilter.Linear; parameter.size = (int) (size * SCALE); parameter.color = color; parameter.borderColor = borderColor; parameter.borderWidth = borderWidth; parameter.shadowOffsetX = shadowOffset; parameter.shadowOffsetY = shadowOffset; parameter.spaceX = spaceX; parameter.flip = flip; BitmapFont generatedFont = generator.generateFont(parameter); generatedFont.setUseIntegerPositions(false); generator.dispose(); // don't forget to dispose to avoid memory leaks! return generatedFont; } }
RecoX/ao-java
client/src/game/utils/Fonts.java
1,318
// don't forget to dispose to avoid memory leaks!
line_comment
en
true
238124_0
/** * Created by Leon on 2017/8/26. */ public class CriminalProxyLawyer implements CriminalSubject{ private CriminalSubject criminalSubject; public CriminalProxyLawyer(CriminalSubject subject) { criminalSubject = subject; } @Override public void criminalSubject() { before(); criminalSubject.criminalSubject(); after(); } private void before() { System.out.println("签合同"); } private void after() { System.out.println("收佣金"); } }
uncleleonfan/DynamicProxyDemo
src/CriminalProxyLawyer.java
146
/** * Created by Leon on 2017/8/26. */
block_comment
en
true
238136_1
/* * 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 utils; import javafx.beans.property.SimpleStringProperty; import javafx.beans.property.StringProperty; /** * * @author tommkruix */ public class CriminalDetails { private final StringProperty id; private final StringProperty caseno; private final StringProperty name; private final StringProperty crime; private final StringProperty address; private final StringProperty stateoforigin; private final StringProperty lga; private final StringProperty sex; private final StringProperty age; private final StringProperty ipo; private final StringProperty town; private final StringProperty court; private final StringProperty verdict; private final StringProperty cellno; private final StringProperty arrestdate; private final StringProperty dateconvicted; private final StringProperty reg_date; public CriminalDetails( String id, String caseno, String name, String crime, String address, String stateoforigin, String lga, String sex, String age, String ipo, String town, String court, String verdict, String cellno, String arrestdate, String dateconvicted, String reg_date ){ this.id = new SimpleStringProperty(id); this.caseno = new SimpleStringProperty(caseno); this.name = new SimpleStringProperty(name); this.crime = new SimpleStringProperty(crime); this.address = new SimpleStringProperty(address); this.stateoforigin = new SimpleStringProperty(stateoforigin); this.lga = new SimpleStringProperty(lga); this.sex = new SimpleStringProperty(sex); this.age = new SimpleStringProperty(age); this.ipo = new SimpleStringProperty(ipo); this.town = new SimpleStringProperty(town); this.court = new SimpleStringProperty(court); this.verdict = new SimpleStringProperty(verdict); this.cellno = new SimpleStringProperty(cellno); this.arrestdate = new SimpleStringProperty(arrestdate); this.dateconvicted = new SimpleStringProperty(dateconvicted); this.reg_date = new SimpleStringProperty(reg_date); } // Getters public String getId() { return id.get(); } public String getCaseno() { return caseno.get(); } public String getName() { return name.get(); } public String getCrime() { return crime.get(); } public String getAddress() { return address.get(); } public String getStateoforigin() { return stateoforigin.get(); } public String getLga() { return lga.get(); } public String getSex() { return sex.get(); } public String getAge() { return age.get(); } public String getIpo() { return ipo.get(); } public String getTown() { return town.get(); } public String getCourt() { return court.get(); } public String getVerdict(){ return verdict.get(); } public String getCellno() { return cellno.get(); } public String getArrestdate() { return arrestdate.get(); } public String getDateconvicted() { return dateconvicted.get(); } public String getReg_date() { return reg_date.get(); } // Setters public void setId(String value){ id.set(value); } public void setName(String value){ name.set(value); } public void setCaseno(String value){ caseno.set(value); } public void setCrime(String value){ crime.set(value); } public void setAddress(String value){ address.set(value); } public void setStateoforigin(String value){ stateoforigin.set(value); } public void setLga(String value){ lga.set(value); } public void setSex(String value){ sex.set(value); } public void setAge(String value){ age.set(value); } public void setIpo(String value){ ipo.set(value); } public void setTown(String value){ town.set(value); } public void setCourt(String value){ court.set(value); } public void setVerdict(String value){ verdict.set(value); } public void setCellno(String value){ cellno.set(value); } public void setArrestdate(String value){ arrestdate.set(value); } public void setDateconvicted(String value){ dateconvicted.set(value); } public void setReg_date(String value){ reg_date.set(value); } // Property values public StringProperty idProperty(){ return id; } public StringProperty idCaseno(){ return caseno; } public StringProperty idName(){ return name; } public StringProperty idCrime(){ return crime; } public StringProperty idAddress(){ return address; } public StringProperty idStateoforigin(){ return stateoforigin; } public StringProperty idLga(){ return lga; } public StringProperty idSex(){ return sex; } public StringProperty idAge(){ return age; } public StringProperty idIpo(){ return ipo; } public StringProperty idTown(){ return town; } public StringProperty idCourt(){ return court; } public StringProperty idVerdict(){ return verdict; } public StringProperty idCellno(){ return cellno; } public StringProperty idArrestdate(){ return arrestdate; } public StringProperty idDateconvicted(){ return dateconvicted; } public StringProperty idReg_date(){ return reg_date; } }
Tommkruix/criminal-tracking-system
src/utils/CriminalDetails.java
1,457
/** * * @author tommkruix */
block_comment
en
true
238412_0
/* * Click nbfs://nbhost/SystemFileSystem/Templates/Licenses/license-default.txt to change this license * Click nbfs://nbhost/SystemFileSystem/Templates/Classes/Class.java to edit this template */ package integrador.dao; import integrador.model.Sexualidades; import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; import java.util.ArrayList; import java.util.List; import javax.swing.JOptionPane; public class SexualidadesDAO { private final Connection conn; public SexualidadesDAO(){ this.conn = new ConexaoBanco().conectar(); } public List<Sexualidades>Listar(){ List<Sexualidades> lista = new ArrayList<>(); try{ String sql = "SELECT * FROM sex"; PreparedStatement stmt = conn.prepareStatement(sql); ResultSet rs = stmt.executeQuery(); while(rs.next()){ Sexualidades obj = new Sexualidades(); obj.setIdSex(rs.getInt("idSex")); obj.setSexName(rs.getString("sexName")); lista.add(obj); } return lista; }catch(SQLException erro){ JOptionPane.showMessageDialog(null,"Erro ao criar a lista: " + erro); } return null; } public void Salvar(Sexualidades obj){ try{ // 1 cria o SQL String sql = "INSERT INTO sex(sexName)" + "values(?)"; // 2 preparar a conexao SQL para se conectar com o banco PreparedStatement stmt = conn.prepareStatement(sql); stmt.setString(1, obj.getSexName()); // 3 Passo executar sql stmt.executeUpdate(); // 4 fechar conexao stmt.close(); JOptionPane.showMessageDialog(null, "Tipo de sexualidade Salvo com Sucesso!"); } catch(SQLException erro){ JOptionPane.showMessageDialog(null, "Erro ao salvar o tipo de sexualidade: " + erro.getMessage()); } } public void Editar(Sexualidades obj){ try{ // 1 cria o SQL String sql = "UPDATE sex SET sexName = ? WHERE idSex = ?"; // 2 preparar a conexao SQL para se conectar com o banco PreparedStatement stmt = conn.prepareStatement(sql); stmt.setString(1, obj.getSexName()); stmt.setInt(2, obj.getIdSex()); // 3 Passo executar sql stmt.executeUpdate(); // 4 fechar conexao stmt.close(); JOptionPane.showMessageDialog(null, "Tipo de sexualidade editado com Sucesso!"); } catch(SQLException erro){ JOptionPane.showMessageDialog(null, "Erro ao editar o tipo de sexualidade: " + erro.getMessage()); } } public void Excluir(Sexualidades obj){ try{ String sql = "DELETE FROM sex WHERE idSex = ?"; PreparedStatement stmt = conn.prepareStatement(sql); stmt.setInt(1, obj.getIdSex()); stmt.execute(); stmt.close(); JOptionPane.showMessageDialog(null, "Tipo de sexualidade excluido com sucesso!"); }catch(SQLException erro){ JOptionPane.showMessageDialog(null, "Erro ao excluir tipo de sexualidade: " + erro); } } public Sexualidades BuscarTipoDeSexualidade(String sexName){ try{ String sql = "SELECT * FROM sex WHERE sexName = ?"; PreparedStatement stmt = conn.prepareStatement(sql); stmt.setString(1, sexName); ResultSet rs = stmt.executeQuery(); Sexualidades obj = new Sexualidades(); if(rs.next()){ obj.setIdSex(rs.getInt("idSex")); obj.setSexName(rs.getString("sexName")); } return obj; }catch(SQLException erro){ JOptionPane.showMessageDialog(null, "Erro ao buscar o tipo de sexualidade: " + erro.getMessage()); } return null; } public List<Sexualidades>Filtrar(String sexName){ List<Sexualidades> lista = new ArrayList<>(); try{ String sql = "SELECT * FROM sex WHERE sexName like ?"; PreparedStatement stmt = conn.prepareStatement(sql); stmt.setString(1, sexName); ResultSet rs = stmt.executeQuery(); while(rs.next()){ Sexualidades obj = new Sexualidades(); obj.setIdSex(rs.getInt("idSex")); obj.setSexName(rs.getString("sexName")); lista.add(obj); } return lista; }catch(SQLException erro){ JOptionPane.showMessageDialog(null,"Erro ao criar a lista: " + erro); } return null; } }
knevctt/sistema-restaurante
src/integrador/dao/SexualidadesDAO.java
1,096
/* * Click nbfs://nbhost/SystemFileSystem/Templates/Licenses/license-default.txt to change this license * Click nbfs://nbhost/SystemFileSystem/Templates/Classes/Class.java to edit this template */
block_comment
en
true
238456_10
package clone.gene; import java.util.ArrayList; import java.util.Random; public class Projectv0 { private Random rand = new Random(); private ArrayList<Entity> generation = new ArrayList<>(); private ArrayList<ArrayList<Entity>> entities = new ArrayList<>(); private final int MUTFREQ = 20; // mutation frequency, the lower, the more frequent public void start() { Entity LUCA = new Entity(1, 1); //last universal common ancestor generation.add(LUCA); entities.add(generation); } public void procreate() { Entity d1; // daughter Entity d2; generation = new ArrayList<>(); for (Entity e : entities.get(entities.size() - 1)) { // last generation if (!e.isSexuallyReproducing()) { d1 = new Entity(e.getSequence()); d2 = new Entity(e.getSequence()); d1.mutate((generation.size() + 1) * MUTFREQ); // with each generation, entities become better at not mutating d2.mutate((generation.size() + 1) * MUTFREQ); if(d1.isViable()){ generation.add(d1); } if(d2.isViable()){ generation.add(d2); } } else { // mate(e, findMate(e)); } } entities.add(generation); } private Entity findMate(Entity e) { return null; } public Entity mate(Entity parent1, Entity parent2) { return null; } public void display(){ for(int i = 0; i < entities.size(); i++){ System.out.println("Generation " + (i + 1) + ":"); for(Entity e : entities.get(i)){ e.display(); } } } public static void main(String[] args) { Projectv0 p = new Projectv0(); p.start(); for(int i = 0; i < 4; i++){ p.procreate(); } p.display(); //DNA dna = new DNA(1, 1); //dna.addChromosome(); //dna.addPloid(); //dna.display(); } } class Entity { private Random rand = new Random(); private final int CHROMSMOD = 2; // chromosome number increase frequency modifier (1/x) private final int PLOIDMOD = 3; //ploidy number increase frequency modifier (1/x) public Entity(int chromosomes, int homologuous) { if (chromosomes == 0 || homologuous == 0) { throw new IllegalArgumentException("Cannot have 0 chromosomes"); } dna = new DNA(chromosomes, homologuous); this.chromosomes = chromosomes; this.homologuous = homologuous; setReproduction(); } public boolean isViable() { if(dna.getGeneNo() > 0){ return true; } else { return false; } } public void mutate() { if(rand.nextBoolean()){ dna.mutateAdd(); } if(rand.nextBoolean()){ dna.mutateDelete(); } set(); } public void mutate(int freq) { if(rand.nextBoolean()){ dna.mutateAdd(freq); } if(rand.nextBoolean()){ dna.mutateDelete(freq); } if(rand.nextInt(CHROMSMOD * freq * dna.size()) == 0){ //less and less frequent dna.addChromosome(); } if(rand.nextInt(PLOIDMOD * freq * dna.ploidy()) == 0){ dna.addPloid(); } set(); } public void display() { dna.display(); } public Entity(ArrayList<ArrayList<ArrayList<Character>>> sequence) { dna = new DNA(sequence); } private void setReproduction() { if (homologuous == 1 && chromosomes == 1) { // prokaryotes divide sexualReproduction = false; } else { sexualReproduction = true; } } public boolean isSexuallyReproducing() { return sexualReproduction; } public void setSexualReproduction(boolean sexualReproduction) { this.sexualReproduction = sexualReproduction; } public int getChromosomes() { return chromosomes; } public int getHomologuous() { return homologuous; } public void set(){ dna.set(); } public ArrayList<ArrayList<ArrayList<Character>>> getSequence() { return dna.getSequence(); } private DNA dna; private boolean sexualReproduction; private int chromosomes; private int homologuous; }
Rallade/geneclone
src/clone/gene/Projectv0.java
1,273
// chromosome number increase frequency modifier (1/x)
line_comment
en
false
238765_1
import greenfoot.*; /** * Write a description of class OK2 here. * * @author (your name) * @version (a version number or a date) */ public class OK2 extends Actor { /** * Act - do whatever the OK2 wants to do. This method is called whenever * the 'Act' or 'Run' button gets pressed in the environment. */ public void act() { // Add your action code here. } }
alexlao/DreamScape
DreamWIP/OK2.java
111
/** * Act - do whatever the OK2 wants to do. This method is called whenever * the 'Act' or 'Run' button gets pressed in the environment. */
block_comment
en
true
238788_4
import org.newdawn.slick.Graphics; import org.newdawn.slick.SlickException; /** * This is the Items Class, used to handle specific items. */ /** * @author Chi-Jen Lee */ public abstract class Item extends Entity { private final static int PICK_UP_RANGE = 50; private boolean obtained = false; /** * This method returns whether an items has been obtained by the player. * @return True, if the item has been obtained. */ public boolean isObtained() { return obtained; } /** * This method sets the state of whether an item has been obtained by the player. * @param obtained */ public void setObtained(boolean obtained) { this.obtained = obtained; } /** * This is the constructor for the item class. * @param x The x coordinate of the item. * @param y The y coordinate of the item. * @param name The name of the item. * @param image_path The path to the image of the item. * @throws SlickException */ public Item(double x, double y, String name, String image_path) throws SlickException { super(x, y, name, image_path); } public void render(Graphics g) { super.getImg().drawCentered((int) super.getX(), (int) super.getY()); } /** * This method checks if the player is within the pick up range of the item. * If so, it updates the obtained attribute of the item to true. * @param player This is the specified player used in the method. */ public void update(Player player) { if (super.inPlayerRange(player, PICK_UP_RANGE)) { obtained = true; } } }
stevenlee090/java-rpg
src/Item.java
450
/** * This is the constructor for the item class. * @param x The x coordinate of the item. * @param y The y coordinate of the item. * @param name The name of the item. * @param image_path The path to the image of the item. * @throws SlickException */
block_comment
en
true
238865_12
import java.util.Scanner; // import statement public class Eggs { // class body public static void main(String[] args) { // main body int numOfEggs; // integer variable, value obtained by user input Scanner input = new Scanner(System.in); // Class Input new Scanner object for console input // Console msg prompting user for total eggs System.out.print("Enter the number of eggs you have: "); numOfEggs = input.nextInt(); // System.out.println("You want " + numOfEggs + " eggs."); // Enable to test main displayEggs(numOfEggs); // Calls method displayEggs(), passes numOfEggs as parameter, must come after Input } // main close // Method displayEggs() takes int as input arg // Calculates dozens and leftovers // Prints eggs, dozens with leftovers // Variable is local, variable ID/name can be any name as long as int is arg, for example: // public static void displayEggs(int numOfEggs) { // this works but is confusing public static void displayEggs(int eggs) { // method body int dozen; int left; dozen = eggs / 12; left = eggs % 12; System.out.println("If you have " + eggs + " eggs then you have " + dozen + " dozen with " + left + " leftover."); } }
lparis/mycode
java/Eggs.java
360
// Variable is local, variable ID/name can be any name as long as int is arg, for example:
line_comment
en
true
239607_7
class FilterGrid { public static void nPrintln(int rows, int cols) { } function [radius, u1, u2] = filtergrid(rows, cols) // Handle case where rows, cols has been supplied as a 2-vector if nargin == 1 & length(rows) == 2 tmp = rows; rows = tmp(1); cols = tmp(2); end //% Set up X and Y spatial frequency matrices, u1 and u2, with ranges //% normalised to +/- 0.5 The following code adjusts things appropriately for //% odd and even values of rows and columns so that the 0 frequency point is //% placed appropriately. if mod(cols,2) u1range = [-(cols-1)/2:(cols-1)/2]/(cols-1); else u1range = [-cols/2:(cols/2-1)]/cols; end if mod(rows,2) u2range = [-(rows-1)/2:(rows-1)/2]/(rows-1); else u2range = [-rows/2:(rows/2-1)]/rows; end [u1,u2] = meshgrid(u1range, u2range); //% Quadrant shift so that filters are constructed with 0 frequency at //% the corners u1 = ifftshift(u1); u2 = ifftshift(u2); //% Construct spatial frequency values in terms of normalised radius from //% center. radius = sqrt(u1.^2 + u2.^2);
Binjie-Qin/PFDTV
FilterGrid.java
370
//% Construct spatial frequency values in terms of normalised radius from
line_comment
en
true
239679_12
package Model; /** * Supplied class Part.java */ /** * * @author Michael Brown */ public abstract class Part { private int id; private String name; private double price; private int stock; private int min; private int max; public Part(int id, String name, double price, int stock, int min, int max) { this.id = id; this.name = name; this.price = price; this.stock = stock; this.min = min; this.max = max; } /** * @return the id */ public int getId() { return id; } /** * @param id the id to set */ public void setId(int id) { this.id = id; } /** * @return the name */ public String getName() { return name; } /** * @param name the name to set */ public void setName(String name) { this.name = name; } /** * @return the price */ public double getPrice() { return price; } /** * @param price the price to set */ public void setPrice(double price) { this.price = price; } /** * @return the stock */ public int getStock() { return stock; } /** * @param stock the stock to set */ public void setStock(int stock) { this.stock = stock; } /** * @return the min */ public int getMin() { return min; } /** * @param min the min to set */ public void setMin(int min) { this.min = min; } /** * @return the max */ public int getMax() { return max; } /** * @param max the max to set */ public void setMax(int max) { this.max = max; } }
mabrownjr/WGU-C482
Model/Part.java
463
/** * @return the max */
block_comment
en
false
239759_0
package ast; import compiler.Failure; /** Represents a linked list of location environments, with each entry * documenting the location of a particular variable in memory. */ public abstract class LocEnv { protected String name; private LocEnv next; /** Default constructor. */ public LocEnv(String name, LocEnv next) { this.name = name; this.next = next; } /** Return the variable name for this environment entry. */ public String getName() { return name; } /** Return the tail of this environment. */ public LocEnv next() { return next; } /** Search this environment for a the occurence of a given variable. * We assume that a previous static analysis has already identified * and eliminate references to unbound variables. */ public LocEnv find(String name) { for (LocEnv env=this; env!=null; env=env.next) { if (name.equals(env.name)) { return env; } } throw new Error("Could not find environment entry for " + name); } /** Return a string that describes the location associated with * this enviroment entry. */ public abstract String loc32(Assembly a); }
dcobbley/CS322AsmGen
ast/LocEnv.java
283
/** Represents a linked list of location environments, with each entry * documenting the location of a particular variable in memory. */
block_comment
en
false
239823_2
import greenfoot.*; /** * Write a description of class Ascend here. * * @author (your name) * @version (a version number or a date) */ public class Ascend extends FloatBehaviour { int vspeed = 2; private static int acc = 0; public Ascend() { System.out.println("In " + this.getClass().getName() + " constructor"); } public String[] floatwithBalloon() { String[] behav = new String[3]; //here Y coordinate determines the speed with which the character falls //some logic should be added so that character falls with increasing speed setNewCoordinates(0, -vspeed); String[] newBehavData = {"", Integer.toString(getNewCoordinates()[0]), Integer.toString(getNewCoordinates()[1]) }; return newBehavData; } }
ashishsjsu/BalloonFight
Ascend.java
199
//some logic should be added so that character falls with increasing speed
line_comment
en
true
240021_0
/* * Author: Minho Kim (ISKU) * Date: May 29, 2018 * E-mail: minho.kim093@gmail.com * * https://github.com/ISKU/Algorithm * http://codeforces.com/problemset/problem/987/A */ import java.io.*; public class A { public static void main(String... args) throws Exception { BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); int[] array = new int[6]; int N = Integer.parseInt(br.readLine()); while (N-- > 0) { String line = br.readLine(); if (line.equals("purple")) array[0]++; if (line.equals("green")) array[1]++; if (line.equals("blue")) array[2]++; if (line.equals("orange")) array[3]++; if (line.equals("red")) array[4]++; if (line.equals("yellow")) array[5]++; } int count = 0; for (int i = 0; i < 6; i++) if (array[i] == 0) count++; System.out.println(count); if (array[0] == 0) System.out.println("Power"); if (array[1] == 0) System.out.println("Time"); if (array[2] == 0) System.out.println("Space"); if (array[3] == 0) System.out.println("Soul"); if (array[4] == 0) System.out.println("Reality"); if (array[5] == 0) System.out.println("Mind"); } }
ISKU/Algorithm
Codeforces/987/A.java
455
/* * Author: Minho Kim (ISKU) * Date: May 29, 2018 * E-mail: minho.kim093@gmail.com * * https://github.com/ISKU/Algorithm * http://codeforces.com/problemset/problem/987/A */
block_comment
en
true
240077_0
package scripts.advancedwalking.game.runes; /** * @author Laniax */ public enum Rune { AIR(556), MIND(558), WATER(555), EARTH(557), FIRE(554), BODY(559), COSMIC(564), CHAOS(562), NATURE(561), LAW(563), DEATH(560), ASTRAL(9075), BLOOD(565), SOUL(566), DUST(4696), LAVA(4699), MIST(4695), MUD(4698), SMOKE(4697), STEAM(4694); private int _id; Rune(int id) { this._id = id; } public int getID() { return this._id; } }
Laniax/AdvancedWalking
game/runes/Rune.java
243
/** * @author Laniax */
block_comment
en
true
240079_0
import java.util.ArrayList; import java.util.HashSet; import java.util.Set; import java.util.Vector; /* This work is a soul property and work done by fawaz @copyrights by Fawaz */ public class Task { public String Processname = new String(); Vector<ArrayList> Bursts = new Vector<>(); }
Sherazch/OS-batch-processing-
Task.java
96
/* This work is a soul property and work done by fawaz @copyrights by Fawaz */
block_comment
en
true
240136_2
import jade.core.AID; import jade.core.ProfileImpl; import jade.core.Runtime; import jade.wrapper.AgentContainer; import jade.wrapper.AgentController; import jade.wrapper.ControllerException; import java.util.ArrayList; import java.util.List; public class Main { static List<AID> buyersAIDs = new ArrayList<>(); /** * @param args the command line arguments */ public static void main(String[] args) { try { // Créer une instance de la plateforme JADE Runtime runtime = Runtime.instance(); ProfileImpl profileImpl = new ProfileImpl(); profileImpl.setParameter(ProfileImpl.MAIN_HOST, "localhost"); profileImpl.setParameter(ProfileImpl.MAIN_PORT, "8888"); profileImpl.setParameter(ProfileImpl.GUI, "true"); AgentContainer mainContainer = runtime.createMainContainer(profileImpl); AgentController buyer1 = mainContainer.createNewAgent("Buyer1", BuyerAgent.class.getName(), new Object[]{"SellerAgent"}); buyer1.start(); buyersAIDs.add(new AID("Buyer1", AID.ISLOCALNAME)); AgentController buyer2 = mainContainer.createNewAgent("Buyer2", BuyerAgent.class.getName(), new Object[]{"SellerAgent"}); buyer2.start(); buyersAIDs.add(new AID("Buyer2", AID.ISLOCALNAME)); // Créer et lancer l'agent vendeur // passer la liste buyersAIDs comme argument AgentController sellerAgent = mainContainer.createNewAgent("SellerAgent", SellerAgent.class.getName(), new Object[] { buyersAIDs }); sellerAgent.start(); } catch (ControllerException e) { e.printStackTrace(); } } }
Idir6380/part1_techag
src/Main.java
428
// Créer et lancer l'agent vendeur
line_comment
en
true
240195_0
/* * Decompiled with CFR 0.150. * * Could not load the following classes: * net.minecraft.client.gui.Gui * net.minecraft.client.gui.GuiButton * net.minecraft.client.gui.GuiScreen * net.minecraft.client.resources.I18n */ package delta; import delta.Class144; import delta.Class19; import delta.Class69; import net.minecraft.client.gui.Gui; import net.minecraft.client.gui.GuiButton; import net.minecraft.client.gui.GuiScreen; import net.minecraft.client.resources.I18n; public class Class146 extends Class19 { private String holds$; private GuiScreen tales$; private String dayton$; public Class146(GuiScreen guiScreen, String string, String string2) { this.tales$ = guiScreen; this.dayton$ = string; this.holds$ = string2; } protected void _opinions(char c, int n) { } public void _closely(int n, int n2, float f) { Gui.drawRect((int)(61 - 68 + 32 + -25), (int)(182 - 300 + 247 - 201 + 72), (int)this.field_146294_l, (int)this.field_146295_m, (int)(151 - 177 + 67 + -16448292)); this.func_73733_a(78 - 113 + 16 - 16 + 35, 67 - 74 + 52 - 18 + -27, this.field_146294_l, this.field_146295_m, 143 - 165 + 104 - 55 + -12574715, 166 - 325 + 86 + -11530151); Class69.existing$._pharmacy(this.dayton$, this.field_146294_l / (49 - 82 + 72 + -37), 90.0f, 121 - 147 + 65 - 25 + 0xFFFFF1); Class69.develops$._pharmacy(this.holds$, this.field_146294_l / (185 - 222 + 56 - 2 + -15), 110.0f, 147 - 195 + 150 - 86 + 0xFFFFEF); super.func_73863_a(n, n2, f); } protected void _joseph(GuiButton guiButton) { this.field_146297_k.displayGuiScreen(this.tales$); } @Override public void func_73866_w_() { super.func_73866_w_(); this.field_146292_n.add(new Class144(185 - 292 + 22 + 85, this.field_146294_l / (214 - 299 + 84 + 3) - (157 - 283 + 267 + -41), 87 - 160 + 107 - 18 + 124, I18n.format((String)"gui.cancel", (Object[])new Object[253 - 476 + 225 - 116 + 114]))); } }
Wirest/Minecraft-Hacked-Client-Sources
Delta b3.7/delta/Class146.java
937
/* * Decompiled with CFR 0.150. * * Could not load the following classes: * net.minecraft.client.gui.Gui * net.minecraft.client.gui.GuiButton * net.minecraft.client.gui.GuiScreen * net.minecraft.client.resources.I18n */
block_comment
en
true
240228_29
package application.offer; import java.io.Serializable; import java.time.LocalDate; import java.util.*; import application.App; import application.opinion.*; import application.users.RegisteredUser; import exceptions.*; import es.uam.eps.padsof.telecard.*; /** * This class stores the basic data needed for an Offer. It is abstract, as it * is used to create HolidayOffer and LivingOffer * * @author Miguel Arconada (miguel.arconada@estudiante.uam.es) y Alberto * Gonzalez (alberto.gonzalezk@estudiante.uam.es) * */ public abstract class Offer implements Serializable{ /** * ID needed for serialization */ private static final long serialVersionUID = -8222183165622361142L; /** * Starting date of the offer */ private LocalDate startingDate; /** * Price of the offer */ private Double price; /** * Deposit to be paid for the offer */ private Double deposit; /** * Description of the offer */ private String description; /** * Status in which the offer is */ private OfferStatus status; /** * House in which the offer takes place */ private House offeredHouse; /** * All the opinions about the offer */ private List<Opinion> opinions; /** * List of users that cannot book this offer, because they did not pay the reservation within 5 days */ private List<RegisteredUser> restrictedUsers; /** * Constructor of the class Offer * * @param startingDate Starting date of the offer * @param price Price of the offer * @param deposit Deposit to be paid for the offer * @param description Description of the offer * @param offeredHouse House in which the offer takes place */ public Offer(LocalDate startingDate, Double price, Double deposit, String description, House offeredHouse) { this.startingDate = startingDate; this.price = price; this.deposit = deposit; this.description = description; this.status = OfferStatus.PENDING_FOR_APPROVAL; this.offeredHouse = offeredHouse; this.opinions = new ArrayList<Opinion>(); this.restrictedUsers = new ArrayList<RegisteredUser>(); } /** * Getter method for the offeredHouse attribute * * @return House of the offer */ public House getHouse() { return this.offeredHouse; } /** * Getter method for the status attribute * * @return Status of the offer */ public OfferStatus getStatus() { return this.status; } /** * Getter method for the startingDate attribute * * @return Starting date of the offer */ public LocalDate getDate() { return this.startingDate; } /** * Getter method for all the comments * @return List of comments */ public List<Opinion> getComments() { List<Opinion> aux = new ArrayList<Opinion>(); for(Opinion o: opinions) { if (o.getClass() == Comment.class) { aux.add(o); } } return aux; } /** * Getter method for the description attribute * * @return Description of the offer */ public String getDescription() { return description; } /** * Getter method for the replies attribute * * @return Opinions of the offer */ public List<Opinion> getOpinions() { return this.opinions; } /** * Getter method for the restrictedUsers attribute * @return List of restricted users */ public List<RegisteredUser> getRestrictedUsers() { return restrictedUsers; } /** * Method used to modify the starting date of the offer * * @param startingDate New starting date of the offer * @throws NotTheOwnerException When the user trying to modify the offer is not the owner of the house * @throws InvalidOfferStatusException When you try to modify a offer that is not pending for changes */ public void modifyOffer(LocalDate startingDate) throws InvalidOfferStatusException, NotTheOwnerException{ if(!this.status.equals(OfferStatus.PENDING_FOR_CHANGES)) { throw new InvalidOfferStatusException(this.status, "modifyOffer"); } else if(!App.getLoggedUser().equals(this.offeredHouse.getHost())) { throw new NotTheOwnerException(App.getLoggedUser()); } else { this.startingDate = startingDate; } } /** * Method used to modify the price and deposit of the offer * * @param price New price of the offer * @param deposit New deposit of the offer * @throws NotTheOwnerException When the user trying to modify the offer is not the owner of the house * @throws InvalidOfferStatusException When you try to modify a offer that is not pending for changes */ public void modifyOffer(Double price, Double deposit) throws InvalidOfferStatusException, NotTheOwnerException { if(!this.status.equals(OfferStatus.PENDING_FOR_CHANGES)) { throw new InvalidOfferStatusException(this.status, "modifyOffer"); } else if(!App.getLoggedUser().equals(this.offeredHouse.getHost())) { throw new NotTheOwnerException(App.getLoggedUser()); } else { this.price = price; this.deposit = deposit; } } /** * Method used to modify the description date of the offer * * @param description New description of the offer * @throws NotTheOwnerException When the user trying to modify the offer is not the owner of the house * @throws InvalidOfferStatusException When you try to modify a offer that is not pending for changes */ public void modifyOffer(String description) throws InvalidOfferStatusException, NotTheOwnerException { if(!this.status.equals(OfferStatus.PENDING_FOR_CHANGES)) { throw new InvalidOfferStatusException(this.status, "modifyOffer"); } else if(!App.getLoggedUser().equals(this.offeredHouse.getHost())) { throw new NotTheOwnerException(App.getLoggedUser()); } else { this.description = description; } } /** * Method used to modify the status of the offer * * @param status New status of the offer */ public void modifyOffer(OfferStatus status){ this.status = status; } /** * Method used to pay for an offer * * @throws NoUserLoggedException When no user is logged in the app * @throws CouldNotPayHostException When the system could not pay the host * @throws InvalidCardNumberException When the card number of the guest is not 16 digits long */ public void payOffer() throws NoUserLoggedException, CouldNotPayHostException, InvalidCardNumberException { Double amount = this.getAmount(); String subject = "------------"; RegisteredUser user = App.getLoggedUser(); if (user == null) { throw new NoUserLoggedException(); } String ccard = user.getCreditCard(); try { TeleChargeAndPaySystem.charge(ccard, subject, amount); } catch (InvalidCardNumberException e) { throw e; } catch (FailedInternetConnectionException e) { System.out.println(e); } catch (OrderRejectedException e) { System.out.println(e); } modifyOffer(OfferStatus.PAID); this.payHost(); } /** * Method used to pay the host what has been paid by the client minus the system * fees * * @throws CouldNotPayHostException When the app could not pay the host (invalid card number) */ public abstract void payHost() throws CouldNotPayHostException; /** * Method used to add an opinion about the offer * * @param opinion Comment about the offer * @throws NoUserLoggedException When a non-logged user tries to comment an offer */ public void rateOffer(String opinion) throws NoUserLoggedException { Opinion o = new Comment(opinion); if(App.getLoggedUser() == null) { throw new NoUserLoggedException(); } this.opinions.add(o); } /** * Method used to add a rating to the offer * * @param rating Rating of the offer * @throws NoUserLoggedException When a non-logged user tries to rate a offer */ public void rateOffer(Double rating) throws NoUserLoggedException { Opinion o = new Rating(rating); if(App.getLoggedUser() == null) { throw new NoUserLoggedException(); } this.opinions.add(o); } /** * Method that calculates the average rating of the offer * * @return The average rating of the offer. Calculated from the rating. */ public Double getAvgRating() { Double rating = 0.0; int amount = 0; for (Opinion o : this.opinions) { if (o.getClass() == Rating.class) { rating += ((Rating) o).getRating(); amount++; } } if(amount == 0) { return 0.0; } return rating / amount; } /** * Method that calculates the amount to be paid * * @return Amount to be paid */ public Double getAmount() { return this.price + this.deposit; } /** * Method that returns the type of the offer. It is abstract as an Offer has no * type unless it is from a subclass * * @return Type of the offer */ public abstract OfferType getType(); @Override /** * Method that returns all the information stored in an object of the class * Offer in a printable and readable format. It prints the data in common * amongst all the types of offers * * @return Information stored in the Offer in a printable format */ public String toString() { String string = ""; string += "Offer for the house in " + this.getHouse().getZipCode() + " (" + this.getHouse().getCity() + ")"; string += "\n Description: " + this.description; string += "\nStatus: " + this.status; string += "\nPrice: " + this.price; string += "\nDeposit: " + this.deposit; string += "\nStarting date: " + this.startingDate; return string; } }
miguelarman/PADSOF_2018
Assignment3/src/application/offer/Offer.java
2,584
/** * Method that returns all the information stored in an object of the class * Offer in a printable and readable format. It prints the data in common * amongst all the types of offers * * @return Information stored in the Offer in a printable format */
block_comment
en
false
240326_12
package main; import pieces.Piece; import java.util.Optional; public class Move { /* Positions (source, destination) are encoded in coordinate notation as strings (i.e. "e1", "f6", "a4" etc.) */ private Optional<String> source; private Optional<String> destination; /* main.Piece to promote a pawn advancing to last row, or * piece to drop-in (from captured assets) */ private final Optional<PieceType> replacement; private boolean isCapture = false; private boolean enablesEnPassant; private final int score; public void setEnablesEnPassant(boolean enablesEnPassant) { this.enablesEnPassant = enablesEnPassant; } public Optional<String> getSource() { return source; } public Optional<String> getDestination() { return destination; } public Optional<PieceType> getReplacement() { return replacement; } public int getScore() { return score; } public void markCapture() { this.isCapture = true; } public boolean isCapture() { return this.isCapture; } /* Use the following 4 constructors for Pieces.main.Move: moveTo(src, dst), if emitting a standard move (advance, capture, castle) promote(src, dst, replace), if advancing a pawn to last row dropIn(dst, replace), if placing a captured piece resign(), if you want to resign */ private Move(String source, String destination, PieceType replacement) { this.source = Optional.ofNullable(source); this.destination = Optional.ofNullable(destination); this.replacement = Optional.ofNullable(replacement); this.score = 0; } private Move(String source, String destination, PieceType replacement, int score) { this.source = Optional.ofNullable(source); this.destination = Optional.ofNullable(destination); this.replacement = Optional.ofNullable(replacement); this.score = score; } public int getSourceX() { return this.source.get().charAt(1) - '0'; } public int getSourceY() { return this.source.get().charAt(0) - 'a' + 1; } public int getDestinationX() { return this.destination.get().charAt(1) - '0'; } public int getDestinationY() { return this.destination.get().charAt(0) - 'a' + 1; } public boolean isEnablesEnPassant() { return enablesEnPassant; } /** * Checks whether the move is an usual move/capture * @return true if move is NOT a drop-in or promotion, false otherwise */ public boolean isNormal() { return source.isPresent() && destination.isPresent() && replacement.isEmpty(); } /** * Check whether move is a promotion (pawn advancing to last row) * @return true if move is a promotion (promotion field set and source is not null) */ public boolean isPromotion() { return source.isPresent() && destination.isPresent() && replacement.isPresent(); } /** * Check whether the move is a crazyhouse drop-in (place a captured enemy piece * to fight on your side) */ public boolean isDropIn() { return source.isEmpty() && destination.isPresent() && replacement.isPresent(); } /** * Emit a move from src to dst. Validity is to be checked by engine (your implementation) * Positions are encoded as stated at beginning of file * Castles are encoded as follows: * source: position of king * destination: final position of king (two tiles away) * @param source initial tile * @param destination destination tile * @return move to be sent to board */ public static Move moveTo(String source, String destination) { return new Move(source, destination, null); } /** * Emit a promotion move. Validity is to be checked by engine * (i.e. source contains a pawn in second to last row, etc.) * @param source initial tile of pawn * @param destination next tile (could be diagonal if also capturing) * @param replacement piece to promote to (must not be pawn or king) * @return move to be sent to board */ public static Move promote(String source, String destination, PieceType replacement) { return new Move(source, destination, replacement); } /** * Emit a drop-in (Crazyhouse specific move where player summons * a captured piece onto a free tile. Pawns can not be dropped in first and last rows) * @param destination * @param replacement * @return */ public static Move dropIn(String destination, PieceType replacement) { return new Move(null, destination, replacement); } public boolean isCastle() { return source.isPresent() && destination.isPresent() && (Math.abs(getDestinationY() - getSourceY()) == 2); } public static Move resign() { return new Move(null, null, null); } public static String serializeMove(Move move) { if (move.isNormal()) return move.getSource().orElse("") + move.getDestination().orElse(""); else if (move.isPromotion() && move.getReplacement().isPresent()) { String pieceCode = switch (move.getReplacement().get()) { case BISHOP -> "b"; case KNIGHT -> "n"; case ROOK -> "r"; case QUEEN -> "q"; default -> ""; }; return move.getSource().orElse("") + move.getDestination().orElse("") + pieceCode; } else if (move.isDropIn() && move.getReplacement().isPresent()) { String pieceCode = switch (move.getReplacement().get()) { case BISHOP -> "B"; case KNIGHT -> "N"; case ROOK -> "R"; case QUEEN -> "Q"; case PAWN -> "P"; default -> ""; }; return pieceCode + "@" + move.getDestination().get(); } else { return "resign"; } } public static Move deserializeMove(String s) { if (s.charAt(1) == '@') { /* Drop-in */ PieceType piece = switch (s.charAt(0)) { case 'P' -> PieceType.PAWN; case 'R' -> PieceType.ROOK; case 'B' -> PieceType.BISHOP; case 'N' -> PieceType.KNIGHT; case 'Q' -> PieceType.QUEEN; case 'K' -> PieceType.KING; /* This is an illegal move */ default -> null; }; return Move.dropIn(s.substring(2, 4), piece); } else if (s.length() == 5) { /* Pawn promotion */ PieceType piece = switch (s.charAt(4)) { case 'p' -> PieceType.PAWN; /* This is an illegal move */ case 'r' -> PieceType.ROOK; case 'b' -> PieceType.BISHOP; case 'n' -> PieceType.KNIGHT; case 'q' -> PieceType.QUEEN; case 'k' -> PieceType.KING; /* This is an illegal move */ default -> null; }; return Move.promote(s.substring(0, 2), s.substring(2, 4), piece); } /* Normal move/capture/castle/en passant */ return Move.moveTo(s.substring(0, 2), s.substring(2, 4)); } }
OctavianMihaila/Chess-engine-Crazyhouse
main/Move.java
1,766
/* This is an illegal move */
block_comment
en
true
240400_1
public class StateDecider { int[] grid; // 1 -> black ---- 2 -> white public boolean turn; // true -> black ---- false -> white int noFilled; static int[] xs; static int[] ys; static final int CELLS = 271; static final int XS = 225; static final int YS = 76; static final int W = 38; static final int H = 19; static final double XDIST = 19.72; static final double YDIST = 34.2; static boolean[] visited; static final int expectedDist = 45; static boolean[] lineVisited; static Pair[][] neighbors; static int opponentCount; public boolean isValid(int idx) { if (grid[idx] != 0) return false; Pair[] nearest = getNearestSix(idx); int cfilled = 0; for (int i = 0; i < nearest.length; i++) { int nidx = nearest[i].idx; if (grid[nidx] != 0) { cfilled++; } } if (cfilled > 1 || (cfilled == 1 && noFilled == 1)) return true; else return false; } public Pair[] getNearestSix(int idx) { return neighbors[idx]; } boolean isWinning(int idx) { return trapped(idx) || (countConsecutive(idx) >= 5); } public int countConsecutive(int idx) { int color = grid[idx]; int x = xs[idx]; int y = ys[idx]; Pair[] neighbors = getNearestSix(idx); int line = 0; for (Pair p : neighbors) { int nx = xs[p.idx]; int ny = ys[p.idx]; if (color == grid[p.idx]) { lineVisited = new boolean[CELLS]; int dir = (ny - y) / (nx - x); lineVisited[idx] = true; int line1 = checkLine(p.idx, dir, nx, ny, 2); int line2 = checkLine(idx, dir, x, y, 0); line = Math.max(line, line1 + line2); } } return line; } public int checkLine(int idx, int m, int x, int y, int depth) { lineVisited[idx] = true; if (depth == 5) return depth; int color = grid[idx]; Pair[] neighbors = getNearestSix(idx); for (Pair p : neighbors) { int nx = xs[p.idx]; int ny = ys[p.idx]; int slope = (ny - y) / (nx - x); if (!lineVisited[p.idx] && color == grid[p.idx] && slope == m) { return checkLine(p.idx, slope, nx, ny, depth + 1); } } return depth; } private boolean trapped(int idx) { int searchfor; if (turn) searchfor = 2; else searchfor = 1; Pair[] neighbors = getNearestSix(idx); boolean allfree = true; for (int i = 0; i < neighbors.length; i++) { visited = new boolean[CELLS]; // this was a huge bug, I was initializing the array before the loop so // sometimes it doesn't find a way out to the edge int nidx = neighbors[i].idx; if (grid[nidx] == searchfor || grid[nidx] == 0) { opponentCount = 0; if (grid[nidx] == searchfor) opponentCount++; boolean componentFree = freeDfs(nidx, searchfor); if (opponentCount > 0) allfree &= componentFree; } } return !allfree; } private boolean freeDfs(int i, int color) { visited[i] = true; Pair[] neighbors = getNearestSix(i); if (neighbors.length < 6) return true; boolean currentFree = false; for (Pair p : neighbors) { if (!visited[p.idx] && (grid[p.idx] == 0 || grid[p.idx] == color)) { if (grid[p.idx] == color) opponentCount++; currentFree |= freeDfs(p.idx, color); } } return currentFree; } double dist(int x, int y, int x2, int y2) { return Math.sqrt((x - x2) * (x - x2) + (y - y2) * (y - y2)); } }
ATAboukhadra/ANDANTINO
src/StateDecider.java
1,227
// true -> black ---- false -> white
line_comment
en
true
240443_3
import java.util.*; import java.util.stream.Collectors; class Addressbook { HashMap<Integer, Person> contactList = new HashMap<>(); HashMap<String, List<Person>> cityDictionary = new HashMap<>(); HashMap<String, List<Person>> stateDictionary = new HashMap<>(); public void addPerson(AddressbookService addressBookService) { Person newPerson = new Person(); addressBookService.setValues(newPerson); if (!isDuplicate(newPerson)) { int countId = contactList.size() + 1; contactList.put(countId, newPerson); // Update dictionaries updateCityDictionary(newPerson); updateStateDictionary(newPerson); System.out.println("Contact added with contactid: " + countId); } else { System.out.println("Duplicate entry. Person with the same name already exists."); } } public void searchByCityOrState(String cityOrState) { System.out.println("Search results in " + cityOrState + ":"); contactList.values().stream() .filter(person -> person.getCity().equalsIgnoreCase(cityOrState) || person.getState().equalsIgnoreCase(cityOrState)) .forEach(person -> System.out.println(person.toString())); } private boolean isDuplicate(Person newPerson) { return contactList.values().stream().anyMatch(existingPerson -> existingPerson.equals(newPerson)); } private void updateCityDictionary(Person person) { cityDictionary.computeIfAbsent(person.getCity(), k -> new ArrayList<>()).add(person); } private void updateStateDictionary(Person person) { stateDictionary.computeIfAbsent(person.getState(), k -> new ArrayList<>()).add(person); } public void viewPersonsByCity(String city) { System.out.println("Persons in " + city + ":"); cityDictionary.getOrDefault(city, Collections.emptyList()) .forEach(person -> System.out.println(person.toString())); } public void viewPersonsByState(String state) { System.out.println("Persons in " + state + ":"); stateDictionary.getOrDefault(state, Collections.emptyList()) .forEach(person -> System.out.println(person.toString())); } public void display(Person person) { for (Map.Entry<Integer, Person> entry : contactList.entrySet()) { System.out.println(entry.getKey() + ": " + entry.getValue().toString()); } } public long getCountByCity(String city) { return cityDictionary.getOrDefault(city, Collections.emptyList()).size(); } public long getCountByState(String state) { return stateDictionary.getOrDefault(state, Collections.emptyList()).size(); } public void sortEntriesByName() { List<Person> sortedList = contactList.values().stream() .sorted(Comparator.comparing(Person::getFirstname)) .collect(Collectors.toList()); // Print sorted entries System.out.println("Sorted entries by name:"); sortedList.forEach(person -> System.out.println(person.toString())); } public void sortEntriesByCity() { List<Person> sortedList = contactList.values().stream() .sorted(Comparator.comparing(Person::getCity)) .collect(Collectors.toList()); // Print sorted entries System.out.println("Sorted entries by City:"); sortedList.forEach(person -> System.out.println(person.toString())); } public void sortEntriesByState() { List<Person> sortedList = contactList.values().stream() .sorted(Comparator.comparing(Person::getState)) .collect(Collectors.toList()); // Print sorted entries System.out.println("Sorted entries by State:"); sortedList.forEach(person -> System.out.println(person.toString())); } public void sortEntriesByZip() { List<Person> sortedList = contactList.values().stream() .sorted(Comparator.comparingInt(Person::getZip)) .collect(Collectors.toList()); // Print sorted entries System.out.println("Sorted entries by Zip:"); sortedList.forEach(person -> System.out.println(person.toString())); } }
K0more/AddressBook_Java_Practice
src/Addressbook.java
958
// Print sorted entries
line_comment
en
true
240625_1
package edu.hawaii.ics621; import java.util.ArrayList; import java.util.List; import java.util.Random; import edu.hawaii.ics621.algorithms.KMeans; public class Main { public static final int INPUT_SIZE = 1000; public static final int CLUSTERS = 5; /** * @param args */ public static void main(String[] args) { // Generate a list of items. List<DoublePoint> inputs = new ArrayList<DoublePoint>(); Random generator = new Random(); for (int i = 0; i < 100; i++) { inputs.add(new DoublePoint(generator.nextDouble(), generator.nextDouble())); } KMeans clusterer = new KMeans(); System.out.println("Clustering items"); List<DoublePoint> results = clusterer.cluster(inputs, CLUSTERS); DoublePoint point; for (int i = 0; i < results.size(); i++) { point = results.get(i); System.out.println("Cluster " + (i + 1) + ": " + point.toString()); } } }
keokilee/kmeans-hadoop
src/edu/hawaii/ics621/Main.java
281
// Generate a list of items.
line_comment
en
false
240633_16
/* * this class receives Opponent, Team Score, and Opponent Score info from Scraper.java * stores that information into its own Array Lists * and then uses that info to insert into the DB */ package scoresESPN; import java.sql.Connection; import java.sql.DriverManager; import java.sql.Statement; import java.util.ArrayList; import java.util.Map; public class updateScoresDB { // DB Info String DBName = "Scores2016"; String DBurl = "jdbc:mysql://localhost:3306/" + DBName + "?useSSL=false"; String DBusername = "root"; String DBpassword = "Wutangclan25"; public String teamName; // array of opponents faced by team one public static ArrayList<String> opponentsArrayList = new ArrayList<String>(); // array for points scored by team one on offense public static ArrayList<Integer> scoresArrayList = new ArrayList<Integer>(); // array for points given up by team one on defense public static ArrayList<Integer> opponentsScoresArrayList = new ArrayList<Integer>(); public static void main(String[] args) { } public void receiveTeamName(String team) { teamName = team; } public void receiveTeamOpponentsArray(ArrayList<String> opponentsArray) { for (String opp : opponentsArray) { opponentsArrayList.add(opp); } } public void receiveTeamScoresArray(ArrayList<Integer> scoresArray) { for (Integer score : scoresArray) { scoresArrayList.add(score); } } public void receiveTeamOpponentScoresArray(ArrayList<Integer> oppScoreArray) { for (Integer score : oppScoreArray) { opponentsScoresArrayList.add(score); } } public void teamUpdateDB() { for (int i = 0; i < opponentsArrayList.size(); i++) { String opponent = opponentsArrayList.get(i); int teamScore = scoresArrayList.get(i); int opponentScore = opponentsScoresArrayList.get(i); // check for hawaii as opponent if (opponent.contains("'")) { teamHawaii(teamScore, opponentScore); continue; } // check for San Jose St as opponent Boolean b = opponent.startsWith("San Jos"); if (b) { teamSanJose(teamScore, opponentScore); continue; } try { // 1. Get a connection to database Connection myConn = DriverManager.getConnection(DBurl, DBusername, DBpassword); // 2. Create a statement Statement myStmt = myConn.createStatement(); // 3. Execute a SQL Query int yourRs = myStmt.executeUpdate( "INSERT INTO `" + DBName + "`.`" + teamName + "`" + " (Opponent, TeamScore, OpponentScore) VALUES(" + "'" + opponent + "'" + ", " + teamScore + ", " + opponentScore + ");" ); } catch (Exception ex) { System.out.println("exception is " + ex); } } // clear out all Array Lists opponentsArrayList.clear(); scoresArrayList.clear(); opponentsScoresArrayList.clear(); } // handles Hawaii as opponent name public void teamHawaii(int teamScore, int opponentScore) { try { // 1. Get a connection to database Connection myConn = DriverManager.getConnection(DBurl, DBusername, DBpassword); // 2. Create a statement Statement myStmt = myConn.createStatement(); // 3. Execute a SQL Query int yourRs = myStmt.executeUpdate( "INSERT INTO `" + DBName + "`.`" + teamName + "`" + " (Opponent, TeamScore, OpponentScore) VALUES('Hawaii', " + teamScore + ", " + opponentScore + ");" ); } catch (Exception ex) { System.out.println("exception is " + ex); } } // handles San Jose State as opponent name public void teamSanJose(int teamScore, int opponentScore) { try { // 1. Get a connection to database Connection myConn = DriverManager.getConnection(DBurl, DBusername, DBpassword); // 2. Create a statement Statement myStmt = myConn.createStatement(); // 3. Execute a SQL Query int yourRs = myStmt.executeUpdate( "INSERT INTO `" + DBName + "`.`" + teamName + "`" + " (Opponent, TeamScore, OpponentScore) VALUES('San Jose State', " + teamScore + ", " + opponentScore + ");" ); } catch (Exception ex) { System.out.println("exception is " + ex); } } }
SpencerCornelia/CollegeFootballGambling
src/scoresESPN/updateScoresDB.java
1,204
// handles San Jose State as opponent name
line_comment
en
true
240696_0
/* Copyright INRIA/Scilab - Sylvestre LEDRU # Sylvestre LEDRU - <sylvestre.ledru@inria.fr> <sylvestre@ledru.info> This software is a computer program whose purpose is to generate C++ wrapper for Java objects/methods. This software is governed by the CeCILL license under French law and abiding by the rules of distribution of free software. You can use, modify and/ or redistribute the software under the terms of the CeCILL license as circulated by CEA, CNRS and INRIA at the following URL "http://www.cecill.info". As a counterpart to the access to the source code and rights to copy, modify and redistribute granted by the license, users are provided only with a limited warranty and the software's author, the holder of the economic rights, and the successive licensors have only limited liability. In this respect, the user's attention is drawn to the risks associated with loading, using, modifying and/or developing or reproducing the software by the user in light of its specific status of free software, that may mean that it is complicated to manipulate, and that also therefore means that it is reserved for developers and experienced professionals having in-depth computer knowledge. Users are therefore encouraged to load and test the software's suitability as regards their requirements in conditions enabling the security of their systems and/or data to be ensured and, more generally, to use and operate it in the same conditions as regards security. The fact that you are presently reading this means that you have had knowledge of the CeCILL license and that you accept its terms. For more information, see the file COPYING */ package inherit; public class Son extends Father{ public Son(){ System.out.println("Java Son Constructor"); } public String sonMethod(){ return "in sonMethod"; } }
opencollab/giws
examples/inherit/inherit/Son.java
481
/* Copyright INRIA/Scilab - Sylvestre LEDRU # Sylvestre LEDRU - <sylvestre.ledru@inria.fr> <sylvestre@ledru.info> This software is a computer program whose purpose is to generate C++ wrapper for Java objects/methods. This software is governed by the CeCILL license under French law and abiding by the rules of distribution of free software. You can use, modify and/ or redistribute the software under the terms of the CeCILL license as circulated by CEA, CNRS and INRIA at the following URL "http://www.cecill.info". As a counterpart to the access to the source code and rights to copy, modify and redistribute granted by the license, users are provided only with a limited warranty and the software's author, the holder of the economic rights, and the successive licensors have only limited liability. In this respect, the user's attention is drawn to the risks associated with loading, using, modifying and/or developing or reproducing the software by the user in light of its specific status of free software, that may mean that it is complicated to manipulate, and that also therefore means that it is reserved for developers and experienced professionals having in-depth computer knowledge. Users are therefore encouraged to load and test the software's suitability as regards their requirements in conditions enabling the security of their systems and/or data to be ensured and, more generally, to use and operate it in the same conditions as regards security. The fact that you are presently reading this means that you have had knowledge of the CeCILL license and that you accept its terms. For more information, see the file COPYING */
block_comment
en
true
240730_1
/* Copyright or (C) or Copr. GET / ENST, Telecom-Paris, Ludovic Apvrille * * ludovic.apvrille AT enst.fr * * This software is a computer program whose purpose is to allow the * edition of TURTLE analysis, design and deployment diagrams, to * allow the generation of RT-LOTOS or Java code from this diagram, * and at last to allow the analysis of formal validation traces * obtained from external tools, e.g. RTL from LAAS-CNRS and CADP * from INRIA Rhone-Alpes. * * This software is governed by the CeCILL license under French law and * abiding by the rules of distribution of free software. You can use, * modify and/ or redistribute the software under the terms of the CeCILL * license as circulated by CEA, CNRS and INRIA at the following URL * "http://www.cecill.info". * * As a counterpart to the access to the source code and rights to copy, * modify and redistribute granted by the license, users are provided only * with a limited warranty and the software's author, the holder of the * economic rights, and the successive licensors have only limited * liability. * * In this respect, the user's attention is drawn to the risks associated * with loading, using, modifying and/or developing or reproducing the * software by the user in light of its specific status of free software, * that may mean that it is complicated to manipulate, and that also * therefore means that it is reserved for developers and experienced * professionals having in-depth computer knowledge. Users are therefore * encouraged to load and test the software's suitability as regards their * requirements in conditions enabling the security of their systems and/or * data to be ensured and, more generally, to use and operate it in the * same conditions as regards security. * * The fact that you are presently reading this means that you have had * knowledge of the CeCILL license and that you accept its terms. */ package ui.sd; import myutil.GraphicLib; import ui.*; import ui.util.IconManager; import java.awt.*; /** * Class SDCoregion * Action state of a sequence diagram * Creation: 07/10/2004 * @version 1.0 07/10/2004 * @author Ludovic APVRILLE */ public class SDCoregion extends TGCOneLineText implements SwallowedTGComponent { public SDCoregion(int _x, int _y, int _minX, int _maxX, int _minY, int _maxY, boolean _pos, TGComponent _father, TDiagramPanel _tdp) { super(_x, _y, _minX, _maxX, _minY, _maxY, _pos, _father, _tdp); width = 20; height = 100; minWidth = 20; nbConnectingPoint = 0; addTGConnectingPointsComment(); moveable = true; editable = false; removable = true; value = "action"; name = "action state"; myImageIcon = IconManager.imgic520; } public void internalDrawing(Graphics g) { g.drawRect(x - width/2, y, width, height); } public TGComponent isOnMe(int _x, int _y) { if (GraphicLib.isInRectangle(_x, _y, x - width/2, y, width, height)) { return this; } return null; } public int getType() { return TGComponentManager.SD_COREGION; } }
mhaeuser/TTool
src/main/java/ui/sd/SDCoregion.java
905
/** * Class SDCoregion * Action state of a sequence diagram * Creation: 07/10/2004 * @version 1.0 07/10/2004 * @author Ludovic APVRILLE */
block_comment
en
true
240950_16
/* * Register File - It handles all the operations that are carried on register and its values. A single array was used for all register to avoid writing * operations again. Character array with 1 and 0 was used for Flag Register. */ public class regFile { private short[] Reg = new short[31]; private char[] flag = {'0','0','0','0','0','0','0','0','0','0','0','0','0','0','0','0'}; public regFile() { setReg((byte) 16, (short) 0); // first special purpose register (Zero Register) //setReg((byte) 17, (short) 0); // code base //setReg((byte) 18, (short) 0); code limit //setReg((byte) 19, (short) 0); // code counter //setReg((byte) 20, (short) 0); // stack base //setReg((byte) 21, (short) 0); // stack limit (50 bytes) //setReg((byte) 22, (short) 0); // stack counter //setReg((byte) 23, (short) 0); // data base //setReg((byte) 24, (short) 0); // data limit //setReg((byte) 25, (short) 0); // data counter } public short getReg(byte code) { return Reg[code]; } public void setReg(byte code, short value) { Reg[code] = value; } /** * @dev The function checks if answer is negative or zero and set sign or zero bit accordingly in flag register. * @param answer */ public void setZero_Sign(short answer) { if (answer == 0) flag[1] = '1'; else flag[1] = '0'; if (answer < 0) flag[2] ='1'; else flag[2] ='0'; } /** * @dev The function checks if there would be carry in answer after applying shift or rotate operations. * If target value is less than 0 means when MSB is ON. * @param trg */ public void setCarry(short trg) { if(trg<0) flag[0] = '1'; else flag[0] = '0'; } /** * @dev Checks for the overflow, Each case is checked differently depending on operations. * 1 = ADD, 2 = SUBTRACT, 3 = MULTIPLY, 5 = AND , 6 = OR. * @param trg = target register value before operation * @param src = source register value before operation * @param x */ public void setOverflow(short trg, short src, int x) { boolean bit = false; short result; int itrg = 0, isrc=0, iresult=0; switch (x) { case 1: result = (short) (trg + src); if (src<0 && trg<0 && result>0) bit = true; else if (src>0 && trg>0 && result<0) bit = true; break; case 2: result = (short) (trg - src); if (src<0 && trg>0 && result<0) bit = true; else if (src>0 && trg<0 && result>0) bit = true; break; case 3: result = (short) (trg * src); if (src == 0 || trg == 0) bit = false; if (src == result / trg) bit = false; else bit = true; break; case 5: result = (short) (trg & src); itrg = (int) trg; isrc = (int) src; iresult = itrg & isrc; if(iresult != result) bit = true; break; case 6: result = (short) (trg | src); itrg = (int) trg; isrc = (int) src; iresult = itrg | isrc; if(iresult != result) bit = true; break; } if(!bit) flag[3] = '0'; else flag[3] = '1'; } /** * @dev Reinitialize flag register values to 0. */ public void reFlag() { for(int i = flag.length-1 ; i >=0 ; i--){ flag[i] = '0'; } } /** * @dev It returns the value of bit at the index x in flag register. * @param x * @return */ public char getFlag(int x) { return flag[x]; } public void setFlag(int x, char value) { flag[x] = value; } /** * @dev Following are the arithmetic, logical, rotate, shift operations on registers and immediate. * @param trg = target register * @param src = source register * @param num = immediate */ public void MOV(byte trg, byte src) { Reg[trg] = Reg[src]; } public void ADD(byte trg, byte src) { setOverflow(Reg[trg], Reg[src], 1); Reg[trg] += Reg[src]; setZero_Sign(Reg[trg]); } public void SUB(byte trg, byte src) { setOverflow(Reg[trg], Reg[src], 2); Reg[trg] -= Reg[src]; setZero_Sign(Reg[trg]); } public void MUL(byte trg, byte src) { setOverflow(Reg[trg], Reg[src], 3); Reg[trg] *= Reg[src]; setZero_Sign(Reg[trg]); } public void DIV(byte trg, byte src) { if(Reg[trg] != 0) { Reg[trg] /= Reg[src]; setZero_Sign(Reg[trg]); } else System.out.println("Not divisible by 0"); } public void AND(byte trg, byte src) { setOverflow(Reg[trg], Reg[src], 5); Reg[trg] &= Reg[src]; setZero_Sign(Reg[trg]); } public void OR(byte trg, byte src) { setOverflow(Reg[trg], Reg[src], 6); Reg[trg] |= Reg[src]; setZero_Sign(Reg[trg]); } public void MOVI(byte trg, short num) { Reg[trg] = num; } public void ADDI(byte trg, short num) { setOverflow(Reg[trg], num, 1); Reg[trg] += num; setZero_Sign(Reg[trg]); } public void SUBI(byte trg, short num) { setOverflow(Reg[trg], num, 2); Reg[trg] -= num; setZero_Sign(Reg[trg]); } public void MULI(byte trg, short num) { setOverflow(Reg[trg], num, 3); Reg[trg] *= num; setZero_Sign(Reg[trg]); } public void DIVI(byte trg, short num) { if(Reg[trg] != 0) { Reg[trg] /= num; setZero_Sign(Reg[trg]); } else System.out.println("Not divisible by 0"); } public void ANDI(byte trg, short num) { setOverflow(Reg[trg], num, 5); Reg[trg] &= num; setZero_Sign(Reg[trg]); } public void ORI(byte trg, short num) { setOverflow(Reg[trg], num, 6); Reg[trg] |= num; setZero_Sign(Reg[trg]); } public void SHL(byte trg) { setCarry(Reg[trg]); Reg[trg] <<= 1; setZero_Sign(Reg[trg]); } public void SHR(byte trg) { setCarry(Reg[trg]); Reg[trg] <<= 1; setZero_Sign(Reg[trg]); } public void RTL(byte trg) { setCarry(Reg[trg]); Reg[trg] = (short) Integer.rotateLeft(Reg[trg],1); setZero_Sign(Reg[trg]); } public void RTR(byte trg) { setCarry(Reg[trg]); Reg[trg] = (short) Integer.rotateLeft(Reg[trg],-1); setZero_Sign(Reg[trg]); } public void INC(byte trg) { Reg[trg]++; } public void DEC(byte trg) { Reg[trg]--; } /** * @dev General Register are printed first then Special Register. * For special register address is converted to int first to avoid negative addresses. * Flag register is printed in binary with MSB = flag[16] and LSB = flag[0]. */ public String printGenReg() { String output = ""; //System.out.println("General Register values:"); output += "\n" + "General Register values:" + "\n"; for (int i = 0; i < 16; i++) { //System.out.println("Reg " + (i) + ": " + Reg[i]); output += "Reg " + (i) + ": " + Reg[i] + "\n"; } //System.out.println("Special Register values:"); output += "Special Register values:" + "\n"; for (int i = 16; i < Reg.length; i++) { //System.out.println("Reg " + (i) + ": " + Short.toUnsignedInt(Reg[i])); output += "Reg " + (i) + ": " + Short.toUnsignedInt(Reg[i]) + "\n"; } //System.out.println("Flag Register"); for(int i = flag.length-1 ; i >=0 ; i--){ //System.out.print(flag[i]); output += flag[i]; } System.out.println(); output += "\n"; System.out.println("------------------------------"); output += "------------------------------" + "\n"; return output; } }
shariqanwar20/Operating-System
regFile.java
2,543
/** * @dev Following are the arithmetic, logical, rotate, shift operations on registers and immediate. * @param trg = target register * @param src = source register * @param num = immediate */
block_comment
en
true
241114_0
/* Staircase Your teacher has given you the task to draw the structure of a staircase. Being an expert programmer, you decided to make a program for the same. You are given the height of the staircase. You need to print a staircase as shown in the example. Input Format You are given an integer N depicting the height of the staircase. Constraints 1≤N≤100 Output Format Draw a staircase of height N in the format given below. For example: # ## ### #### ##### ###### Staircase of height 6, note that last line has 0 spaces before it. */ import java.io.*; import java.util.*; import java.text.*; import java.math.*; import java.util.regex.*; public class Solution { public static void main(String[] args) { Scanner sc = new Scanner(System.in); int num = Integer.parseInt(sc.nextLine()); for(int j=0;j<num;j++){ for(int i=1;i<=num;i++){ System.out.print(i<num-j?" ":"#"); } System.out.println(""); } } }
jhflorey/HackerRank
staircase.java
286
/* Staircase Your teacher has given you the task to draw the structure of a staircase. Being an expert programmer, you decided to make a program for the same. You are given the height of the staircase. You need to print a staircase as shown in the example. Input Format You are given an integer N depicting the height of the staircase. Constraints 1≤N≤100 Output Format Draw a staircase of height N in the format given below. For example: # ## ### #### ##### ###### Staircase of height 6, note that last line has 0 spaces before it. */
block_comment
en
true
241594_0
public class Player { Boolean advantage; Score score; int setWon; int gameWon; public Player(){ this.setAdvantage(false); score = Score.LOVE; } public int getSet() { return setWon; } public void setSet(int set) { this.setWon = set; } public void winGame() { gameWon++; } public int getGameWon() { return gameWon; } public Boolean hasAdvantage() { return advantage; } public void setAdvantage(Boolean advantage) { this.advantage = advantage; } public Score getScore(){ return score; } public void winPoint(){ switch(score){ case LOVE: score = Score.FIFTEEN; break; case FIFTEEN : score = Score.THIRTY; break; case THIRTY: score = Score.FORTY; break; case FORTY: //please do stuff break; } } }
CodingDojoPolytech/tennis
src/Player.java
289
//please do stuff
line_comment
en
true
241643_0
package James_Module2; public class TennisGame { private static final int WINNING_SCORE = 4; public String getScore(int player1Points, int player2Points) { if (isGameWon(player1Points, player2Points)) { return getWinningPlayerName(player1Points, player2Points) + " wins"; } if (isGameInDeuce(player1Points, player2Points)) { return "Deuce"; } if (isGameWon(player1Points, player2Points)) { return getWinningPlayerName(player1Points, player2Points) + " wins"; } if (isGameInDeuce(player1Points, player2Points)) { return "Deuce"; } if (isAdvantage(player1Points, player2Points)) { return getAdvantagePlayerName(player1Points, player2Points) + " has advantage"; } if (isGameInTieBreak(player1Points, player2Points)) { return "Tiebreak"; } // Add other scoring conditions and logic here... return "Current score"; } private boolean isGameInTieBreak(int player1Points, int player2Points) { return isScoreGreaterThanWinning(player1Points) && isScoreGreaterThanWinning(player2Points) && Math.abs(player1Points - player2Points) == 1; } private String getAdvantagePlayerName(int player1Points, int player2Points) { return (player1Points > player2Points) ? "Player 1" : "Player 2"; } private boolean isAdvantage(int player1Points, int player2Points) { return isScoreGreaterThanWinning(player1Points) && isScoreGreaterThanWinning(player2Points) && Math.abs(player1Points - player2Points) == 1; } private boolean isGameWon(int player1Points, int player2Points) { return isScoreGreaterThanWinning(player1Points) || isScoreGreaterThanWinning(player2Points) && Math.abs(player1Points - player2Points) >= 2; } private boolean isScoreGreaterThanWinning(int score) { return score >= WINNING_SCORE; } private String getWinningPlayerName(int player1Points, int player2Points) { return (player1Points > player2Points) ? "Player 1" : "Player 2"; } private boolean isGameInDeuce(int player1Points, int player2Points) { return isScoreAtLeast(player1Points) && isScoreAtLeast(player2Points) && player1Points == player2Points; } private boolean isScoreAtLeast(int playerPoints) { return playerPoints >= 3; } public static void main(String[] args){ TennisGame tennisGame = new TennisGame(); int player1Points = 3; int player2Points = 3; String currentScore = tennisGame.getScore(player1Points, player2Points); System.out.println("Current Score: " + currentScore); } }
nhathuynguyenhai1999/Java_Homework
TennisGame.java
723
// Add other scoring conditions and logic here...
line_comment
en
true
241647_3
import java.util.Scanner; /** * * @author */ public class TennisKata { private int player1Points = 0; private int player2Points = 0; private final int FOUR = 4; private final int THREE = 3; private final int TWO = 2; private final int ONE = 1; private final String PLAYER_1 = "Player 1"; private final String PLAYER_2 = "Player 2"; private Scanner scanner; public static void main(String args[]) { TennisKata kata = new TennisKata(); kata.getPlayerPoints(); System.out.println(kata.processPlayerPoints()); } /** * Takes input points for Player 1 and Player 2. */ private void getPlayerPoints() { scanner = new Scanner(System.in); getPlayer1Points(); getPlayer2Points(); } /** * Takes and validates input for Player 1 points. */ private void getPlayer1Points() { try { System.out.println("Enter player 1 points:"); player1Points = Integer.parseInt(scanner.next()); } catch (NumberFormatException e) { System.out.println("Please enter valid points"); getPlayer1Points(); } } /** * Takes and validates input for Player 2 points. */ private void getPlayer2Points() { try { System.out.println("Enter player 2 points:"); player2Points = Integer.parseInt(scanner.next()); } catch (NumberFormatException e) { System.out.println("Please enter valid points"); getPlayer2Points(); } } /** * Processes the points depending upon conditions. * * @return String value stating the result. */ private String processPlayerPoints() { String result = getWinnerIfAvailable(); if (result != null) { return (result + " wins"); } result = getDeuceIfAvailable(); if (result != null) { return result; } result = getAdvantagePlayerIfAvailable(); if (result != null) { return (result + " has advantage"); } if (arePointsEqual()) { return (getPointsValue(player1Points) + " all"); } return (getPointsValue(player1Points) + "," + getPointsValue(player2Points)); } /** * Returns winner player. If a player has at least 4 points and leads by at * least 2 points then he is the winner. * * @return winner player. */ private String getWinnerIfAvailable() { if ((player1Points >= FOUR) && (player1Points >= (player2Points + TWO))) { return PLAYER_1; } if ((player2Points >= FOUR) && (player2Points >= (player1Points + TWO))) { return PLAYER_2; } return null; } /** * Returns player with advantage. If both player has at least 3 points and a * player is leading with 1 point then that player has advantage. * * @return player with advantage. */ private String getAdvantagePlayerIfAvailable() { if (player1Points >= THREE && player2Points >= THREE) { if (player1Points == player2Points + ONE) { return PLAYER_1; } if (player2Points == player1Points + ONE) { return PLAYER_2; } } return null; } /** * Returns deuce if both players have at least 3 points and have same points * * @return deuce based on condition. */ private String getDeuceIfAvailable() { if (player1Points >= THREE && arePointsEqual()) { return "Deuce"; } return null; } /** * Returns true if both players have same points. * * @return true if both players have same points. */ private boolean arePointsEqual() { return player1Points == player2Points; } /** * Returns points value in Tennis terminology. * * @param points * @return points value in tennis terminology. */ private String getPointsValue(int points) { switch (points) { case 0: return "Love"; case ONE: return "Fifteen"; case TWO: return "Thirty"; case THREE: return "Forty"; default: System.out.println("Entered value is not legal."); } return null; } }
onkariwaligunje/2019_DEV_018
TennisKata.java
1,047
/** * Takes and validates input for Player 2 points. */
block_comment
en
false
241912_0
class Solution783 { class Solution { private int minDiff = Integer.MAX_VALUE; private TreeNode previous; /** * 783. Minimum Distance Between BST Nodes https://leetcode.com/problems/minimum-distance-between-bst-nodes/description/ * Inorder traversal of a BST processes the nodes in sorted order. We maintain the previously seen element while traversing * and compare with min seen so far to keep track of the min difference. * * @param root TreeNode * Root of the tree * @return Min difference between any two nodes * @timeComplexity O(n) where n is the number of nodes in tree * @spaceComplexity O(1) */ public int minDiffInBST(TreeNode root) { if (root == null) { return minDiff; } // Traverse left minDiffInBST(root.left); // Traverse root if (previous != null) { minDiff = Math.min(minDiff, root.val - previous.val); } previous = root; // Traverse right minDiffInBST(root.right); return minDiff; } } }
prabhakar97/leetcode
src/L783.java
271
/** * 783. Minimum Distance Between BST Nodes https://leetcode.com/problems/minimum-distance-between-bst-nodes/description/ * Inorder traversal of a BST processes the nodes in sorted order. We maintain the previously seen element while traversing * and compare with min seen so far to keep track of the min difference. * * @param root TreeNode * Root of the tree * @return Min difference between any two nodes * @timeComplexity O(n) where n is the number of nodes in tree * @spaceComplexity O(1) */
block_comment
en
true
242383_2
import weka.core.Instances; import weka.core.converters.ArffSaver; import weka.core.converters.CSVLoader; import weka.classifiers.trees.BFTree; import weka.core.SelectedTag; import weka.core.Instance; import java.util.Enumeration; import weka.classifiers.meta.AdaBoostM1; import java.io.File; /** * */ public class adult { /** * main method, runs things * @param args [description] */ public static void main(String[] args) throws Exception{ //load training data CSVLoader trainingdata = new CSVLoader(); trainingdata.setSource(new File("adult.data")); Instances data = trainingdata.getDataSet(); data.setClassIndex(data.numAttributes()-1); //load testing data CSVLoader testingdata = new CSVLoader(); testingdata.setSource(new File("adult.test")); Instances test = testingdata.getDataSet(); test.setClassIndex(test.numAttributes()-1); BFTree classifier = new BFTree(); classifier.setPruningStrategy(new SelectedTag(BFTree.PRUNING_POSTPRUNING, BFTree.TAGS_PRUNING)); classifier.buildClassifier(data); //System.out.println(classifier.classifyInstance(test.firstInstance())); double sumDifferences = 0; int count = 0; // for (Enumeration<Instance> e = test.enumerateInstances(); e.hasMoreElements();) { // Instance i = e.nextElement(); // //System.out.print(classifier.classifyInstance(i)+" "); // //System.out.println(i.value(test.numAttributes()-1)); // sumDifferences += (classifier.classifyInstance(i) - i.value(test.numAttributes()-1)) * (classifier.classifyInstance(i) - i.value(test.numAttributes()-1)); // count++; // //sum squared differences // } // System.out.println(count); // System.out.println(sumDifferences/count); count = 0; sumDifferences = 0; AdaBoostM1 clf = new AdaBoostM1(); String[] options = {"-I 25", "-W weka.classifiers.trees.BFTree"}; clf.setOptions(options); clf.buildClassifier(data); System.out.println(clf.getRevision()); for (Enumeration<Instance> e = test.enumerateInstances(); e.hasMoreElements();) { Instance i = e.nextElement(); sumDifferences += (clf.classifyInstance(i) - i.value(test.numAttributes()-1)) * (clf.classifyInstance(i) - i.value(test.numAttributes()-1)); count++; //sum squared differences } System.out.println(count); System.out.println(sumDifferences/count); } }
irapha/Machine-Learning
P1/Adults/adult.java
685
//load training data
line_comment
en
true
242436_0
/* 53. Input data exactly in the following format, and * print sum of all integer values. “67, 89, 23, 67, 12, 55, 66”. * (Hint use String class split method and Integer class parseInt method) . */ package p51_60; import java.util.Scanner; public class q53 { public static void main(String[] args) { // TODO Auto-generated method stub Scanner sc = new Scanner(System.in); System.out.println("Enter the String : "); String str = sc.nextLine(); String[] st = str.split(",\\s"); //", " int[] arr = new int[st.length]; for (int i = 0; i < st.length; i++) { arr[i] = Integer.parseInt(st[i]); } for (int i : arr) { System.out.println(i); } sc.close(); } }
adinathraut20/Java_Module
eclipse-workspace/Assignment50-70/src/p51_60/q53.java
253
/* 53. Input data exactly in the following format, and * print sum of all integer values. “67, 89, 23, 67, 12, 55, 66”. * (Hint use String class split method and Integer class parseInt method) . */
block_comment
en
true
242446_1
/* * To change this template, choose Tools | Templates * and open the template in the editor. */ package Map; import java.awt.Color; import java.awt.Dimension; import java.awt.Graphics; import java.awt.geom.Point2D; /** * * @author toddbodnar */ public interface map { public void draw(Graphics g); public void addPoint(Color c, Point2D location); public void addRectangle(Color c, Point2D[] bounds); public Dimension getDimensions(); }
digitalepidemiologylab/2016_TwitterEpi
.metadata/.plugins/org.eclipse.core.resources/.history/f9/d0ebdb3ed8fe00161a5efe1fc641ff0f
131
/** * * @author toddbodnar */
block_comment
en
true
242455_0
import java.util.Scanner; class HelloWorld{ public static void main(String args[]){ // From Another Class anotherClass myObject = new anotherClass(); myObject.myMessage(); // From Java Class Scanner shaf = new Scanner (System.in); javaClass myJavaObject = new javaClass(); System.out.println("Enter Your name here: "); String name = shaf.nextLine(); myJavaObject.myJavaClass(name); } }
findalam/selenium
.metadata/.plugins/org.eclipse.core.resources/.history/1b/b0330c06f64700181111ba913a214b81
128
// From Another Class
line_comment
en
true
242498_0
//Method Overriding and Inheritance: Create a class bankaccount with attributes acc_number and balance,and methods deposit(double amount) and withdraw(double amount) to add and subtract money from balance respectively.Then create two subclasses savings and checking which inherit from bankaccount. In savings, override withdraw() with a minimum balance $100 and in checking, override withdraw() method to allow overdraft upto $100 import java.util.Scanner; class bankaccount { String acc_no; double balance; bankaccount(String acc_no, double balance) { this.acc_no = acc_no; this.balance = balance; } void deposit(double amount) { if (amount > 0) { balance += amount; System.out.print("Successfully deposited Rs." + amount + " to A/C " + acc_no + ". Current balance Rs." + balance); } else { System.out.println("Please enter a valid amount"); } } void withdraw(double amount) { if (amount <= balance && amount > 0) { balance -= amount; System.out.print("Successfully withdrew Rs." + amount + " to A/C " + acc_no + ". Current balance Rs." + balance); } else { System.out.print("Please enter a valid amount.."); } } } class savings extends bankaccount { double min = 100.00; savings(String acc_no, double balance) { super(acc_no, balance); } void withdraw(double amount) { if (balance - amount >= min && amount > 0) { System.out.println("Successfully withdrew Rs." + amount + " to A/C " + acc_no + ". Current balance Rs." + balance); } else { System.out.println("Can't withdraw money. Balance is too low."); } } } class checking extends bankaccount { checking(String acc_no, double balance) { super(acc_no, balance); } void withdraw(double amount) { if (balance - amount >= -100.00) { balance -= amount; System.out.println("Successfully withdrew Rs." + amount + " to A/C " + acc_no + ". Current balance Rs." + balance); } else { System.out.println("Can't withdraw money. Overdraft exceeded."); } } } class myaccount { public static void main(String[] args) { Scanner sc = new Scanner(System.in); System.out.print("Enter account number: "); String acc_no = sc.nextLine(); System.out.print("Enter balance: "); double balance = sc.nextDouble(); sc.nextLine(); int choice; do { System.out.println("\n\t 1: Cash Deposit \n\t 2: Cash Withdraw \n\t 0: Exit: "); System.out.print("Enter choice :"); choice = sc.nextInt(); sc.nextLine(); switch (choice) { case 1: System.out.println("\t\t*****Cash Deposit****"); System.out.print("Enter amount: "); double depositAmount = sc.nextDouble(); sc.nextLine(); bankaccount b = new bankaccount(acc_no, balance); b.deposit(depositAmount); break; case 2: System.out.println("\t\t*****Cash Withdrawal****"); System.out.print("Enter amount: "); double withdrawalAmount = sc.nextDouble(); sc.nextLine(); // Creating separate instances for savings and checking accounts savings w1 = new savings(acc_no, balance); w1.withdraw(withdrawalAmount); checking w2 = new checking(acc_no, balance); w2.withdraw(withdrawalAmount); break; case 0: System.out.println("\n\t*****THANK YOU VISIT AGAIN****"); sc.nextLine(); break; default: System.out.println("\t\tWrong Choice"); } } while (choice != 0); sc.close(); } }
dipanjanchat/java-assignments
myaccount.java
971
//Method Overriding and Inheritance: Create a class bankaccount with attributes acc_number and balance,and methods deposit(double amount) and withdraw(double amount) to add and subtract money from balance respectively.Then create two subclasses savings and checking which inherit from bankaccount. In savings, override withdraw() with a minimum balance $100 and in checking, override withdraw() method to allow overdraft upto $100
line_comment
en
true