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
34303_0
import java.io.BufferedReader; import java.io.FileReader; import java.io.IOException; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import java.util.Objects; public class aoc7 { public static void main(String[] args) { BufferedReader reader; try { reader = new BufferedReader(new FileReader("C:\\Users\\Gebruiker\\git\\aoc2022\\sample7.txt")); String line = reader.readLine(); Directory topLeveldirectory = new Directory("/", null); Directory currentDirectory = topLeveldirectory; while (line != null) { String[] lineParts = line.split(" "); if(lineParts[0].equals("$")){ if(lineParts[1].equals("cd")){ if(lineParts[2].equals("..")){ currentDirectory = currentDirectory.parent; }else if(lineParts[2].equals("/")){ currentDirectory = topLeveldirectory; }else{ currentDirectory = (Directory) currentDirectory.retrieveContent(lineParts[2]); } line = reader.readLine(); }else if(lineParts[1].equals("ls")){ line = reader.readLine(); while (line != null && !line.startsWith("$")){ lineParts = line.split(" "); if(lineParts[0].equals("dir")){ currentDirectory.addContent(new Directory(lineParts[1], currentDirectory)); }else{ currentDirectory.addContent(new File(Integer.parseInt(lineParts[0]), lineParts[1], currentDirectory)); } line = reader.readLine(); } } } } int unusedSpace = 70000000 - topLeveldirectory.getSize(); int spaceNeeded = 30000000 - unusedSpace; System.out.println(topLeveldirectory.getSolutionPart2(spaceNeeded, 70000000)); //System.out.println(topLeveldirectory.getSolutionPart1()); reader.close(); } catch (IOException e) { e.printStackTrace(); } } } abstract class Item{ public String name; public Directory parent; public Item(String name, Directory parent){ this.name = name; this.parent = parent; } abstract int getSize(); } class Directory extends Item{ private List<Item> contents = new ArrayList<Item>(); public Directory(String name, Directory parent) { super(name, parent); } public void addContent(Item item){ this.contents.add(item); } public Item retrieveContent(String name){ return contents.stream().filter(c -> c.name.equals(name)).findFirst().get(); } @Override int getSize() { int size = 0; for(Item item : contents){ size += item.getSize(); } return size; } int getSolutionPart1() { int size = this.getSize(); if(size >= 100000){ size = 0; } for(Item item : contents){ if(item instanceof Directory) { size += ((Directory) item).getSolutionPart1(); } } return size; } int getSolutionPart2(int spaceNeeded, int smallestOption){ int sizeSmallestOption = smallestOption; for(Item item : contents){ if(item instanceof Directory) { int dirSize = item.getSize(); if(dirSize > spaceNeeded){ if(dirSize< sizeSmallestOption){ sizeSmallestOption = dirSize; } sizeSmallestOption = ((Directory) item).getSolutionPart2(spaceNeeded, sizeSmallestOption); } } } return sizeSmallestOption; } } class File extends Item{ private final int size; public File(int size, String name, Directory parent){ super(name, parent); this.size = size; } @Override int getSize() { return size; } }
NickDecoster/aoc2022
aoc7.java
924
//System.out.println(topLeveldirectory.getSolutionPart1());
line_comment
en
true
35021_2
/** * Represents an edge of a vertex in a directed graph. * @author dielhennr */ public class Edge { private int dest; private int rating; /** * Edge Constructor * @param dest, rating */ public Edge(int dest, int rating) { this.dest = dest; this.rating = rating; } /** * Returns the value of the vertex connected to the edge. * @return dest */ public int getDest() { return this.dest; } /** * Returns the rating of the edge. * @return rating */ public int getRating() { return this.rating; } }
dielhennr/project3-dielhennr
Edge.java
168
/** * Returns the value of the vertex connected to the edge. * @return dest */
block_comment
en
true
35291_0
/*=========================================================================== * * PUBLIC DOMAIN NOTICE * National Center for Biotechnology Information * * This software/database is a "United States Government Work" under the * terms of the United States Copyright Act. It was written as part of * the author's official duties as a United States Government employee and * thus cannot be copyrighted. This software/database is freely available * to the public for use. The National Library of Medicine and the U.S. * Government have not placed any restriction on its use or reproduction. * * Although all reasonable efforts have been taken to ensure the accuracy * and reliability of the software and data, the NLM and the U.S. * Government do not and cannot warrant the performance or results that * may be obtained by using this software or data. The NLM and the U.S. * Government disclaim all warranties, express or implied, including * warranties of performance, merchantability or fitness for any particular * purpose. * * Please cite the author in any work or product based on this material. * * =========================================================================== * */ public enum tt { SPOT, FRAG, ALIG, REF, RDGRP, PILEUP, NONE; public static tt from_string( final String s ) { try { return Enum.valueOf( tt.class, s.trim().toUpperCase() ); } catch ( IllegalArgumentException e ) { } return NONE; } }
ncbi/ngs-tools
tools/ngs_sql/src/tt.java
362
/*=========================================================================== * * PUBLIC DOMAIN NOTICE * National Center for Biotechnology Information * * This software/database is a "United States Government Work" under the * terms of the United States Copyright Act. It was written as part of * the author's official duties as a United States Government employee and * thus cannot be copyrighted. This software/database is freely available * to the public for use. The National Library of Medicine and the U.S. * Government have not placed any restriction on its use or reproduction. * * Although all reasonable efforts have been taken to ensure the accuracy * and reliability of the software and data, the NLM and the U.S. * Government do not and cannot warrant the performance or results that * may be obtained by using this software or data. The NLM and the U.S. * Government disclaim all warranties, express or implied, including * warranties of performance, merchantability or fitness for any particular * purpose. * * Please cite the author in any work or product based on this material. * * =========================================================================== * */
block_comment
en
true
35470_4
package EECEBP; public class Unit { // Constructor public Unit (int numberOfInputUnits) { //Create an array of weight with the same size as the vector of inputs to the unit weight = new double[numberOfInputUnits]; weightDiff = new double[numberOfInputUnits]; //Initialize the weights and threshold to the node initializeWeights(); } //vector of weights from previous units to current unit public double weight[]; //weight difference between the (n-1)th and nth iteration public double weightDiff[]; public double output; public double signalError; //Initialize both bias and unit weights to random values in the range -0.5 to +0.5 private void initializeWeights(){ for(int i=0; i<weight.length; i++) { //Initialize weights to random values in the range -0.5 to +0.5 weight[i] = Math.random()-0.5; //Initially, weightDiff is assigned to 0 so that the momentum term //can work during the 1st iteration weightDiff[i] = 0; } } };
zmike808/Backpropagation_Learning
Unit.java
277
//weight difference between the (n-1)th and nth iteration
line_comment
en
true
35480_17
import java.util.ArrayList; public class Gizmo { /** Returns the name of the manufacturer of this Gizmo. */ public String getMaker() { /* implementation not shown */ } /** * Returns true if this Gizmo is electronic, and false otherwise. */ public boolean isElectronic() { /* implementation not shown */ } /** * Returns true if this Gizmo is equivalent to the Gizmo object represented by * the parameter, and false otherwise. */ public boolean equals(final Object other) { /* implementation not shown */ } // There may be instance variables, constructors, and methods // not shown. } public class OnlinePurchaseManager { /** * An ArrayList of purchased Gizmo objects, instantiated in the constructor. */ private ArrayList<Gizmo> purchases; /** * Returns the number of purchased Gizmo objects that are electronic and are * manufactured by maker, as described in part (a). */ public int countElectronicsByMaker(final String maker) { /* to be implemented in part (a) */ int counter = 0; for(final Gizmo x : purchases) { if(x.getMaker().equals(maker) && x.isElectronic()) { counter++; } } return counter; } /** * Returns true if any pair of adjacent purchased Gizmo objects are equivalent, * and false otherwise, as described in part (b). */ public boolean hasAdjacentEqualPair() { /* to be implemented in part (b) */ Gizmo g1 = purchases.get(0); for(int i = 1; i < purchases.size(); i++) { Gizmo g2 = purchases.get(i); if(g1.equals(g2)) { return true; } g1 = g2; } return false; } // There may be instance variables, constructors, and methods // not shown. // 1. public Gizmo getCheapestGizmoByMaker(final String maker) { // 2. We would need to add a getter function getPrice() method in the Gizmo class. Add a new private instance variable of type double to store the price of the Gizmo. // 3. For our getPrice() method, first modify the Gizmo datatype to include price in double type. Loop through arraylist to find lowest price using getPrice() // We would also need to add a double parameter in the constructor of Gizmo to set the price during construction of the object. /**** PART C SAMPLE RESPONSE ****/ // Header: public Gizmo getCheapestGizmoByMaker(String maker) // In order to get the cheapest Gizmo by a particular maker, the Gizmo class would need // to add a new private instance variable of type double to store the price of the Gizmo // and/or include a getter function to return the price of the Gizmo (such as getPrice()). // The constructor of the Gizmo would also change to add a double parameter to set // the price during construction of the object. } }
xzrderek/ap-practice
Gizmo.java
703
// 3. For our getPrice() method, first modify the Gizmo datatype to include price in double type. Loop through arraylist to find lowest price using getPrice()
line_comment
en
true
35520_3
import javax.swing.BorderFactory; import javax.swing.JButton; import javax.swing.JFrame; import javax.swing.JLabel; import javax.swing.JPanel; import java.awt.BorderLayout; import java.awt.Color; import java.awt.GridLayout; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; public class GUI { public static void main(String[] args) { // Creates a new JFrame object JFrame frame = new JFrame(); // Creates a new JLabel that displays a welcome message on the GUI JLabel labelone = new JLabel("Welcome to USA states and capitals learner!"); // Centering the JLabel and setting the font color as white labelone.setHorizontalAlignment(JLabel.CENTER); labelone.setForeground(Color.white); // Creates a new JLabel that tells user to choose a game mode JLabel labeltwo = new JLabel("Choose your mode"); // Centering the JLabel and setting the font color as white labeltwo.setHorizontalAlignment(JLabel.CENTER); labeltwo.setForeground(Color.white); // Creates a new JButton named "States" for the states mode JButton buttonStates = new JButton("States"); // Sets the border around the button and the font color as blue buttonStates.setBackground(Color.blue); buttonStates.setOpaque(true); buttonStates.setForeground(Color.blue); // Creates a new JButton named "Capitals" for the capitals mode JButton buttonCapitals = new JButton("Capitals"); // Sets the border around the button and the font color as blue buttonCapitals.setBackground(Color.blue); buttonCapitals.setOpaque(true); buttonCapitals.setForeground(Color.blue); // Action listener for the capitals button that executes code for the capitals game mode buttonCapitals.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { // Code for capitals mode GuessCapital s = new GuessCapital(); int count = 0; Picture p = new Picture("States_of_the_USA_by_numbers.jpg"); p.show(); for (int i = 0; i < 50; i++) { System.out.println(s.questionGenerator()); String response = StdIn.readLine(); if (response.equalsIgnoreCase("Quit")) { s.numberOfQuestions--; System.out.println(s.result()); break; } s.checkAnswer(response); System.out.println(s.showIncorrectAns()); count++; } if (count == 50) System.out.println(s.result()); } }); // Action listener for the states button that executes code for the states game mode buttonStates.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { // code for states mode GuessState t = new GuessState(); int count = 0; Picture p = new Picture("States_of_the_USA_by_numbers.jpg"); p.show(); for (int i = 0; i < 50; i++) { System.out.println(t.questionGenerator()); String response = StdIn.readLine(); if (response.equalsIgnoreCase("Quit")) { t.numberOfQuestions--; System.out.println(t.result()); break; } t.checkAnswer(response); System.out.println(t.showIncorrectAns()); count++; } if (count == 50) System.out.println(t.result()); } }); // Creates a new JPanel object and sets up its border and layout JPanel panel = new JPanel(); panel.setBorder(BorderFactory.createEmptyBorder(30, 30, 10, 30)); panel.setLayout(new GridLayout(0, 1)); // Adding components to the JPanel, including the labels and buttons panel.add(labelone); panel.add(labeltwo); panel.add(buttonStates); panel.add(buttonCapitals); // Setting the panel color to red panel.setBackground(Color.RED); // Adding the panel to the JFrame and centering it frame.add(panel, BorderLayout.CENTER); // GUI closes when exited out of frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); // Title of the GUI/JFrame frame.setTitle("USA States and Capitals Learner"); frame.pack(); frame.setVisible(true); } }
BlaqPanther/States-and-Capital-Learner-
GUI.java
1,041
// Creates a new JLabel that tells user to choose a game mode
line_comment
en
true
35914_4
package Solved; /* ID: bigfish2 LANG: JAVA TASK: shopping */ import java.io.*; import java.util.*; public class shopping { static int options; static int[][] path; static long[][][][][] dp; static int[][] items; public static void main (String [] args) throws IOException { BufferedReader f = new BufferedReader(new FileReader("shopping.in")); PrintWriter out = new PrintWriter(new BufferedWriter(new FileWriter("shopping.out"))); options = Integer.parseInt(f.readLine()); path = new int[options][12]; for(int y = 0; y<options;y++){ StringTokenizer st = new StringTokenizer(f.readLine()); path[y][0] = Integer.parseInt(st.nextToken()); for(int x = 1; x<=2*path[y][0];x++){ path[y][x] = Integer.parseInt(st.nextToken()); } path[y][2*path[y][0]+1] = Integer.parseInt(st.nextToken()); } int want = Integer.parseInt(f.readLine()); items = new int[want][3]; for(int y = 0;y<want;y++){ StringTokenizer st = new StringTokenizer(f.readLine()); items[y][0] = Integer.parseInt(st.nextToken()); items[y][1] = Integer.parseInt(st.nextToken()); items[y][2] = Integer.parseInt(st.nextToken()); } dp = new long[6][6][6][6][6]; for(int y = 0;y<path.length;y++){ int width = path[y][0]; for(int x = 1;x<=width;x++){ if(path[y][2*x-1]==items[0][0]) path[y][2*x-1] = 0; else if(path[y][2*x-1]==items[1][0]) path[y][2*x-1] = 1; else if(path[y][2*x-1]==items[2][0]) path[y][2*x-1] = 2; else if(path[y][2*x-1]==items[3][0]) path[y][2*x-1] = 3; else if(path[y][2*x-1]==items[4][0]) path[y][2*x-1] = 4; } } int[] temp = new int[5]; for(int x = 0;x<items.length;x++){ temp[x] = items[x][1]; } long answer = recurse(temp[0], temp[1], temp[2], temp[3], temp[4]); out.println(answer); // print(); f.close(); out.close(); System.exit(0); } static void print(){ for(int y = 0;y<6;y++){ for(int x = 0;x<6;x++){ System.out.print(dp[y][x][0][0][0]); } System.out.println(); } } static long recurse(int a, int b, int c, int d, int e){ if(a==0&&b==0&&c==0&&d==0&&e==0){ //System.out.println("zero"); return 0; } if(a<0||b<0||c<0||d<0||e<0) return Integer.MAX_VALUE; if(dp[a][b][c][d][e]!=0) return dp[a][b][c][d][e]; long min = Integer.MAX_VALUE; long result; result = recurse(a-1, b, c, d, e)+items[0][2]; if(result<min) min = result; if(items.length>1){ result = recurse(a, b-1, c, d, e) + items[1][2]; if(result<min) min = result; if(items.length>2){ result = recurse(a, b, c-1, d, e) + items[2][2]; if(result<min) min = result; if(items.length>3){ result = recurse(a, b, c, d-1, e) + items[3][2]; if(result<min) min = result; if(items.length>4){ result = recurse(a, b, c, d, e-1) + items[4][2]; if(result<min) min = result; } } } } for(int y = 0;y<path.length;y++){ int width = path[y][0]; int A = a; int B = b; int C = c; int D = d; int E = e; for(int x = 1;x<=width;x++){ if(path[y][2*x-1]==0) A-=path[y][2*x]; else if(path[y][2*x-1]==1) B-=path[y][2*x]; else if(path[y][2*x-1]==2) C-=path[y][2*x]; else if(path[y][2*x-1]==3) D-=path[y][2*x]; else if(path[y][2*x-1]==4) E-=path[y][2*x]; } //System.out.println(A+" "+B+" "+C+" "+D+" "+E); result = recurse(A, B, C, D, E)+path[y][2*width+1]; if(result<min) min = result; } return dp[a][b][c][d][e] = min; } static void print(int[][] path){ for(int y = 0;y<path.length;y++){ for(int x = 0;x<path[0].length;x++){ //if(path[y][x] == 0) break; System.out.print(path[y][x]+" "); } System.out.println(); } } }
hughbzhang/Competitive_Programming
shopping.java
1,481
//if(path[y][x] == 0) break;
line_comment
en
true
36167_11
/** * Represents a job for an elevator, containing information about the destination floor, pickup floor, timestamp, button pressed, and any faults. * @authors Sami Mnif, Muaadh Ali, Jalal Mourad, Jordan Bayne */ import java.io.Serializable; public class Job implements Serializable { private String timeStamp; private int destinationFloor, pickupFloor; public int capacity; private String button; private int fault; /** * Constructs a new job with the specified parameters. * * @param timeStamp the timestamp of the job * @param destinationFloor the destination floor of the job * @param pickupFloor the pickup floor of the job * @param button the button pressed for the job * @param fault the fault status of the job */ public Job(String timeStamp, int destinationFloor, int pickupFloor, String button, int fault) { capacity = 1; this.timeStamp = timeStamp; this.destinationFloor = destinationFloor; this.pickupFloor = pickupFloor; this.button = button; this.fault = fault; } /** * Gets the timestamp of the job. * * @return the timestamp */ public String getTimeStamp() { return timeStamp; } /** * Gets the destination floor of the job. * * @return the destination floor */ public int getDestinationFloor() { return destinationFloor; } /** * Gets the pickup floor of the job. * * @return the pickup floor */ public int getPickupFloor() { return pickupFloor; } /** * Gets the button pressed for the job. * * @return the button pressed */ public String getButton() { return button; } /** * Sets the timestamp of the job. * * @param timeStamp the new timestamp */ public void setTimeStamp(String timeStamp) { this.timeStamp = timeStamp; } /** * Sets the destination floor of the job. * * @param destinationFloor the new destination floor */ public void setDestinationFloor(int destinationFloor) { this.destinationFloor = destinationFloor; } /** * Sets the pickup floor of the job. * * @param pickupFloor the new pickup floor */ public void setPickupFloor(int pickupFloor) { this.pickupFloor = pickupFloor; } /** * Sets the button pressed for the job. * * @param button the new button pressed */ public void setButton(String button) { this.button = button; } /** * Sets the fault status of the job. * * @param fault the new fault status */ public void setFault(int fault) { this.fault = fault; } /** * Gets the fault status of the job. * * @return the fault status */ public int getFault() { return fault; } }
Samimnif/SYSC3303-Elevator-Sim
Job.java
677
/** * Gets the fault status of the job. * * @return the fault status */
block_comment
en
false
36408_0
public class DRoot { public static int digital_root(int n) { /* Finds the digital root of n by recursively summing the digits of n until the sum is only 1 digit Returns the single digit root of n e.g digital_root(12345) = 6 (1+2+3+4+5=15 -> 1+5 = 6) */ char[] digits = new Integer(n).toString().toCharArray(); int sum = 0; while(digits.length > 1) { sum = 0; for (int i = 0; i<digits.length; i++) { sum += Character.getNumericValue(digits[i]); } digits = new Integer(sum).toString().toCharArray(); } return sum; } }
cBrayton/CodeWars
DRoot.java
186
/* Finds the digital root of n by recursively summing the digits of n until the sum is only 1 digit Returns the single digit root of n e.g digital_root(12345) = 6 (1+2+3+4+5=15 -> 1+5 = 6) */
block_comment
en
true
37469_36
/** * Represents time - hours:minutes. * @author Michal Danishevsky * @vertion 20.04.2020 */ public class Time1{ private int _hour; private int _minute; final int MAXIMUM_MINUTES=60; final int MINIMUM_MINUTES=0; final int MAXIMUM_HOURS=24; final int MINIMUM_HOURS=0; /** * Constructs a Time1 object * @param h Time's hour * @param m Time's minute */ public Time1(int h,int m){ /* _hour get the given hour if given hour in the * range of hour and get the value 0 if not */ if(h < MAXIMUM_HOURS && h > MINIMUM_HOURS) _hour=h; else _hour=0; /* _minute get the given minute if given minute in the * range of minute and get 0 if not */ if(m < MAXIMUM_MINUTES && m > MINIMUM_MINUTES) _minute=m; else _minute=0; }//end of Time1 /** * Copy the hour and minutes from other time to this time * @param other The time object from which to construct the new time */ public Time1(Time1 other){ _hour=other._hour; _minute=other._minute; }//end of Time1 /** * Return the time's hour * @return Time's hour */ public int getHour(){ return _hour; }//end of getHour /** * Return the time's minute * @return Time's minute */ public int getMinute(){ return _minute; }//end of getMinute /** * Sets the time's hour to new given hour if the new given hour * in the range of hour if not the hour stay the same hour * @param num New hour */ public void setHour(int num){ if(num < MAXIMUM_HOURS && num > MINIMUM_HOURS) _hour = num; }//end of setHour /** * Sets the time's minute to new given minute if the new given minute * in the range of minute if not the minute stay the same minute * @param num New minute */ public void setMinute(int num){ if(num < MAXIMUM_MINUTES && num > MINIMUM_MINUTES) _minute = num; }//end of setMinute /** * Returns a string representation of this time ("hh:mm") * @return This time in pattern hh:mm */ public String toString(){ if(_hour < 10 && _minute < 10) return "0" + _hour + ":" + 0 + _minute; //the minute and the hour are smaller than ten else if(_hour < 10) return "0" + _hour + ":" + _minute; //only the minute is bigger than ten else if(_minute < 10) return _hour + ":" + 0 + _minute; //only the hour is bigger than ten else return _hour + ":" + _minute; //the minute and the hour are bigger than ten }//end of toString /** * Return how much minutes passed from the midnight (00:00) * @return The minutes from midnight */ public int minFromMidnight(){ return (_hour * MAXIMUM_MINUTES + _minute); }//end of minFromMidnight /** * Checks if the received time is equal to this time * @param other The time to be compared with this time * @return True if they are the same time and * false if they are differents times */ public boolean equals(Time1 other){ if(_minute == other._minute && _hour == other._hour) return true;//there is the same time else return false;//they are differents times }//end of equals /** * Check if this time before the other time * @param other The time to be compared with this time * @return True if this time before the other time else it is return false */ public boolean before(Time1 other){ if(_hour == other._hour) if(_minute < other._minute) return true;//this time before the other time if(_hour < other._hour) return true;//this time before the other time else return false;/* they are the same time or the other time before this time */ }//end of before /** * Check if this time after the other time * @param other The time to be compared with this time * @return True if this time before the other time else it is return false */ public boolean after(Time1 other){ if(other.before(this)) return true;/*other time is before this time so this time after the other time*/ else return false;/*the times are equals or other time is after this time*/ }//end of after /** * Calculates the difference (in minutes) between two times. * Assumption: this time is after other time * @param other The time to check the difference * @return The difference in minute */ public int difference(Time1 other){ int totalMinuteDifference; int minuteDifference = _minute - other._minute;//minutes difference int hourDifference = _hour - other._hour;//hour difference /*minutes can't to be negetive so if it happend need convert hour to minutes*/ if(minuteDifference < MINIMUM_MINUTES){ hourDifference--; minuteDifference = minuteDifference + MAXIMUM_MINUTES; }//end of if //total the difference in minutes totalMinuteDifference = minuteDifference + MAXIMUM_MINUTES * hourDifference; return totalMinuteDifference; }//end of difference /** * Add minutes to this time to make new time * @param num Minutes to add * @return The new time */ public Time1 addMinutes(int num){ Time1 newTime = new Time1(this);//make new time newTime._minute += num;//add the minutes num = newTime._minute / MAXIMUM_MINUTES;//only hours stay to add newTime._minute %= MAXIMUM_MINUTES;//they are only 60 minuts in hour newTime._hour += num;//add the hours newTime._hour %= MAXIMUM_HOURS;//they are only 24 hours in day /*minutes can't to be negetive so if it happend need convert hour to minutes*/ if(newTime._minute < MINIMUM_MINUTES){ newTime._hour--; newTime._minute += MAXIMUM_MINUTES; }//end of if /*hours can't to be negetive so if it happend need convert day to hours*/ if(newTime._hour < MINIMUM_HOURS) newTime._hour += MAXIMUM_HOURS; return new Time1(newTime); }//end of addMinutes }//end of class
mich153/Railway-Station
Time1.java
1,583
/** * Calculates the difference (in minutes) between two times. * Assumption: this time is after other time * @param other The time to check the difference * @return The difference in minute */
block_comment
en
false
37508_0
import greenfoot.*; /** * Write a description of class Pet here. * * Tristan Walker * version 1 */ public class Pet extends MightyPet { private String name; private int age; private String image; private String sound; private boolean isFriendly; public Pet() { this.name = new String(); this.age = 0; this.sound = new String("boing.wav"); this.isFriendly = false; this.playPetSound(); } public Pet(String petName, int petAge, String imageFileName, String soundFileName) { this.name = petName; this.age = petAge; this.image = imageFileName; this.sound = soundFileName; this.isFriendly = false; setImage(this.image); } /** * Act - do whatever the Pet 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. } public void playPetSound() { Greenfoot.playSound(this.sound); } }
cookiedancer/KidEngineers
Pet.java
276
/** * Write a description of class Pet here. * * Tristan Walker * version 1 */
block_comment
en
true
39000_7
/** This class represents the Pawn piece in Chess */ public class Pawn extends Piece { /** * Creates a new Piece with a given color at (x,y) * * @param isBlack Color of the piece, true if is black and white if false * @param x X coordinate of the piece * @param y Y coordinate of the piece */ public Pawn(boolean isBlack, int x, int y) { super(isBlack, x, y); } @Override public String getName() { return "Pawn"; } @Override public String getSymbol() { return (isBlack) ? "P" : "p"; } /** * Checks if can be promoted * * @return true if pawn can be promoted, false otherwise */ public boolean canBePromoted() { // If pawn is at end of board, it can promote if (isBlack) { if (getY() == 7) { return true; } } else { if (getY() == 0) { return true; } } return false; } @Override public boolean canMove(int newX, int newY) { // 1) are coordinates in range if (!validCoordinates(newX, newY)) return false; // Checks piece color as it can only move in one direction depending which color // it is if (isBlack) { // no moving backwards, too far, or left/right more than 1 square if (y >= newY || newY - y > 2 || Math.abs(newX - x) > 1) { return false; } // checks movement if still in home row as it can move two squares if (newY - y == 2 && y == 1 && x == newX) { if ((Board.getPiece(x, y + 1) == null) && (Board.getPiece(x, y + 2) == null)) { return true; } else { return false; } } // pawn is moving 1 square ahead in its row if (newY - y == 1 && x == newX) { if (Board.getPiece(x, y + 1) == null) { return true; } else { return false; } } // pawn is capturing a piece diagonally if (newY - y == 1 && Math.abs(x - newX) == 1) { if (validCoordinates(newX, newY) && Board.getPiece(newX, newY) != null) { return true; } else { return false; } } } else { // no moving backwards, too far, or left/right more than 1 square if (y <= newY || y - newY > 2 || Math.abs(newX - x) > 1) { return false; } // checks movement if still in home row as it can move two squares if (y - newY == 2 && y == 6 && x == newX) { if (Board.getPiece(x, y - 1) == null && Board.getPiece(x, y - 2) == null) { return true; } else { return false; } } // pawn is moving 1 square ahead in its row if (y - newY == 1 && x == newX) { if (Board.getPiece(x, y - 1) == null) { return true; } else { return false; } } // pawn is capturing a piece diagonally if (y - newY == 1 && Math.abs(x - newX) == 1) { if (validCoordinates(newX, newY) && Board.getPiece(newX, newY) != null) { return true; } else { return false; } } } return false; } @Override public void updateLegalMoves() { legalMoves.clear(); if (isBlack) { // vertical moves if (Board.testMove(isBlack, x, y, x, y + 1)) legalMoves.add(new Move(x, y + 1)); if (Board.testMove(isBlack, x, y, x, y + 2)) legalMoves.add(new Move(x, y + 2)); // diagonal captures if (Board.testMove(isBlack, x, y, x + 1, y + 1)) legalMoves.add(new Move(x + 1, y + 1)); if (Board.testMove(isBlack, x, y, x - 1, y + 1)) legalMoves.add(new Move(x - 1, y + 1)); } else { // vertical moves if (Board.testMove(isBlack, x, y, x, y - 1)) legalMoves.add(new Move(x, y - 1)); if (Board.testMove(isBlack, x, y, x, y - 2)) legalMoves.add(new Move(x, y - 2)); // diagonal captures if (Board.testMove(isBlack, x, y, x + 1, y - 1)) legalMoves.add(new Move(x + 1, y - 1)); if (Board.testMove(isBlack, x, y, x - 1, y - 1)) legalMoves.add(new Move(x - 1, y - 1)); } } }
dylanboyling/Chess
Pawn.java
1,290
// no moving backwards, too far, or left/right more than 1 square
line_comment
en
true
39062_4
package com.example.dspritzman.myapplication; import android.graphics.Bitmap; import android.util.Log; import java.util.ArrayList; /** * Created by Shane McDonald on 3/21/2015. */ public class Game { WeaponInventory wInventory; LevelManager lManager; ArrayList<Bullet> Bullets = new ArrayList<Bullet>(); int score; Game(){ wInventory = new WeaponInventory(); wInventory.addWeapon('a', true, true); wInventory.addWeapon('b', false, false); wInventory.addWeapon('c', false, false); wInventory.addWeapon('d', false, false); wInventory.addWeapon('e', false, false); score = 0; lManager = new LevelManager(); Health = 2000; Money = 0; ActiveW = 0; } public void tick() { lManager.tick(); Collision_Detect(); updateBullets(); } public int getScore() { return lManager.getScore(); } public void addBullet(int xOrigin, int yOrigin, int xTouch, int yTouch) { BulletPhysics physics = new BulletPhysics(xOrigin, yOrigin, xTouch, yTouch); Bullet b = new Bullet(xOrigin, yOrigin, physics.getRise(), physics.getRun()); Bullets.add(b); Log.e("add", "add: " + Bullets.get(0).getX()); } public void gainMoney(int amount) { Money = Money + amount; } public void loseMoney(int amount) { if(Money > 0 && amount <= Money) { Money = Money - amount; } else { // not enough money error message } } public void SelectWeapon(int index) { wInventory.getIndex(ActiveW).ToggleEquipped(); wInventory.getIndex(index).ToggleEquipped(); ActiveW = index; } public int getMoney() { return Money; } public int getHealth() { return Health; } public void loseHealth(int amount) { if(Health > 0 && amount < Health) { Health = Health - amount; } else { GameOver(); } } public void GameOver(){ // Game Over message } public int getPuffSize() { return lManager.getPuffSize(); } public int getNarwhalSize() { return lManager.getNarwhalize(); } public int getManSize() { return lManager.getManSize(); } public int getFlyingSize() { return lManager.getFlyingSize(); } public int getSeaSize() { return lManager.getFlyingSize(); } public Pufferfish puffIterator(int i) { return lManager.puffIterator(i); } public Narwhal narIterator(int i) { return lManager.narIterator(i); } public Manatee manIterator(int i) { return lManager.manIterator(i); } public FlyingFish flyIterator(int i) { return lManager.flyIterator(i); } //public SeaHorse seaIterator(int i) { //return lManager.seaIterator(i); } private double Distance(int xa, int ya, int xb, int yb) { int x1 = xa; int x2 = xb; int xSqr = (x2 - x1) * (x2 - x1); int y1 = ya; int y2 = yb; int ySqr = (y2 - y1) * (y2 - y1); double distance = Math.sqrt(xSqr + ySqr); return distance; } public void updateBullets() { for (int i = 0; i < Bullets.size(); ++i) { Bullets.get(i).setX(Bullets.get(i).getX() + Bullets.get(i).getRun()); Bullets.get(i).setY(Bullets.get(i).getY() + Bullets.get(i).getRise()); } } public void Collision_Detect(){ //Log.e("manatee", "1: " + Bullets.size() + "2: " ); for(int i = 0; i < Bullets.size() && Bullets.size() != 0; i++) { boolean stop = false; if (Bullets.get(i).getY() > 1280 || Bullets.get(i).getX() > 720 || Bullets.get(i).getX() < 0) { Bullets.remove(i); } for (int f = 0; f < getFlyingSize() && getFlyingSize() > 0 && !stop && Bullets.size() > 0; f++) { if (Bullets.get(i) != null && flyIterator(f) != null) { if (Distance(Bullets.get(i).getX(), Bullets.get(i).getY(), flyIterator(f).getX(), flyIterator(f).getY()) < flyIterator(f).getRadius()) { flyIterator(f).takeDamage(50); Bullets.remove(i); stop = true; } } } for (int p = 0; p < getPuffSize() && getPuffSize() > 0 && !stop && Bullets.size() > 0; p++) { if (Bullets.get(i) != null && puffIterator(p) != null) { if (Distance(Bullets.get(i).getX(), Bullets.get(i).getY(), puffIterator(p).getX(), puffIterator(p).getY()) < puffIterator(p).getRadius()) { puffIterator(p).takeDamage(50); Bullets.remove(i); stop = true; } } } /* for (int s = 0; s < getSeaSize() && getSeaSize() > 0; s++) { if(Distance(Bullets.get(s).getX(), Bullets.get(s).getY(), seaIterator(s).getX(), seaIterator(s).getY()) < seaIterator(s).getRadius()){ seaIterator(s).takeDamage(50); Bullets.remove(s); break; } }*/ for (int m = 0; m < getManSize() && getManSize() > 0 && !stop && Bullets.size() > 0; m++) { if (Bullets.get(i) != null && manIterator(m) != null) { if (Distance(Bullets.get(i).getX(), Bullets.get(i).getY(), manIterator(m).getX(), manIterator(m).getY()) < manIterator(m).getRadius()) { manIterator(m).takeDamage(50); Bullets.remove(i); Log.e("manatee", "hit dat"); stop = true; } } } for (int n = 0; n < getNarwhalSize() && getNarwhalSize() > 0 && !stop && Bullets.size() > 0; n++) { if (Bullets.get(i) != null && narIterator(n) != null) { if (Distance(Bullets.get(i).getX(), Bullets.get(i).getY(), narIterator(n).getX(), narIterator(n).getY()) < narIterator(n).getRadius()) { narIterator(n).takeDamage(50); Bullets.remove(i); stop = true; } } } } } private int ActiveW; private int Money; private int Health; }
takashiw/Scurvy-Android-Game
Game.java
1,844
//return lManager.seaIterator(i);
line_comment
en
true
39509_11
public abstract class Country { // 1️⃣ FIRST // 🔴 Create a String attribute named 'continent' and set it to a continent of your choice. Example: "Asia" // 🔴 Create an abstract method named 'sayHello()' // ⬇️------------Write your code below (approx. 2 lines of code)-----------⬇️ // ⬆️--------------------------------END HERE------------------------------⬆️ void welcome() { // Non-abstract method, need not be implemented by subclasses // Method will be inherited by subclasses, so if not overriden, this will be run when this method is called: System.out.println("Welcome to this country!"); } public static void main(String[] args) { // 4️⃣ FOURTH // 🔴 Create an instance of both the countries that you created. // 🔴 Call all the methods of the first country (sayHello() and welcome()) // 🔴 Then print all its attributes (continent and capital) // 🔴 Do the same for the other country // MAKE SURE THE OUTPUT MATCHES THE FORMAT OF THE ONE GIVEN IN THE INSTRUCTIONS // ⬇️------------Write your code below (approx. 10 lines of code)-----------⬇️ // ⬆️--------------------------------END HERE------------------------------⬆️ } } // 2️⃣ SECOND // 🔴 Create a class with the name of a country (example: India) that extends the class Country // 🔴 Create an attribute 'capital' and set it to the capital of the chosen country // 🔴 Implement the 'sayHello()' method that you created in the Country class earlier. // Inside the body of the method, print "Hello!" in the language of the chosen country. (example: "Namaste!") // 🔴 Implement (and therefore override) the 'welcome()' method that is given in the Country class. // Inside the body of the method, print a welcome message in the language of the chosen country. (example: "Is desh me aapka swagat hai!") // ⬇️------------Write your code below (approx. 7 lines of code)-----------⬇️ // ⬆️--------------------------------END HERE------------------------------⬆️ // 3️⃣ THIRD // 🔴 Create another class extending country just like above with an attribute 'capital' and method 'sayHello()' but NOT the method 'welcome()'. // ⬇️------------Write your code below (approx. 5 lines of code)-----------⬇️ // ⬆️--------------------------------END HERE------------------------------⬆️
Github-Amity/Abstraction
Country.java
597
// 🔴 Do the same for the other country
line_comment
en
true
39748_0
import java.util.*; import java.awt.Point; import java.math.*; import java.io.*; import static java.lang.Math.*; public class P585 { public static void main(String[] args) { Scanner in = new Scanner(System.in); int c1 = 0; int c2 = 0; int c3 = 0; int n = in.nextInt(); in.nextLine(); for(int i=0; i<n; i++) { String s = in.nextLine(); if(s.equals("Macaroni Penguin")) c1++; if(s.equals("Little Penguin")) c2++; if(s.equals("Emperor Penguin")) c3++; } if(c1>c2 && c1>c3) System.out.println("Macaroni Penguin"); if(c2>c1 && c2>c3) System.out.println("Little Penguin"); if(c3>c2 && c3>c1) System.out.println("Emperor Penguin"); //BufferedReader in = new BufferedReader(new InputStreamReader(System.in)); } }
jonathanpaulson/Timus
P585.java
277
//BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
line_comment
en
true
40546_4
//1 Объявить два списка список ArrayList, в каждый добавить по 20 случайных чисел. // далить из первого списка элементы отсутствующие во втором списке. // Отсортировать первый список методом sort класса Collections. //2 * Отсортировать второй список методом sort списка и компаратором по уменьшению. //3 **Отсортировать первый список пузырьковой сортировкой самостоятельно, без использования доп методов и классов. package org.example; import java.util.ArrayList; import java.util.Collections; import java.util.Comparator; import java.util.Random; public class hw3 { public static void main(String[] args) { ArrayList<Integer> list = new ArrayList<>(); ArrayList<Integer> list1 = new ArrayList<>(); Random random = new Random(); for (int i = 0; i < 20; i++) { list.add(random.nextInt(20)); } for (int i = 0; i < 20; i++) { list1.add(random.nextInt(20)); } list.forEach(nik -> System.out.print(nik + " ")); System.out.println(); list1.forEach(nik -> System.out.print(nik + " ")); System.out.println(); list.remove(list1); list.forEach(nik -> System.out.print(nik + " ")); System.out.println(); Collections.sort(list); list.forEach(nik -> System.out.print(nik + " ")); System.out.println(); list.sort(new Comparator<Integer>() { @Override public int compare(Integer o1, Integer o2) { return o2-o1; } }); System.out.println(list); System.out.println(); } }
VladTalanov/HW_JAVA
HW3.java
498
//3 **Отсортировать первый список пузырьковой сортировкой самостоятельно, без использования доп методов и классов.
line_comment
en
true
40626_0
import java.util.HashMap; public class MediaLib { private HashMap<String, Book> books; private HashMap<String, Movie> movies; private HashMap<String, Song> songs; public static String owner = "PLTW Steven"; private static int numEntries = 0; public MediaLib() { books = new HashMap<>(); movies = new HashMap<>(); songs = new HashMap<>(); } public static int getNumEntries() { return numEntries; } public void addBook(String title, Book book) { books.put(title, book); numEntries++; } public void addMovie(String title, Movie movie) { movies.put(title, movie); numEntries++; } public void addSong(String title, Song song) { songs.put(title, song); numEntries++; } public Book getBook(String title) { return books.get(title); } public Movie getMovie(String title) { return movies.get(title); } public Song getSong(String title) { return songs.get(title); } public void removeBook(String title) { if (books.containsKey(title)) { books.remove(title); numEntries--; } } public void removeMovie(String title) { if (movies.containsKey(title)) { movies.remove(title); numEntries--; } } public void removeSong(String title) { if (songs.containsKey(title)) { songs.remove(title); numEntries--; } } public static String getOwner() { return owner; } public static void changeOwner(String newOwner) { owner = newOwner; } public String toString() { return "Current Library: " + books.values() + " // " + movies.values() + " // " + songs.values(); } }
GitHubEmploy/2.5.7
MediaLib.java
431
// " + movies.values() + " // " + songs.values();
line_comment
en
true
41189_2
package main; import javafx.application.Application; import javafx.fxml.FXMLLoader; import javafx.scene.Parent; import javafx.scene.Scene; import javafx.stage.Stage; import utilities.DBConnection; import java.sql.*; import java.util.Locale; /** This is the Main class of my application. * * <p><b> * * The javadocs folder is located in the Project primary folder. * * </b></p> * * @author Todd Rasband*/ public class Main extends Application { /** This method sets up the initial JavaFX application stage. * * @param primaryStage The primary stage to be set. * @throws Exception The exception thrown. */ @Override public void start(Stage primaryStage) throws Exception{ Parent root = FXMLLoader.load(getClass().getResource("../view/Login.fxml")); primaryStage.setTitle("SCHEDULING SYSTEM"); primaryStage.setScene(new Scene(root)); primaryStage.show(); } /** <b> * The javadocs folder is located in the Project primary folder. * </b> * * <p> * This method calls for and establishes the database connection. * </p> * @param args The arguments. * @throws SQLException The exception that will be thrown in an error. */ public static void main(String[] args) throws SQLException { // The following two lines were used for testing purposes //Locale.setDefault(new Locale("fr")); //System.setProperty("user.timezone", "America/New_York"); DBConnection.startConnection(); launch(args); DBConnection.endConnection(); } }
Rasbandit/wgu-c195
src/main/Main.java
393
/** <b> * The javadocs folder is located in the Project primary folder. * </b> * * <p> * This method calls for and establishes the database connection. * </p> * @param args The arguments. * @throws SQLException The exception that will be thrown in an error. */
block_comment
en
false
41199_0
/** This program tests the DataSetGen class. */ public class Main { public static void main(String[] args) { DataSetGen<BankAccount> bankData = new DataSetGen<BankAccount>(); bankData.add(new BankAccount(0)); bankData.add(new BankAccount(10000)); bankData.add(new BankAccount(2000)); System.out.println("Bank Account"); System.out.println("Average balance: " + bankData.getAverage()); System.out.println("Expected: 4000"); BankAccount max = bankData.getMaximum(); System.out.println("Highest balance: " + max.getBalance()); System.out.println("Expected: 10000"); DataSetGen<BaseballPlayer> battingAvgData = new DataSetGen<BaseballPlayer>(); System.out.println("Batting Averages"); battingAvgData.add(new BaseballPlayer("Derek Jeter", "New York Yankees", .323)); battingAvgData.add(new BaseballPlayer("Melky Cabria","San Fransico Giants", .346)); battingAvgData.add(new BaseballPlayer("Adrian Beltre","Texas Rangers", .319)); System.out.println("Average batting average: " + battingAvgData.getAverage()); System.out.println("Expected: .329"); BaseballPlayer maxA = battingAvgData.getMaximum(); System.out.println("Highest batting average: " + maxA.getBattingAverage() + " "+ maxA.getName() + " of the " + maxA.getTeam()); System.out.println("Expected: .346 Melky Cabria of the San Fransicso Giants"); } }
fmancia1/Lab.1
Main.java
428
/** This program tests the DataSetGen class. */
block_comment
en
true
41318_1
import greenfoot.*; // (World, Actor, GreenfootImage, Greenfoot and MouseInfo) import java.util.*; import java.util.ArrayList; /** * Write a description of class card here. * * @author (your name) * @version (a version number or a date) */ public class card extends Actor { private int suit; private int rank; private GreenfootImage card; /** * Act - do whatever the card 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. } public card(int rank, int suit){ this.rank = rank; this.suit = suit; card = new GreenfootImage(convertRank(rank) + "_of_" + convertSuit(suit) + ".png"); } private String convertRank(int rank){ String s = ""; if (rank < 10){ rank++; s = Integer.toString(rank); } else if (rank == 10){ s = "jack"; } else if (rank == 11){ s = "queen"; } else if (rank == 12){ s = "king"; } else{ s = "ace"; } return s; } private String convertSuit(int suit){ String s = ""; if (suit == 0){ s = "clubs"; } else if (suit == 1){ s = "diamonds"; } else if (suit == 2){ s = "hearts"; } else{ s = "spades"; } return s; } public int getRank(){ return rank; } public int getSuit(){ return suit; } public void drawACard(){ card.scale(70, 70); setImage(card); } }
yewlee0218/APCSFinalProjectERS
card.java
453
/** * Write a description of class card here. * * @author (your name) * @version (a version number or a date) */
block_comment
en
true
41375_3
import java.util.ArrayList; import java.util.Collections; import java.util.List; public class Deck { private List<Card> deck = new ArrayList<>(); private final String WILD = Main.getWildCard(); private final String WILD_PLUS_4 = Main.getWildPlus4(); private String[] colorsAssortment = {"blue", "green", "red", "yellow"}; // display cards in deck public void displayCards() { for(Card card : this.deck) { System.out.print(card.getCardName() + " "); } } // add a card to the deck public final void addCard(Card card) { this.deck.add(card); } // remove card from deck public final Card removeCard() { Card topCard = deck.get(this.deck.size() - 1); this.deck.remove(topCard); return topCard; } /* remove the bottom card before starting the game this will be the first card in the discard pile */ public final Card removeBottomCard() { Card bottomCard = deck.get(0); this.deck.remove(bottomCard); return bottomCard; } // get number of cards public final int numberOfCards() { return this.deck.size(); } // return the cards as a list public final List<Card> getDeck() { return this.deck; } // shuffle cards public final void shuffleCards() { Collections.shuffle(this.deck); } // create a new deck of cards public final void createNewDeck(List<Card> stackOfCards) { for(Card card : stackOfCards) { for(int i = 0; i < this.colorsAssortment.length; i++) { // reset wild cards if(card.getCardName().equals(colorSymbol(i) + "_" + WILD)) { card.setCardName(WILD); card.setCardColor(""); } // reset wild +4 cards if(card.getCardName().equals(colorSymbol(i) + "_" + WILD_PLUS_4)) { card.setCardName(WILD_PLUS_4); card.setCardColor(""); } } // add cards to new deck this.deck.add(card); } } // get wild card protected final String getWildCard() { return WILD; } // get wild +4 card protected final String getWildPlus4() { return WILD_PLUS_4; } // get assortment of colors protected final String[] getAssortment() { return this.colorsAssortment; } // get a color in the assortment public final String getColor(int index) { return this.colorsAssortment[index]; } // get the number of colors in the assortment public final int getNumberOfColors() { return this.colorsAssortment.length; } // returns color symbol to be checked public final char colorSymbol(int index) { return (this.colorsAssortment[index].toUpperCase()).charAt(0); } }
CoderJ01/uno-card-game
Deck.java
727
/* remove the bottom card before starting the game this will be the first card in the discard pile */
block_comment
en
false
41546_1
import java.text.DecimalFormat; public class bmi{ public static void main (String[] args) { float weight, height; double bmi; try { weight = Float.parseFloat(args[0]); height = Float.parseFloat(args[1]); } catch (Exception e) { System.out.println("You must provide your weight in kilos and your hight in meters as commandline arguments"); return; } //If the user likely have entered its height in cm instead of in meters if (height >= 100) { System.out.println("Did you provide your hight in cm? Or are you really " + height + "m. It is now convertet to meters. "); height = height/100; } //If the user likely have entered the wronge height in meters since he is taller then 3 meters if (height < 100 && height > 3) { System.out.println( "Are you really " + height + "m? " ); System.out.println("You should first provide your weight in kilos and then your hight in meters as commandline arguments. "); return; } //If the user likely have changed the order of the commandline arguments if (height > weight && weight < 3) { System.out.println("It is likely that you have passed your hight as the first commandline argument and weight as the second. "); System.out.println("You should first provide your weight in kilos and then your hight in meters"); return; } //If the user passes negative values if (height < 0 || weight < 0) { System.out.println("You have provided a negative value for your height or your weight, that is not physically possible. "); System.out.println("Please try again. "); System.out.println("You should first provide your weight in kilos and then your hight in meters as commandline arguments. "); return; } bmi = weight / (height*height); if (bmi < 18.5) { System.out.println( "The bmi calculator states that you are underweight, with a bmi of " + new DecimalFormat("#.00").format(bmi) ); } else if (bmi >= 18.5 && bmi <=24.9 ) { System.out.println( "The bmi calculator states that you have a normal weight, with a bmi of " + new DecimalFormat("#.00").format(bmi) ); } else if (bmi > 24.9 && bmi < 30) { System.out.println( "The bmi calculator states that you are overweight, with a bmi of " + new DecimalFormat("#.00").format(bmi) ); } else { System.out.println( "The bmi calculater states that you are obese, with a bmi of " + new DecimalFormat("#.00").format(bmi) ); } } }
Trudelutten/Task-Day-2
bmi.java
702
//If the user likely have entered the wronge height in meters since he is taller then 3 meters
line_comment
en
false
42579_2
/** * Properties and methods for moons. */ public class Moon extends SolarObject { private double dist_offset; private Planet planet; /** * Setting up the moon object. * * @param ss the solar system the planet will be added to * @param dist distance between the moon and the planet (in million km) * @param dist_offset the distance offset (due to different scaling ratio between distance and diameter of solar objects, * a moon can be rendered inside a planet, thus this offset value) (in pixels) * @param dia diameter of the moon (in million km) * @param col color of the moon * @param ang angle to add per move * @param planet the planet the moon is revolving around */ public Moon(SolarSystem ss, double dist, double dist_offset, double dia, String col, double ang, Planet planet) { this.ss = ss; this.dist = calc_display_dist(dist) + dist_offset; this.dist_offset = dist_offset; this.dia = calc_display_dia(dia); this.col = col; this.current_ang = 90; this.ang = ang; this.planet = planet; } /** * Triggers the moon to move 1 step foward */ public void move() { current_ang = calc_new_ang(current_ang, ang); ss.drawSolarObjectAbout(dist, current_ang, dia, col, planet.get_dist(), planet.get_ang()); } }
gabrielchl/java-solar-system-model
Moon.java
376
/** * Triggers the moon to move 1 step foward */
block_comment
en
false
42984_1
package dataCollector; import java.io.File; import java.io.IOException; import java.net.MalformedURLException; import java.net.SocketTimeoutException; import javax.xml.transform.Transformer; import javax.xml.transform.TransformerConfigurationException; import javax.xml.transform.TransformerException; import javax.xml.transform.TransformerFactory; import javax.xml.transform.dom.DOMSource; import javax.xml.transform.stream.StreamResult; import org.htmlcleaner.CleanerProperties; import org.htmlcleaner.HtmlCleaner; import org.htmlcleaner.PrettyXmlSerializer; import org.htmlcleaner.TagNode; import org.jsoup.Jsoup; import org.jsoup.helper.W3CDom; public class HTML_XMLParser { private File xmlFile; private Throwable x; private org.jsoup.nodes.Document jsoupDoc = null; private W3CDom w3cDom; private org.w3c.dom.Document w3cDoc; private int index, endIndex,index_2; private boolean timeOut; private String xml_path, fileName; private HtmlCleaner cleaner; private CleanerProperties props; private PrettyXmlSerializer xml; private TagNode tagNode; private TransformerFactory tFactory; private Transformer transformer; private DOMSource source; private StreamResult result; public String parseHTML(String link, int pageNumber) throws IOException{ timeOut = true; index = link.indexOf("/", 40); endIndex = link.indexOf("/", index + 1); fileName = link.substring(index + 1, endIndex) + "_" + pageNumber; // get next page if it is not 1 if(pageNumber != 1){ link = getNextPage(link, pageNumber); } // if it is the first page, the xml file is already created when // WebScraper.getNumberOfPagesPerLink(String link) is executed // IMPROVE HERE !!! while(timeOut){ try { jsoupDoc = Jsoup.connect(link).get(); timeOut = false; } catch(SocketTimeoutException ex){ timeOut = true; } catch(MalformedURLException exx){ System.out.println("ERROR in getting the jSoup DOM from " + link); return "Bad Link"; } catch (IOException e) { timeOut = true; } } w3cDom = new W3CDom(); w3cDoc = w3cDom.fromJsoup(jsoupDoc); xmlFile = new File("C:/Users/Norbert/Desktop/XML Files/" + fileName + ".xml"); try { tFactory = TransformerFactory.newInstance(); transformer = tFactory.newTransformer(); source = new DOMSource(w3cDoc); result = new StreamResult(xmlFile); transformer.transform(source, result); } catch (TransformerConfigurationException tce) { System.out.println("* Transformer Factory error"); System.out.println(" " + tce.getMessage()); x = tce; if (tce.getException() != null) x = tce.getException(); x.printStackTrace(); } catch (TransformerException te) { System.out.println("* Transformation error"); System.out.println(" " + te.getMessage()); x = te; if (te.getException() != null) x = te.getException(); x.printStackTrace(); } cleaner = new HtmlCleaner(); props = cleaner.getProperties(); props.setTranslateSpecialEntities(true); // set some properties to non-default values props.setTransResCharsToNCR(true); props.setOmitComments(true); xml = new PrettyXmlSerializer(props); tagNode = new HtmlCleaner(props).clean(xmlFile); // do parsing // serialize to xml file xml_path = "C:/Users/Norbert/Desktop/XML Files/" + fileName + ".xml"; xml.writeToFile(tagNode, xml_path, "utf-8"); return xml_path; } private String getNextPage(String link, int pageNumber){ //http://www.airlinequality.com/airline-reviews/air-canada/?sortby=post_date%3ADesc&pagesize=100 //http://www.airlinequality.com/airline-reviews/air-canada/page/2/?sortby=post_date%3ADesc&pagesize=100 index_2 = link.indexOf("?"); return link.substring(0, index_2) + "page/" + pageNumber + "/" + link.substring(index_2); } }
norberte/DataCollector
HTML_XMLParser.java
1,164
// if it is the first page, the xml file is already created when
line_comment
en
true
43191_3
import java.util.*; public class ifelse { public static void main(String[]argu){ Scanner sc = new Scanner(System.in); // Question to check weather the he is adult or under age System.out.print("Age: "); int ag= sc.nextInt(); if (ag>18){ System.out.println("You are an Adult"); } else{ System.out.println("You are under age"); } System.out.println("\n"); //Question to check weather the he is odd or even System.out.println("To cheek Weather the number is odd or eve"); System.out.print("Number: "); int numb=sc.nextInt(); if(numb % 2 ==0) { System.out.println("Even"); } else{ System.out.println("Odd"); System.out.println("\n"); //Question to check weather the the number equal or greater or lesser System.out.print("a="); int a1 = sc.nextInt(); System.out.print("b="); int b1= sc.nextInt(); if (a1==b1){ System.out.println("Equal"); } else{ // insted of writing lots of if else or nested if else we use else if if (a1>b1){ System.out.println("a is greater"); } else { System.out.println("a is lesser"); } } } //ok System.out.println("Next number: "); int v = sc.nextInt(); if( v <=10){ System.out.println("kid"); System.out.println("sjn"); } else{ if ((v>10)&&(v<=20)){ System.out.println("Teen");} else if((v>20)&&(v<=40)){ System.out.println("adult"); } else{ System.out.println("40+"); } } sc.close(); } }
RiteshSharmaop/Java
ifelse.java
480
// insted of writing lots of if else or nested if else we use else if
line_comment
en
false
43653_24
/** * This is the Craps Game main file in this class. Responsible for most game functions. * * @author TJ Zimmerman * @version 1.01 */ public class Craps { /**Makes objects for each of the two dice. */ public GVdie d1, d2; /**Initializes and sets the return point of the game to * negative one. */ public int point; /**Initializes and sets the games credits to 10.*/ public int credits; /**Sets the inital welcome message to the game.*/ public String message; /**Sets the boolean up that controls which portion of * the game you're on. */ public boolean comeoutlegal; /** * Constructer sets the variables to paramters. */ public Craps () { d1 = new GVdie(); d2 = new GVdie(); point = -1; credits = 10; message = "Hello! Welcome to Craps! Press 'Come Out' to begin!"; comeoutlegal = true; } /** * Returns credits for each game. * @return credits */ public int getCredits() { return credits; } /** * Returns current point for each game. * @return point */ public int getPoint() { return point; } /** * Returns message for each game. * @return message */ public String getMessage() { return message; } /** * This sets the credits to amount of amount is greater than * inital credits. */ public void setCredits (int amount) { if (amount >= 0) { credits = amount; } } /** * This is the primary method that the come out function of the * game uses. A nested if then statement incorporates logic into * the game and makes it behave properly. */ public void comeOut() { int r1 = 0; int r2 = 0; /** * This loop sets your credit score modifiers and what * portion of the game you will continue to. */ if (comeoutlegal && credits >= 1) { d1.roll(); d2.roll(); r1 = d1.getValue(); r2 = d2.getValue(); int dt = r1+r2; if (dt == 7) { credits++; message = "Rolled 7: +1 credit! Come out, again!"; //Continue to Come out. } else if (dt == 11) { credits++; message = "Rolled 11: +1 credit! Come out, again!"; //Continue to Come out. } else if (dt == 2) { credits--; message = "Rolled 2: -1 credit. Come out again!"; //Continue to Come out. } else if (dt == 3) { credits--; message = "Rolled 3: -1 credit. Come out again!"; //Continue to Come out. } else if (dt == 12) { credits--; message = "Rolled 12: -1 credit. Come out again!"; //Continue to Come out. } else { point = dt; comeoutlegal = false; message = "You rolled a(n) " + dt + ". Roll out, now!"; //Move to Roll out. } } else { message = "You're out of credits! Press Reset Game to" + "play again!"; } } /** * This is the primary method that the roll function of the game * uses. A nested if then statement incorporates logic into the * game and makes it behave properly. */ public void roll () { int r1 = 0; int r2 = 0; /** * This loop sets your credit score modifiers and what * portion of the game you will continue to. */ if (!comeoutlegal) { d1.roll(); d2.roll(); r1 = d1.getValue(); r2 = d2.getValue(); int dt = r1+r2; if (dt == 7) { credits--; point = -1; message = "Rolled 7: -1 credit. Come out now!"; comeoutlegal = true; //Move to Come out. } else if (dt == point) { credits++; point = -1; message = "Rolled point. +1 credit. Come out now!"; comeoutlegal = true; //Move to Come out. } else { message = "Rolled a(n) " + dt + ". Not a 7 or " + point + ". Roll again!"; //Continue to Roll. } } else { message = "ERROR, See Roll method to debug!!"; } } /** * While it wasn't required, I felt like adding a reset method * anyway as it would be very simple and would certainly * enhance the game. */ public void reset() { point = -1; credits = 10; message = "Hello! Welcome to Craps! Press 'Come Out' to begin!"; comeoutlegal = true; } /** * While it wasn't required, I felt like adding an exit method * anyway as it would be very simple and would certainly * enhance the game. */ public void exit() { System.exit(0); } /** * This method decides whether the roll option should be used or not. */ public boolean okToRoll() { if (comeoutlegal == false) { return true; } else if (comeoutlegal == true) { return false; } return comeoutlegal; } /** * This method instantiates the die objects and supplies them with * a value. */ public GVdie getDie (int num) { { if(num == 1) { return d1; } else { return d2; } } } /** * Main Method is used to test the principal logic of the game. */ public static void main (String[] args) { Craps crapsgame = new Craps(); crapsgame.getMessage(); crapsgame.comeOut(); crapsgame.getMessage(); /** *This loop continues to roll the dice until it is time to move *on to comeoutlegal part. */ while (crapsgame.okToRoll()) { crapsgame.roll(); System.out.println (crapsgame.getMessage()); } System.out.println ( "Total Credits: " + crapsgame.getCredits()); } }
zimmertr/Craps
Craps.java
1,579
/** * While it wasn't required, I felt like adding a reset method * anyway as it would be very simple and would certainly * enhance the game. */
block_comment
en
false
43663_2
// Import javafx classes import javafx.geometry.Pos; import javafx.scene.Scene; import javafx.scene.control.Label; import javafx.scene.layout.HBox; import javafx.scene.layout.VBox; import javafx.scene.media.Media; import javafx.scene.media.MediaPlayer; import javafx.scene.paint.Color; import javafx.scene.text.Font; import javafx.scene.text.Text; import javafx.util.Duration; import java.io.File; // This class contains everything required to create the menu page class menu { // Declare and initialize text, hbox, vbox, labels, scene, media, and mediaplayer used in the menu page Text title = new Text(); Text menuLabel = new Text(); Text quitLabel = new Text(); HBox titlePage; VBox buttonOptions; VBox credits; VBox vbox; Label creditsLabel = new Label(""); Scene menuScene; Media media; MediaPlayer mediaPlayer; // Method to set the menu page public void setMenu() { // Set the title for the menu title.setText("PAKMAN"); Font titleFont = Font.loadFont("file:PacMan/Resources/Font/pac.ttf", 60); //Setting the font title.setFont(titleFont); title.setFill(Color.YELLOW); // Font for the label options Font labelFont = Font.loadFont("file:PacMan/Resources/Font/pac.ttf", 18); menuLabel.setText("Push SPACE Key"); quitLabel.setText("Push ESC to quit"); menuLabel.setFont(labelFont); quitLabel.setFont(labelFont); menuLabel.setFill(Color.CYAN); quitLabel.setFill(Color.RED); // HBox for the title titlePage = new HBox(10, title); titlePage.setAlignment(Pos.TOP_CENTER); // VBox for the button options buttonOptions = new VBox(100, menuLabel, quitLabel); buttonOptions.setAlignment(Pos.CENTER); // Credit Label and VBox for the label creditsLabel.setText("Not \u00a9 2023 LTD does not exist.\n All rights unreserved"); creditsLabel.setStyle("-fx-text-fill: white; -fx-font-size: 14px"); credits = new VBox(50, creditsLabel); credits.setAlignment(Pos.BOTTOM_CENTER); // General VBox for all elements in the page vbox = new VBox(50, titlePage, buttonOptions); vbox.setAlignment(Pos.CENTER); vbox.getChildren().addAll(credits); vbox.setStyle("-fx-background-color: black;"); // Set Scene menuScene = new Scene(vbox); } // Method used to play the music for the menu page public void playMusic() { media = new Media(new File("Pacman/Resources/music/menu.wav").toURI().toString()); mediaPlayer = new MediaPlayer(media); mediaPlayer.play(); mediaPlayer.setAutoPlay(true); mediaPlayer.setOnEndOfMedia(() -> mediaPlayer.seek(Duration.ZERO)); } }
ZyadKhan05/PakMan
menu.java
753
// Declare and initialize text, hbox, vbox, labels, scene, media, and mediaplayer used in the menu page
line_comment
en
false
43825_18
import java.rmi.*; import java.net.*; import java.util.*; import java.io.*; import java.nio.file.*; import java.math.BigInteger; import java.security.*; // import a json package import com.google.gson.Gson; /* JSON Format { //use method put in chord to send to the cloud // use md5 of localfile for GUID for page // delete pages then delete the file as well //page is an actually physical file in the cloud //use put() from Chord to upload to the network "metadata" : { file : { name : "File1" numberOfPages : "3" pageSize : "1024" //dont worry about this size : "2291" page : { number : "1" //dont worry about number, since JSON keeps track this. guid : "22412" size : "1024" } page : { number : "2" guid : "46312" size : "1024" } page : { number : "3" guid : "93719" size : "243" } } } } */ public class DFS implements Serializable { int port; Chord chord; private long guid; private Gson gson; private String json; private FileStream filestream; private String listOfFiles; private File metafile_physicalFile; /** * Constructor for the DFS class. Takes * an integer as the port number. * @param port * @throws Exception */ public DFS(int port) throws Exception { gson = new Gson(); this.port = port; long guid = md5("" + port); setGuid(guid); chord = new Chord(port, guid); Files.createDirectories(Paths.get(guid+"/repository/")); } public void setGuid(long Guid) { this.guid = Guid; } public long getGUID() { return this.guid; } public String getStringOfFiles() { return this.listOfFiles; } public void setStringOfFiles(String stringToConcatenate) { this.listOfFiles.concat(stringToConcatenate); } /** * Runs the md5 algorithm on an object and * returns its guid * @param objectName is a String and the only * input * @return a guid in the form of a long */ private long md5(String objectName) { try { MessageDigest m = MessageDigest.getInstance("MD5"); m.reset(); m.update(objectName.getBytes()); BigInteger bigInt = new BigInteger(1,m.digest()); return Math.abs(bigInt.longValue()); } catch(NoSuchAlgorithmException e) { //e.printStackTrace(); System.out.println("Caught error in md5() method"); } return 0; } //end md5() method /** Method to join a process to a Chord network * @param ip IP address of the machine's network you wish to join * @param port of the network * @throws Exception */ public void join(String ip, int port) throws Exception { chord.joinRing(ip, port); //chord.Print(); } public Metadata readMetaData() throws Exception, RemoteException { Metadata metadata = null; try { long guid = md5("Metadata"); ChordMessageInterface peer = chord.locateSuccessor(guid); //locate the processor that has the meatadata FileStream metadataraw = peer.get(guid); //locates the file File peerFile = metadataraw.getFile(); //gets the file String fileName = peer.getId() + "/repository/" + guid; System.out.println(fileName); //check the filepath for debugging File newFile = new File(fileName); FileOutputStream output = new FileOutputStream(peerFile); while (metadataraw.available() > 0) { output.write(metadataraw.read()); } output.close(); FileReader fileReader = new FileReader(new File(fileName)); metadata = this.getGsonObject().fromJson(fileReader, Metadata.class); //Reads metadata }catch(RemoteException e) { // System.out.println("1"); debugging print return metadata = new Metadata(); }catch(FileNotFoundException e) { // System.out.println("2"); debugging print return metadata = new Metadata(); } return metadata; } public void writeMetaData(Metadata metadata) throws Exception { try { long guid = md5("Metadata"); //which process has that file ChordMessageInterface process = chord.locateSuccessor(guid); //I know which node has the metadata //Following block is to write to localFile String tempFile = process.getId() + "/repository/"+guid; //System.out.println("\nHere is the file path:\t" + tempFile); File tempFile_file = new File(tempFile); if(tempFile_file.exists()) { FileWriter writer = new FileWriter(tempFile_file); gson.toJson(metadata, writer); writer.close(); } else { FileWriter writer = new FileWriter(tempFile_file); gson.toJson(metadata, writer); writer.close(); } //chords put doesn't seem to put back into the cloud? how to fix process.put(guid, new FileStream(tempFile)); System.out.println("\nUpdating metadata by calling the writeMetadata() method."); } catch (FileNotFoundException e) { System.out.println("File: Does not exist (DFS.writeMedata"); e.printStackTrace();; } } public Gson getGsonObject() { return this.gson; } /** * Creates a new file with the inputted name * into the metadata object. * @param fileName * @throws Exception */ public void touch(String fileName) throws Exception { // TODO: Create the file fileName by adding a new entry to the Metadata // Write Metadata Metadata metadata = readMetaData(); //always read first when creating metadata.createFile(fileName); this.writeMetaData(metadata); } /** * Returns a list of the files in the * metadata in the form of a string. * @return * @throws Exception */ public String ls() throws Exception { Metadata metadata = readMetaData(); //always read first when creating // TODO: returns all the files in the Metadata String listOfFiles = ""; listOfFiles = metadata.getFileNames(); return listOfFiles; /* Metadata metadata = gson.fromJson(json, Metadata.class); //listOfFiles = metadata.getFileNames(); setStringOfFiles(metadata.getFileNames()); return this.getStringOfFiles(); */ } /** * Renames the metadata object. * @param oldName * @param newName * @throws Exception */ public void mv(String oldName, String newName) throws Exception { Metadata metadata = readMetaData(); //always read first when creating metadata.changeName(oldName, newName); writeMetaData(metadata); } /** * Deletes a file and all of its pages * from the metadata. * @param fileName * @throws Exception */ public void delete(String fileName) throws Exception { // TODO: remove all the pages in the entry fileName in the Metadata and then the entry // for each page in Metadata.filename // peer = chord.locateSuccessor(page.guid); // peer.delete(page.guid) // delete Metadata.filename Metadata metadata = readMetaData(); //always read first when creating metadata.delete(fileName); writeMetaData(metadata); // Write Metadata } /** * Returns a page from a file from the metadata * in the form of a FileStream. * @param fileName * @param pageNumber * @return * @throws Exception */ public FileStream read(String fileName, int pageNumber) throws Exception, NullPointerException { // TODO: read pageNumber from fileName FileStream fileStream = null; try { Metadata metadata = readMetaData(); //always read first when creating Page page = metadata.getFile(fileName).getPage(pageNumber-1); // System.out.println("Page number: " +page.getNumberofPage()); debugging prints // System.out.println("Read the file's page " + page.getGUID()); debugging pints ChordMessageInterface peer = chord.locateSuccessor(page.getGUID()); fileStream = peer.get(page.getGUID()); } catch(NullPointerException e) { System.out.println("\nThe file or page you are trying to read does not exist or is null. Returning an empty filestream."); fileStream = new FileStream(); } return fileStream; } //end read() method /** * Returns the last page of a file in the metadata * in the form of a Filestream. * @param fileName * @return Filestream * @throws Exception */ public FileStream tail(String fileName) throws Exception, RemoteException, IOException, NullPointerException { FileStream tail = null; try { Metadata metadata = readMetaData(); //always read first when creating Page page = metadata.getFile(fileName).getLastPage(); System.out.println("\nRead the file's page:\t" + page.getGUID()); ChordMessageInterface peer = chord.locateSuccessor(page.getGUID()); //return peer.get(page.getGUID()); tail = peer.get(page.getGUID()); } catch (NullPointerException e) { //TODO: Implement adding a page. System.out.println("\nNullPointerException. File does not exist -- creating file instead."); this.touch(fileName); //File localFile = new File(fileName); String localFile = "localFile"; this.append(fileName, localFile); Metadata metadata = readMetaData(); //always read first when creating Page page = metadata.getFile(fileName).getLastPage(); System.out.println("\nRead the file's page:\t" + page.getGUID()); ChordMessageInterface peer = chord.locateSuccessor(page.getGUID()); tail = peer.get(page.getGUID()); } return tail; } /** * Returns the first page of the file in the * metadata. * @param fileName * @return * @throws Exception */ public FileStream head(String fileName) throws Exception { return read(fileName, 1); } /** * Adds a new file to the end of the array of * files in the metadata. * @param filename * @param filepath * @throws Exception */ public void append(String filename, String localFile) throws Exception { Metadata metadata = readMetaData(); //always read first when creating File local_file = new File(localFile); if (local_file.exists()) { System.out.println("\nAttempting to append file:\t "+ localFile); guid = md5(localFile); Page page = new Page(0, guid, 0); metadata.getFile(filename).addPage(page); ChordMessageInterface peer = chord.locateSuccessor(guid); peer.put(guid, new FileStream(localFile)); writeMetaData(metadata); } else { System.out.println("\n" + localFile +" does not exist. Creating the file locally."); File newFile = new File(localFile); newFile.createNewFile(); guid = md5(localFile); Page page = new Page(0, guid, 0); metadata.getFile(filename).addPage(page); ChordMessageInterface peer = chord.locateSuccessor(guid); peer.put(guid, new FileStream(localFile)); writeMetaData(metadata); } } //end append() method } //end DFS.java class
AlmondBro/CECS327-Distributed-File-System
DFS.java
2,768
//System.out.println("\nHere is the file path:\t" + tempFile);
line_comment
en
true
43967_0
import java.io.*; public class Queue { int Q[]; int f=-1; int r=-1; int size; public static void main (String args[])throws IOException{ Queue ob=new Queue(); BufferedReader br=new BufferedReader (new InputStreamReader (System.in)); System.out.println("Enter array size"); size=Integer.parseInt(br.readLine()); Q=new int [size]; int choice; System.out.println("Enter 1 to enqueue, 2 for dequeue, 3 for display, 4 for exit"); switch(choice){ case 1: System.out.println("Enter element to enqueue "); int e=Integer.parseInt(br.readLine()); ob.enqueue(e); break; case 2: ob.dequeue(); break; case 3: ob.display(); break; case 4: System.out.println("Exit Program"); System.exit(0); default : System.out.println("INVALID CHOICE"); } } void enqueue(int item){ if(r==size){ System.out.println("Queue overflows"); } else if(f=-1&&r=-1){ f=0; r=0; Q[r]=item; System.out.println("Element inserted"); } else{ r=r+1; Q[r]=item; System.out.println("Element is inserted"); } } void dequeue(){ int val=0; if (f=-1&&r=-1){ System.out.println("Queue Underflows"); } else if(f==r){ val=Q[f]; System.out.println("Element deleted is"+val); f=-1; r=-1; } else{ val=Q[f]; System.out.println("Element deleted is:"+val); f=f+1; } } } 👋 Hi, I’m @aarushinair - Aarushi Nair (she/her/ella) 👀 I’m a Computer Science Engineering Student 💞️ I’m looking to collaborate on #java, #python, #R, #applicationdevelopment 🌱 #GirlsWhoCode #WomenInTech #WomenInIT #WomenInSTEM #CyberSecurity #QuantumComputing #BlockChain #AI #ML 📫 How to reach me: https://www.linkedin.com/in/aarushinair/ 👩‍🏫 YouTube Channel - Code with Aarushi : https://www.youtube.com/channel/UCKj5T1ELHCmkGKujkpqtl7Q 🙋‍ Follow me on Twitter: https://twitter.com/aarushinair_
aarushinair/Learn-Java-wtih-BlueJ
Queue.java
638
//www.linkedin.com/in/aarushinair/
line_comment
en
true
44282_5
import javax.sound.midi.MidiChannel; import javax.sound.midi.MidiSystem; import javax.sound.midi.Synthesizer; import javax.sound.midi.Sequence; import javax.sound.midi.Sequencer; import java.io.File; /** * Plays one or more notes through Midi. If you find yourself wanting to use lots of individual * sound files for a scenario, such as emulating an instrument for example, you may find using * midi a better choice. It has several advantages over using lots of wav files: * <ul> * <li>It takes up far less space, so less disk space is used and loading times are reduced</li> * <li>You can switch between instruments really easily if you wish</li> * <li>You can adjust things like the length of time notes are held for really easily</li> * <li>You can generally manipulate the details of midi notes far more easily than you can with actual sound files</li> * <li>If you really want to be clever, you can add pitch bend, adjust how quickly notes are played and more!</li> * </ul> * However, Midi is not always suited to the task - the sounds aren't always the same on each * computer (since they're generated through the sound card and not in advance) and the quality * won't be as good as a recorded sound. If you're looking for special effects, a backing track * or in game sounds then chances are you'll be better off using normal sound files. * * @author Michael Berry (mjrb4) * @version 12/02/09 */ public class Note { /** The default instrument to use if one isn't specified in the constructor.*/ public static int DEFAULT_INSTRUMENT = 4; /** The channel used to play the Midi notes. */ private MidiChannel channel; /** A sequencer used to play Midi files. */ private static Sequencer sequencer; /** * Try to set the seqencer up. */ { try { sequencer = MidiSystem.getSequencer(); } catch(Exception ex) { ex.printStackTrace(); } } /** * Create a new MidiPlayer object with a default * instrument specified by DEFAULT_INSTRUMENT - * usually a piano sound. */ public Note() { channel = getChannel(DEFAULT_INSTRUMENT); } /** * Create a new MidiPlayer object with a specified * instrument. * @param instrument the instrument to use */ public Note(int instrument) { channel = getChannel(instrument); } /** * Change the instrument this MidiPlayer uses. * @param instrument the instrument to change to */ public void setInstrument(int instrument) { channel.programChange(instrument); } /** * Get the instrument the MidiPlayer is using * at present. * @return the instrument in use. */ public int getInstrument() { return channel.getProgram(); } /** * Converts a string description of the key * to the number used by the MidiPlayer. * @throws RuntimeException if the key name is invalid. */ public int getNumber(String key) { try { String note = new Character(key.charAt(0)).toString(); boolean accidental = false; if(key.charAt(1)=='b') { note += "b"; accidental = true; } else if(key.charAt(1)=='#') { note += "#"; accidental = true; } int offset = 1; if(accidental) offset = 2; int number = Integer.parseInt(key.substring(offset)); int midiNum = (number+1)*12; midiNum += getOffset(note); return midiNum; } catch(Exception ex) { throw new RuntimeException(key + " is an invalid key name..."); } } /** * Set how far each note is (relatively in semitones) above C. */ private int getOffset(String note) { if(note.equalsIgnoreCase("C")) return 0; if(note.equalsIgnoreCase("C#")) return 1; if(note.equalsIgnoreCase("Db")) return 1; if(note.equalsIgnoreCase("D")) return 2; if(note.equalsIgnoreCase("D#")) return 3; if(note.equalsIgnoreCase("Eb")) return 3; if(note.equalsIgnoreCase("E")) return 4; if(note.equalsIgnoreCase("E#")) return 5; if(note.equalsIgnoreCase("F")) return 5; if(note.equalsIgnoreCase("F#")) return 6; if(note.equalsIgnoreCase("Gb")) return 6; if(note.equalsIgnoreCase("G")) return 7; if(note.equalsIgnoreCase("G#")) return 8; if(note.equalsIgnoreCase("Ab")) return 8; if(note.equalsIgnoreCase("A")) return 9; if(note.equalsIgnoreCase("A#")) return 10; if(note.equalsIgnoreCase("Bb")) return 10; if(note.equalsIgnoreCase("B")) return 11; if(note.equalsIgnoreCase("Cb")) return 11; else throw new RuntimeException(); } /** * Play a note - this method doesn't turn the note * off after a specified period of time, the release * method must be called to do that. * @param note the note to play */ public void play(final int note) { channel.noteOn(note, 50); } /** * Release a note that was previously played. If this * note isn't on already, this method will do nothing. */ public void release(final int note) { channel.noteOff(note, 50); } /** * Play a note for a certain amount of time. * @param note the integer value for the note to play * @param length the length to play the note (ms). */ public void play(final int note, final int length) { new Thread() { public void run() { channel.noteOn(note, 50); try { Thread.sleep(length); } catch(InterruptedException ex) {} finally { channel.noteOff(note, 50); } channel.noteOff(note, 50); } }.start(); } /** * Release all notes smoothly. This can be called in the World.stopped() * method to ensure no notes are playing when the scenario has been * stopped or reset. */ public void turnAllOff() { try { channel.allNotesOff(); //This would turn cut notes of immediately and suddenly: //channel.allSoundOff(); sequencer.stop(); sequencer.close(); } catch(Exception ex) {} } /** * Get the MidiChannel object that this MidiPlayer class is using. * If you want to do some more advanced work with the midi channel, you * can use this method to get the MidiChannel object and then work with * it directly. The API for the MidiChannel class is available online * as part of the javax.sound.midi package.<br> * Examples of why you might want to use this - adjusting the speed * notes are played / released with, adding sustain, adding pitch * bend, soloing / muting individual channels - all are fairly advanced * features and as such are not included in this class as standard (to * keep things simple and avoid clutter.) * @return the MidiChannel object behind this MidiPlayer. */ public MidiChannel getMidiChannel() { return channel; } /** * Play a Midi file. */ public static void playMidiFile(String fileName) { try { Sequence sequence = MidiSystem.getSequence(new File(fileName)); sequencer.open(); sequencer.setSequence(sequence); sequencer.start(); } catch(Exception ex) { ex.printStackTrace(); } } /** * Stop playing a Midi file. */ public static void stopMidiFile() { sequencer.stop(); } /** * Internal method to get the channel from the synthesizer in use. * @param instrument the instrument to load initially. */ private MidiChannel getChannel(int instrument) { try { Synthesizer synthesizer = MidiSystem.getSynthesizer(); synthesizer.open(); for (int i=0; i<synthesizer.getChannels().length; i++) { synthesizer.getChannels()[i].controlChange(7, 127); } return synthesizer.getChannels()[instrument]; } catch(Exception ex) { ex.printStackTrace(); return null; } } }
amilich/Orbital_Mechanics
Note.java
2,210
/** * Create a new MidiPlayer object with a default * instrument specified by DEFAULT_INSTRUMENT - * usually a piano sound. */
block_comment
en
false
44401_0
/* * 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. */ /** * * @author Win 7 */ package Logic; public class Sales { }
Beno7/Blue-Repo
Sales.java
68
/* * 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. */
block_comment
en
true
44473_11
/** * This class creates a BakeShop and allows to sublit BakeryOrder to the BakeShop * * @author Iryna Sherepot * @version 7/19/18 */ public class BakeShop { // instance variables private int bakerCount; private int pieCount; private int cakeCount; private int cupcakeDozCount; private int orderCount; private int itemCount ; private double totalSales; private double orderPrice; private BakeryOrder oneOrder; //constants private static final int EACH_BAKER_CAPACITY = 25; //==============CONSTRUCTORS=============== /** * Constructor for objects of class BakeShop */ public BakeShop() { this(0); } /** Full constructor for class BakeShop. * * @param The number of bakers in a shop- must be non-negative */ public BakeShop(int bakerCount) { if(bakerCount < 0){ throw new IllegalArgumentException("Number of bakers has to be non-negative"); } this.bakerCount = bakerCount; } //===================ACCESSORS========================== /** * This methods access bakerCount fiels to show the number of bakers in a shop * * @return the number of bakers in a shop */ public int getBakerCount() { return bakerCount; } /** * Accesses pieCount fiels to show the number of pies * * @return number of pies processed by the shop */ public int getPiesOnOrderCount(){ return this.pieCount; } /** * Accesses cakeCount field to show the number of cakes processed * * @return number of cakes processed by the shop */ public int getCakesOnOrderCount(){ return this.cakeCount; } /** * Accesses cupcakeDozCount field to show the number of dozen cupcakes processdd * * @return number of cupcake dozens processed by the shop */ public int getCupcakeDozOnOrderCount(){ return this.cupcakeDozCount; } /** * Accesses orderCount field to show the number of orders processdd * * @return number of orders dozens processed by the shop */ public int getOrderCount(){ return this.orderCount; } /** * Accesses totalSales field to show the total sales of the shop after processed orders * * @return the total amount of sales of all orders processed */ public double getTotalSales(){ return this.totalSales; } /** * Calculates average order price for all orders * If no orders, returns 0 evarage price * @return double The average price of processed orders in a shop. */ public double getAvgOrderPrice(){ if(getOrderCount() == 0){ return 0; }else{ return (double)(getTotalSales() / getOrderCount()); } } //===================OTHER METHODS============================================ /** * This method submits BakeryOrder to the Shop * It maintains the items counts, order count, order price and total sales * Bakeshop will reject order if order puts shop over capacity * @param The BakeryOrder * @return The price of the order just processed. */ public double submitOrder(BakeryOrder OneOrder) { if((OneOrder.getItemCount() + this.itemCount) > EACH_BAKER_CAPACITY * getBakerCount()){ throw new IllegalArgumentException("Order puts bakery over it's capacity"); } this.pieCount += OneOrder.getPieCount(); this.cakeCount += OneOrder.getCakeCount(); this.cupcakeDozCount += OneOrder.getCupcakeDozenCount(); this.totalSales += OneOrder.getPrice(); this.orderPrice = OneOrder.getPrice(); this.itemCount += OneOrder.getItemCount(); this.orderCount ++; return this.orderPrice; } /** * Increases number of bakers by one */ public void hireOneBaker(){ this.bakerCount += 1; } /** * Decreases number of bakers by one * Cannot fire more bakers than bakery has */ public void fireOneBaker() { if(bakerCount == 0){ throw new IllegalArgumentException("You can't fire more bakers than you have"); } this.bakerCount -= 1; } /** * Returns a string representation of Bake Shop's instance variables. * @return info String represendtation instance variables */ public String toString() { String info = ""; info += "cake On Order Count: " + this.cakeCount; info += "\npie On: " + this.pieCount; info += "\ncupcakeDozCount: " + this.cupcakeDozCount; info += "\nOrderTotal is :" + this.orderPrice; info += "\nTotal Sales are $%5.2f"+ this.totalSales; info += "\nItem Count is :" + this.itemCount; info += "\nBaker Count is: " + this.bakerCount; info += "\nOrderCount is:" + this.orderCount; return info; } }
isherep/CSC142-Bakeshop
BakeShop.java
1,253
/** * Accesses orderCount field to show the number of orders processdd * * @return number of orders dozens processed by the shop */
block_comment
en
false
44489_3
// Write a class, Commission, which has an instance variable, sales; an appropriate // constructor; and a method, commission() that returns the commission. // Now write a demo class to test the Commission class by reading a sale from the user, // using it to create a Commission object after validating that the value is not negative. // Finally, call the commission() method to get and print the commission. If the sales are // negative, your demo should print the message “Invalid Input” class Commission { private int sales; public Commission(int sales) { this.sales = sales; } public int commission() { if (sales < 0) { System.out.println("Invalid Input"); return -1; } if (sales < 100) { return 0; } else if (sales < 200) { return sales * 5 / 100; } else if (sales < 300) { return sales * 10 / 100; } else { return sales * 15 / 100; } } } public class Q6 { public static void main(String[] args) { Commission commission = new Commission(100); System.out.println(commission.commission()); } }
swapnadeepmohapatra/java-college-assignments
lab5/Q6.java
311
// using it to create a Commission object after validating that the value is not negative.
line_comment
en
true
44775_4
class AVLTree { class Node { int key, height; Node left, right; Node(int d) { key = d; height = 1; } } Node root; int height(Node N) { if (N == null) return 0; return N.height; } int max(int a, int b) { return (a > b) ? a : b; } Node rightRotate(Node y) { Node x = y.left; Node T2 = x.right; x.right = y; y.left = T2; y.height = max(height(y.left), height(y.right)) + 1; x.height = max(height(x.left), height(x.right)) + 1; return x; } Node leftRotate(Node x) { Node y = x.right; Node T2 = y.left; y.left = x; x.right = T2; x.height = max(height(x.left), height(x.right)) + 1; y.height = max(height(y.left), height(y.right)) + 1; return y; } int getBalance(Node N) { if (N == null) return 0; return height(N.left) - height(N.right); } Node insert(Node node, int key) { if (node == null) return (new Node(key)); if (key < node.key) node.left = insert(node.left, key); else if (key > node.key) node.right = insert(node.right, key); else return node; node.height = 1 + max(height(node.left), height(node.right)); int balance = getBalance(node); // Left Left if (balance > 1 && key < node.left.key) return rightRotate(node); // Right Right if (balance < -1 && key > node.right.key) return leftRotate(node); // Left Right if (balance > 1 && key > node.left.key) { node.left = leftRotate(node.left); return rightRotate(node); } // Right Left if (balance < -1 && key < node.right.key) { node.right = rightRotate(node.right); return leftRotate(node); } /* return the (unchanged) node pointer */ return node; } void preOrder(Node node) { if (node != null) { System.out.print(node.key + " "); preOrder(node.left); preOrder(node.right); } } public static void main(String[] args) { AVLTree tree = new AVLTree(); tree.root = tree.insert(tree.root, 3); tree.root = tree.insert(tree.root, 2); tree.root = tree.insert(tree.root, 1); tree.root = tree.insert(tree.root, 4); tree.root = tree.insert(tree.root, 5); tree.root = tree.insert(tree.root, 6); tree.root = tree.insert(tree.root, 7); tree.root = tree.insert(tree.root, 8); tree.root = tree.insert(tree.root, 9); System.out.println("Preorder traversal" + " of constructed tree is : "); tree.preOrder(tree.root); } }
Rohith2201/DSA-LAB-CODES
avl.java
922
/* return the (unchanged) node pointer */
block_comment
en
true
45075_8
/** * This class models a Box used for inventory * * */ public class Box { private static int nextInventoryNumber = 1; // generator of unique inventory numbers private Color color; // color of this box private final int INVENTORY_NUMBER; // unique inventory number of this box /** * Creates a new Box and initializes its instance fields color and unique inventory number * * @param color color to be assigned of this box. It can be any of the constant color values * defined in the enum Color: Color.BLUE, Color.BROWN, or Color.YELLOW */ public Box(Color color) { this.color = color; this.INVENTORY_NUMBER = nextInventoryNumber++; } /** * Returns the color of this box * * @return the color of this box */ public Color getColor() { return color; } /** * returns the inventory number of this box * * @return the unique inventory number of this box */ public int getInventoryNumber() { return this.INVENTORY_NUMBER; } /** * Returns a String representation of this box in the format "color INVENTORY_NUMBER" * * @return a String representation of this box */ @Override public String toString() { return color.toString() + " " + this.INVENTORY_NUMBER; } /** * This method sets the nextInventoryNumber to 1. This method must be used in your tester methods * only. */ public static void restartNextInventoryNumber() { nextInventoryNumber = 1; } }
Rago200/Inventory-Storage-System
Box.java
362
/** * This method sets the nextInventoryNumber to 1. This method must be used in your tester methods * only. */
block_comment
en
false
45664_0
import java.io.File; import java.io.FileNotFoundException; import java.util.Scanner; public class t { public static void main(String args[]) { Thread1 t1 = new Thread1(); t1.start(); Thread2 t2 = new Thread2(); t2.start(); } } class Thread1 extends Thread { public void run() { String text = "D://javaworkspace1//HelloWorld//src//a.txt"; Scanner in = null; try { in = new Scanner(new File(text)); } catch (FileNotFoundException e) { // TODO Auto-generated catch block e.printStackTrace(); } int sum = 0; while (in.hasNextInt()) { sum +=in.nextInt(); } System.out.println(text+" sum " + sum); } } class Thread2 extends Thread { public void run() { String text = "D://javaworkspace1//HelloWorld//src//b.txt"; Scanner in = null; try { in = new Scanner(new File(text)); } catch (FileNotFoundException e) { // TODO Auto-generated catch block e.printStackTrace(); } int sum = 0; while (in.hasNextInt()) { sum +=in.nextInt(); } System.out.println(text+" sum " + sum); } }
ethanhe42/introduction-to-java
4/t.java
359
//javaworkspace1//HelloWorld//src//a.txt";
line_comment
en
true
45782_127
package KHS; import java.util.Scanner; // p.110 (3) 금액을 입력받아 500 동전, 100동전, 50동전, 10동전, 1동전 몇개인지 출력 // 금액입력 : 1167 // 2 1 1 1 7 // (2번) 2자리 정수를 입력받고 10의 자리와 1의 자리가 같은지 출력 // 2자리 정수입력: 77 // 같음, 10의 자리 = 7, 1의 자리 = 7 // p.112 (11번) 정수를 입력받아 3 4 5 는 봄, 6 7 8 은 여름, 9 10 11 은 가을, 12 1 2 는 겨울, 그 외 잘못입력 // 자연수 n을 입력받아 1+2+...+n=??? 출력하도록 수정 // "1~10 범위 자연수 n을 입력받아(범위 벗어나면 다시 입력) 1+2+...+n=??? 출력하도록 수정 public class Week02 { public static void main(String[] args) { // TODO Auto-generated method stub Scanner scan = new Scanner(System.in); //int [] intArray1 = { 1, 2, 3, 4, 5}; //int [] intArray2 = new int[] {1, 2, 3, 4, 5}; //int [] intArray3 = new int[5]; // int n; // do { // System.out.print("1~10 범위 자연수 입력 : "); // n = scan.nextInt(); // }while(n < 1 || n >10); // // int sum = 0; // for (int i = 1; i <= n; i++) { // sum = sum + i; // sum += i; // System.out.print(i); // if (i<n) { // System.out.print("+"); // // } // } // System.out.println("=" + sum); // System.out.print("자연수 입력: "); // int n = scan.nextInt(); // int sum = 0; // // //for(int i = 1; i <= n; i++) { // // int i = 1; // while(i<=n) { // sum += i; // System.out.print(i); // if(i<n) { // System.out.print("+"); // } // i++; // } // System.out.println("=" + sum); // int sum = 0; // for (int i = 1; i <= 10; i++) { // sum = sum + i; // sum += i; // System.out.print(i); // if (i<10) { // System.out.print("+"); // // } // } // System.out.println("=" + sum); // int Season = scan.nextInt(); // // switch(Season) { // // case 3,4,5: ~~ Java에서는 OK // case 12: // System.out.println(Season + " 는 겨울"); // break; // case 1: // System.out.println(Season + " 은 겨울"); // break; // case 2: // System.out.println(Season + " 는 겨울"); // break; // case 3: // System.out.println(Season + " 은 봄"); // break; // case 4: // System.out.println(Season + " 는 봄"); // break; // case 5: // System.out.println(Season + " 는 봄"); // break; // case 6: // System.out.println(Season + " 은 여름"); // break; // case 7: // System.out.println(Season + " 은 여름"); // break; // case 8: // System.out.println(Season + " 은 여름"); // break; // case 9: // System.out.println(Season + " 는 가을"); // break; // case 10: // System.out.println(Season + " 은 가을"); // break; // case 11: // System.out.println(Season + " 은 가을"); // break; // default: // System.out.println("잘못입력"); // } // char grade; // System.out.print("정수입력: "); // int score = scan.nextInt(); // switch(score / 10) { // // case 10: // case 9: // grade = 'A'; // break; // case 8: // grade = 'B'; // break; // case 7: // grade = 'C'; // break; // case 6: // grade = 'D'; // break; // default: // grade = 'F'; // break; // } // System.out.println("학점 = " + grade); // System.out.print("2자리 정수입력: "); // int a = scan.nextInt(); // // int a10 = a / 10; // int a1 = a % 10; // // if(a10 == a1) { // System.out.print("같음, 10의 자리 = " + a10 + ", 1의 자리 = " + a1 ); // // } // else // System.out.print("다름, 10의 자리 = " + a10 + ", 1의 자리 = " + a1); // // System.out.print("금액입력 : "); // int amount = scan.nextInt(); // // int coin500 = amount / 500; // int coin100 = (amount % 500) / 100; // int coin50 = (amount % 100) / 50; //((amount % 500)% 100)/50; // int coin10 = (amount % 50) / 10; //(((amount % 500)% 100)%50) / 10; // int coin1 = amount % 10; //((((amount % 500)%100)%50)%10) / 1; // // if (amount > 0) { // // System.out.println(coin500 + " " + coin100 + " " + coin50 + " " + coin10 + " " + coin1 + " "); // // } // else // System.out.println("다시 입력해주세요"); // System.out.print("점수를 입력하세요: "); // // int score = scan.nextInt(); // // // if (score >= 60) { // System.out.print("학년을 입력하세요: "); // int year = scan.nextInt(); // // if(year != 4) // System.out.println("합격"); // else if(score >= 70) // System.out.println("합격"); // else // System.out.println("불합격"); // // } // else // System.out.println("불합격"); // // System.out.print("정수 : "); // int time = scan.nextInt(); // int sec = time % 60; // int min = (time / 60) % 60; // int hour =(time / 60) / 60; // // System.out.println(time + " = " + hour + "시 " + min + "분 " + sec + "초 "); // } }
hskim26/Java-Programing
Week02.java
2,490
// if(a10 == a1) {
line_comment
en
true
46449_1
public class User { public String nama; public int telepon; public void setNama(String nama){ this.nama = nama; } public void setTelepon(int telepon){ this.telepon = telepon; } public void register(){ System.out.println("Berhasil"); } // TODO Create Attribute of User; Name and Phone Number then Create Setter // TODO Create Method to Register User and Display User's Name and Phone Number and success message }
AkbarDwiPutra/OOP-ADIS-AKBAR-1202213184
User.java
114
// TODO Create Method to Register User and Display User's Name and Phone Number and success message
line_comment
en
false
46644_2
import greenfoot.*; // (World, Actor, GreenfootImage, Greenfoot and MouseInfo) /** * This is the reward in the game when the hero kills a mob * * @author (Herman Isayenka) * @version (June 2024) */ public class Coin extends Actor { public Coin() { GreenfootImage image = new GreenfootImage("images/coin.png"); image.scale(60,60); setImage(image); } /** * Act - do whatever the Coin wants to do. This method is called whenever * the 'Act' or 'Run' button gets pressed in the environment. */ public void act() { } }
yrdsb-peths/final-greenfoot-project-herman888
Coin.java
170
/** * Act - do whatever the Coin wants to do. This method is called whenever * the 'Act' or 'Run' button gets pressed in the environment. */
block_comment
en
false
46669_1
/** Ability.java * An abstract class representing all abilities on the map * @author Katherine Liu and Rachel Liu * @version 1.0 June 9, 2021 */ abstract class Ability extends GroundGameObjects { /** * Ability * This constructor ensures each Ability is created with the necessary attributes * @param x The top left x-coordinate of the ability's skin * @param y The top left y-coordinate of the ability's skin * @param width The total width of the ability * @param height The total height of the ability */ Ability(int x, int y, int width, int height) { super(x,y,width,height); } }
kkatherineliu/roadbound401
Ability.java
164
/** * Ability * This constructor ensures each Ability is created with the necessary attributes * @param x The top left x-coordinate of the ability's skin * @param y The top left y-coordinate of the ability's skin * @param width The total width of the ability * @param height The total height of the ability */
block_comment
en
true
46755_0
/* * Search.java * * Created on October 1, 2005, 9:38 AM */ /** * n here must be a power of * a power of 2 */ class MultiProcessor implements Runnable { Thread t[]; int Shared[][]; int key; int n; int place; int loc; boolean foundFlag; MultiProcessor(int A[], int target) { int i = 0, j = 0; n = (int)Math.sqrt(A.length); t = new Thread[n]; Shared = new int[n][n]; while(i < n ) { j = 0; t[i] = new Thread(this, Integer.toString(i)); while (j < n) { Shared[i][j] = A[n * i + j]; j++; } i++; } foundFlag = false; key = target; for (i = 0; i < n; i++) t[i].start(); } public void run() { int i = Integer.parseInt(Thread.currentThread().getName()); System.out.println("In thread " + i); try { synchronized(this) { if (key >= Shared[i][0] && key <= Shared[i][n - 1]) { place = i; foundFlag = true; notifyAll(); } else if (!foundFlag && i != n - 1) { wait(); } else { notifyAll(); } } } catch (InterruptedException ie) { } if (foundFlag) { if (key == Shared[place][i]) loc = 4 * place + i; } else loc = -1; } } public class Search { MultiProcessor m; static int loc; public Search() throws InterruptedException{ int A[] = { 1, 3, 4, 5, 8, 9, 12, 14, 17, 18, 20, 21, 24, 25, 27, 30 }; m = new MultiProcessor(A, 15); for (int j = 0; j < m.n; j++) m.t[j].join(); loc = m.loc; } public static void main(String[] args) throws InterruptedException{ Search s = new Search(); System.out.println("Found at " + loc); } }
thomascherickal/Java-Code
Search.java
602
/* * Search.java * * Created on October 1, 2005, 9:38 AM */
block_comment
en
true
46980_24
import java.util.*; public class MyClass { static String initialLeaderString, finalLeaderString; //declare static strings public static void main(String args[]) { ProgramIntro(); int pot = pot(); boolean finalLeader = userInputLeadersInFinalCount(); boolean originalLeader = userInputLeadersInOGCount(); outro(finalLeader, originalLeader, calculation(pot, finalLeader, originalLeader)); } // Subteam keys static final int BUILD = 0; static final int DESIGN = 1; static final int FINANCE = 2; static final int GRAPHICS = 3; static final int MARKETING = 4; static final int MEDIA = 5; static final int OUTREACH = 6; static final int PROGRAMMING = 7; static final int INITIATIVES = 8; // Used for simple access to array returned by calculation public static void ProgramIntro() { System.out.println("This program will calculate subteam sizes based on predetermined \nsubteam ratios that the user will input!"); System.out.println("The questions are as follows:"); System.out.println("How many people are on the team in total?"); System.out.println("Are leaders included in the total count?"); System.out.println("Are leaders included in the original number of people on the team?"); } public static int pot() { Scanner potScanner = new Scanner(System.in); //takes user input System.out.println("How many people are on the team in total?"); //prints question int pot = potScanner.nextInt(); //"pot" means people on team if (pot < 0) { pot = 0; //this makes it so that if someone were to put a negative number, then "pot" is set to 0 } return pot; //returns value of "pot" } public static int[] calculation(int total, boolean fcLead, boolean ogLead) { // Gaven /* * Takes in the total size of the team and returns the size of each individual * subteam in an array */ if(ogLead == true){ // Remove leaders from the totals to streamline process total -= 11; } if(total < 0){ //In the event of a number too low for realistic results System.out.println("Error: not enough members; please try again"); System.exit(1); } // Calculate numbers for each subteam int buildNum = (int)(total * 0.3); int designNum = (int)(total * 0.125); int financeNum = (int)(total * 0.1); int graphicsNum = (int)(total * 0.1); int marketingNum = (int)(total * 0.075); int mediaNum = (int)(total * 0.075); int outreachNum = (int)(total * 0.05); int programmingNum = (int)(total * 0.125); int initiativesNum = (int)(total * 0.05); if(fcLead == true){ // Add subteam leaders to final counts buildNum += 2; designNum += 1; financeNum += 1; graphicsNum += 1; marketingNum += 1; mediaNum += 1; outreachNum += 1; programmingNum += 1; initiativesNum += 1; } // Create and return an array int[] numbers = {buildNum, designNum, financeNum, graphicsNum, marketingNum, mediaNum, outreachNum, programmingNum, initiativesNum}; return numbers; } public static boolean userInputLeadersInFinalCount() { //Returns whether leaders will be included in final count; Made by Andrew boolean leadersIncludedFinalCount = false; Scanner myObj = new Scanner(System.in); System.out.println("Are leaders included in the final count? (yes or no)"); String leaderIncludedFinalCount = myObj.nextLine(); if (leaderIncludedFinalCount.equals("yes")) { //System.out.println("Leaders will be included in final count"); leadersIncludedFinalCount = true; } else if (leaderIncludedFinalCount.equals("no")) { //System.out.println("Leaders will not be included in final count"); leadersIncludedFinalCount = false; } else { System.out.println("Please enter a correct response. (Non-capital yes or no)"); leaderIncludedFinalCount = myObj.nextLine(); if (leaderIncludedFinalCount.equals("yes")) { //System.out.println("Leaders will be included in final count"); leadersIncludedFinalCount = true; } else if (leaderIncludedFinalCount.equals("no")) { //System.out.println("Leaders will not be included in final count"); leadersIncludedFinalCount = false; } else { System.out.println("Restart the program"); } } return leadersIncludedFinalCount; } public static boolean userInputLeadersInOGCount() { //Returns whether leaders were included in original count; Made by Andrew boolean leadersIncludedOGCount = true; Scanner myObj = new Scanner(System.in); System.out.println("Were leaders included in the original count? (yes or no)"); String leaderIncludedOGCount = myObj.nextLine(); if (leaderIncludedOGCount.equals("yes")) { //System.out.println("Leaders were included in original count"); leadersIncludedOGCount = true; } else if (leaderIncludedOGCount.equals("no")) { //System.out.println("Leaders were not included in original count"); leadersIncludedOGCount = false; } else { System.out.println("Please enter a correct response. (Non-capital yes or no)"); leaderIncludedOGCount = myObj.nextLine(); if (leaderIncludedOGCount.equals("yes")) { //System.out.println("Leaders were included in original count"); leadersIncludedOGCount = true; } else if (leaderIncludedOGCount.equals("no")) { //System.out.println("Leaders were not included in original count"); leadersIncludedOGCount = false; } else { System.out.println("Restart the program"); } } return leadersIncludedOGCount; } public static void outro(boolean finalLeaders, boolean initialLeaders, int [] array) { if(initialLeaders) { initialLeaderString = "Including leaders in the original count"; } else { initialLeaderString = "Excluding leaders in the original count"; } if(finalLeaders) { finalLeaderString = "including leaders in the final count."; } else { finalLeaderString = "excluding leaders in the final count."; } System.out.println(initialLeaderString + " and " + finalLeaderString); System.out.println("there will be:"); System.out.println(array[0] + " builders"); System.out.println(array[1] + " designers"); System.out.println(array[2] + " financers"); System.out.println(array[3] + " graphical creators"); System.out.println(array[4] + " marketers"); System.out.println(array[5] + " photographers"); System.out.println(array[6] + " outreachers"); System.out.println(array[7] + " programmers"); System.out.println(array[8] + " initiaters"); } }
FRC-Team-1710/SubTeamCalculator
MyClass.java
1,757
//System.out.println("Leaders were not included in original count");
line_comment
en
true
47077_1
package workertest; import com.beust.jcommander.JCommander; import com.beust.jcommander.Parameter; import com.google.devtools.build.lib.worker.WorkerProtocol.WorkRequest; import com.google.devtools.build.lib.worker.WorkerProtocol.WorkResponse; import java.io.IOException; import java.nio.file.Files; import java.nio.file.Path; /** Powers the `echo()` Starlark rule. */ public final class Echo { @Parameter(names = "--in") private Path in; @Parameter(names = "--out") private Path out; @Parameter(names = "--persistent_worker") private boolean worker; private Echo() {} /** * There are three paths through this main method. * * <ul> * <li>If this binary is invoked from the echo() action that does not set `supports-workers`, * the args are delivered as regular command-line args, {@link #echo()} is called once, and * the binary exits. * <li>If this binary is invoked from the echo() action that sets `supports-workers`, but Bazel * decides not to run it as a worker, there is a single command-line arg * `@blah.worker_args`. The flag parsing library silently replaces this with the contents of * `blah.worker_args` (see {@link JCommander.Builder#expandAtSign(Boolean)} {@link #echo()} * is called once, and the binary exits. * <li>If this binary is invoked from the echo() action that sets `supports-workers` and Bazel * decides to run it as a worker, there is a single command-line arg `--persistent_worker`. * The binary executes an {@link #workerMain() infinite loop}, reading {@link WorkRequest} * protos from stdin and writing {@link WorkResponse} protos to stdout. * </ul> */ public static void main(String[] args) throws IOException { Echo e = new Echo(); JCommander.newBuilder().addObject(e).build().parse(args); if (e.worker) { workerMain(); } else { e.echo(); } } private static void workerMain() throws IOException { while (true) { WorkRequest workRequest = WorkRequest.parseDelimitedFrom(System.in); Echo e = new Echo(); JCommander.newBuilder() .addObject(e) .build() .parse(workRequest.getArgumentsList().toArray(new String[] {})); e.echo(); WorkResponse.getDefaultInstance().writeDelimitedTo(System.out); } } private void echo() throws IOException { Files.write(out, Files.readAllLines(in)); } }
Ubehebe/bazel-worker-examples
Echo.java
646
/** * There are three paths through this main method. * * <ul> * <li>If this binary is invoked from the echo() action that does not set `supports-workers`, * the args are delivered as regular command-line args, {@link #echo()} is called once, and * the binary exits. * <li>If this binary is invoked from the echo() action that sets `supports-workers`, but Bazel * decides not to run it as a worker, there is a single command-line arg * `@blah.worker_args`. The flag parsing library silently replaces this with the contents of * `blah.worker_args` (see {@link JCommander.Builder#expandAtSign(Boolean)} {@link #echo()} * is called once, and the binary exits. * <li>If this binary is invoked from the echo() action that sets `supports-workers` and Bazel * decides to run it as a worker, there is a single command-line arg `--persistent_worker`. * The binary executes an {@link #workerMain() infinite loop}, reading {@link WorkRequest} * protos from stdin and writing {@link WorkResponse} protos to stdout. * </ul> */
block_comment
en
false
47120_0
public class day1 { public static void main(String[] args) { System.out.println("Hello there! I have started 100 days of code, really excited!!"); System.out.println("This println is use to break the string and start it from next line."); System.out.print("Thankyou!/n"); System.out.print("Join me on twitter"); } } //Hello world with concept of output, understanding of print, println, \n.
Ankush-Katiyar/100DaysOfCode
Day1.java
111
//Hello world with concept of output, understanding of print, println, \n.
line_comment
en
false
47405_3
//QNO1: Write a program to print numbers between 100 and 200 which are exactly divisible by 5. import java.util.Scanner; class DivByFive { public static void main(String[] args) { for (int i = 100; i <= 200; i++) { // System.out.println(i +""); if (i % 5 == 0) { System.out.print(i + " "); } } } } // ONO 2:Write a program to find the sum of first N natural numbers class SumOfNatural { public static void main(String[] args) { Scanner sc = new Scanner(System.in); System.out.println("enter an number"); int a = sc.nextInt(); int i; int sum = 0; for (i = 1; i <= a; i++) { sum = sum + i; } System.out.println("sum is :" + sum); } } // QNO 3:Write a prigram to input and a number and find its reverse. class Reverse { public static void main(String[] args) { Scanner sc = new Scanner(System.in); System.out.println("enter an number"); int rev = 0; int n = sc.nextInt(); while (n > 0) { int r = n % 10; rev = rev * 10 + r; n = n / 10; } System.out.println("reverse is " + rev); } } // QNO 4a: Write a program to display the series class Series { public static void main(String[] args) { for (int i = 1; i <= 5; i++) { for (int j = 1; j <= i; j++) { System.out.print("*"); } System.out.println(); } } } // (4b) class Series2 { public static void main(String[] args) { int sp = 1; for (int i = 5; i >= 1; i -= 2) { for (int k = 1; k <= sp; k++) { System.out.print(" "); } for (int j = 1; j <= i; j++) { System.out.print("*"); } System.out.println(""); sp++; } } } class Series3 { // public static void main(String[] args) public static void main(String[] args) { for (int i = 5; i >= 1; i--) { for (int j = 1; j <= i; j++) { System.out.print(j); } System.out.println(); } } } // 4D class Series4 { public static void main(String[] args) { for (int i = 1; i <= 5; i++) { for (int j = 1; j <= i; j++) { System.out.print(j); } System.out.println(); } } } // Qno 5; WRITE A PROGRAM TO PRINT ALL PRIME NUMBERS BETWWEN 100 AND 200class class PrimeNumbers { public static void main(String[] args) { System.out.println("Prime numbers between 100 and 200 are:"); for (int i = 100; i <= 200; i++) { if (isPrime(i)) { System.out.print(i+" "); } } } // Function to check if a number is prime static boolean isPrime(int num) { if (num <= 1) { return false; // Not prime } for (int i = 2; i < num; i++) { if (num % i == 0) { return false; // Not prime } } return true; // Prime } } //Qno 6 Write a program to print all palindrome number from 100 to 500 class PalindromeNumbers { public static void main(String[] args) { System.out.println("Palindrome numbers between 100 and 500 are:"); for (int num = 100; num <= 500; num++) { if (isPalindrome(num)) { System.out.print(num+" "); } } } // Function to check if a number is palindrome static boolean isPalindrome(int num) { int originalNum = num; int revNum = 0; while (num != 0) { int digit = num % 10; revNum = revNum * 10 + digit; num /= 10; } return originalNum == revNum; } }
RohanLakhemaru/Java-BCA-3rd-Lab
lab2.java
1,148
// QNO 3:Write a prigram to input and a number and find its reverse.
line_comment
en
true
47971_0
// LeetCode 205 Isomorphic Strings // Reference: https://leetcode.com/problems/isomorphic-strings/?envType=study-plan-v2&envId=top-interview-150 class Solution { public boolean isIsomorphic(String s, String t) { // Base case: for different length of two strings if(s.length() != t.length()) return false; // Create two maps for s & t strings... int[] map1 = new int[256]; int[] map2 = new int[256]; // Traverse all elements through the loop for (int idx = 0; idx < s.length(); idx++){ // Compare the maps, if not equal, return false... if(map1[s.charAt(idx)] != map2[t.charAt(idx)]) return false; // Insert each character if string s and t into separate map... map1[s.charAt(idx)] = idx + 1; map2[t.charAt(idx)] = idx + 1; } return true; // Otherwise return true... } }
ElsaYilinWang/LeetCode
205.java
258
// LeetCode 205 Isomorphic Strings
line_comment
en
true
48681_8
import flowers.Flowers; import java.util.ArrayList; import java.util.Arrays; import java.util.Comparator; /** * The `Bouquet` class represents a collection of flowers.Flowers and provides methods to manage and * perform operations on the flowers in the bouquet. */ public class Bouquet { private final ArrayList<Flowers> bouquetOfFlowers = new ArrayList<>(); private final ArrayList<Accessory> accessories = new ArrayList<>(); /** * Gets the bouquet of the flowers. * * @return The bouquet of the flowers. */ public ArrayList<Flowers> getBouquetOfFlowers() { return this.bouquetOfFlowers; } /** * Adds a flowers to the bouquet. * * @param flowers The flowers to add to the bouquet. */ public void addFlowersToBouquet(Flowers flowers) { this.bouquetOfFlowers.add(flowers); } /** * Adds an accessory to the bouquet. * * @param accessory The accessory to add to the bouquet. */ public void addAccessory(Accessory accessory) { accessories.add(accessory); } /** * Gets the accessories. * * @return The accessories. */ public ArrayList<Accessory> getAccessories() { return this.accessories; } /** * Display flowers in the bouquet. * * @param flowersList The flowers to display. */ public void displayFlowers(ArrayList<Flowers> flowersList) { for (Flowers flowers : flowersList) System.out.println(flowers); } /** * Gives the total price of flowers in bouquet. * * @return The total price of the bouquet. */ public int getPriceOfBouquet() { int priceOfBouquet = 0; for (Flowers flower : this.bouquetOfFlowers) { priceOfBouquet += flower.getTotalPrice(); } for (Accessory accessory : this.accessories) { priceOfBouquet += accessory.getPrice(); } return priceOfBouquet; } /** * Sorts flowers in the bouquet by their freshness in ascending order. * * @return The ArrayList sorted by freshness of flowers in the bouquet. */ public ArrayList<Flowers> sortByFreshness() { Flowers[] copiedArray = this.bouquetOfFlowers.toArray(new Flowers[0]); Arrays.sort(copiedArray, Comparator.comparingInt(Flowers::getLevelOfFreshness)); return new ArrayList<>(Arrays.asList(copiedArray)); } /** * Finds and returns a list of flowers in the bouquet within a specified range. * * @param min The minimum length of flower. * @param max The maximum length of flower. */ public ArrayList<Flowers> findingFlowersByLengths(int min, int max) { ArrayList<Flowers> flowersByLengths = new ArrayList<>(); for (Flowers flower : this.bouquetOfFlowers) { if (flower.getLength() > min && flower.getLength() < max) { flowersByLengths.add(flower); } } return flowersByLengths; } }
danil2205/Lab6-Java-Software-Development
Bouquet.java
806
/** * Finds and returns a list of flowers in the bouquet within a specified range. * * @param min The minimum length of flower. * @param max The maximum length of flower. */
block_comment
en
false
48682_1
public interface Accessories { // There's Ring and Necklace | Each Added up Different Stats to The Characters double getStats(); // Stat get from each accessories (May be different Stats depends on type of accessories) - Ring increases Character's HP - Necklace increase Character's Atk }
261200-2566-2/lab05-group3
src/Accessories.java
65
// Stat get from each accessories (May be different Stats depends on type of accessories) - Ring increases Character's HP - Necklace increase Character's Atk
line_comment
en
false
48718_1
import java.io.IOException; import java.util.*; import javax.xml.parsers.ParserConfigurationException; import javax.xml.parsers.SAXParser; import javax.xml.parsers.SAXParserFactory; import org.xml.sax.Attributes; import org.xml.sax.SAXException; import org.xml.sax.helpers.DefaultHandler; //////////////////////////////////////////////////////////// /************** * * SAX parser use callback function to notify client object of the XML document * structure. You should extend DefaultHandler and override the method when * parsing the XML document * ***************/ //////////////////////////////////////////////////////////// public class SaxParserDataStore extends DefaultHandler { SmartPhone smartphone; Laptop laptop; Tablet tablet; TV tv; Accessory accessory; static HashMap<String, SmartPhone> smartphones; static HashMap<String, Laptop> laptops; static HashMap<String, Tablet> tablets; static HashMap<String, TV> tvs; static HashMap<String, Accessory> accessories; String xmlFileName; HashMap<String,String> accessoryHashMap; String elementValueRead; String currentElement = ""; public SaxParserDataStore() { } public SaxParserDataStore(String xmlFileName) { this.xmlFileName = xmlFileName; smartphones = new HashMap<String, SmartPhone>(); laptops = new HashMap<String, Laptop>(); tablets = new HashMap<String, Tablet>(); tvs = new HashMap<String, TV>(); accessories = new HashMap<String, Accessory> (); accessoryHashMap = new HashMap<String, String>(); parseDocument(); } private void parseDocument() { SAXParserFactory factory = SAXParserFactory.newInstance(); try { SAXParser parser = factory.newSAXParser(); parser.parse(xmlFileName, this); } catch (ParserConfigurationException e) { System.out.println("ParserConfig error"); } catch (SAXException e) { System.out.println("SAXException : xml not well formed"); } catch (IOException e) { System.out.println("IO error"); } } //////////////////////////////////////////////////////////// /************* * * There are a number of methods to override in SAX handler when parsing * your XML document : * * Group 1. startDocument() and endDocument() : Methods that are called at * the start and end of an XML document. Group 2. startElement() and * endElement() : Methods that are called at the start and end of a document * element. Group 3. characters() : Method that is called with the text * content in between the start and end tags of an XML document element. * * * There are few other methods that you could use for notification for * different purposes, check the API at the following URL: * * https://docs.oracle.com/javase/7/docs/api/org/xml/sax/helpers/DefaultHandler.html * ***************/ //////////////////////////////////////////////////////////// // when xml start element is parsed store the id into respective hashmap for // smartphone,laptops etc @Override public void startElement(String str1, String str2, String elementName, Attributes attributes) throws SAXException { if (elementName.equalsIgnoreCase("smartphone")) { currentElement = "smartphone"; smartphone = new SmartPhone(); smartphone.setId(attributes.getValue("id")); } if (elementName.equalsIgnoreCase("tablet")) { currentElement = "tablet"; tablet = new Tablet(); tablet.setId(attributes.getValue("id")); } if (elementName.equalsIgnoreCase("laptop")) { currentElement = "laptop"; laptop = new Laptop(); laptop.setId(attributes.getValue("id")); } if (elementName.equalsIgnoreCase("tv")) { currentElement = "tv"; tv = new TV(); tv.setId(attributes.getValue("id")); } if (elementName.equals("accessory")) { currentElement = "accessory"; accessory = new Accessory(); accessory.setId(attributes.getValue("id")); } } // when xml end element is parsed store the data into respective hashmap for // smartphone,laptops etc respectively @Override public void endElement(String str1, String str2, String element) throws SAXException { if (element.equals("smartphone")) { smartphones.put(smartphone.getId(), smartphone); return; } if (element.equals("tablet")) { tablets.put(tablet.getId(), tablet); return; } if (element.equals("laptop")) { laptops.put(laptop.getId(), laptop); return; } if (element.equals("tv")) { tvs.put(tv.getId(), tv); return; } if (element.equals("accessory")) { accessories.put(accessory.getId(),accessory); return; } if (element.equals("item")) { accessoryHashMap.put(elementValueRead,elementValueRead); } if (element.equalsIgnoreCase("accessories")){ if(currentElement.equals("smartphone")) { smartphone.setAccessories(accessoryHashMap); accessoryHashMap=new HashMap<String,String>(); return; } else if (currentElement.equals("tablet")) { tablet.setAccessories(accessoryHashMap); accessoryHashMap=new HashMap<String,String>(); return; } else if (currentElement.equals("tv")) { tv.setAccessories(accessoryHashMap); accessoryHashMap=new HashMap<String,String>(); return; } else if (currentElement.equals("laptop")) { laptop.setAccessories(accessoryHashMap); accessoryHashMap=new HashMap<String,String>(); return; } } if (element.equalsIgnoreCase("image")) { if (currentElement.equals("smartphone")) smartphone.setImage(elementValueRead); if (currentElement.equals("laptop")) laptop.setImage(elementValueRead); if (currentElement.equals("tablet")) tablet.setImage(elementValueRead); if (currentElement.equals("tv")) tv.setImage(elementValueRead); if (currentElement.equals("accessory")) accessory.setImage(elementValueRead); return; } if (element.equalsIgnoreCase("discount")) { if (currentElement.equals("smartphone")) smartphone.setDiscount(Double.parseDouble(elementValueRead)); if (currentElement.equals("laptop")) laptop.setDiscount(Double.parseDouble(elementValueRead)); if (currentElement.equals("tablet")) tablet.setDiscount(Double.parseDouble(elementValueRead)); if (currentElement.equals("tv")) tv.setDiscount(Double.parseDouble(elementValueRead)); if (currentElement.equals("accessory")) accessory.setDiscount(Double.parseDouble(elementValueRead)); return; } if (element.equalsIgnoreCase("condition")) { if (currentElement.equals("smartphone")) smartphone.setCondition(elementValueRead); if (currentElement.equals("laptop")) laptop.setCondition(elementValueRead); if (currentElement.equals("tablet")) tablet.setCondition(elementValueRead); if (currentElement.equals("tv")) tv.setCondition(elementValueRead); if (currentElement.equals("accessory")) accessory.setCondition(elementValueRead); return; } if (element.equalsIgnoreCase("manufacturer")) { if (currentElement.equals("smartphone")) smartphone.setManufacturer(elementValueRead); if (currentElement.equals("laptop")) laptop.setManufacturer(elementValueRead); if (currentElement.equals("tablet")) tablet.setManufacturer(elementValueRead); if (currentElement.equals("tv")) tv.setManufacturer(elementValueRead); if (currentElement.equals("accessory")) accessory.setManufacturer(elementValueRead); return; } if (element.equalsIgnoreCase("name")) { if (currentElement.equals("smartphone")) smartphone.setName(elementValueRead); if (currentElement.equals("laptop")) laptop.setName(elementValueRead); if (currentElement.equals("tablet")) tablet.setName(elementValueRead); if (currentElement.equals("tv")) tv.setName(elementValueRead); if (currentElement.equals("accessory")) accessory.setName(elementValueRead); return; } if (element.equalsIgnoreCase("price")) { if (currentElement.equals("smartphone")) smartphone.setPrice(Double.parseDouble(elementValueRead)); if (currentElement.equals("laptop")) laptop.setPrice(Double.parseDouble(elementValueRead)); if (currentElement.equals("tablet")) tablet.setPrice(Double.parseDouble(elementValueRead)); if (currentElement.equals("tv")) tv.setPrice(Double.parseDouble(elementValueRead)); if (currentElement.equals("accessory")) accessory.setPrice(Double.parseDouble(elementValueRead)); return; } } // get each element in xml tag @Override public void characters(char[] content, int begin, int end) throws SAXException { elementValueRead = new String(content, begin, end); } ///////////////////////////////////////// // Kick-Start SAX in main // //////////////////////////////////////// // call the constructor to parse the xml and get product details public static void addHashmap() { new SaxParserDataStore(Properties.TOMCAT_HOME + Properties.WEBAPP_PATH + Properties.PROJECT_PATH + Properties.PRODUCT_CATALOG_PATH); } public static ArrayList<Product> getAllProducts() { ArrayList<Product> productList = new ArrayList<>(); productList.addAll(smartphones.values()); productList.addAll(laptops.values()); productList.addAll(tablets.values()); productList.addAll(tvs.values()); productList.addAll(accessories.values()); return productList; } }
mfshao/SE452_BestDealDBMongo
src/SaxParserDataStore.java
2,557
/************** * * SAX parser use callback function to notify client object of the XML document * structure. You should extend DefaultHandler and override the method when * parsing the XML document * ***************/
block_comment
en
true
48723_5
import java.util.ArrayList; import java.util.HashMap; /** * @author Shweta * This class represents Car Manufacturers * */ public abstract class Manufacturer { private String manufacturerName; private ArrayList<Car> cars; private HashMap<String,Accessory> accessories; public Manufacturer() { cars = new ArrayList<Car>(); accessories = new HashMap<String,Accessory>(); } /* * Sets a Manufacturer Name. */ public void setManufacturerName(String name){ if(name!= null) { manufacturerName = name; } else { throw new NullPointerException("Please provide a manufacturer name"); } } /* *@return Manufacturer Name of the object this */ public String getManufacturerName(){ if(manufacturerName != null) { return manufacturerName; } else { throw new NullPointerException("Manufacturer not present"); } } /* * @param car to be added to manufacturer. */ public void addCar(Car car){ if(car!=null) { cars.add(car); } else { throw new NullPointerException("Cannot pass null values for Car"); } } /* * @param car to be removed from manufacturer */ public void removeCar(Car car){ if(cars.contains(car)) { cars.remove(car); } else { throw new NullPointerException("Car not present"); } } /* * @param accessoryName - Name of the accessory to be added * @param accessoryValue - Accessory object that stores details about * accessories offered by a manufacturer */ public void addAccessories(String accessoryName,Accessory accessoryValue){ accessories.put(accessoryName, accessoryValue); } /* * @param accessory name * @returns accessory object if accessory is offered by the * manufacturer */ public Accessory getAccessories(String accessoryName) { if(accessories.containsKey(accessoryName)) { return accessories.get(accessoryName); } else { throw new NullPointerException("No such accessory offered by manufacturer."); } } public abstract void printCars(); public ArrayList<Car> getCars() { return cars; } }
HyesungKo/src
Manufacturer.java
578
/* * @param accessoryName - Name of the accessory to be added * @param accessoryValue - Accessory object that stores details about * accessories offered by a manufacturer */
block_comment
en
true
48999_0
/* * Copyright (C) 2011 Paul Bourke <[email protected]> * * 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 org.confab; import java.util.ArrayList; import java.util.List; public class Forum extends BulletinBoardEntity { public String description; public String numViewing; public int numTopics; public int numPosts; public List<String> moderators; public List<Forum> subForums; public List<ForumThread> topics; public Forum(BulletinBoard parent) { super(); this.parent = parent; this.url = parent.url; description = new String(); numViewing = new String(); numTopics = 0; numPosts = 0; moderators = new ArrayList<String>(); subForums = new ArrayList<Forum>(); topics = new ArrayList<ForumThread>(); } }
brk3/libconfab
src/org/confab/Forum.java
360
/* * Copyright (C) 2011 Paul Bourke <[email protected]> * * 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/> */
block_comment
en
true
49101_0
/* * * Author : Rashid A. Aljohani * Thursday, March 13, 2017 * */ public class Weight{ private Node source; private double weight; private Node destination; public Weight(Node source, double weight, Node destination){ this.source = source; this.weight = weight; this.destination = destination; } public void update_weight_hiddens(double lc){ double NEW = weight + (lc * destination.get_delta() * source.get_input()); weight = NEW; } public void update_weight_outputs(double lc, double delta){ double NEW = weight + (lc * delta * source.get_actual()); weight = NEW; } public double get_weight(){ return weight; } public Node get_source(){ return source; } public Node get_destination(){ return destination; } public String toString(){ return source + "--( " + weight + " ) --> " + destination; } }
RashidAljohani/Multi-Layered-Artificial-Neural-Network-Backpropagation
Weight.java
275
/* * * Author : Rashid A. Aljohani * Thursday, March 13, 2017 * */
block_comment
en
true
49283_9
import java.util.ArrayList; /** * A Player in the Uno Game. * * @author Malcolm Ryan * @version 23 September 2010 */ public class Player { private String myName; private ArrayList<Card> myCards; /** * Create a player. The player's hand is initially empty. * * @params The player's name */ public Player(String name) { myName = name; myCards = new ArrayList<Card>(); } /** * Access the player's name */ public String getName() { return myName; } /** * Access the player's hand */ public ArrayList<Card> getCards() { return myCards; } /** * Clear the player's hand */ public void clearCards() { myCards.clear(); } /** * Add a card to the player's hand * * @param card The card to add. */ public void gainCard(Card card) { myCards.add(card); } /** * Choose a card to play. * * @param pileCard The card on the top of the pile to be played on. * @return A card that can be played on the pileCard, or null if none is available */ public Card playCard(Card pileCard) { // play the first playable card we can find for (Card c : myCards) { if (c.canPlayOn(pileCard)) { myCards.remove(c); return c; } } // no card to play return null; } /** * The string representation of the player */ public String toString() { return myName; } }
nluo/UNO-assignments
Player.java
400
/** * The string representation of the player */
block_comment
en
true
49291_0
/* * Solution to problem "Play With Math" on Sphere Online Judge * http://www.spoj.com/problems/ENIGMATH/ * Written by Phillip Shih * September 21, 2015 */ import java.util.*; public class Main { public static void main(String[] args) { Scanner in = new Scanner(System.in); int cases = in.nextInt(); for(int n=0;n<cases;n++) { int a = in.nextInt(); int b = in.nextInt(); int gcd = gcd(a,b); int x = b/gcd; int y = a/gcd; System.out.println(x + " " + y); } } public static int gcd(int a,int b) { if(b > a){return gcd(b,a);} if(b == 0){return a;} return gcd(b, a%b); } }
PhilShih/Solutions-to-Online-Judge-Problems
EnigMath.java
229
/* * Solution to problem "Play With Math" on Sphere Online Judge * http://www.spoj.com/problems/ENIGMATH/ * Written by Phillip Shih * September 21, 2015 */
block_comment
en
true
49304_0
/* * @author <[email protected]> * @version 1.0 * @since September 21, 2017 * (c) Copyright 2017 Cédric Clément. */ import java.io.UnsupportedEncodingException; import java.security.NoSuchAlgorithmException; import java.security.SecureRandom; import javax.crypto.NoSuchPaddingException; import javax.crypto.spec.SecretKeySpec; public class SymKeyGen { private SecretKeySpec secretKey; public SymKeyGen(int length, String algorithm) throws UnsupportedEncodingException, NoSuchAlgorithmException, NoSuchPaddingException { SecureRandom rnd = new SecureRandom(); byte [] key = new byte [length]; rnd.nextBytes(key); this.secretKey = new SecretKeySpec(key, algorithm); } public SecretKeySpec getKey(){ return this.secretKey; } public byte[] getKeyBytes(){ return this.getKey().getEncoded(); } }
cedric-c/CSI_4139_2017
SymKeyGen.java
227
/* * @author <[email protected]> * @version 1.0 * @since September 21, 2017 * (c) Copyright 2017 Cédric Clément. */
block_comment
en
true
49724_0
// Project is regarding testing yahoo signup page using selenium and generating report using testng import org.openqa.selenium.By; import org.openqa.selenium.WebDriver; import org.openqa.selenium.chrome.ChromeDriver; import org.testng.annotations.DataProvider; import org.testng.annotations.Test; public class yahoo { static WebDriver driver; @Test(dataProvider="create") public static void Test(String fname,String lname,String mail,String passwd,String dob,String num)throws InterruptedException { System.setProperty("webdriver.chrome.driver", "C:\\Users\\kusha\\OneDrive\\Desktop\\project\\chromedriver_win32\\chromedriver.exe"); driver = new ChromeDriver(); driver.get("https://login.yahoo.com/account/create?lang=en-IN&src=ym&done=https%3A%2F%2Fin.mail.yahoo.com%2F%3Fguce_referrer%3DaHR0cHM6Ly93d3cuZ29vZ2xlLmNvbS8%26guce_referrer_sig%3DAQAAAFz4lzumyyTw_ImVgPcWOFo68r_UlfmfABB3F6JGoL5t8wwAIcIgfBeZ2sUdQLqw1ROTw_8IJrhBE9LET2FbqNSX7VAgzylOR96hOqYEN6DZFR3-ALLzUMZ5i_zH9Tc7kYdInQOP8A10sK9i3d6db96slyxBImZk4kppSgaFeLjF&specId=yidregsimplified"); driver.manage().window().maximize(); driver.findElement(By.xpath("//*[@id=\"usernamereg-firstName\"]")).sendKeys(fname); driver.findElement(By.xpath("//*[@id=\"usernamereg-lastName\"]")).sendKeys(lname); driver.findElement(By.xpath("//*[@id=\"usernamereg-userId\"]")).sendKeys(mail); driver.findElement(By.xpath("//*[@id=\"usernamereg-password\"]")).sendKeys(passwd); driver.findElement(By.xpath("//*[@id=\"usernamereg-birthYear\"]")).sendKeys(dob); driver.findElement(By.xpath("//*[@id=\"reg-submit-button\"]")).click(); try { driver.findElement(By.xpath("/html/body/div[1]/div[2]/div[1]/div[2]/form/fieldset/input")).sendKeys(num); driver.findElement(By.xpath("/html/body/div[1]/div[2]/div[1]/div[2]/form/div[2]/button")).click(); } catch(Exception e) { driver.close(); } driver.close(); } @DataProvider(name="create") public static Object[][] getData(){ return new Object[][] { {"Ram","K","Rm028","Ram@123","20002","7890789090"}, {"","N","krishfeb2002","Krishl@123","2002","9090908790"}, {"Nayak","","nayak8789","nayak","2000","6767676789"}, {"Varma","K","Varma90872","Varma@123","2002","9879879890"}, {"Abhay","@","Abhay9089","543211","2002","9809809009"} }; } public static void main(String[] args) throws InterruptedException { } }
Hit07/Yahoo-Selenium
yahoo.java
915
// Project is regarding testing yahoo signup page using selenium and generating report using testng
line_comment
en
true
50002_19
package game; import java.util.ArrayList; public class Crew { private static String crewName; private static String shipName; private static int shieldLevel = 1000; private static int maxShieldLevel = 1000; private static ArrayList<CrewMember> crewList = new ArrayList<CrewMember>(); private static ArrayList<MedicalItem> medicalItemsList = new ArrayList<MedicalItem>(); private static ArrayList<Food> foodList = new ArrayList<Food>(); private static int amountOfMoney=100; /** * Returns the name of the crew * @return crew name */ public static String getName() { return crewName; } /** * Set crew name * @param name name for crew */ public static void setName(String name) { crewName = name; } /** * Returns the name of the ship * @return Ship name */ public static String getShipName() { return shipName; } /** * Set the ship name * @param name name for spaceship */ public static void setShipName(String name) { shipName = name; } /** * Returns the shield level * @return shield level */ public static int getShieldLevel() { return shieldLevel; } /** * Increases the shield level * @param HP Amount of level that is added to the shield level * @return True if the shield has been fully repaired or false if it increases the shield level */ public static boolean addShipLevel(int HP) { if(shieldLevel == maxShieldLevel) { System.out.printf("Our ship no need to be repaired\n"); return false; } else { shieldLevel += HP; if(shieldLevel >= maxShieldLevel) { shieldLevel = maxShieldLevel; System.out.printf("%s has been fully repaired\n", shipName); return true; } else { System.out.printf("%s has been repaired (%d/1000ShieldLevel)\n", shipName, shieldLevel); return true; } } } /** * Decreases the shield level * @param HP Amount of level that is taken to the shield level */ public static void minusShipLevel(int HP) { shieldLevel -= HP; if(shieldLevel < 0) { shieldLevel = 0; // System.out.println("You lost the game"); } System.out.printf("%s lost %d shield (%d/%d)\n", shipName, HP, shieldLevel, maxShieldLevel); } /** * Return the list of crew * @return Crew list */ public static ArrayList<CrewMember> getCrew() { return crewList; } /** * Adds the crew member to the crew list * @param crew A crew member that is added to the crew list */ public static void addCrew(CrewMember crew) { crewList.add(crew); } /** * Removes the crew member to the crew list * @param crew A crew member that is removed to the crew list * @return True if the crew member has been successfully removed or false if not */ public static boolean removeCrew(CrewMember crew) { if(crewList.contains(crew)){ crewList.remove(crew); return true; } else { return false; } } /** * to reset crew list */ public static void resetCrew() { crewList = new ArrayList<CrewMember>(); } /** * Returns the list of medical items * @return Medical item list */ public static ArrayList<MedicalItem> getMedicalItems() { return medicalItemsList; } /** * Adds a medical item to the list * @param item A medical item that is added in the list */ // should be divided to addMedicalItem (if the medical item is purchased) and removeMedicalItem (if the medical item has been used) public static void setMedicalItems(MedicalItem item) { medicalItemsList.add(item); } /** * Returns a list of foods * @return Food list */ public static ArrayList<Food> getFoods() { return foodList; } /** * Adds a food item to the list * @param food A food item that is added in the list */ // should be divided to addFood (if the food is purchased) and removeFood (if the food has been consumed) public static void setFoods(Food food) { foodList.add(food); } /** * Returns the amount of money that the player * @return Amount of money that the player has */ public static int getAmountOfMoney() { return amountOfMoney; } /** * Decreases the current amount of money * @param item An item that has a cost to minus to the current amount of money when bought */ public static void minusMoney(Item item) { amountOfMoney -= item.getCost(); } /** * Adds a money to the current money * @param money An amount that is added to current amount of money */ public static void addMoney(int money) { amountOfMoney += money; } }
EnyangZhang/spaceship-game
src/game/Crew.java
1,356
/** * Decreases the current amount of money * @param item An item that has a cost to minus to the current amount of money when bought */
block_comment
en
false
50207_0
package Java_Project; import java.util.ArrayList; public class Point { private ArrayList<Point> neighbors; private int currentState; private int nextState; private final int DEAD = 0; private final int MIN_FRIENDS = 2; private final int MAX_FRIENDS = 3; public Point() { currentState = 0; nextState = 0; neighbors = new ArrayList<Point>(); } public int getState() { return currentState; } public void setState(int s) { currentState = s; } public void calculateNewState() { //TODO: insert logic which updates according to currentState and number of active neighbors int s = getState(); if (s == 1) { nextState = shouldWheatDie() ? DEAD : s; } else if (s == 2) { nextState = shouldCockroachDie(); } else if (s == 3) { nextState = shouldThisDie() ? DEAD : s; } else { nextState = shouldThisBeBorn(); } } public void changeState() { currentState = nextState; } public void addNeighbor(Point nei) { neighbors.add(nei); } private boolean shouldWheatDie() { int aliveFriends = countAliveFriends(2); boolean shouldDie = aliveFriends >= 1; System.out.println("alive friends: " + aliveFriends + "; " + (shouldDie ? "dying" : "living")); return shouldDie; } private int shouldCockroachDie() { int state = 0; int aliveFriends = countAliveFriendsC(); if (aliveFriends > 0) state = (aliveFriends > MAX_FRIENDS || aliveFriends < MIN_FRIENDS)?0:2; else if (aliveFriends == -1) state = 0; return state; } private boolean shouldThisDie() { int aliveFriends = countAliveFriends(3); boolean shouldDie = aliveFriends > MAX_FRIENDS || aliveFriends < MIN_FRIENDS; System.out.println("alive friends: " + aliveFriends + "; " + (shouldDie ? "dying" : "living")); return shouldDie; } private int shouldThisBeBorn() { boolean shouldStart = false; int[] state = countAliveFriends(); if (state != null) shouldStart = state[0] == MAX_FRIENDS; if (shouldStart) return state[1]; else return 0; } private int countAliveFriends(int s) { int aliveFriends = 0; System.out.print("friends: " + neighbors.size() + "; "); for (Point neighbor : neighbors) { if (neighbor.getState() == s) { ++aliveFriends; } } return aliveFriends; } private int countAliveFriendsC() { int aliveFriends = 0; System.out.print("friends: " + neighbors.size() + "; "); for (Point neighbor : neighbors) { if (neighbor.getState() == 2) { ++aliveFriends; } if (neighbor.getState() == 3) { aliveFriends = -1; break; } } return aliveFriends; } private int[] countAliveFriends() { System.out.print("friends: " + neighbors.size() + "; "); int cockroach = 0, ladybug = 0; for (Point neighbor : neighbors) { if (neighbor.getState() == 2) { cockroach += 1; } else if (neighbor.getState() == 3) ladybug += 1; } if (cockroach != 0 || ladybug != 0) return cockroach>ladybug? new int[]{cockroach, 2} : new int[]{ladybug, 3}; else return null; } }
turdalievargen32/Java_Project
Point.java
912
//TODO: insert logic which updates according to currentState and number of active neighbors
line_comment
en
true
50440_0
/** * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * <p/> * http://www.apache.org/licenses/LICENSE-2.0 * <p/> * 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 kafka.examples; public class KafkaProperties { public static final String TOPIC = "topic1"; public static final String KAFKA_SERVER_URL = "localhost"; public static final int KAFKA_SERVER_PORT = 9092; public static final int KAFKA_PRODUCER_BUFFER_SIZE = 64 * 1024; public static final int CONNECTION_TIMEOUT = 100000; public static final String TOPIC2 = "topic2"; public static final String TOPIC3 = "topic3"; public static final String CLIENT_ID = "SimpleConsumerDemoClient"; private KafkaProperties() {} }
mrb/checkstyle-test
K_2.java
339
/** * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * <p/> * http://www.apache.org/licenses/LICENSE-2.0 * <p/> * 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
50500_0
//Using TCP/IP sockets, write a client – server program to make the client send the file name and to make the server send back the contents of the requested file if present //java TCPServer import java.io.File; import java.io.IOException; import java.io.PrintStream; import java.net.ServerSocket; import java.net.Socket; import java.util.Scanner; class TCPServer { public static void main(String [] args) { try{ ServerSocket serverSocket= new ServerSocket(1300); Socket socket = serverSocket.accept(); System.out.println("Accepted"); Scanner socketScanner= new Scanner(socket.getInputStream()); String filename = socketScanner.nextLine().trim(); PrintStream printStream = new PrintStream(socket.getOutputStream()); File file = new File(filename); if(file.exists()){ Scanner fileScanner = new Scanner(file); while(fileScanner.hasNextLine()){ printStream.println(fileScanner.nextLine()); } fileScanner.close(); } else{ System.out.println("File Does not Exists"); } System.in.read(); socket.close(); serverSocket.close(); } catch(IOException e){ System.out.println(e.getMessage()); } } }
shreyashbandekar/JSS-CN.lab
4s.java
300
//Using TCP/IP sockets, write a client – server program to make the client send the file name and to make the server send back the contents of the requested file if present
line_comment
en
false
50738_6
// we included the import statements for you import java.awt.Color; import java.awt.Font; import java.awt.Graphics2D; import java.awt.Rectangle; import java.awt.font.FontRenderContext; import java.awt.geom.Rectangle2D; /** * Bar class * A labeled bar that can serve as a single bar in a bar graph. * The text for the label is centered under the bar. * * NOTE: we have provided the public interface for this class. Do not change * the public interface. You can add private instance variables, constants, * and private methods to the class. You will also be completing the * implementation of the methods given. * */ public class Bar { /** Creates a labeled bar. You give the height of the bar in application units (e.g., population of a particular state), and then a scale for how tall to display it on the screen (parameter scale). @param bottom location of the bottom of the bar @param left location of the left side of the bar @param width width of the bar (in pixels) @param applicationHeight height of the bar in application units @param scale how many pixels per application unit @param color the color of the bar @param label the label under the bar */ //Declare private instance variables for features of the bar private int bottom; private int left; private int width; private int applicationHeight; private double scale; private Color color; private String label; //Bar constructor initializes all the instance variables declared public Bar(int bottom, int left, int width, int applicationHeight, double scale, Color color, String label) { this.bottom = bottom; this.left = left; this.width = width; this.applicationHeight = applicationHeight; this.scale = scale; this.color = color; this.label = label; } /** Draw the labeled bar. @param g2 the graphics context */ public void draw(Graphics2D g2) { int height = applicationHeight; // Declare and initialize the x and y coordinates for the top-left corner of the rectangle. int x = left; //the x-coordinate. int y = (bottom - height); //the y-coordinate. // Construct a rectangle Rectangle rectangle = new Rectangle(x, y, width, height); g2.setColor(color); // Sets this graphics context's color to the specified color. g2.fill(rectangle); // Fills the interiors of the rectangle with graphics context's current color. Font font = g2.getFont(); //Get the default font for the graphics context FontRenderContext context = g2.getFontRenderContext(); Rectangle2D labelBounds = font.getStringBounds(label, context); // Label specifications. int widthOfLabel = (int) labelBounds.getWidth(); int heightOfLabel = (int) labelBounds.getHeight(); g2.setColor(Color.black); int barLabelFont = (x + (width/2)) - (widthOfLabel/2); // Draw the string. g2.drawString(label, barLabelFont,(bottom+20)); } }
Anashwara16/Coin-Toss-Simulator
Bar.java
744
// Declare and initialize the x and y coordinates for the top-left corner of the rectangle.
line_comment
en
false
51115_4
/** * This creates a new ARFF Relation document * It is used to build the training data. IT hs the methods needed to turn either a file of HTML text of lexis articles * or a tab delimited filed of attributes into an arrff files which can be read into a weka * instances object * * @author Rachel Warren * @version 12/14/2013 */ import org.jsoup.Jsoup; import org.jsoup.helper.Validate; import org.jsoup.nodes.Document; import org.jsoup.nodes.Element; import org.jsoup.select.Elements; import java.io.*; import java.util.Scanner; import java.text.*; import java.util.*; import java.util.Calendar; import java.text.*; import java.util.*; import weka.core.Utils; public class Relation { // instance variables - replace the example below with your own private final String name; private final String author; private final String docName; /** * Defualt Constructor for objects of class Relation */ public Relation() { name = "Defualt" ; author = "John Smith" ; docName = "defualt.arff" ; } /** * Constructor for objects of class Relation given string values as parameters * @param n-the name of the relation * @param a-the author * @param docName- the file path of the ARFF doc you want to create MUST be a .arff file */ public Relation(String n, String a, String d) { name = n; author = a; docName = d; } /** * Writes the attribute header to a arff document * @param date the date of this article, will be in the comment * @param atNames the name of the attributes * @param atTypes the types of the attributes precondition: |atName| = |atTypes * */ public void arffHeader(String Date, String description, String[] atNames, String[] atTypes) throws IOException{ File output = new File(this.docName) ; output.createNewFile(); BufferedWriter w = new BufferedWriter(new FileWriter(output)); try{ String[] lines = {"% Title: ARFF file for " + this.name, "%" + description, "%Created by " + this.author, " ", "@RELATION " + this.name, " ", " %attribute declarations", } ; for (String l : lines) { w.newLine(); w.write(l); w.flush(); } for(int i = 0; i<atNames.length; i++) { w.newLine(); w.write("@ATTRIBUTE " + atNames[i] + " " + atTypes[i]); w.flush(); } w.newLine(); w.write("@data"); w.flush(); } finally{ w.close(); } } /** * taboDel2arff converts a tab delimited file to the arff file format. * Note: only supports String and Numeric types, use the Numeric to Nominal Filter after applying to convert the numeric vectors. * @param tabName * @param Date * @param Description a comment about what this relation is * @param atNames the names of the attributes * @param atTypes the tyes of the attributes * |atName| = |atTypes * * @throws IOException if it cannot find the location to right too */ public void tabDel2arff(String tabName, String Date, String description, String[] atNames, String[] atTypes) throws IOException{ arffHeader(Date, description, atNames, atTypes) ; BufferedWriter w = new BufferedWriter(new FileWriter(this.docName, true)); //Read Document File tn = new File(tabName); Scanner in = new Scanner(tn); String next = in.nextLine(); try{ while (in.hasNextLine()) { String[] values = next.split("\\t", -1); String s = "" ; for (int i = 0; i < atNames.length; i++){ if(atTypes[i].equals("STRING")) { //String attribute s = s + Utils.quote(values[i]); } else if(atTypes[i].contains("DATE")) { s = s + "\"" + values[i] + "\""; } else if (atTypes[i].equals("NUMERIC")) { s = s + values[i]; } else { s = s + "\"" + values[i] + "\""; } if (i !=atNames.length-1) { s = s + ", "; } } w.newLine(); next = in.nextLine(); w.write(s); w.flush(); } } //end try finally { w.close(); } } /** * New Doc creates a new ARFF document with the relation header. The document name will be equal to the * value of the field "docName" * * @param date String representation of the date created * @param description comment describing what this relation does, will appear as a * comment in the header * * @throws IOException if the file path cannot be found */ public void newDoc(String Date, String description ) throws IOException { File output = new File(docName); output.createNewFile(); BufferedWriter w = new BufferedWriter(new FileWriter(output)); try{ String[] lines = {"% Title: ARFF file for " + this.name, "%" + description, "%Created by " + this.author, " ", "@RELATION " + this.name, " ", " %attribute declarations", "@ATTRIBUTE lexisnumber NUMERIC", "@ATTRIBUTE date DATE \"yyyy-MM-dd\" ", "@ATTRIBUTE articletitle STRING", "@ATTRIBUTE source STRING", "@ATTRIBUTE wordcount NUMERIC" , "@ATTRIBUTE text STRING", "@ATTRIBUTE class {0, 1}", " ", "%Instances", " ", "@data", " " }; for (String l : lines) { w.newLine(); w.write(l); w.flush(); } }//end try finally{ w.close(); } } /** * addArticles method parses a document of lexis-nexis querries (in html format) and adds the * articles as instances to this Relation * * @param the file path name, must be in HTML format * @return void * * @throws IOException if the filepath cannot be found */ public void addArticles(String lexisdoc) throws IOException{ BufferedWriter w = new BufferedWriter(new FileWriter(this.docName, true)); //Read Html Document File lexis = new File(lexisdoc); Scanner in = new Scanner(lexis); String next = in.nextLine(); try{ while (in.hasNextLine()) { boolean inDoc = false; if (next.contains("<DOCFULL>")){ inDoc = true; } String articleHTML = " "; while(inDoc) { next= in.nextLine(); if (next.contains("DOCFULL")){ inDoc = !inDoc; //LexisInstance a = new LexisInstance(articleHTML); Article a = new Article(articleHTML); w.write(a.toARFFString()); w.newLine(); w.flush(); } else { articleHTML = articleHTML + next ; } } next = in.nextLine(); } }//end try block finally{ w.close(); } }//end method /** * LexisInstances method parses a document of lexis-nexis querries (in html format) and returns them as an arrayList of the LexisInstance types * * @param the file path name, must be in HTML format * @return an array of the Lexis Instance objects * * @throws IOException if the filepath cannot be found */ public ArrayList<String> LexisInstances(String lexisdoc) throws IOException { ArrayList<String> textList = new ArrayList<String>(); //Read Html Document File lexis = new File(lexisdoc); Scanner in = new Scanner(lexis); String next = in.nextLine(); while (in.hasNextLine()) { boolean inDoc = false; if (next.contains("<DOCFULL>")){ inDoc = true; } String articleHTML = " "; while(inDoc) { next= in.nextLine(); if (next.contains("DOCFULL")){ inDoc = !inDoc; //LexisInstance a = new LexisInstance(articleHTML); textList.add(articleHTML); } else { articleHTML = articleHTML + next ; } } next = in.nextLine(); } return textList; }//end me /** * Adds instances to this relation of the articles in the lexisdoc which it takes as its parameter. * * @param lexisdox a document of html text of the lexisnexis output * * @throws IOException if the filepath cannot be found */ public int addInstance(String lexisdoc) throws IOException { int i = 0 ; BufferedWriter w = new BufferedWriter(new FileWriter(this.docName, true)); //Read Html Document File lexis = new File(lexisdoc); Scanner in = new Scanner(lexis); String next = in.nextLine(); try{ while (in.hasNextLine()) { boolean inDoc = false; if (next.contains("<DOCFULL>")){ inDoc = true; } String articleHTML = " "; while(inDoc) { next= in.nextLine(); if (next.contains("DOCFULL")){ inDoc = !inDoc; Article a = new Article(articleHTML); w.write(a.toARFFString()); i++; w.newLine(); w.flush(); } else { articleHTML = articleHTML + next ; } } next = in.nextLine(); } }//end try block finally{ w.close(); } return i ; }//end method }
rachelwarren/CompSeniorProject
Relation.java
2,409
/** * Writes the attribute header to a arff document * @param date the date of this article, will be in the comment * @param atNames the name of the attributes * @param atTypes the types of the attributes precondition: |atName| = |atTypes * */
block_comment
en
false
51162_0
import javax.swing.*; import java.awt.event.*; import java.awt.Font; import java.awt.Color; import javax.swing.border.Border; import java.sql.*; public class as6 implements ActionListener { JFrame fp,f,f1; JPanel p1, p2; JLabel lreg2; JLabel l1, l2, l3, l4, l5, l6, l7, l8, l9; JTextField t1, t2, t3, t4, t5, t6, t7, t8, t9 ; JButton b1, b2, b3, b4,bshop; Border bordhead; Color col1,colo; Font fnl,fnh ; public as6() { f = new JFrame ("Login page"); f1 = new JFrame ("register page"); p1 = new JPanel(); p1.setBackground(Color.pink); p1.setLayout(null); bordhead = BorderFactory.createLineBorder(Color.white,5); col1 = new Color(255, 0, 0, 100); colo = new Color(255,0,0,1); fnl = new Font("San-Serif",Font.PLAIN ,30); fnh = new Font("Serif",Font.BOLD ,60); lreg2 = new JLabel("REGISTRATION"); lreg2.setFont(fnh); lreg2.setForeground(Color.white); lreg2.setBorder(bordhead); lreg2.setBounds(200,0,500,90); JPanel ph2 = new JPanel(); ph2.setBackground(Color.BLACK); ph2.setBounds(0, 0,750,100); ph2.add(lreg2); p2 = new JPanel(); p2.setBackground(Color.black); p2.setBounds(0,100,750,500); p2.setLayout(null); l1= new JLabel("Name"); l2= new JLabel("Password"); l3= new JLabel("Address"); l4= new JLabel("Email ID"); l5= new JLabel("Mobile num:"); l6= new JLabel("Age"); l7= new JLabel("Registered Name :"); l8= new JLabel("Password :"); l1.setBounds( 100, 10, 200, 30); l2.setBounds( 100, 50, 200, 30); l3.setBounds( 100, 90, 200, 30); l4.setBounds( 100, 130, 200, 30); l5.setBounds( 100, 170, 200, 30); l6.setBounds( 100, 210, 200, 30); l7.setBounds( 120, 120, 300, 33); l8.setBounds( 120, 158, 200, 30); l1.setForeground(Color.white); l2.setForeground(Color.white); l3.setForeground(Color.white); l4.setForeground(Color.white); l8.setForeground(Color.black); l5.setForeground(Color.white); l6.setForeground(Color.white); l7.setForeground(Color.black); l1.setBackground(Color.BLACK); l2.setBackground(Color.BLACK); l3.setBackground(Color.BLACK); l7.setBackground(Color.BLACK); l1.setFont(fnl); l2.setFont(fnl); l3.setFont(fnl); l4.setFont(fnl); l5.setFont(fnl); l6.setFont(fnl); l7.setFont(fnl); l8.setFont(fnl); b1= new JButton("Register"); b1.addActionListener(this); b1.setFont(fnl); b1.setBackground(Color.BLACK); b1.setForeground(Color.white); b1.setBounds(200, 260, 300, 30); b4= new JButton("back"); b4.addActionListener(this); b4.setFont(fnl); b4.setBackground(Color.BLACK); b4.setForeground(Color.white); b4.setBounds(200, 300, 300, 30); b2= new JButton("Login"); b2.addActionListener(this); b2.setFont(fnl); b2.setBackground(Color.BLACK); b2.setForeground(Color.white); b2.setBounds(200, 225, 300, 30); b3= new JButton("REGISTER NEW"); b3.addActionListener(this); b3.setFont(fnl); b3.setBackground(Color.BLACK); b3.setForeground(Color.white); b3.setBounds(200, 270, 300, 30); ImageIcon ph1 = new ImageIcon("grocery.jpg"); JLabel phot1 = new JLabel("",ph1,JLabel.CENTER); phot1.setBounds(0,0, 750, 500); ImageIcon photo2 = new ImageIcon("g2.jpg"); JLabel phot2 = new JLabel("",photo2,JLabel.CENTER); phot2.setBounds(0,0, 750, 500); t1= new JTextField(20); t2= new JTextField(20); t3= new JTextField(20); t4= new JTextField(20); t5= new JTextField(20); t6= new JTextField(20); t7= new JTextField(20); t8= new JTextField(20); t1.setBounds(350, 10, 200, 30); t2.setBounds(350, 50, 200, 30); t3.setBounds(350, 90, 200, 30); t4.setBounds(350, 130, 200, 30); t5.setBounds(350, 170, 200, 30); t6.setBounds(350, 210, 200, 30); t7.setBounds(380, 120, 200, 30); t8.setBounds(380, 160, 200, 30); p2.add(l1); p2.add(t1); p2.add(l2); p2.add(t2); p2.add(l3); p2.add(t3); p2.add(l4); p2.add(t4); p2.add(l5); p2.add(t5); p2.add(b1); p2.add(b4); p1.add(b3); p1.add(b2); p2.add(l6); p2.add(t6); p2.add(phot1); p1.add(l7); p1.add(t7); p1.add(l8); p1.add(t8); p1.add(phot2); f.add(p1); f1.add(p2); f1.add(ph2); f1.setBounds(550,250,750,500); f.setBounds( 550,250,750,500); f.setVisible(true); f.setResizable(false); f1.setResizable(false); f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); } public void actionPerformed(ActionEvent ae) { if(ae.getSource()==b1) { String en = t1.getText(); String nm = t2.getText(); String br = t3.getText(); String br1 = t4.getText(); int sm = Integer.parseInt(t5.getText()); int sm1 = Integer.parseInt(t6.getText()); try { Class.forName("com.mysql.jdbc.Driver"); Connection con = DriverManager.getConnection("jdbc:mysql://localhost:3308/Dbdemo1", "root" , "root1"); PreparedStatement pstmt = con.prepareStatement("insert into registration1 values(?,?,?,?,?,?)"); pstmt.setString(1, en); pstmt.setString(2, nm); pstmt.setString(3, br); pstmt.setString(4, br1); pstmt.setInt(5, sm); pstmt.setInt(6, sm1); int i = pstmt.executeUpdate(); if(i!=0) JOptionPane.showMessageDialog(f,"1 record registered succesfully!!!"); else JOptionPane.showMessageDialog(f,"ERROR!!!"); con.close(); t1.setText(""); t2.setText(""); t3.setText(""); t4.setText(""); t5.setText(""); t6.setText(""); } catch(Exception e) { System.out.println(e.getMessage()); } } if(ae.getSource()==b3) { f1.setVisible(true); f.setVisible(false); } if(ae.getSource()==b4) { f.setVisible(true); f1.setVisible(false); } if(ae.getSource()==b2) { String en = t7.getText(); String br = t8.getText(); try { Class.forName("com.mysql.jdbc.Driver"); Connection con = DriverManager.getConnection("jdbc:mysql://localhost:3308/Dbdemo1","root" , "root1"); PreparedStatement pstmt = con.prepareStatement("select * from registration1 where name= ? and pass=?"); pstmt.setString(1, en); pstmt.setString(2, br); ResultSet rs = pstmt.executeQuery(); if(!rs.next()) JOptionPane.showMessageDialog(f,"Bad credrntials!!"); else{ Shop page = new Shop(); page.setVisible(true); } con.close(); t7.setText(""); t8.setText(""); } catch(Exception e) { System.out.println(e.getMessage()); } } } public static void main(String [] args) { new as6(); } }
rohitbhure/Grocery-Shop
as6.java
2,762
//localhost:3308/Dbdemo1",
line_comment
en
true
51387_0
/*Given head, the head of a linked list, determine if the linked list has a cycle in it. There is a cycle in a linked list if there is some node in the list that can be reached again by continuously following the next pointer. Internally, pos is used to denote the index of the node that tail's next pointer is connected to. Note that pos is not passed as a parameter. Return true if there is a cycle in the linked list. Otherwise, return false. Example 1: Input: head = [3,2,0,-4], pos = 1 Output: true Explanation: There is a cycle in the linked list, where the tail connects to the 1st node (0-indexed). Example 2: Input: head = [1,2], pos = 0 Output: true Explanation: There is a cycle in the linked list, where the tail connects to the 0th node. Example 3: Input: head = [1], pos = -1 Output: false Explanation: There is no cycle in the linked list. Constraints: The number of the nodes in the list is in the range [0, 104]. -105 <= Node.val <= 105 pos is -1 or a valid index in the linked-list.*/ /** * Definition for singly-linked list. * class ListNode { * int val; * ListNode next; * ListNode(int x) { * val = x; * next = null; * } * } */ public class Solution { public boolean hasCycle(ListNode head) { ListNode fast=head; ListNode slow=head; while(fast!=null && fast.next!=null){ fast=fast.next.next; slow=slow.next; if(slow==fast){ return true; } } return false; } }
Shaik-Sohail-72/DSA
p63.java
440
/*Given head, the head of a linked list, determine if the linked list has a cycle in it. There is a cycle in a linked list if there is some node in the list that can be reached again by continuously following the next pointer. Internally, pos is used to denote the index of the node that tail's next pointer is connected to. Note that pos is not passed as a parameter. Return true if there is a cycle in the linked list. Otherwise, return false. Example 1: Input: head = [3,2,0,-4], pos = 1 Output: true Explanation: There is a cycle in the linked list, where the tail connects to the 1st node (0-indexed). Example 2: Input: head = [1,2], pos = 0 Output: true Explanation: There is a cycle in the linked list, where the tail connects to the 0th node. Example 3: Input: head = [1], pos = -1 Output: false Explanation: There is no cycle in the linked list. Constraints: The number of the nodes in the list is in the range [0, 104]. -105 <= Node.val <= 105 pos is -1 or a valid index in the linked-list.*/
block_comment
en
true
51790_0
package ProjectEuler;/* Author : Ashutosh Kumar Date : 12/04/20 Email : [email protected] Published on : 2020,April,Sunday Description : By listing the first six prime numbers: 2, 3, 5, 7, 11, and 13, we can see that the 6th prime is 13. What is the 10 001st prime number? */ public class Question7 { public static void main(String[] args) { int count = 0; for (long next = 2; count <= 10001; next++) { if (isPrime(next)) { System.out.println(next+" "+count); count++; } } } static boolean isPrime(long n) { if(n%2==0) return false; for (int next = 2; next <= Math.sqrt(n); next++) { if (n % next == 0) return false; } return true; } }
kashutoshswe/Project-Euler
Question7.java
266
/* Author : Ashutosh Kumar Date : 12/04/20 Email : [email protected] Published on : 2020,April,Sunday Description : By listing the first six prime numbers: 2, 3, 5, 7, 11, and 13, we can see that the 6th prime is 13. What is the 10 001st prime number? */
block_comment
en
true
52495_9
import java.util.*; import java.sql.*; interface duties_and_salaries { void salary(); } abstract class employee implements duties_and_salaries { private String name; private int salary=0; private int id; public employee() { } public employee(String name, int id) { this.name = name; this.id = id; } public String getName() { return name; } public int getSalary() { return salary; } public void setSalary(int salary) { this.salary = salary; } public void setName(String name) { this.name = name; } public void setId(int id) { this.id = id; } public int getId() { return id; } public void addEmployee() { // we should execute differnt queries based on the type int type = -1; /* * type=1-->manager * type=2-->Caretaker * type=3-->Doctor * type=4-->ChartedAccountant * type=5-->ZooGuide */ if (this instanceof manager) type = 1; else if (this instanceof caretaker) type = 2; else if (this instanceof doctor) type = 3; else if (this instanceof ChartedAccountant) type = 4; else if (this instanceof ZooGuide) type = 5; Database db = new Database(); try { db.Establish(); } catch (Exception e1) { e1.printStackTrace(); } switch (type) { case 1: manager y1 = (manager) this; db.setQuery(String.format("insert into manager values(%d,\"%s\",%d)",y1.getId(),y1.getName(),y1.getSalary())); break; case 2: caretaker y2 = (caretaker) this; db.setQuery(String.format("insert into caretaker values(%d,\"%s\",%d)", y2.getId(), y2.getName(), y2.getSalary())); break; case 4: ChartedAccountant y4 = (ChartedAccountant) this; db.setQuery(String.format("insert into chartedaccountant values(%d,\"%s\",%d,%d)", y4.getId(), y4.getName(), y4.getSalary(),y4.currentFinancialPosition)); break; case 3: doctor y3 = (doctor) this; db.setQuery(String.format("insert into doctor values(%d,\"%s\",%d,%d)", y3.getId(), y3.getName(), y3.getSalary(),y3.CasesTaken)); break; case 5: ZooGuide y5 = (ZooGuide) this; db.setQuery(String.format("insert into zooguide values(%d,\"%s\",%d,%f)", y5.getId(), y5.getName(), y5.getSalary(),y5.getAvgrating())); break; default: System.out.println("In the Default Statement"); } try { int rs = db.Update(); } catch (SQLException e) { System.out.println("here bro while adding message to database error occurred!!+_+ O_O"); e.printStackTrace(); } try { db.Close(db.getSt(), db.getCon()); } catch (SQLException e) { System.out.println("Error in closing ¬_¬"); e.printStackTrace(); } } public void update_salary_IN_Database() { String s = "employee"; if (this instanceof manager) s = "manager"; else if (this instanceof caretaker) s = "caretaker"; else if (this instanceof doctor) s = "doctor"; else if (this instanceof ChartedAccountant) s = "chartedaccountant"; else if (this instanceof ZooGuide) s = "zooguide"; Database db = new Database(); try { db.Establish(); } catch (Exception e1) { // TODO Auto-generated catch block e1.printStackTrace(); } // need to test this line of code . db.setQuery(String.format("update %s set salary=%d where id= %d",s, salary, id)); try { int rs = db.Update(); System.out.println(rs); } catch (SQLException e) { System.out.println("while updating salary..."); e.printStackTrace(); } try { db.Close(db.getSt(), db.getCon()); } catch (SQLException e) { System.out.println("Error in closing ¬_¬"); e.printStackTrace(); } } } class manager extends employee { public manager() { } public manager(String name, int id, int salary) { super(name, id); super.setSalary(salary); } public void sendmessage(int recieversid, String msgid, String body) { // id is for whom we want to send message m = new message(msgid, getId(), body); m.setReceiversId(recieversid); m.storeMessage(); } public void salary() { super.setSalary(100000); this.update_salary_IN_Database(); } } class caretaker extends employee { ArrayList<message> inbox = new ArrayList<message>(); public caretaker(String name, int id) { super.setName(name); super.setId(id); } public void sendMessage(int receiversId, String msgId, String body) { message m = new message(msgId, getId(), body); m.setReceiversId(receiversId); m.storeMessage(); } public void salary() { super.setSalary(50000); this.update_salary_IN_Database(); } } class doctor extends employee { ArrayList<message> inbox = new ArrayList<message>(); ArrayList<String> patientList = new ArrayList<>(); int CasesTaken = 3; public doctor() { } public doctor(String name, int id, int salary) { super(name, id); super.setSalary(salary); } public void salary() { setSalary(getSalary() + 1000 * CasesTaken); System.out.println("Your salary is :" + getSalary()); this.update_salary_IN_Database(); } } class ChartedAccountant extends employee { ArrayList<message> inbox = new ArrayList<message>(); static int currentFinancialPosition = 0; public ChartedAccountant() { } public ChartedAccountant(String name, int id) { super(name, id); } public void salary() { this.update_salary_IN_Database(); } public void addsponcer(String Name, int donatedAmount,int id) { sponcers s = new sponcers(Name, donatedAmount,id); currentFinancialPosition += donatedAmount; s.storeSponcer(); // need to add in transaction log if we maintain one ZooManagement.sl.add(s); } public void showFinancialStatus() { System.out.printf("The current Financial status is : %d\n", currentFinancialPosition); } } class ZooGuide extends employee { private int baseSalary; // give bonus based on the ratings they got. ArrayList<Integer> ratings = new ArrayList<>(); ArrayList<message> inbox = new ArrayList<message>(); private double avgrating=0; public ZooGuide(int baseSalary) { this.baseSalary = baseSalary; } public ZooGuide(String name, int id, int baseSalary) { super(name, id); this.baseSalary = baseSalary; } public double getAvgrating() { return avgrating; } public void setAvgrating(double avgrating) { this.avgrating = avgrating; } public int getBaseSalary() { return baseSalary; } public void setBaseSalary(int baseSalary) { this.baseSalary = baseSalary; } public void calculateAvgRating() { int total = 0; int avg; for (int i = 0; i < ratings.size(); i++) { total += ratings.get(i); avg = total / ratings.size(); System.out.println("The Average IS:" + avg); setAvgrating(avg); } } public void addRating(int rating) { ratings.add(rating); System.out.println("Rating added succesfully"); } public void salary() { double sal = baseSalary + avgrating * 5000; super.setSalary((int) Math.round(sal)); this.update_salary_IN_Database(); } } class sponcers extends Database { String Name; int donatedAmount; int id; public sponcers() { } public sponcers(String name, int donatedAmount, int id) { Name = name; this.donatedAmount = donatedAmount; this.id = id; } public int getId() { return id; } public void setId(int id) { this.id = id; } public String getName() { return Name; } public void setName(String name) { Name = name; } public int getDonatedAmount() { return donatedAmount; } public void setDonatedAmount(int donatedAmount) { this.donatedAmount = donatedAmount; } public void storeSponcer() { Database db = new Database(); try { db.Establish(); } catch (Exception e1) { e1.printStackTrace(); } db.setQuery(String.format("insert into sponcers values(%d,\"%s\",%d)", id, Name, donatedAmount)); try { db.Update(); } catch (SQLException e) { System.out.println("here bro while adding message to database error occurred!!+_+ O_O"); e.printStackTrace(); } try { db.Close(db.getSt(), db.getCon()); } catch (SQLException e) { System.out.println("Error in closing ¬_¬"); e.printStackTrace(); } } @Override public String toString() { return String.format("Name: %s ,Donated Amount: %d\n", this.getName(), this.getDonatedAmount()); } } public class employeemodule { public static void main(String args[]) { employee doc1 = new doctor("vikram", 508, 1000); employee ct1 = new caretaker("raj", 106); employee m1 = new manager("hari", 101, 300000); employee ca1 = new ChartedAccountant("Ramesh", 333); employee zg1 = new ZooGuide("harry", 205, 30000); // new message().showUnreadMessages(108); // m1.sendmessage(106, "c-150", "Assemble here at hall"); // ct1.sendMessage(108, "S-200", "A unread message for the second time "); // // ZooManagement.displayAllMessages(); // System.out.println("here"); // m1.sendmessage(106, "c-157", "Assemble here at room"); // new message().showUnreadMessages(108); // doc1.addEmployee(); // doc1.salary(); // doc1.salary(); // ct1.addEmployee(); // m1.addEmployee(); // ca1.addEmployee(); // zg1.addEmployee(); // new ChartedAccountant().addsponcer("gokul", 300000, 980); // new ChartedAccountant().addsponcer("rishi", 70000, 549); // ZooManagement.update_employee_detail("doctor", 508, "name", "vikram"); // ZooManagement.update_employee_detail("doctor", 508, "salary", "667744"); // ZooManagement.update_employee_detail("zooguide", 205, "Average_Rating", "4.7"); ZooManagement.update_employee_detail("zooguide", 205, "salary", "50000"); zg1.salary(); } }
SriGanesh737/Project-Anwel
employeemodule.java
2,977
// ct1.sendMessage(108, "S-200", "A unread message for the second time ");
line_comment
en
true
53215_0
/*Shyam has given a positive number 'N'. Now his sir has given a homework to print all numbers with unique digits below 'N' Sample Test Case-1 input = 100 output = 1 2 3 4 5 6 7 8 9 10 12 13 14 15 16 17 18 19 20 21 23 24 25 26 27 28 29 30 31 32 34 35 36 37 38 39 40 41 42 43 45 46 47 48 49 50 51 52 53 54 56 57 58 59 60 61 62 63 64 65 67 68 69 70 71 72 73 74 75 76 78 79 80 81 82 83 84 85 86 87 89 90 91 92 93 94 95 96 97 98 Sample Test Case-2 input = 10 output = 1 2 3 4 5 6 7 8 9 10 */ import java.util.*; class P1{ public static void main(String args[]){ Scanner sc=new Scanner(System.in); int num=sc.nextInt(); HashSet<Character> hs=new HashSet<>(); ArrayList<Integer> al=new ArrayList<>(); int i=1; while(i<=num){ if(i<=10){ //String st=String.valueOf(i); al.add(i); i++; } else{ String st=String.valueOf(i); for(int j=0;j<st.length();j++){ hs.add(st.charAt(j)); } if(st.length()==hs.size()){ al.add(Integer.parseInt(st)); } hs.clear(); i++; } } System.out.println(al); } }
SadhvikaK/Miscellaneous
P1.java
553
/*Shyam has given a positive number 'N'. Now his sir has given a homework to print all numbers with unique digits below 'N' Sample Test Case-1 input = 100 output = 1 2 3 4 5 6 7 8 9 10 12 13 14 15 16 17 18 19 20 21 23 24 25 26 27 28 29 30 31 32 34 35 36 37 38 39 40 41 42 43 45 46 47 48 49 50 51 52 53 54 56 57 58 59 60 61 62 63 64 65 67 68 69 70 71 72 73 74 75 76 78 79 80 81 82 83 84 85 86 87 89 90 91 92 93 94 95 96 97 98 Sample Test Case-2 input = 10 output = 1 2 3 4 5 6 7 8 9 10 */
block_comment
en
true
53819_2
import java.awt.*; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; class LoanCalculatorFrame extends Frame { private TextField loanAmountField, interestRateField, loanTermField, resultField; private double monthlyPayment; // Declare as an instance variable public LoanCalculatorFrame() { setTitle("Loan Calculator"); setSize(400, 200); setLocationRelativeTo(null); initComponents(); } private void initComponents() { setLayout(new FlowLayout()); loanAmountField = new TextField(10); interestRateField = new TextField(10); loanTermField = new TextField(10); resultField = new TextField(10); resultField.setEditable(false); add(new Label("Loan Amount:")); add(loanAmountField); add(new Label("Annual Interest Rate (%):")); add(interestRateField); add(new Label("Loan Term (years):")); add(loanTermField); Button calculateButton = new Button("Calculate"); calculateButton.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { calculateLoan(); // Print monthly payment to console } }); add(calculateButton); add(new Label("Monthly Payment:")); add(resultField); addWindowListener(new java.awt.event.WindowAdapter() { public void windowClosing(java.awt.event.WindowEvent windowEvent) { System.exit(0); } }); } private void calculateLoan() { try { double loanAmount = Double.parseDouble(loanAmountField.getText()); double annualInterestRate = Double.parseDouble(interestRateField.getText()); int loanTermInYears = Integer.parseInt(loanTermField.getText()); double monthlyInterestRate = annualInterestRate / 100 / 12; int numberOfPayments = loanTermInYears * 12; if (1 + monthlyInterestRate != 1) { monthlyPayment = (loanAmount * monthlyInterestRate) / (1 - Math.pow(1 + monthlyInterestRate, -numberOfPayments)); } else { // Handle the case where the denominator is zero (prevent division by zero) monthlyPayment = Double.POSITIVE_INFINITY; } resultField.setText(String.format("%.2f", monthlyPayment)); // Print monthly payment to console System.out.println("Monthly Payment: $" + monthlyPayment); } catch (NumberFormatException ex) { ex.printStackTrace(); // Handle the exception as needed } } public static void main(String[] args) { LoanCalculatorFrame loanCalculatorFrame = new LoanCalculatorFrame(); loanCalculatorFrame.setVisible(true); } }
RAJA-072/JAVA
gui.java
620
// Handle the case where the denominator is zero (prevent division by zero)
line_comment
en
true
54299_0
package Prototype_003; import javax.swing.SwingUtilities; /* * DawnTrades is a free and open-source stock charting Java program * that is intended to assist with trading publicly available common stock. * * Java and the Java Library xChart is utilized for the creation of DawnTrades * due to the relative ease and convenience of making fast programs with graphs/charts. * * Currently, the development of this working prototype does not have all the features * that are going to be present in the final non-prototype build. * All features, User Interfaces (U.I.), and methodologies are subject to change * during the development and improvement of this and future working prototypes. * * DawnTrades currently has: * * A simple static graph that shows the stock price of a single stock ticker. * Inserting stock data via .csv file. * Stock indicators. * Technical Analysis integration. * * For long time goals: * * Using Funadamental Analysis combined with Technical Analysis * to provide accurate predictions that can be displayed on charts. * Be able to predict time to buy and sell for * 1 day, 5 days, 1 week, 1 month, 3 months, 6 months, 1 year, 2 years, 5 years, 10 years, and lifetime of stock. * Clean, simple, easy to understand User Interface (U.I.) * Fast - Trades today happen between milliseconds to nanoseconds. * Should speed be balanced by accuracy, or should speed be prioritized over accuracy? * * Extra features that could be added: * Customizations of U.I. * Customization of trading strategies. * * Derived and modified from a simple program given by ChatGPT. * * Java Version: Java 8+ * * Java Library: XChart * * @Authors: Wei Jian Zhen, Jawad Rahman * * @License: Apache 2.0 Open-Source License && Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) */ public class Main { public static void main(String[] args) { SwingUtilities.invokeLater(new Runnable() { @Override public void run() { new TabbedFrontEnd().createAndDisplayGUI(); } }); } }
WeiJian123-tech/DawnTrades
Main.java
567
/* * DawnTrades is a free and open-source stock charting Java program * that is intended to assist with trading publicly available common stock. * * Java and the Java Library xChart is utilized for the creation of DawnTrades * due to the relative ease and convenience of making fast programs with graphs/charts. * * Currently, the development of this working prototype does not have all the features * that are going to be present in the final non-prototype build. * All features, User Interfaces (U.I.), and methodologies are subject to change * during the development and improvement of this and future working prototypes. * * DawnTrades currently has: * * A simple static graph that shows the stock price of a single stock ticker. * Inserting stock data via .csv file. * Stock indicators. * Technical Analysis integration. * * For long time goals: * * Using Funadamental Analysis combined with Technical Analysis * to provide accurate predictions that can be displayed on charts. * Be able to predict time to buy and sell for * 1 day, 5 days, 1 week, 1 month, 3 months, 6 months, 1 year, 2 years, 5 years, 10 years, and lifetime of stock. * Clean, simple, easy to understand User Interface (U.I.) * Fast - Trades today happen between milliseconds to nanoseconds. * Should speed be balanced by accuracy, or should speed be prioritized over accuracy? * * Extra features that could be added: * Customizations of U.I. * Customization of trading strategies. * * Derived and modified from a simple program given by ChatGPT. * * Java Version: Java 8+ * * Java Library: XChart * * @Authors: Wei Jian Zhen, Jawad Rahman * * @License: Apache 2.0 Open-Source License && Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) */
block_comment
en
true
54989_0
import java.util.*; public class Ans { public static int[] Check(int[] qu, int[] input) { int[][] ans = A(qu, input, 0, 0); return new int[]{ans[2][0], B(ans[0], ans[1], 0)}; } private static int[][] A(int[] qu, int[] input, int i, int count) { if(i >= qu.length) return new int[][]{qu, input, {count}}; if(qu[i] == input[i]) { count++; List<Integer> copy = new ArrayList<Integer>(Arrays.asList(ArrayUtils.toObject(qu))); copy.remove(i); qu = ArrayUtils.toPrimitive(copy.toArray(new Integer[0])); copy = new ArrayList<Integer>(Arrays.asList(ArrayUtils.toObject(input))); copy.remove(i); input = ArrayUtils.toPrimitive(copy.toArray(new Integer[0])); return A(qu, input, i, count); } return A(qu, input, i+1, count); } private static int B(int[] qu, int[] input, int i) { if(i >= qu.length) return 0; return BInside(qu, input, i, 0); } private static int BInside(int[] qu, int[] input, int i, int j) { if(j >= qu.length) return B(qu, input, i+1); if(i == j || qu[i] != input[j]) return BInside(qu, input, i, j+1); return B(qu, input, i+1)+1;//找到重複的數字後輪i,剩餘的j不用輪了 } }
caeser/Guess_number_team_HW
Ans.java
438
//找到重複的數字後輪i,剩餘的j不用輪了
line_comment
en
true
55540_3
package FibFrog; import java.util.*; // for using "point" (java.awt.*) import java.awt.*; class Solution { public int solution(int[] A) { // note: cannot use "List" (both java.util.* and java.awt.* have "List") ArrayList<Integer> fibonacci = new ArrayList<>(); fibonacci.add(0); // note: f(0) = 0 (as in the quesion) fibonacci.add(1); // note: using "while" is better than "for" (avoid errors) while(true){ int temp1 = fibonacci.get( fibonacci.size()-1 ); int temp2 = fibonacci.get( fibonacci.size()-2 ); fibonacci.add( temp1 + temp2 ); // if already bigger than length, then break; if(temp1 + temp2 > A.length){ break; } } // reverse "List": from big to small Collections.reverse(fibonacci); // use "queue" with "point" // point(x,y) = point("position", "number of steps") ArrayList<Point> queue = new ArrayList<>(); queue.add( new Point(-1, 0) ); // position:-1, steps:0 // index: the current index for queue element int index=0; while(true){ // cannot take element from queue anymore if(index == queue.size() ){ return -1; } // take element from queue Point current = queue.get(index); // from big to small for(Integer n: fibonacci){ int nextPosition = current.x + n; // case 1: "reach the other side" if(nextPosition == A.length){ // return the number of steps return current.y + 1; } // case 2: "cannot jump" // note: nextPosition < 0 (overflow, be careful) else if( (nextPosition > A.length) || (nextPosition < 0)|| (A[nextPosition]==0) ){ // note: do nothing } // case 3: "can jump" (othe cases) else{ // jump to next position, and step+1 Point temp = new Point(nextPosition, current.y + 1); // add to queue queue.add(temp); A[nextPosition] = 0; // key point: for high performance~!! } } index++; // take "next element" from queue } } }
Mickey0521/Codility
FibFrog.java
586
// note: using "while" is better than "for" (avoid errors)
line_comment
en
false
55646_2
import javax.swing.*; import java.awt.*; import java.awt.event.*; import java.sql.*; public class App { JLabel Tittle,RollNo, Name, Tamil, English, Maths, Science, Social; JTextField RollNoIn, NameIn, TamilIn , EnglishIn, MathsIn, ScienceIn, SocialIn; JButton Submit, Reset, Result; public void MarkTool(){ JFrame frame1 = new JFrame("MarkEntry"); frame1.getContentPane().setBackground(Color.decode("#191E29")); Tittle= new JLabel("MARK ENTRY TOOL"); Tittle.setForeground(Color.decode("#01C38D")); Tittle.setBounds(150,10,120,40); RollNo= new JLabel("RollNo"); RollNo.setForeground(Color.decode("#01C38D")); RollNo.setBounds(90, 70, 50, 40); RollNoIn= new JTextField(); RollNoIn.setBackground(Color.decode("#132D46")); RollNoIn.setForeground(Color.decode("#01C38D")); RollNoIn.setBounds(200,75,120,25); Name= new JLabel("Name"); Name.setForeground(Color.decode("#01C38D")); Name.setBounds(90,122,50,40); NameIn= new JTextField(); NameIn.setBackground(Color.decode("#132D46")); NameIn.setForeground(Color.decode("#01C38D")); NameIn.setBounds(200,125,120,25); Tamil= new JLabel("Tamil"); Tamil.setForeground(Color.decode("#01C38D")); Tamil.setBounds(90,170,50,40); TamilIn=new JTextField(); TamilIn.setBackground(Color.decode("#132D46")); TamilIn.setForeground(Color.decode("#01C38D")); TamilIn.setBounds(200,175,120,25); English= new JLabel("English"); English.setForeground(Color.decode("#01C38D")); English.setBounds(90,220,50,40); EnglishIn= new JTextField(); EnglishIn.setBackground(Color.decode("#132D46")); EnglishIn.setForeground(Color.decode("#01C38D")); EnglishIn.setBounds(200,225,120,25); Maths= new JLabel("Maths"); Maths.setForeground(Color.decode("#01C38D")); Maths.setBounds(90,270,50,40); MathsIn= new JTextField(); MathsIn.setBackground(Color.decode("#132D46")); MathsIn.setForeground(Color.decode("#01C38D")); MathsIn.setBounds(200,275,120,25); Science= new JLabel("Science"); Science.setForeground(Color.decode("#01C38D")); Science.setBounds(90,320,50,40); ScienceIn= new JTextField(); ScienceIn.setBackground(Color.decode("#132D46")); ScienceIn.setForeground(Color.decode("#01C38D")); ScienceIn.setBounds(200,325,120,25); Social= new JLabel("Social"); Social.setForeground(Color.decode("#01C38D")); Social.setBounds(90,368,50,40); SocialIn= new JTextField(); SocialIn.setBackground(Color.decode("#132D46")); SocialIn.setForeground(Color.decode("#01C38D")); SocialIn.setBounds(200,375,120,25); Submit= new JButton("Submit"); Submit.setBackground(Color.decode("#01C38D")); Submit.setForeground(Color.decode("#132D46")); Submit.setBounds(110,430,80,25); Reset= new JButton("Reset"); Reset.setBackground(Color.decode("#01C38D")); Reset.setForeground(Color.decode("#132D46")); Reset.setBounds(230,430,80,25); Result= new JButton("Result"); Result.setBackground(Color.decode("#01C38D")); Result.setForeground(Color.decode("#132D46")); Result.setBounds(165,480,80,25); frame1.add(Tittle); frame1.add(RollNo);frame1.add(RollNoIn); frame1.add(Name);frame1.add(NameIn); frame1.add(Tamil);frame1.add(TamilIn); frame1.add(English);frame1.add(EnglishIn); frame1.add(Maths);frame1.add(MathsIn); frame1.add(Science);frame1.add(ScienceIn); frame1.add(Social);frame1.add(SocialIn); frame1.add(Submit);frame1.add(Reset); frame1.add(Result); frame1.setSize(400, 570); frame1.setLocationRelativeTo(null); frame1.setLayout(null); frame1.setResizable(false); frame1.setVisible(true); Submit.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { try { String query="insert into stu_details (Roll_no, Name, Tamil, English, Maths, Science, Social) values (?,?,?,?,?,?,?);"; Connection con = DriverManager.getConnection("jdbc:mysql://localhost:3306/studentdetails", "root", "1234"); PreparedStatement pst= con.prepareStatement(query); pst.setInt(1, Integer.parseInt(RollNoIn.getText())); pst.setString(2, NameIn.getText()); pst.setInt(3,Integer.parseInt(TamilIn.getText())); pst.setInt(4,Integer.parseInt(EnglishIn.getText())); pst.setInt(5,Integer.parseInt(MathsIn.getText())); pst.setInt(6,Integer.parseInt(ScienceIn.getText())); pst.setInt(7,Integer.parseInt(SocialIn.getText())); int i= pst.executeUpdate(); JOptionPane.showMessageDialog(null,"Inserted into Database!!"); }catch (Exception er){ JOptionPane.showMessageDialog(null,er.getMessage()); } } }); Reset.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { RollNoIn.setText(null); NameIn.setText(null); TamilIn.setText(null); EnglishIn.setText(null); MathsIn.setText(null); ScienceIn.setText(null); SocialIn.setText(null); } }); Result.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { frame1.dispose(); Result(); } }); } public void Result(){ //creating Result frame JFrame frame2=new JFrame("RESULT"); JLabel Topic2=new JLabel("RESULT"); Topic2.setBounds(165,5,100,40); JLabel EnterRollNo=new JLabel("Enter the RollNo"); EnterRollNo.setBounds(80,50,150,40); JTextField RollNo2=new JTextField(); RollNo2.setBounds(210,60,120,20); JButton GetMarks=new JButton("GetMarks"); GetMarks.setBounds(90,120,95,25); JButton Back=new JButton("Back"); Back.setBounds(230,120,80,25); JLabel ShowResult=new JLabel("Your Result Shown Below : "); ShowResult.setBounds(78,165,160,40); frame2.add(Topic2); frame2.add(EnterRollNo); frame2.add(RollNo2); frame2.add(GetMarks); frame2.add(Back); frame2.add(ShowResult); frame2.setSize(400,570); frame2.setResizable(false); frame2.setLocationRelativeTo(null); frame2.setLayout(null); frame2.setVisible(true); Back.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { frame2.dispose(); MarkTool(); } }); GetMarks.addActionListener(new ActionListener() { public void actionPerformed (ActionEvent e){ try { String queryG="select*from stu_details where Roll_no="+Integer.parseInt(RollNo2.getText()); Connection con1 = DriverManager.getConnection("jdbc:mysql://localhost:3306/studentdetails", "root", "1234"); Statement st= con1.createStatement(); ResultSet rs=st.executeQuery(queryG); rs.next(); JLabel FinalResultRollNo = new JLabel("RollNo :" + " " + rs.getInt(1)); FinalResultRollNo.setBounds(80, 210, 120, 25); JLabel FinalResultName = new JLabel("Name :" + " " + rs.getString(2)); FinalResultName.setBounds(80, 235, 200, 25); JLabel FinalResultTamil = new JLabel("Tamil :" + " " + rs.getInt(3)); FinalResultTamil.setBounds(80, 263, 120, 25); JLabel FinalResultEnglish = new JLabel("English :" + " " + rs.getInt(4)); FinalResultEnglish.setBounds(80, 290, 120, 25); JLabel FinalResultMaths = new JLabel("Maths :" + " " + rs.getInt(5)); FinalResultMaths.setBounds(80, 320, 120, 25); JLabel FinalResultScience = new JLabel("Science :" + " " + rs.getInt(6)); FinalResultScience.setBounds(80, 350, 120, 25); JLabel FinalResultSocial = new JLabel("Social :" + " " + rs.getInt(7)); FinalResultSocial.setBounds(80, 380, 120, 25); int FinalTotal=rs.getInt(3)+rs.getInt(4)+rs.getInt(5)+rs.getInt(6)+rs.getInt(7); JLabel Total=new JLabel("Total :"+" "+FinalTotal+"/"+"500"); Total.setBounds(80,410,140,25); JButton Clear=new JButton("Clear"); Clear.setBounds(150,445,80,25); frame2.add(FinalResultRollNo); frame2.add(FinalResultName); frame2.add(FinalResultTamil); frame2.add(FinalResultEnglish); frame2.add(FinalResultMaths); frame2.add(FinalResultScience); frame2.add(FinalResultSocial); frame2.add(Total); frame2.add(Clear); frame2.setSize(400, 570); frame2.setResizable(false); frame2.setLayout(null); frame2.setLocationRelativeTo(null); frame2.setVisible(true); GetMarks.setVisible(false); Clear.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { FinalResultRollNo.setText(null); FinalResultTamil.setText(null); FinalResultName.setText(null); FinalResultEnglish.setText(null); FinalResultMaths.setText(null); FinalResultScience.setText(null); FinalResultSocial.setText(null); Total.setText(null); Clear.setVisible(false); GetMarks.setVisible(true); } }); }catch (Exception er){ JOptionPane.showMessageDialog(null,er.getMessage()); } } }); } public static void main(String[] args) { App a=new App(); a.MarkTool(); } }
lokesh-weby/STUDENT_DATABASE
src/App.java
2,882
//localhost:3306/studentdetails", "root", "1234");
line_comment
en
true
56292_1
package orderSpecs; import java.util.Comparator; /** This class represents a side, either buy or sell. * * There are only two possible choices, a buy or a sell, so * we will make it impossible to instantiate other Side objects * by making the constructor of this class private. We will * create two Side object, a Side.BUY and Side.SELL and make * those static and public so they can be accessed by other * classes. The side object also knows how to compare prices * via two possible comparators, a BidComparator and an * OfferComparator. (When comparing prices in the bid book, * we start with the highest first, and in the offer book, * with the lowest first.) * */ public class Side { private static Comparator<Price> BidComparator = new Comparator<Price>() { @Override public int compare(Price o1, Price o2) { return o2.compareTo( o1 ); } }; private static Comparator<Price> OfferComparator = new Comparator<Price>() { @Override public int compare(Price o1, Price o2) { return o1.compareTo( o2 ); } }; public static Side BUY = new Side( "BUY", BidComparator ); public static Side SELL = new Side( "SELL", OfferComparator ); private String _description; private int _hashCode; private Comparator<Price> _comparator; /** Instantiate side object. Save description string - eg "BUY" - and * comparator, and save a permanent hashCode value (not necessary * to compue it on the fly) * * @param description "BUY" or "SELL" * @param comparator Comparator for comparing prices in bid or * offer book */ private Side( String description, Comparator<Price> comparator ) { _description = description; _hashCode = _description.hashCode(); _comparator = comparator; } @Override public String toString() { return String.format( "%s(%s)", this.getClass().getName(), _description ); } @Override public int hashCode() { return _hashCode; } @Override public boolean equals( Object o ) { // There are only two Side objects, so there is no // need for comparisons beyond identity comparisons return( this == o ); } /** * @return Give access to side-specific comparator of prices */ public Comparator<Price> getComparator() { return _comparator; } }
contactsonle/Exchange-Imitation
Side.java
604
/** Instantiate side object. Save description string - eg "BUY" - and * comparator, and save a permanent hashCode value (not necessary * to compue it on the fly) * * @param description "BUY" or "SELL" * @param comparator Comparator for comparing prices in bid or * offer book */
block_comment
en
true
56588_3
import java.io.*; import java.util.*; public class Q8 { /** * TODO: Generate an n*n square where the rows, columns, and diagonal sum to the same number: * * Notes: * 1. n will always be an odd integer * 2. Every number in the square can only be used once * 3. The numbers in the square should be from 1 to n*n * * @param n --> the dimensions of the square * * @return new int[][] --> a 2D integer array containing the square */ public static int[][] generateSquare(int n) { boolean[][] addOne = new boolean[n][n]; for(int row = 0; row < n; row++) { for(int column = 0; column < n; column++) { addOne[row][column] = false; } } int[][] perfectSquare = new int[n][n]; // double sumPerRow = ((n * n) * (n * n + 1) / 2) / n; int startingCorner = (((n * n) / 2) + 1) - (n / 2); for(int i = 0; i < n; i++) { perfectSquare[n - 1 - i][i] = startingCorner + i; } perfectSquare[n / 2][n - 1] = 1; for(int i = n - 2; i >= 0; i--) { perfectSquare[n / 2][i] = perfectSquare[n/2][i + 1] + n + 1; } for(int row = 0; row < n / 2; row++) { int columnIndex = (n - 2 * row) - 1; addOne[row][columnIndex - 1] = true; } for(int row = n - 1; row > n / 2; row--) { int columnIndex = 2 * ((n - 1) - row); addOne[row][columnIndex + 1] = true; } for(int row = 0; row < n; row++) { if(row == n/2) { //do nothing } else { int solvedPosition = n - 1 - row; for(int position = solvedPosition - 1; position >= 0; position--) { if(addOne[row][position]) { perfectSquare[row][position] = perfectSquare[row][position + 1] + 1; } else { perfectSquare[row][position] = (perfectSquare[row][position + 1] + n + 1) % (n * n); } } for(int position = solvedPosition + 1; position < n ; position++) { int target = position - 1; if(addOne[row][position]) { System.out.println("in add"); perfectSquare[row][position] = perfectSquare[row][target] - 1; } else { perfectSquare[row][position] = (perfectSquare[row][target] - n - 1) % (n * n); if(perfectSquare[row][position] < 0) { perfectSquare[row][position] = n * n + perfectSquare[row][position]; } } } } } return perfectSquare; } /* * It is unnecessary to edit the "main" method of each problem's provided code * skeleton. The main method is written for you in order to help you conform to * input and output formatting requirements. */ public static void main(String[] args) { Scanner in = new Scanner(System.in); int cases = Integer.parseInt(in.nextLine()); for (; cases > 0; cases--) { // User Input int n = Integer.parseInt(in.nextLine()); // Function Call int magicSquare[][] = generateSquare(n); // Terminal Output for (int i = 0; i < n; i++) { for (int j = 0; j < n; j++) System.out.print(magicSquare[i][j] + " "); System.out.println(); } } in.close(); } }
sqqueak/competitive-coding
marquette acm/2022/Q8.java
1,008
/* * It is unnecessary to edit the "main" method of each problem's provided code * skeleton. The main method is written for you in order to help you conform to * input and output formatting requirements. */
block_comment
en
true
57408_5
package hw1; import static java.lang.System.out; import java.io.*; import java.util.*; import java.util.Map.Entry; import java.util.concurrent.*; import java.security.MessageDigest; import java.security.NoSuchAlgorithmException; public class MP1 { Random generator; String userName; String inputFileName; Integer inputFileLineCount = 50000; String delimiters = " \t,;.?!-:@[](){}_*/"; String[] stopWordsArray = { "i", "me", "my", "myself", "we", "our", "ours", "ourselves", "you", "your", "yours", "yourself", "yourselves", "he", "him", "his", "himself", "she", "her", "hers", "herself", "it", "its", "itself", "they", "them", "their", "theirs", "themselves", "what", "which", "who", "whom", "this", "that", "these", "those", "am", "is", "are", "was", "were", "be", "been", "being", "have", "has", "had", "having", "do", "does", "did", "doing", "a", "an", "the", "and", "but", "if", "or", "because", "as", "until", "while", "of", "at", "by", "for", "with", "about", "against", "between", "into", "through", "during", "before", "after", "above", "below", "to", "from", "up", "down", "in", "out", "on", "off", "over", "under", "again", "further", "then", "once", "here", "there", "when", "where", "why", "how", "all", "any", "both", "each", "few", "more", "most", "other", "some", "such", "no", "nor", "not", "only", "own", "same", "so", "than", "too", "very", "s", "t", "can", "will", "just", "don", "should", "now" }; private Integer cap = 20; private Set<String> stopWords; public MP1(String userName, String inputFileName) { this.userName = userName; this.inputFileName = inputFileName; } public void dumpList(List<Map.Entry<String, Integer>> s) { out.println("list: "); for (Map.Entry<String, Integer> e : s) { out.println(e.getKey() + " : " + e.getValue()); } out.println(); } public void dumpQueue(Queue<Map.Entry<String, Integer>> q) { out.println("queue: "); while (q.size() != 0) { Map.Entry<String, Integer> e = q.poll(); out.println(e.getKey() + " : " + e.getValue()); } out.println(); } public void dumpMap(Map<String, Integer> s) { out.println("list: "); for (Map.Entry<String, Integer> e : s.entrySet()) { out.println(e.getKey() + " : " + e.getValue()); } out.println(); } void initialRandomGenerator(String seed) throws NoSuchAlgorithmException { MessageDigest messageDigest = MessageDigest.getInstance("SHA"); messageDigest.update(seed.toLowerCase().trim().getBytes()); byte[] seedMD5 = messageDigest.digest(); long longSeed = 0; for (int i = 0; i < seedMD5.length; i++) { longSeed += ((long) seedMD5[i] & 0xffL) << (8 * i); } this.generator = new Random(longSeed); } Integer[] getIndexes() throws NoSuchAlgorithmException { Integer n = 10000; Integer number_of_lines = inputFileLineCount; Integer[] ret = new Integer[n]; this.initialRandomGenerator(this.userName); for (int i = 0; i < n; i++) { ret[i] = generator.nextInt(number_of_lines); } return ret; } /** * Find large frequency elements by min heap * @param freq * @return */ public String[] FindLargesByHeap(Map<String, Integer> freq) { String[] ret = new String[cap]; /* * Construct a min heap * Notice the capacity */ int capacity = cap + 20; PriorityQueue<Map.Entry<String, Integer>> queue = new PriorityQueue<Map.Entry<String, Integer>>( capacity, new Comparator<Map.Entry<String, Integer>>(){ /* * Notice the comparison function is exactly reverse to that of sort */ public int compare(Entry<String, Integer> o1, Entry<String, Integer> o2) { int comp = o1.getValue().compareTo(o2.getValue()); if (comp != 0) { return comp; } else { return o2.getKey().compareTo(o1.getKey()); } } }); for (Map.Entry<String, Integer> e : freq.entrySet()) { queue.add(e); if(queue.size() > capacity) queue.poll(); } // reverse & filter the queue ArrayList<String> arr = new ArrayList<String>(cap); while(queue.size() > 0){ Map.Entry<String, Integer> e = queue.poll(); if (stopWords.contains(e.getKey()) == false) { arr.add(e.getKey()); //out.println(e + " : " + e.getValue()); } } int size = arr.size(); for(int i = 0;i < cap && size - 1 - i > -1;i++) { ret[i] = arr.get(size - 1 - i); } return ret; } /** * Find large frequency elements by sort * @param freq * @return */ public String[] FindLargesBySort(Map<String, Integer> freq) { String[] ret = new String[cap]; List<Map.Entry<String, Integer>> arr = new ArrayList<Map.Entry<String, Integer>>( freq.entrySet()); Collections.sort(arr, new Comparator<Map.Entry<String, Integer>>(){ public int compare(Entry<String, Integer> o1, Entry<String, Integer> o2) { int comp = o2.getValue().compareTo(o1.getValue()); if(comp != 0){ return comp; } else { return o1.getKey().compareTo(o2.getKey()); } } }); for (int i = 0, j = 0; i < arr.size() && j < cap; i++) { String e = arr.get(i).getKey(); if (stopWords.contains(e) == false) { ret[j++] = e; // out.println(e + " : " + arr.get(i).getValue()); } } return ret; } public String[] process() throws Exception { String[] lines = new String[inputFileLineCount]; int ctr = 0; try (BufferedReader br = new BufferedReader(new FileReader( inputFileName))) { String line; while ((line = br.readLine()) != null) { line = line.trim(); lines[ctr++] = line; } } catch (Exception e) { out.println(e); } Integer[] indexes = getIndexes(); ConcurrentHashMap<String, Integer> freq = new ConcurrentHashMap<String, Integer>(); for (Integer i : indexes) { StringTokenizer stk = new StringTokenizer(lines[i], delimiters); while (stk.hasMoreElements()) { String e = stk.nextToken().trim().toLowerCase(); Integer found = freq.get(e); if (found != null) { freq.put(e, found + 1); } else { freq.put(e, 1); } } } //dumpMap(freq); String[] ret = FindLargesBySort(freq); //String[] ret = FindLargesByHeap(freq); //String[] ret = new String[cap]; return ret; } public void preprocess(){ stopWords = new HashSet<String>(); for (String e : stopWordsArray) { stopWords.add(e); } } public static void main(String[] args) throws Exception { if (args.length < 1) { System.out.println("MP1 <User ID>"); } else { String userName = args[0]; String inputFileName = "./input.txt"; MP1 mp = new MP1(userName, inputFileName); mp.preprocess(); String[] topItems = mp.process(); for (String item : topItems) { System.out.println(item); } } } }
jz33/Coursera-Cloud-Computing-Applications-Solution-Manual
hw1/MP1.java
2,131
/** * Find large frequency elements by sort * @param freq * @return */
block_comment
en
false
57533_0
import java.util.*; import java.util.Map.Entry; import java.util.regex.*; import java.util.stream.*; import java.io.*; import java.math.*; import java.text.*; /* * @author Theodoric Keith Lim */ class A1Paper { static final double A2LongEdge = Math.pow(2, -3.0 / 4); static final double A2ShortEdge = Math.pow(2, -5.0 / 4); public static void main(String[] args) { // Taping by the longedge is the best method Kattio sc = new Kattio(System.in); int n = sc.getInt(); long[] papers = new long[n - 1]; for (int i = 0; i < n - 1; i++) papers[i] = sc.getLong(); double tapeCount = 0; long paperCount = 1; // Start from 1 as we represent 1 A2 paper double constructLongEdge = A2LongEdge; double constructShortEdge = A2ShortEdge; for (int i = 0; i < n - 1 && paperCount > 0; i++) { // 3. Tape length of long edges tapeCount += paperCount * constructLongEdge; // 1. The amount of paper required for that size to get an A1 paperCount *= 2; paperCount -= papers[i]; // 2. Go to next paper size double tmp = constructLongEdge; constructLongEdge = constructShortEdge; constructShortEdge = tmp / 2; } System.out.println(paperCount > 0 ? "impossible" : tapeCount); sc.close(); } }
cowturtle/Kattis
A1Paper.java
408
/* * @author Theodoric Keith Lim */
block_comment
en
true
57935_2
/** * 随时关闭所有Activity * 主要是利用list集合存储所有Act */ public class ActivityCollector { public static LinkedList<Activity> activities = new LinkedList<Activity>(); public static void addActivity(Activity activity) { activities.add(activity); } public static void removeActivity(Activity activity) { activities.remove(activity); } public static void finishAll() { for(Activity activity:activities) { if(!activity.isFinishing()) { activity.finish(); } } } } /* *杀死整个App,连后台都要杀死 *可配合上面的代码使用 *退出应用程序 */ public void AppExit(Context context) { try { ActivityCollector.finishAll(); ActivityManager activityMgr = (ActivityManager) context .getSystemService(Context.ACTIVITY_SERVICE); activityMgr.killBackgroundProcesses(context.getPackageName()); System.exit(0); } catch (Exception ignored) {} } /* *双击返回键退出程序 *定义一个变量标志是否退出 */ private static boolean isExit = false; Handler mHandler = new Handler() { @Override public void handleMessage(Message msg) { super.handleMessage(msg); isExit = false; } }; public boolean onKeyDown(int keyCode, KeyEvent event) { if (keyCode == KeyEvent.KEYCODE_BACK) { if (!isExit) { isExit = true; Toast.makeText(getApplicationContext(), "再按一次退出程序", Toast.LENGTH_SHORT).show(); // 利用handler延迟发送更改状态信息 mHandler.sendEmptyMessageDelayed(0, 2000); } else { exit(this); } return false; } return super.onKeyDown(keyCode, event); }
xsfelvis/CoreCode_Fragments
ActivityUtil.java
424
/* *双击返回键退出程序 *定义一个变量标志是否退出 */
block_comment
en
true
58013_2
import java.util.HashMap; import java.util.ArrayList; /** * A class that defines a camp object that can be interacted with by users */ public class Camp { private String name; private String description; private int year; private ArrayList<Activity> activities = new ArrayList<Activity>(); /** * A hashmap that holds the weeks this camp is available for. A director can choose * how many weeks to create the camp for */ private HashMap<Integer, Week> masterSchedule = new HashMap<Integer, Week>(); /** * An empty constructor, useful for creating a new instance of camp where attributes are unknown */ public Camp() { } /** * A constructor with all attributes of camp. Useful for reading camp objects in JSON * @param name A string for the name of the camp * @param description A string for the description of the camp * @param year An int for the year of the camp * @param weeks An integer for the number of weeks for the camp * @param activities An array list storing the activites available at the camp */ public Camp(String name, String description, int year, int weeks, ArrayList<Activity> activities) { this.name = name; this.description = description; this.year = year; masterSchedule = new HashMap<Integer, Week>(weeks); this.activities = activities; } public Camp(String name, String description, HashMap<Integer, Week> masterSchedule, ArrayList<Activity> activities, int year) { // TODO figure out Calendar constructor this.name = name; this.description = description; this.masterSchedule = masterSchedule; this.activities = activities; this.year = year; } public Camp(String name, String description) { this.name = name; this.description = description; masterSchedule = new HashMap<Integer, Week>(); } public Camp(String name, String description, int weekNumber) { this.name = name; this.description = description; masterSchedule = new HashMap<Integer, Week>(weekNumber); } public void addCamp(String name, String desc, int year, HashMap<Integer, Week> masterSchedule, ArrayList<Activity> activities) { this.name = name; this.description = desc; this.year = year; this.masterSchedule = masterSchedule; this.activities = activities; } public int getYear() { return year; } public void setYear(int year) { this.year = year; } public HashMap<Integer, Week> getMasterSchedule() { return masterSchedule; } public void setMasterSchedule(HashMap<Integer, Week> masterSchedule) { this.masterSchedule = masterSchedule; } public void setActivities(ArrayList<Activity> activities) { this.activities = activities; } public Camp(String name, String description, ArrayList<Activity> activities) { this.name = name; this.description = description; this.activities = activities; masterSchedule = new HashMap<Integer, Week>(); } public String getName() { return name; } public void setName(String name) { this.name = name; } public String getDescription() { return description; } public void setDescription(String description) { this.description = description; } public Week getWeek(Integer num) { Week week = new Week(); for (HashMap.Entry<Integer, Week> entry : masterSchedule.entrySet()) { Integer weekInt = entry.getKey(); Week thisWeek = entry.getValue(); if (num == weekInt) { week = thisWeek; } } return week; } public ArrayList<Week> getWeeks() { ArrayList<Week> weeks = new ArrayList<Week>(); for (HashMap.Entry<Integer, Week> entry : masterSchedule.entrySet()) { Week week = entry.getValue(); weeks.add(week); } return weeks; } public boolean qualifiesForDiscount(ArrayList<Camper> campers) { for (int i = 0; i < masterSchedule.size(); i++) { if (masterSchedule.get((Integer) i).containsCamper(campers)) { return true; } } return false; } public String getActivities() { String displayActivities = new String(); for (Activity activity : activities) { displayActivities += activity.toString() + "\n"; } return displayActivities; } public ArrayList<Activity> getActivitiesArrayList() { return activities; } public boolean addActivity(Activity activity) { if (activity == null) { return false; } else { activities.add(activity); return true; } } public void printMasterSchedule() { for (int i = 0; i < masterSchedule.size(); i++) { System.out.println(masterSchedule.get(i).getTheme()); } } public String viewCalendar() { String temp = new String(); for (int i = 0; i < masterSchedule.size(); i++) { temp = temp + "\t\tWeek: " + i + "\n" + masterSchedule.get(i).viewSchedule() + "\n\n"; } return temp; } public String toString() { return "CAMP: name: " + name + " description: " + description + "masterSchedule " + masterSchedule + " activities " + activities; } }
dbkaiser25/CampButterflies
Camp.java
1,240
/** * An empty constructor, useful for creating a new instance of camp where attributes are unknown */
block_comment
en
false
58017_5
import java.io.PrintWriter; import java.util.ArrayList; //Helper class to implement common methods for all classes public class Helper { public final static int ActivityServerPort = 8082; public final static int RoomServerPort = 8081; public final static int ReservationServerPort = 8080; public final static String ActivitiesPath = "./activities.txt"; public final static String ReservationsPath = "./reservations.txt"; public final static String RoomsPath = "./rooms.txt"; //A method which takes status code and message and handles the response public static void printHtmlMessage(String status, String message, PrintWriter out) { if (status.equals("200")) { out.println("HTTP/1.1 200 OK"); out.println("Content-Type: text/html"); out.println(); out.println("<html><head><title>200 OK</title></head><body><h1>200 OK</h1><p>" + message + "</p></body></html>"); out.flush(); } else if (status.equals("400")) { out.println("HTTP/1.1 400 Bad Request"); out.println("Content-Type: text/html"); out.println(); out.println("<html><head><title>400 Bad Request</title></head><body><h1>400 Bad Request</h1><p>" + message + "</p></body></html>"); out.flush(); } if (status.equals("403")) { out.println("HTTP/1.1 403 Forbidden"); out.println("Content-Type: text/html"); out.println(); out.println("<html><head><title>403 Forbidden</title></head><body><h1>403 Forbidden</h1><p>" + message + "</p></body></html>"); out.flush(); } else if (status.equals("404")) { out.println("HTTP/1.1 404 Not Found"); out.println("Content-Type: text/html"); out.println(); out.println("<html><head><title>404 Not Found</title></head><body><h1>404 Not Found</h1><p>" + message + "</p></body></html>"); out.flush(); } } public static boolean isNumeric(String string) { try { Integer.parseInt(string); return true; } catch (NumberFormatException e) { return false; } } public static boolean resetDatabase() { //remove all lines in the files activites.txt, reservations.txt and rooms.txt try { PrintWriter out = new PrintWriter(Helper.ActivitiesPath); out.print(""); out.close(); out = new PrintWriter(Helper.ReservationsPath); out.print(""); out.close(); out = new PrintWriter(Helper.RoomsPath); out.print(""); out.close(); return true; } catch (Exception e) { return false; } } public static boolean resetRooms() { //remove all lines in the file rooms.txt try { PrintWriter out = new PrintWriter(Helper.RoomsPath); out.print(""); out.close(); return true; } catch (Exception e) { return false; } } public static boolean resetActivities() { //remove all lines in the file activities.txt try { PrintWriter out = new PrintWriter(Helper.ActivitiesPath); out.print(""); out.close(); return true; } catch (Exception e) { return false; } } public static boolean resetReservations() { //remove all lines in the file reservations.txt try { PrintWriter out = new PrintWriter(Helper.ReservationsPath); out.print(""); out.close(); return true; } catch (Exception e) { return false; } } //method that converts numbers betwen 1 and 7 to days of the week public static String convertDay(int day) { switch (day) { case 1: return "Monday"; case 2: return "Tuesday"; case 3: return "Wednesday"; case 4: return "Thursday"; case 5: return "Friday"; case 6: return "Saturday"; case 7: return "Sunday"; default: return "Invalid day"; } } public static String convertDuration(int hour, int duration) { int endHour = hour + duration; return hour + ":00-" + endHour + ":00"; } }
enginbektas/Reservation_App_Socket_Programming_Java
src/Helper.java
1,079
//remove all lines in the file reservations.txt
line_comment
en
true
58798_0
/** * Something smart here about how this is the abstract class */ public abstract class Note { }
aidanholc/Transcriber
Note.java
24
/** * Something smart here about how this is the abstract class */
block_comment
en
true
58903_0
import java.util.ArrayList; /** * Route consists of 2 nodes and the distance between them. * Subclasses have different speeds based on the type of vehicle on them. * * @author Greg Myers * @version 10/05/2011 */ public class Route { private Node node1; private Node node2; private int length; protected String type; private int speedPrivate; private int speedCommercial; private ArrayList<Vehicle> vehiclesOnRoad; public String getType() { return type; } public int getSpeed(String t) { return 0; } public int getRate(String t) { return 0; } public boolean hasPoints() { if ((node1.hasPoint()) && (node2.hasPoint())) { return true; } return false; } public int getLength() { return length; } public Route() { vehiclesOnRoad = new ArrayList<Vehicle>(); } public Route(String t) { type = t; vehiclesOnRoad = new ArrayList<Vehicle>(); } public ArrayList<Vehicle> getVehicles() { return vehiclesOnRoad; } public void setLength(int l) { length = l; } public void setNodes(Node n1,Node n2) { node1 = n1; node2 = n2; } public char otherNode(char node) { if (node == node1.getName()) { return node2.getName(); } else { return node1.getName(); } } public ArrayList<Vehicle> moveVehicles(String time) { ArrayList<Vehicle> vList = new ArrayList<Vehicle>(); if (vehiclesOnRoad.size()>0){ for (int i = 0; i < vehiclesOnRoad.size();i++) { vehiclesOnRoad.get(i).travel(); if (vehiclesOnRoad.get(i).getDistanceTraveled()>=length) { FileHandler.writeEndSectData(vehiclesOnRoad.get(i).getRegistration(),time); vList.add(vehiclesOnRoad.remove(i)); } } return vList; } return null; } public boolean matchingNode(char node) { if ((node == node1.getName())||(node == node2.getName())){ return true; }else{ return false; } } public Node getNode1() { return node1; } public Node getNode2() { return node2; } }
BookOfGreg/RoadMap
Route.java
609
/** * Route consists of 2 nodes and the distance between them. * Subclasses have different speeds based on the type of vehicle on them. * * @author Greg Myers * @version 10/05/2011 */
block_comment
en
false
59319_7
package com.example.termproject; import android.Manifest; import android.app.Activity; import android.content.Context; import android.content.DialogInterface; import android.content.pm.PackageManager; import android.support.annotation.NonNull; import android.support.v4.app.ActivityCompat; import android.support.v4.content.ContextCompat; import android.support.v7.app.AlertDialog; import android.support.v7.app.AppCompatDelegate; import android.view.View; import android.widget.ImageView; public class Utils { public final static int sREQUEST_CODE_SETTINGS = 100, sREQUEST_CODE_LOCATION_PERMISSION = 100; // background // ---------- public static void showHideBackground (boolean usePicBackground, ImageView background) { int visibilityMode = usePicBackground ? View.VISIBLE : View.INVISIBLE; // Set the ImageView's visibility to be show or hidden as per the user preference assert background != null; background.setVisibility (visibilityMode); } // Location public static void promptToAllowPermissionRequest (Activity activity) { DialogInterface.OnClickListener okListener = getLocationPromptOkOnClickListener (activity); DialogInterface.OnClickListener cancelListener = Utils.getNewEmptyOnClickListener (); Utils.showYesNoDialog (activity, "Permission Denied", "The Location Permission is requested for Night Mode " + "display purposes.\n\nWould you like to again " + "be prompted to allow this permission?", okListener, cancelListener); } @NonNull private static DialogInterface.OnClickListener getLocationPromptOkOnClickListener (final Activity activity) { return new DialogInterface.OnClickListener () { @Override public void onClick (DialogInterface dialog, int which) { Utils.getLocationPermission (activity, sREQUEST_CODE_LOCATION_PERMISSION); } }; } // Night Mode // ---------- public static void getLocationPermission (Activity activity, int code) { // Here, activity is the current activity if (ContextCompat.checkSelfPermission (activity, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) { ActivityCompat.requestPermissions (activity, new String[] {Manifest.permission.ACCESS_COARSE_LOCATION}, code); } } public static void applyNightModePreference (Activity activity, boolean useNightMode) { int defaultNightMode = AppCompatDelegate.getDefaultNightMode (); int userPrefNightMode = useNightMode ? AppCompatDelegate.MODE_NIGHT_AUTO : AppCompatDelegate.MODE_NIGHT_NO; if ((useNightMode && (defaultNightMode != userPrefNightMode)) || (!useNightMode && defaultNightMode == AppCompatDelegate.MODE_NIGHT_AUTO)) { applyNightMode (activity, userPrefNightMode); } } private static void applyNightMode (final Activity activity, int userPrefNightMode) { // Inform the user so they're not staring at a white screen while the Activity is recreated //Toast.makeText (activity, "Applying Night Mode Preference", Toast.LENGTH_SHORT).show (); // Set the Default Night Mode to match the User's Preference AppCompatDelegate.setDefaultNightMode (userPrefNightMode); // recreate the Activity to make the Night Mode Setting active activity.recreate (); } // AlertDialog // ----------- @NonNull public static DialogInterface.OnClickListener getNewEmptyOnClickListener () { return new DialogInterface.OnClickListener () { @Override public void onClick (DialogInterface dialog, int which) { } }; } /** * Shows an Android (nicer) equivalent to JOptionPane * * @param strTitle Title of the Dialog box * @param strMsg Message (body) of the Dialog box */ public static void showYesNoDialog (Context context, String strTitle, String strMsg, DialogInterface.OnClickListener okListener, DialogInterface.OnClickListener cancelListener) { // create the listener for the dialog final DialogInterface.OnClickListener emptyOnClickListener = getNewEmptyOnClickListener (); // Create the AlertDialog.Builder object AlertDialog.Builder ADBuilder = new AlertDialog.Builder (context); // Use the AlertDialog's Builder Class methods to set the title, icon, message, et al. // These could all be chained as one long statement, if desired ADBuilder.setTitle (strTitle); ADBuilder.setIcon (android.R.drawable.ic_dialog_alert); ADBuilder.setMessage (strMsg); ADBuilder.setCancelable (true); ADBuilder.setPositiveButton (context.getString (R.string.yes), okListener != null ? okListener : emptyOnClickListener); ADBuilder.setNegativeButton (context.getString (R.string.no), cancelListener != null ? cancelListener : emptyOnClickListener); // Create and Show the Dialog ADBuilder.show (); } /** * Shows an Android (nicer) equivalent to JOptionPane * * @param strTitle Title of the Dialog box * @param strMsg Message (body) of the Dialog box */ public static void showInfoDialog (Context context, String strTitle, String strMsg) { // create the listener for the dialog final DialogInterface.OnClickListener emptyOnClickListener = getNewEmptyOnClickListener (); // Create the AlertDialog.Builder object AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder (context); // Use the AlertDialog's Builder Class methods to set the title, icon, message, et al. // These could all be chained as one long statement, if desired alertDialogBuilder.setTitle (strTitle); alertDialogBuilder.setIcon (android.R.drawable.ic_dialog_info); alertDialogBuilder.setMessage (strMsg); alertDialogBuilder.setCancelable (true); alertDialogBuilder.setNeutralButton (context.getString (android.R.string.ok), emptyOnClickListener); // Create and Show the Dialog alertDialogBuilder.show (); } /** * Overloaded XML version of showInfoDialog(String, String) method * * @param titleID Title stored in XML resource (e.g. strings.xml) * @param msgID Message (body) stored in XML resource (e.g. strings.xml) */ public static void showInfoDialog (Context context, int titleID, int msgID) { showInfoDialog (context, context.getString (titleID), context.getString (msgID)); } }
eitan613/androidTermProject
Utils.java
1,453
// Inform the user so they're not staring at a white screen while the Activity is recreated
line_comment
en
false
59519_16
/* A book IS A product that has additional information - e.g. title, author A book also comes in different formats ("Paperback", "Hardcover", "EBook") The format is specified as a specific "stock type" in get/set/reduce stockCount methods. */ public class Book extends Product { private String author; private String title; // Stock related information NOTE: inherited stockCount variable is used for EBooks private int paperbackStock; private int hardcoverStock; private int year; public Book(String name, String id, double price, int paperbackStock, int hardcoverStock, String title, String author) { // Make use of the constructor in the super class Product. Initialize additional Book instance variables. // Set category to BOOKS super(name, id, price, 100000, Product.Category.BOOKS); this.paperbackStock = paperbackStock; this.hardcoverStock = hardcoverStock; this.title = title; this.author = author; this.year = 0; } // Another constructor method that uses the year variable aswell public Book(String name, String id, double price, int paperbackStock, int hardcoverStock, String title, String author, int year) { super(name, id, price, 100000, Product.Category.BOOKS); this.paperbackStock = paperbackStock; this.hardcoverStock = hardcoverStock; this.title = title; this.author = author; this.year = year; } // Check if a valid format public boolean validOptions(String productOptions) { // check productOptions for "Paperback" or "Hardcover" or "EBook" // if it is one of these, return true, else return false if (productOptions.equalsIgnoreCase("Paperback") || productOptions.equalsIgnoreCase("Hardcover") || productOptions.equalsIgnoreCase("EBook")) { return true; } else { return false; } } // Override getStockCount() in super class. public int getStockCount(String productOptions) { // Use the productOptions to check for (and return) the number of stock for "Paperback" etc // Use the variables paperbackStock and hardcoverStock at the top. // For "EBook", use the inherited stockCount variable. if (productOptions.equalsIgnoreCase("Paperback")) { return this.paperbackStock; } else if (productOptions.equalsIgnoreCase("Hardcover")) { return this.hardcoverStock; } else if (productOptions.equalsIgnoreCase("EBook")) { return super.getStockCount(productOptions); } return 1; } public void setStockCount(int stockCount, String productOptions) { // Use the productOptions to check for (and set) the number of stock for "Paperback" etc // Use the variables paperbackStock and hardcoverStock at the top. // For "EBook", set the inherited stockCount variable. if (productOptions.equalsIgnoreCase("Paperback")) { this.paperbackStock = stockCount; } else if (productOptions.equalsIgnoreCase("Hardcover")) { this.hardcoverStock = stockCount; } else if (productOptions.equalsIgnoreCase("EBook")) { super.setStockCount(stockCount, productOptions); } } /* * When a book is ordered, reduce the stock count for the specific stock type */ public void reduceStockCount(String productOptions) { // Use the productOptions to check for (and reduce) the number of stock for "Paperback" etc // Use the variables paperbackStock and hardcoverStock at the top. // For "EBook", set the inherited stockCount variable. if (productOptions.equalsIgnoreCase("Paperback")) { this.paperbackStock -= 1; } else if (productOptions.equalsIgnoreCase("Hardcover")) { this.hardcoverStock -= 1; } else if (productOptions.equalsIgnoreCase("EBook")) { super.reduceStockCount(productOptions); } } public String getAuthor() { return this.author; } public int getYear() { return this.year; } /* * Print product information in super class and append Book specific information title and author */ public void print() { // Replace the line below. // Make use of the super class print() method and append the title and author info. See the video super.print(); if (this.year != 0) { System.out.printf(" Title: %-30s Author: %-20s Year: %-4s", this.title, this.author, this.year); } else { System.out.printf(" Title: %-30s Author: %-1s", this.title, this.author); } } }
KevinBasta/Ecommerce-OOP-System
Book.java
1,124
// Use the productOptions to check for (and reduce) the number of stock for "Paperback" etc
line_comment
en
true
59555_0
/* ** Read about this code at http://shutdownhook.com ** MIT license details at https://github.com/seanno/shutdownhook/blob/main/LICENSE */ public enum StateProvince { AL("Alabama"), AK("Alaska"), AB("Alberta"), AS("American Samoa"), AZ("Arizona"), AR("Arkansas"), AE("Armed Forces (AE)"), AA("Armed Forces Americas"), AP("Armed Forces Pacific"), BC("British Columbia"), CA("California"), CO("Colorado"), CT("Connecticut"), DE("Delaware"), DC("District Of Columbia"), FL("Florida"), GA("Georgia"), GU("Guam"), HI("Hawaii"), ID("Idaho"), IL("Illinois"), IN("Indiana"), IA("Iowa"), KS("Kansas"), KY("Kentucky"), LA("Louisiana"), ME("Maine"), MB("Manitoba"), MD("Maryland"), MA("Massachusetts"), MI("Michigan"), MN("Minnesota"), MS("Mississippi"), MO("Missouri"), MT("Montana"), NE("Nebraska"), NV("Nevada"), NB("New Brunswick"), NH("New Hampshire"), NJ("New Jersey"), NM("New Mexico"), NY("New York"), NF("Newfoundland"), NC("North Carolina"), ND("North Dakota"), NT("Northwest Territories"), NS("Nova Scotia"), NU("Nunavut"), OH("Ohio"), OK("Oklahoma"), ON("Ontario"), OR("Oregon"), PA("Pennsylvania"), PE("Prince Edward Island"), PR("Puerto Rico"), QC("Quebec"), RI("Rhode Island"), SK("Saskatchewan"), SC("South Carolina"), SD("South Dakota"), TN("Tennessee"), TX("Texas"), UT("Utah"), VT("Vermont"), VI("Virgin Islands"), VA("Virginia"), WA("Washington"), WV("West Virginia"), WI("Wisconsin"), WY("Wyoming"), YT("Yukon Territory"); StateProvince(String displayName) { this.displayName = displayName; } public String getDisplayName() { return(displayName); } public static StateProvince find(String input) { for (StateProvince sp : StateProvince.values()) { if (sp.name().equalsIgnoreCase(input)) return(sp); if (sp.getDisplayName().equalsIgnoreCase(input)) return(sp); } return(null); } private String displayName; }
seanno/shutdownhook
trials/StateProvince.java
766
/* ** Read about this code at http://shutdownhook.com ** MIT license details at https://github.com/seanno/shutdownhook/blob/main/LICENSE */
block_comment
en
true
59557_1
/** * Copyright 2011-2023 Texas Torque. * * This file is part of TorqueLib, which is licensed under the MIT license. * For more details, see ./license.txt or write <[email protected]>. */ package org.texastorque.torquelib.control; import java.util.function.Function; import edu.wpi.first.math.controller.PIDController; /** * A class representation of a PID controller that extends * the WPILib PIDController. * * @apiNote Functional replacement for KPID * ({@link org.texastorque.torquelib.legacy.KPID}) * * @author Justus Languell */ public final class TorquePID extends PIDController { // * Variable fields public static final class Builder { private double proportional, integral = 0, derivative = 0, feedForward = 0, minOutput = -1, maxOutput = 1, integralZone = 0, period = .02, minInput = 0, maxInput = 0, tolerance = -1; private boolean hasIntegralZone = false, hasContinuousRange = false; private Builder(final double proportional) { this.proportional = proportional; } public final Builder addIntegral(final double integral) { this.integral = integral; return this; } public final Builder addDerivative(final double derivative) { this.derivative = derivative; return this; } public final Builder addFeedForward(final double feedForward) { this.feedForward = feedForward; return this; } public final Builder addMinOutput(final double minOutput) { this.minOutput = minOutput; return this; } public final Builder addMaxOutput(final double maxOutput) { this.maxOutput = maxOutput; return this; } public final Builder addOutputRange(final double minOutput, final double maxOutput) { this.minOutput = minOutput; this.maxOutput = maxOutput; return this; } public final Builder addIntegralZone(final double integralZone) { this.hasIntegralZone = true; this.integralZone = integralZone; return this; } public final Builder addMinContinuousInput(final double min) { this.hasContinuousRange = true; this.minInput = min; return this; } public final Builder addMaxContinuousInput(final double max) { this.hasContinuousRange = true; this.maxInput = max; return this; } public final Builder addContinuousInputRange(final double min, final double max) { this.hasContinuousRange = true; this.minInput = min; this.maxInput = max; return this; } public final Builder setPeriod(final double period) { this.period = period; return this; } public final Builder setTolerance(final double tolerance) { this.tolerance = tolerance; return this; } public final TorquePID build() { return new TorquePID(this); } } public static final Builder create() { return new Builder(1); } // * Construction and builder public static final Builder create(final double p) { return new Builder(p); } private final double proportional, integral, derivative, feedForward, minOutput, maxOutput, integralZone, period; private final boolean hasIntegralZone; private TorquePID(final Builder b) { super(b.proportional, b.integral, b.derivative, b.period); if (b.hasContinuousRange) enableContinuousInput(b.minInput, b.maxInput); if (b.tolerance != -1) setTolerance(b.tolerance); proportional = b.proportional; integral = b.integral; derivative = b.derivative; feedForward = b.feedForward; minOutput = b.minOutput; maxOutput = b.maxOutput; integralZone = b.integralZone; hasIntegralZone = b.hasIntegralZone; period = b.period; } // * Getters public final double getProportional() { return proportional; } public final double getIntegral() { return integral; } public final double getDerivative() { return derivative; } public final double getFeedForward() { return feedForward; } public final double getMinOutput() { return minOutput; } public final double getMaxOutput() { return maxOutput; } public final double getIntegralZone() { return integralZone; } public final boolean hasIntegralZone() { return hasIntegralZone; } @Override public final String toString() { return String.format("PID(PRO: %3.2f, INT: %3.2f, DER: %3.2f, F: %3.2f, MIN: %3.2f, MAX: %3.2f, IZO: %3.2f)", proportional, integral, derivative, feedForward, minOutput, maxOutput, integralZone); } // * PIDController generator methods public final PIDController createPIDController() { return new PIDController(proportional, integral, derivative, period); } public final PIDController createPIDController(final Function<PIDController, PIDController> function) { return function.apply(createPIDController()); } }
TexasTorque/TorqueLib
control/TorquePID.java
1,218
/** * A class representation of a PID controller that extends * the WPILib PIDController. * * @apiNote Functional replacement for KPID * ({@link org.texastorque.torquelib.legacy.KPID}) * * @author Justus Languell */
block_comment
en
true
59587_0
import java.util.Scanner; public class ThreeD { public static void main(String[] args) { // covid cases -> 2 country -> 3 state -> 2 city Scanner sc = new Scanner(System.in); String country[] = { "India", "America" }; String states[][] = { { "UP", "Bihar", "MP" }, { "North America", "South America", "East America" }, }; String cityName[][][] = { { { "Noida", "GZB" }, { "Mithila", "Patna" }, { "Rewa", "Maihar" } }, { { "new york", "W. DC" }, { "san deigo", "san fransisco" }, { "texas", "california" } } }; int covidCases[][][] = new int[2][3][2]; System.out.println("Enter covid cases"); for (int i = 0; i < 2; i++) { System.out.println(country[i]+":"); for (int j = 0; j < 3; j++) { System.out.println("\t"+states[i][j]+":"); for (int k = 0; k < 2; k++) { System.out.print("\t\t"+cityName[i][j][k]+": "); covidCases[i][j][k] = sc.nextInt(); } } } System.out.println("All Cities are :"); for (int i = 0; i < 2; i++) { System.out.println("Country " + (i + 1)); for (int j = 0; j < 3; j++) { System.out.println("\tState " + (j + 1)); for (int k = 0; k < 2; k++) { System.out.print("\t\tCity " + (k + 1) + " : "); System.out.println(cityName[i][j][k] + "(" + covidCases[i][j][k] + ")"); } } } sc.close(); } }
amantiwari8861/javaV1
07 Arrays/ThreeD.java
520
// covid cases -> 2 country -> 3 state -> 2 city
line_comment
en
true
60110_1
import java.util.*; import java.util.Scanner; public class Spy implements FieldBase{ private String status = "Alive"; private int spyID; //Spy constructor with spyID to be set at the time of instantiation. public Spy(int id){ this.spyID = id; } //Calls the unregisterDead() method of FieldBase if the status of the Spy is dead. public void isDead(){ if (status == "Dead") { FieldBase.unregisterDead(spyID); } } //Public methods to access Spy Status and Spy ID public String getStatus(){ return status; } public int getSpyID(){ return spyID; } //If a spy dies, its status can be changed to dead. public String setStatus(String s){ status = s; return status; } }
Insiyah2110/InsiyahUjjainwala
Spy.java
196
//Calls the unregisterDead() method of FieldBase if the status of the Spy is dead.
line_comment
en
true
60147_7
import java.awt.Image; import java.io.File; import javax.swing.ImageIcon; import javax.swing.JFileChooser; import javax.swing.JOptionPane; public class signup extends javax.swing.JFrame { File ph; JFileChooser jfc; public signup() { initComponents(); setSize(500,600); setVisible(true); } /** * This method is called from within the constructor to initialize the form. * WARNING: Do NOT modify this code. The content of this method is always * regenerated by the Form Editor. */ @SuppressWarnings("unchecked") // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents private void initComponents() { usernamelb = new javax.swing.JLabel(); Usernametf = new javax.swing.JTextField(); emaillb = new javax.swing.JLabel(); Emailtf = new javax.swing.JTextField(); passwordlb = new javax.swing.JLabel(); phonelb = new javax.swing.JLabel(); phonetf = new javax.swing.JTextField(); passwordtf = new javax.swing.JPasswordField(); photolb = new javax.swing.JLabel(); photolb1 = new javax.swing.JLabel(); browsebt = new javax.swing.JButton(); submitbt = new javax.swing.JButton(); jLabel7 = new javax.swing.JLabel(); setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE); getContentPane().setLayout(null); usernamelb.setText("Username"); getContentPane().add(usernamelb); usernamelb.setBounds(20, 80, 90, 30); getContentPane().add(Usernametf); Usernametf.setBounds(120, 80, 350, 30); emaillb.setText("Email"); getContentPane().add(emaillb); emaillb.setBounds(20, 140, 90, 30); getContentPane().add(Emailtf); Emailtf.setBounds(120, 140, 350, 30); passwordlb.setText("Password"); getContentPane().add(passwordlb); passwordlb.setBounds(20, 200, 90, 30); phonelb.setText("Phone"); getContentPane().add(phonelb); phonelb.setBounds(20, 270, 90, 30); getContentPane().add(phonetf); phonetf.setBounds(120, 270, 350, 30); getContentPane().add(passwordtf); passwordtf.setBounds(120, 200, 350, 30); photolb.setText("Photo"); getContentPane().add(photolb); photolb.setBounds(20, 380, 80, 30); photolb1.setText("preview"); getContentPane().add(photolb1); photolb1.setBounds(130, 350, 160, 120); browsebt.setText("Browse"); browsebt.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { browsebtActionPerformed(evt); } }); getContentPane().add(browsebt); browsebt.setBounds(370, 350, 110, 30); submitbt.setText("Submit"); submitbt.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { submitbtActionPerformed(evt); } }); getContentPane().add(submitbt); submitbt.setBounds(370, 400, 110, 30); jLabel7.setFont(new java.awt.Font("Times New Roman", 1, 32)); // NOI18N jLabel7.setHorizontalAlignment(javax.swing.SwingConstants.CENTER); jLabel7.setText("Sign Up"); getContentPane().add(jLabel7); jLabel7.setBounds(10, 10, 490, 40); pack(); }// </editor-fold>//GEN-END:initComponents private void browsebtActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_browsebtActionPerformed jfc=new JFileChooser(); int ans=jfc.showOpenDialog(this); if(ans==JFileChooser.APPROVE_OPTION) { ph=jfc.getSelectedFile(); ImageIcon ic = new ImageIcon(ph.getPath()); Image img = ic.getImage().getScaledInstance(photolb1.getWidth(), photolb1. getHeight(), Image.SCALE_SMOOTH); ImageIcon ic1 = new ImageIcon(img); photolb1.setIcon(ic1); } }//GEN-LAST:event_browsebtActionPerformed private void submitbtActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_submitbtActionPerformed String username=Usernametf.getText(); String email=Emailtf.getText(); String password=passwordtf.getText(); String phone=phonetf.getText(); if(username.isEmpty()||email.isEmpty()||password.equals("")||phone.isEmpty()||ph == null) { JOptionPane.showMessageDialog(rootPane, "All fileds are Mandatory"); } else { String result=client.SignUp(username, email, password, phone, ph); if(result.trim().equals("exists")) { JOptionPane.showMessageDialog(rootPane, "Already Exist"); } else if(result.trim().equals("success")) { JOptionPane.showMessageDialog(rootPane, "Success"); } else { JOptionPane.showMessageDialog(rootPane, result); } Usernametf.setText(""); Emailtf.setText(""); passwordtf.setText(""); phonetf.setText(""); photolb1.setIcon(null); photolb1.setText("preview"); Usernametf.requestFocus(); } }//GEN-LAST:event_submitbtActionPerformed /** * @param args the command line arguments */ public static void main(String args[]) { /* Set the Nimbus look and feel */ //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) "> /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel. * For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html */ try { for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) { if ("FlatLaf Dark".equals(info.getName())) { javax.swing.UIManager.setLookAndFeel(info.getClassName()); break; } } } catch (ClassNotFoundException ex) { java.util.logging.Logger.getLogger(signup.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (InstantiationException ex) { java.util.logging.Logger.getLogger(signup.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (IllegalAccessException ex) { java.util.logging.Logger.getLogger(signup.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (javax.swing.UnsupportedLookAndFeelException ex) { java.util.logging.Logger.getLogger(signup.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } //</editor-fold> //</editor-fold> /* Create and display the form */ java.awt.EventQueue.invokeLater(new Runnable() { public void run() { new signup().setVisible(true); } }); } // Variables declaration - do not modify//GEN-BEGIN:variables private javax.swing.JTextField Emailtf; private javax.swing.JTextField Usernametf; private javax.swing.JButton browsebt; private javax.swing.JLabel emaillb; private javax.swing.JLabel jLabel7; private javax.swing.JLabel passwordlb; private javax.swing.JPasswordField passwordtf; private javax.swing.JLabel phonelb; private javax.swing.JTextField phonetf; private javax.swing.JLabel photolb; private javax.swing.JLabel photolb1; private javax.swing.JButton submitbt; private javax.swing.JLabel usernamelb; // End of variables declaration//GEN-END:variables }
rc13123/teacher-student-interaction
signup.java
2,010
//GEN-LAST:event_submitbtActionPerformed
line_comment
en
true
60241_0
/* * 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 library; import java.util.*; import java.io.*; import java.util.Date; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.List; /** * * @author Minahil Imtiaz */ public class Loan { private int loanId; private Date issue_date; private Date due_date; private Date return_date; private Users borrower; private Books borrowed_book; private String fine_status; private boolean returned_status; Loan() { loanId = -1; Calendar calendar = Calendar.getInstance(); issue_date = calendar.getTime(); calendar.add(Calendar.DAY_OF_YEAR, 7); due_date = calendar.getTime(); this.return_date = due_date; returned_status = false; fine_status = "no fine"; } Loan(int id ) { loanId = id; Calendar calendar = Calendar.getInstance(); issue_date = calendar.getTime(); calendar.add(Calendar.DAY_OF_MONTH, 7); due_date = calendar.getTime(); this.return_date = due_date; returned_status = false; fine_status = "no fine"; } Loan(int id, int user_id, int borrowedbook_id, boolean returned_status, String fine_status, Date issue_date, Date due_date, Date return_date) { dbConnectivity db = new dbConnectivity(); this.loanId = id; this.issue_date = issue_date; this.return_date = return_date; this.due_date = due_date; this.fine_status = fine_status; this.borrower = db.GetaBorrowerObjectByUserId(user_id); this.borrowed_book = db.GetaBookbyId(borrowedbook_id); this.returned_status = returned_status; } Loan(int id , Users borrower, Books borrowed_book, String finestatus, boolean returned_status, Date issue_date, Date due_date, Date return_date) { this.loanId =id; this.issue_date = issue_date; this.return_date = return_date; this.due_date = due_date; this.fine_status = finestatus; this.borrower = borrower; this.borrowed_book = borrowed_book; this.returned_status = returned_status; } public int GetaBookId() { return this.borrowed_book.GetBookId(); // dbConnectivity db = new dbConnectivity(); // return (db.GetLoanedBookId(this.loanId)); } public String GetFineStatus() { return fine_status; // dbConnectivity db = new dbConnectivity(); // return (db.GetLoanFineStatus(this.loanId)); } public int GetLoanId() { return this.loanId; } public Date getReturnDate() { return this.return_date; // dbConnectivity db = new dbConnectivity(); // return (db.GetReturnDate(this.loanId)); } public Date getDueDate() { return this.due_date; // dbConnectivity db = new dbConnectivity(); // return (db.GetDueDate(this.loanId)); } public Date getIssueDate() { return this.issue_date; // dbConnectivity db = new dbConnectivity(); // return (db.GetIssueDate(this.loanId)); } public Books GetaBook() { // return this.borrowed_book; dbConnectivity db = new dbConnectivity(); return (db.GetLoanedBook(this.loanId)); } public int GetaBorrowerId() { return this.borrower.GetId(); // dbConnectivity db = new dbConnectivity(); // return (db.GetLoaneeId(this.loanId)); } public Users Getborrower() { return this.borrower; } public boolean GetStatus() { return this.returned_status; // dbConnectivity db = new dbConnectivity(); // return (db.GetLoanReturnedStatus(this.loanId)); } public void SetReturnedDate(Date Ret_date) { this.return_date = Ret_date; dbConnectivity db = new dbConnectivity(); db.SetLoanReturnedDate(this.loanId, Ret_date); } public void SetaBook(Books NewBook) { this.borrowed_book = NewBook; dbConnectivity db = new dbConnectivity(); db.SetLoanedBook(this.loanId, this.borrowed_book.GetBookId()); } public void SetaBorrower(Users Loanee) { this.borrower = Loanee; dbConnectivity db = new dbConnectivity(); db.SetLoaneeObject(this.loanId, this.borrower.GetId()); } public void SetReturnStatus(boolean status) { this.returned_status = status; dbConnectivity db = new dbConnectivity(); db.SetReturnStatus(this.loanId, status); } public void SetLoan(Loan Update) { this.borrowed_book = Update.borrowed_book; this.borrower = Update.borrower; this.due_date = Update.due_date; this.issue_date = Update.issue_date; this.fine_status = Update.fine_status; this.return_date = Update.return_date; this.returned_status = Update.returned_status; dbConnectivity db = new dbConnectivity(); db.SetLoan(this.loanId, Update); } public void SetFineStatus(String status) { this.fine_status = status; dbConnectivity db = new dbConnectivity(); db.SetLoanFineStatus(loanId, status); } public boolean GetLoan(ArrayList<Books> BooksList, Borrower Loanee, ArrayList<Users> Borrowers, Staff AdminBody, ArrayList<Loan> LoanList) { System.out.print("Search the book here \n Press 1. to search with title \n Press 2. to search by author name \n 3. to search by subject\n "); Scanner input = new Scanner(System.in); boolean status = false; int command = input.nextInt(); if (command == 1) { System.out.print("Enter the title "); String Title = input.next(); Loanee.SearchBookbyTitle(Title); } else if (command == 2) { System.out.print("Enter the author name "); String A_name = input.next(); Loanee.SearchBookbyAuthor(A_name); } else if (command == 3) { System.out.print("Enter the subject "); String subject = input.next(); Loanee.SearchBookbySubject(subject); } else { System.out.print("You pressed invalid key ! Now displaying all the books "); for (Books b : BooksList) { b.PrintInformation(); } } System.out.print("Now provide the id of book you want "); int id = input.nextInt(); boolean is_available = false; for (Books b : BooksList) { if (b.ChekcAvailability(id) == true) { is_available = true; // return status; } } if (is_available == true) { status = AdminBody.CheckOutItem(id, Loanee, BooksList, this, LoanList); } return status; } public double CalculateFine() { if (return_date.after(due_date)) { long difference = (return_date.getTime() - due_date.getTime()) / 86400000; difference = Math.abs(difference); return 30.0 * difference; } else { return 0.0; } } String PrintLoanInfo() { int id = this.borrower.GetId(); int bookid = borrowed_book.GetBookId(); String resultant=" "; resultant=resultant+"loanId:" + loanId + "\t" + "issue date:" + issue_date + "\t" + "due date" + due_date + "\t" + "return_date:" + return_date + "\t" + "borrower id " + id + "\t" + " borrowed_book :" + bookid + "\t" + "fine status :" + fine_status + "\t" + "returned status" + returned_status + "\n"; return resultant; } }
minaahilimtiaz/Library-Management-System-Java
Loan.java
2,081
/* * 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. */
block_comment
en
true
60524_0
import java.util.Optional; public class Seller extends Actor { public Seller(String storeName, Inventory startingInventory) { name = storeName; inventory = startingInventory; } /** * Purchases an item. As the Seller does not have a money attribute, * the item will always be "bought". */ @Override public void buy(ItemInterface item) { inventory.addOne(item); } /** * Attempt to sell an item by name. If an item with a matching name is * found, the item is removed and returned. * @param itemName * @return The sold item. */ public Optional<ItemInterface> sell(String itemName) { Optional<ItemInterface> result = removeItem(itemName); if (result.isPresent()) { return result; } return Optional.empty(); } }
mq-soft-tech/comp2000_2023_project
src/Seller.java
200
/** * Purchases an item. As the Seller does not have a money attribute, * the item will always be "bought". */
block_comment
en
false
60661_16
// Fichier : Pays.java // BUT INFO 2021/2022 //SAE S2.02 exploitation algorithmique d'un probleme /** package & import */ package sae; import java.util.*; /** Classe Pays du package sae de la SAE S2.02 exploitation algorithmique d'un probleme */ public class Pays { /** nomPays est un String, cet argument vise à attribuer un nom à notre Pays */ private String nomPays; /** courtTrajet est une Liste de Pays, cet argument vise à creer une liste de pays auquel il est lie */ private List<Pays> courtTrajet = new LinkedList<>(); /** quarantaine est un Int, cet argument represente la duree de quarantaine */ private Integer quarantaine = Integer.MAX_VALUE; /** paysVoisins est une HashMap representant les pays voisins */ Map<Pays, Integer> paysVoisisns = new HashMap<>(); /** Constructeur de notre Class Pays qui prend un string en argument */ public Pays(String nomPays) { this.nomPays = nomPays; } /** Methode addDestination qui prend un pays et un int en arguments qui rajoute ces arguments dans la Map */ public void addDestination(Pays destination, int quarantaine) { paysVoisisns.put(destination, quarantaine); } /** Methode getPaysVoisins qui renvoie les pays voisins */ public Map<Pays, Integer> getPaysVoisins(){ return paysVoisisns; } /** Methode getQuarantaine represente le getter de quarantaine */ public Integer getQuarantaine(){ return quarantaine; } /** Methode toString qui renvoie le nom du pays */ public String toString(){ return nomPays; } /** Methode getCourtTrajet qui est le getter de courtTrajet - without brackets*/ public List<Pays> getCourtTrajet(){ return courtTrajet; } /** Methode getCourtTrajet qui est le getter de courtTrajet - without brackets*/ public String getCourtTrajet_toString(){ String courtTrajet_string=courtTrajet.toString(); courtTrajet_string=courtTrajet_string.replace("[", ""); courtTrajet_string=courtTrajet_string.replace("]", ""); return courtTrajet_string; } /** Methode setQuarantaine qui prend un int en argument qui modifie la duree de quarantaine */ public void setQuarantaine(Integer d){ quarantaine=d; } /** Methode setCourtTrajet qui prend une Liste de pays en argument qui modifie courtTrajet */ public void setCourtTrajet(List<Pays> courtT){ courtTrajet=courtT; } /** methode setNomPays qui change le nom d'un pays */ public void setNomPays(String nomP){ nomPays=nomP; } /** Methode qui affiche le plus court chemin entre le pays de depart et le pays d'arrivee */ public static String plusCourtChemin(Pays p1,Pays p2){ return ("Le plus court chemin entre : "+p1+" et "+p2+" est : "+p2.getCourtTrajet_toString()+" et "+p2.toString()); } }
MedFrio/Exploration-algorithmique-d-un-probleme
sae/Pays.java
873
/** Methode setQuarantaine qui prend un int en argument qui modifie la duree de quarantaine */
block_comment
en
true
60699_25
import java.awt.*; import java.awt.event.*; import javax.swing.*; import java.util.HashSet; import java.util.Iterator; import java.util.Random; /** * GameCourt * * This class holds the primary game logic of how different objects * interact with one another. Take time to understand how the timer * interacts with the different methods and how it repaints the GUI * on every tick(). * */ @SuppressWarnings("serial") public class GameCourt extends JPanel { // the state of the game logic private Background background; private Tank tank; private HashSet<GameObj> aliens; private HashSet<Bullet> bullets; private HashSet<GameObj> divers; private JLabel livesDisp; private JLabel waveDisp; private JLabel scoreDisp; private int lives; private int score; private int alien_velocity = 1; private long lastShot; private Timer timer; // Game constants public static final int COURT_WIDTH = 532; public static final int COURT_HEIGHT = 600; public static final int TANK_VELOCITY = 10; public static final int BULLET_VELOCITY = 10; // Update interval for timer in milliseconds public static final int INTERVAL = 35; public GameCourt(JLabel livesDisp, JLabel waveDisp, JLabel scoreDisp){ // creates border around the court area, JComponent method setBorder(BorderFactory.createLineBorder(Color.BLACK)); setBackground(Color.darkGray); // The timer is an object which triggers an action periodically // with the given INTERVAL. One registers an ActionListener with // this timer, whose actionPerformed() method will be called // each time the timer triggers. We define a helper method // called tick() that actually does everything that should // be done in a single timestep. timer = new Timer(INTERVAL, new ActionListener(){ public void actionPerformed(ActionEvent e){ tick(); } }); timer.start(); // MAKE SURE TO START THE TIMER! // Enable keyboard focus on the court area // When this component has the keyboard focus, key // events will be handled by its key listener. setFocusable(true); // this key listener allows the square to move as long // as an arrow key is pressed, by changing the square's // velocity accordingly. (The tick method below actually // moves the square.) addKeyListener(new KeyAdapter(){ public void keyPressed(KeyEvent e){ if (e.getKeyCode() == KeyEvent.VK_LEFT) tank.v_x = -TANK_VELOCITY; else if (e.getKeyCode() == KeyEvent.VK_RIGHT) tank.v_x = TANK_VELOCITY; else if (e.getKeyCode() == KeyEvent.VK_SPACE) { if ((System.currentTimeMillis() - lastShot) > 250) { bullets.add(new Bullet(0, -BULLET_VELOCITY, tank.pos_x + 19, tank.pos_y, COURT_WIDTH, COURT_HEIGHT, false)); lastShot = System.currentTimeMillis(); } } } public void keyReleased(KeyEvent e){ tank.v_x = 0; tank.v_y = 0; } }); this.livesDisp = livesDisp; this.waveDisp = waveDisp; this.scoreDisp = scoreDisp; } /** (Re-)set the state of the game to its initial state. */ public void resetState() { lives = 6; alien_velocity = 1; score = 0; lastShot = 0; } public void reset() { background = new Background(COURT_WIDTH, COURT_HEIGHT, "planet.png"); tank = new Tank(COURT_WIDTH, COURT_HEIGHT); aliens = new HashSet<GameObj>(); bullets = new HashSet<Bullet>(); divers = new HashSet<GameObj>(); int st = 10; //y value to start first alien row int sp = 15; //space between each alien row //add a row of Alien1 ships for (int x = 56; x <= 456; x += 40) { aliens.add(new Alien1(alien_velocity, x, st, COURT_WIDTH, COURT_HEIGHT)); } //add two rows of Alien2 ships for (int x = 52; x <= 452; x += 40) { aliens.add(new Alien2(alien_velocity, x, st + 21 + sp, COURT_WIDTH, COURT_HEIGHT)); aliens.add(new Alien2(alien_velocity, x, st + 21 + sp + 22 + sp, COURT_WIDTH, COURT_HEIGHT)); } //add two rows of Alien3 ships for (int x = 50; x <= 450; x += 40) { aliens.add(new Alien3(alien_velocity, x, st + 21 + sp + 22 + sp + 22 + sp, COURT_WIDTH, COURT_HEIGHT)); aliens.add(new Alien3(alien_velocity, x, st + 21 + sp + 22 + sp + 22 + sp + 23 + sp, COURT_WIDTH, COURT_HEIGHT)); } // Make sure that this component has the keyboard focus requestFocusInWindow(); } public void pause () { timer.stop(); } public void start () { timer.start(); } /** * This method is called every time the timer defined * in the constructor triggers. */ void tick(){ if (lives > 0) { // move the various objects tank.move(); Random m = new Random(); if (m.nextDouble() < 0.0035) { divers.add(new Dive(0, 1, m.nextInt(500-32)+32, 0, COURT_WIDTH, COURT_HEIGHT)); } Iterator<Bullet> bmove = bullets.iterator(); while(bmove.hasNext()) { GameObj bt = bmove.next(); bt.move(); if (bt.hitWall() != null) bmove.remove(); } Iterator<GameObj> awall = aliens.iterator(); while (awall.hasNext()) { if (awall.next().hitWall() != null) { Iterator<GameObj> itr = aliens.iterator(); while (itr.hasNext()) { GameObj x = itr.next(); x.v_x = x.v_x* -1; x.pos_y = x.pos_y + 15; } break; } } Iterator<GameObj> ait = aliens.iterator(); while (ait.hasNext()) { GameObj al = ait.next(); al.move(); if (m.nextDouble() <= 0.002) { bullets.add(new Bullet(0, BULLET_VELOCITY, al.pos_x + al.width/2, al.pos_y, COURT_WIDTH, COURT_HEIGHT, true)); } if ((COURT_HEIGHT - al.pos_y) < 20) { lives = lives - 1; if (lives > 0) reset(); } Iterator<Bullet> bit = bullets.iterator(); while (bit.hasNext()) { Bullet bt = bit.next(); if (bt.intersects(al) && !bt.enemy) { if (al.width == 32) score += 1; else if (al.width == 29) score += 2; else if (al.width == 21) score += 3; ait.remove(); bit.remove(); break; } if (bt.intersects(tank) && bt.enemy) { lives = lives - 1; bit.remove(); } } } Iterator<GameObj> dit = divers.iterator(); while (dit.hasNext()) { GameObj div = dit.next(); if (div.pos_y < 250) { int x = (tank.pos_x - div.pos_x); int y = (tank.pos_y - div.pos_y); div.v_x = x/43; div.v_y = y/65; System.out.println(div.v_x +", "+ div.v_y); } else { div.v_x = 0; div.v_y = 30; } div.move(); if (div.intersects(tank)) { lives = lives - 1; dit.remove(); } else if (div.hitWall() != null) { dit.remove(); } else { Iterator<Bullet> bit = bullets.iterator(); while (bit.hasNext()) { Bullet bt = bit.next(); if (bt.intersects(div) && !bt.enemy) { score += 8; if (m.nextDouble() < 0.7) lives += 1; dit.remove(); bit.remove(); break; } } } } if (aliens.isEmpty() && divers.isEmpty()) { alien_velocity += 1; reset(); } // update the display scoreDisp.setText("Score: " + score); waveDisp.setText("Wave: " + alien_velocity); livesDisp.setText("Lives: " + lives); repaint(); } else { livesDisp.setText("the aliens destroyed you!"); } } @Override public void paintComponent(Graphics g){ super.paintComponent(g); background.draw(g); tank.draw(g); for (GameObj b: bullets) { b.draw(g); } for (GameObj d: divers) { d.draw(g); } for (GameObj a: aliens) { a.draw(g); } } @Override public Dimension getPreferredSize(){ return new Dimension(COURT_WIDTH,COURT_HEIGHT); } }
sw9/space-invaders-java
src/GameCourt.java
2,697
// Make sure that this component has the keyboard focus
line_comment
en
true
61521_0
import java.util.Date; /** * * @author Hishan Indrajith */ public class Offer { private String clientName; private String symbol; private Date date; private double price; public Offer(String clientName, String symbol, Date date, double price) { this.clientName = clientName; this.symbol = symbol; this.date = date; this.price = price; } public String getClientName() { return clientName; } public String getSymbol() { return symbol; } public Date getDate() { return date; } public double getPrice() { return price; } }
HishanIndrajith/java-Auction-Server
Offer.java
162
/** * * @author Hishan Indrajith */
block_comment
en
true
61620_0
import java.util.ArrayList; import java.util.HashMap; import java.util.LinkedList; import java.util.List; import java.util.Map; import java.util.Queue; //https://leetcode.com/problems/jump-game-iv/solutions/1690813/best-explanation-ever-possible-for-this-question/?orderBy=most_votes&languageTags=java class Solution { public int minJumps(int[] arr) { int n = arr.length; if (n == 1) return 0; Map<Integer, List<Integer>> map = new HashMap<>(); int step = 0; // fill the map for (int i = 0; i < n; i++) { map.computeIfAbsent(arr[i], v -> new ArrayList<>()).add(i); } Queue<Integer> q = new LinkedList<>(); q.offer(0); while (!q.isEmpty()) { step++; int size = q.size(); for (int i = 0; i < size; i++) { int j = q.poll(); if (j - 1 >= 0 && map.containsKey(arr[j - 1])) { q.offer(j - 1); } if (j + 1 < n && map.containsKey(arr[j + 1])) { if (j + 1 == n - 1) return step; q.offer(j + 1); } if (map.containsKey(arr[j])) { for (int k : map.get(arr[j])) { if (k != j) { if (k == n - 1) return step; q.offer(k); } } } map.remove(arr[j]); } } return step; } }
kalongn/LeetCode_Solution
1345.java
430
//https://leetcode.com/problems/jump-game-iv/solutions/1690813/best-explanation-ever-possible-for-this-question/?orderBy=most_votes&languageTags=java
line_comment
en
true
61949_1
import greenfoot.*; // (World, Actor, GreenfootImage, Greenfoot and MouseInfo) /** * Write a description of class Menu here. * * @author (your name) * @version (a version number or a date) */ public class Menu extends World { /** * Constructor for objects of class Menu. * */ ImageHelper start = new ImageHelper(new GreenfootImage("Start", 48, Color.BLACK, null)); ImageHelper easy = new ImageHelper(new GreenfootImage("Easy", 48, Color.BLACK, null)); ImageHelper normal = new ImageHelper(new GreenfootImage("Normal", 48, Color.BLACK, null)); public Menu() { // Create a new world with 600x400 cells with a cell size of 1x1 pixels. super(800, 400, 1); setBackground("background.png"); getBackground().setFont(new Font(48)); showText("Game", 400, 100); addObject(start, 400, 200); Greenfoot.start(); } public void act(){ if(Greenfoot.mouseClicked(start)){ showText("Choose Difficulty",400, 250); addObject(easy, 300, 300); addObject(normal, 500, 300); } if(Greenfoot.mouseClicked(easy)){ Greenfoot.setWorld(new MyWorld(true)); } else if(Greenfoot.mouseClicked(normal)){ Greenfoot.setWorld(new MyWorld(false)); } } }
ectodrop/2D-Platformer-Game
Menu.java
392
/** * Write a description of class Menu here. * * @author (your name) * @version (a version number or a date) */
block_comment
en
false
62201_1
import java.io.IOException; import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.Paths; import java.util.ArrayList; import java.util.Arrays; import java.util.List; /*Autômatos de Pilha Determinísticos (P) 0,a;x;y,1 -- (transição de q0 para q1 lendo a da fita, x da pilha e escrevendo y na pilha) */ public class MT extends Leitor{ private String initialStateAP; private String[] finalStatesAP; private List<String[]> conditionsAP; private List<String[]> inputFormatted; private List<String> message; private String output; private String estadoAtual; /* Maquina de Turing -Lê a fita -Executa a função de transição -Escreve -Movimenta para a esquerda ou direita -Vai para o proximo estado - aN bN - n >= 0 -Quando ler um a ou quando ler um B vai para a finalização -Escreve A -Procura b -Vai para a direita enquanto ler a -Até ler b -Se ler b, escreve B -Procura A -Vai para a esquerda enquanto ler b -Até ler A ### Repete o ciclo ### ---Finalização--- -Vai para a direita enquanto ler B, até ler "_" */ public MT(String initialStateAP, String[] finalStatesAP, List<String[]> conditionsAP, String inputIn) throws IOException{ System.out.println("Inicializando o MT.."); this.initialStateAP = initialStateAP; this.finalStatesAP = finalStatesAP; this.conditionsAP = conditionsAP; message= new ArrayList<String>(); inputFormatted = new ArrayList<String[]>(); this.lerEntrada(inputIn); } public String toString(String[] input){ String list = Arrays.toString(input).replace("[", "").replace("]", "").replace(",", "").replace(" ", ""); return list; } public void lerEntrada(String path) throws IOException{ Path arquivo = Paths.get(path); if(!Files.exists(arquivo)){ System.out.println("Não existe"); } List<String> input = Files.readAllLines(arquivo); for(int i = 0; i < input.size(); i++ ){ //System.out.println(input.get(i).split("")); inputFormatted.add(input.get(i).concat("_").split("")); } /*for(int i=0;i<inputFormatted.size();i++){ for(String linhas:inputFormatted.get(i)){ System.out.println(linhas); } }*/ } public void verificarCondicao(String outputOut) throws IOException{ String direction = "R"; for(int i=0;i<this.inputFormatted.size();i++){ int j=-1; String[] tape = inputFormatted.get(i); //Setando o estadoAtual como o primeiro estado estadoAtual = initialStateAP; while(true){ if(direction.equals("R")){ j++; } else if(direction.equals("L")){ j--; } if(j==tape.length){ break; } //encontra todos as opções do estado atual //verifico a entrada com as condições de cada opção, se não bater já para. Se bater trocar //System.out.println(this.conditionsAFD.size()); int achou=0; //Achar as condições do estadoAtual for(String[] aux:conditionsAP){ //Split no aux[1] String[] aux2 = aux[1].split(";"); if(estadoAtual.equals(aux[0])){ //Achamos as condições, agora teremos que verificar se bate com o input //0,a;A;R,1 //aux2[0] a if(tape[j].equals(aux2[0])){ //Escrevendo na fita //aux2[1] A tape[j] = aux2[1]; //aux2[2] = R direction = aux2[2]; //aux[2] = 1 estadoAtual=aux[2]; achou=1; break; } } } if(achou==0){ estadoAtual = "ERRO"; break; } //System.out.println(estadoAtual); } for(String aux:this.finalStatesAP){ if(estadoAtual.equals(aux)){ output = "A"; break; } else{ output="R"; } } message.add(output+";"+toString(tape)); } escreverArquivo(outputOut, message); System.out.println("Finalizando MT...\nFIM"); } }
joaodelrio/machine-simulator
MT.java
1,208
/* Maquina de Turing -Lê a fita -Executa a função de transição -Escreve -Movimenta para a esquerda ou direita -Vai para o proximo estado - aN bN - n >= 0 -Quando ler um a ou quando ler um B vai para a finalização -Escreve A -Procura b -Vai para a direita enquanto ler a -Até ler b -Se ler b, escreve B -Procura A -Vai para a esquerda enquanto ler b -Até ler A ### Repete o ciclo ### ---Finalização--- -Vai para a direita enquanto ler B, até ler "_" */
block_comment
en
true
62601_1
import java.io.*; import java.net.ServerSocket; import java.net.Socket; import java.util.Random; import java.util.Scanner; public class App { private static final String PATH = "./Send/"; //private static final String IP = "127.0.0.1"; //private static final int PORT_FORWARDING = 9081; //private static final int PORT_SENDER = 7777; private static final int PORT_RECEIVER = 6666; private static final int CHUNKSIZE = 1460; private static final int REQUESTFIELDQUANTITY = 4; private static DataOutputStream dataOutputStream = null; private static DataInputStream dataInputStream = null; private static FileOutputStream fileOutputStream; private static byte[][] chunks; //private static long size; public static void clientConnection () { Scanner sc = new Scanner(System.in); Hosts hosts = new Hosts(); String myHost = hosts.getMyAddress(); System.out.println("Ingrese IP: "); String ip = sc.nextLine(); try(Socket socket = new Socket(ip, 9081)) { while(true){ /* Realizar Peticion */ dataInputStream = new DataInputStream(socket.getInputStream()); dataOutputStream = new DataOutputStream(socket.getOutputStream()); System.out.println("Ingrese el destino: "); String To = sc.nextLine(); System.out.println("Ingrese nombre del archivo: "); String Name = sc.nextLine(); System.out.println("Ingrese tamaño del archivo: "); String size = sc.nextLine(); dataOutputStream.writeUTF("From:" + myHost + "\n"+"To:"+To+"\nName:"+Name+"\nSize:"+size+ "\nEOF"); /*if(dataInputStream.readUTF() == null){ break; }else{ String[] paramsRes = decodeRequest(); makeResponse(paramsRes); }*/ } }catch (Exception e){ e.printStackTrace(); } finally{ try { if (dataOutputStream != null) { dataOutputStream.close(); } if (dataInputStream != null) { dataInputStream.close(); } } catch (Exception e) { e.printStackTrace(); } } } public static void receiveRequest () { try(ServerSocket serverSocket = new ServerSocket(PORT_RECEIVER)){ while(true){ Socket clientSocket = serverSocket.accept(); dataInputStream = new DataInputStream(clientSocket.getInputStream()); dataOutputStream = new DataOutputStream(clientSocket.getOutputStream()); String[] params = decodeRequest(); makeResponse(params); //System.out.println(response); //dataOutputStream.writeUTF(makeResponse(params)); dataInputStream.close(); dataOutputStream.close(); clientSocket.close(); } } catch (Exception e){ e.printStackTrace(); } } public static String[] decodeRequest () throws Exception { String[] paramsDecoded = new String[REQUESTFIELDQUANTITY]; String paramsEncoded = dataInputStream.readUTF(); paramsDecoded = paramsEncoded.split("\n"); for (int i = 0; i < paramsDecoded.length; i++) { paramsDecoded[i] = paramsDecoded[i].split(":")[1].trim(); } return paramsDecoded; } public static String makeResponse (String[] params) { String from = params[0]; String to = params[1]; String name = params[2]; int size = Integer.parseInt(params[3]); //byte[] result; long noChunks = (size%((long)CHUNKSIZE)==0L) ? size/((long)CHUNKSIZE) : size/((long)CHUNKSIZE)+1; chunks = new byte[(int)noChunks][CHUNKSIZE]; Random random = new Random(); int frag = random.nextInt((int) noChunks); try { File file = new File(PATH+name); FileInputStream fileInputStream = new FileInputStream(file); // break file into chunks byte[] buffer; for (int i = 0; i < (int)noChunks; i++) { buffer = new byte[CHUNKSIZE]; fileInputStream.read(buffer); chunks[i] = buffer; } dataOutputStream.writeUTF(Messages.makeResponse(from, to, name, chunks[frag].clone(), frag, size)); dataOutputStream.flush(); ConsoleLog.printMessage(from, to, name, size, frag, ConsoleLog.SENT); Log.makeLog(from, to, name, size, frag, ConsoleLog.SENT, !Log.END); fileOutputStream.close(); fileInputStream.close(); } catch (Exception e) { return Messages.makeError(from, to, 0); } return Messages.makeResponse(from, to, name, chunks[frag], frag, size); } /*public static String makeResponse (String[] params) { String from = params[0]; String to = params[1]; String name = params[2]; int size = Integer.parseInt(params[3]); //byte[] result; long noChunks = (size%((long)CHUNKSIZE)==0L) ? size/((long)CHUNKSIZE) : size/((long)CHUNKSIZE)+1; chunks = new byte[(int)noChunks][CHUNKSIZE]; Random random = new Random(); int frag = random.nextInt((int) noChunks); try { File file = new File(PATH+name); FileInputStream fileInputStream = new FileInputStream(file); // break file into chunks byte[] buffer; for (int i = 0; i < (int)noChunks; i++) { buffer = new byte[CHUNKSIZE]; fileInputStream.read(buffer); chunks[i] = buffer; } for (int i = 0; i < (int)noChunks; i++) { dataOutputStream.writeUTF(Messages.makeResponse(from, to, name, chunks[i].clone(), i, size)); dataOutputStream.flush(); // LOGS ConsoleLog.printMessage(from, to, name, size, i, ConsoleLog.SENT); Log.makeLog(from, to, name, size, i, ConsoleLog.SENT, !Log.END); //System.out.println(Messages.makeResponse(from, to, name, chunks[i], i, size)); //System.out.println(i); } fileOutputStream.close(); fileInputStream.close(); } catch (Exception e) { return Messages.makeError(from, to, 0); } return Messages.makeResponse(from, to, name, chunks[frag], frag, size); } */ public static void main(String[] args) { App.clientConnection(); //App.receiveRequest(); } }
gabrielmonzon39/file-transfer-java
App.java
1,560
//private static final int PORT_FORWARDING = 9081;
line_comment
en
true
62662_0
public abstract interface fax { public abstract faw a(); public abstract void a(int paramInt); public abstract void a(faw paramfaw); public abstract int b(); public abstract void b(int paramInt); public abstract int c(); } /* Location: * Qualified Name: fax * Java Class Version: 6 (50.0) * JD-Core Version: 0.7.1 */
reverseengineeringer/com.google.android.youtube
src/fax.java
104
/* Location: * Qualified Name: fax * Java Class Version: 6 (50.0) * JD-Core Version: 0.7.1 */
block_comment
en
true
62672_0
package jdbc; 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.HashSet; import java.util.Set; public class Customer { private String name,phone,address,fax,email,bankName,bankAccount,more; private int id; private static Connection getConnection() { Connection con = null; try { Class.forName("com.mysql.jdbc.Driver"); con = DriverManager .getConnection( "jdbc:mysql://localhost/cm?useUnicode=true&characterEncoding=UTF-8", "customer", "weze3agha9aki6k"); } catch (Exception e) { System.out.println("数据库连接失败" + e.getMessage()); } return con; } /** * 通过以下参数构造Customer自动插入数据库 * @param name * @param phone * @param address * @param fax * @param email * @param bankName * @param bankAccount * @param more */ public Customer(String name, String phone, String address, String fax, String email, String bankName, String bankAccount, String more) { super(); this.name = name; this.phone = phone; this.address = address; this.fax = fax; this.email = email; this.bankName = bankName; this.bankAccount = bankAccount; this.more = more; int auto_id = -1; //进行合同插入操作,只有这里可以插入合同 Connection conn = getConnection(); try { String sql = "insert into customer (name,tel,address,fax,email,bank,account,more) values('"+name+"','"+phone+"','"+address+"','"+fax+"','"+email+"','"+bankName+"','"+bankAccount+"','"+more+"')"; PreparedStatement stmt; try { stmt = conn.prepareStatement(sql, Statement.RETURN_GENERATED_KEYS); stmt.executeUpdate(); ResultSet rs = stmt.getGeneratedKeys(); while (rs.next()) { auto_id = rs.getInt(1); } } catch (SQLException e) { auto_id=-1; e.printStackTrace(); } this.setId(auto_id); conn.close(); } catch (SQLException e) { this.setId(auto_id); System.out.println("插入合同失败"); System.err.println(e); } } /** * 通过ID得到Customer * @param id */ public Customer(int id) { this.id= id; Connection conn = getConnection(); try { String sql = "select *from customer where id = '"+id+"'"; Statement st = (Statement) conn.createStatement(); ResultSet rs = st.executeQuery(sql); while (rs.next()) { this.setName(rs.getString("name")); this.setAddress(rs.getString("address")); this.setPhone(rs.getString("tel")); this.setFax(rs.getString("fax")); this.setBankName(rs.getString("bank")); this.setBankAccount(rs.getString("account")); this.setEmail(rs.getString("email")); this.setMore(rs.getString("more")); } conn.close(); } catch (SQLException e) { System.out.println("查询Customer失败"); System.err.println(e); } } /** * 通过搜索得到Customer * @param q 为""搜索出全部 * @return */ public Set<Customer> getCustomerSet(String q) { Set<Customer> customers = new HashSet<Customer>(); Connection conn = getConnection(); try { String sql = "select *from customer where name like '%"+q+"%'"; Statement st = (Statement) conn.createStatement(); ResultSet rs = st.executeQuery(sql); while (rs.next()) { Customer mCustomer = new Customer(-1); mCustomer.setId(rs.getInt("id")); mCustomer.setName(rs.getString("name")); mCustomer.setAddress(rs.getString("address")); mCustomer.setPhone(rs.getString("tel")); mCustomer.setFax(rs.getString("fax")); mCustomer.setBankName(rs.getString("bank")); mCustomer.setBankAccount(rs.getString("account")); mCustomer.setEmail(rs.getString("email")); mCustomer.setMore(rs.getString("more")); customers.add(mCustomer); } conn.close(); } catch (SQLException e) { System.out.println("查询Customer失败"); System.err.println(e); } return customers; } //以下自动生成 public String getName() { return name; } public void setName(String name) { this.name = name; } public String getPhone() { return phone; } public void setPhone(String phone) { this.phone = phone; } public String getAddress() { return address; } public void setAddress(String address) { this.address = address; } public String getFax() { return fax; } public void setFax(String fax) { this.fax = fax; } public String getEmail() { return email; } public void setEmail(String email) { this.email = email; } public String getBankName() { return bankName; } public void setBankName(String bankName) { this.bankName = bankName; } public String getBankAccount() { return bankAccount; } public void setBankAccount(String bankAccount) { this.bankAccount = bankAccount; } public String getMore() { return more; } public void setMore(String more) { this.more = more; } public int getId() { return id; } public void setId(int id) { this.id = id; } }
tpian928/Contract-Management-System
src/jdbc/Customer.java
1,571
//localhost/cm?useUnicode=true&characterEncoding=UTF-8",
line_comment
en
true
63030_8
import java.awt.Graphics; /** * Enemies try to hunt down and kill Players. */ public class Enemy extends Actor implements ActorCollision { public static final String TITLE = "Enemy"; public static final String NAME = "enemy"; public static final String DEFAULT_IMAGE_PATH = "enemy.png"; @Override public String title() { return TITLE; } @Override public String name() { return NAME; } @Override public String defaultImagePath() { return DEFAULT_IMAGE_PATH; } /** * Enemies' maximum speed. */ public static final int VELOCITY = 4; /** * This is the probability per check for intersection. The actual * probability that an Enemy picks up a given coin is approximately * PICKUP_PROBABILITY * (Coin.WIDTH / VELOCITY) == 0.15. */ public static final double PICKUP_PROBABILITY = 0.02; /** * The minimum amount of time to wait before climbing out of a hole. */ public static final int CLIMB_OUT_TIME = 10000; /** * The coordinates at which the Enemy will respawn after being trapped in a * filled hole. */ private int initX, initY; /** * The last time the Enemy fell into a hole. */ private long lastClimbOutTime; /** * Whether the Enemy is in a hole. */ private boolean isInHole = false; /** * Whether the enemy will try to respawn at the next tick. */ private boolean needsRespawning = false; public Enemy(int x, int y) { super(x, y); initX = x; initY = y; lastClimbOutTime = System.currentTimeMillis(); if (Math.random() < 0.5) setVelocity(VELOCITY, 0); else setVelocity(-VELOCITY, 0); } /** * Reverse directions. */ public void reverse() { xVel = -xVel; } /** * Reverse the Enemy's direction when it hits a Solid. * @param n The WorldNode to check for intersection. */ public void adjustX(WorldNode n) { // If an Enemy is barely overlapping a solid, move it outside of the solid. if (n instanceof Solid) { int oX = x; if (getX() < n.getX() && getX() + getWidth() < n.getX() + VELOCITY + 1 && getY() == n.getY()) x = n.getX() - getWidth(); else if (getX() > n.getX() && getX() > n.getX() + n.getWidth() - VELOCITY - 1 && getY() == n.getY()) x = n.getX() + n.getWidth(); // If we hit a solid, reverse direction. if (oX != x) reverse(); } } @Override public void draw(Graphics g) { if (isInHole) Picture.draw(g, "enemy.png", getX(), getY()); else if (xVel < 0) Picture.draw(g, "enemy-left.png", getX(), getY()); else if (xVel > 0) Picture.draw(g, "enemy-right.png", getX(), getY()); else Picture.draw(g, "enemy.png", getX(), getY()); } @Override public boolean canOccupySameLocationInEditorAs(WorldNode other) { return (other instanceof Pickup); } @Override public void pickUp(Pickup item) { // Only pick up a single coin. if (item instanceof Coin && getGoldValue() == 0 && Math.random() < Enemy.PICKUP_PROBABILITY) super.pickUp(item); } /** * Mark the Enemy as currently in a hole. */ public void setInHole(boolean b) { isInHole = b; if (isInHole) lastClimbOutTime = System.currentTimeMillis(); } /** * Whether the enemy is currently in a hole. */ public boolean isInHole() { return isInHole; } /** * Check whether this Enemy can fall into a given hole. */ public boolean canFallInDug(Dug d) { return (GamePanel.sorta_equals(d.getX(), getX(), getMaxVelocity()) // Check x-location && (d.getY() == getY() + getHeight() // Check y-location || d.getY() == getY())); // Let Enemies walk into holes from the side } /** * Whether the Enemy can climb out of a hole. * Assumes the Enemy is actually in a hole. */ public boolean canClimbOutYet() { long l = System.currentTimeMillis(); if (l - lastClimbOutTime > CLIMB_OUT_TIME) { return true; } return false; } /** * Climb out of a hole. * Assumes the enemy is actually in a hole. */ public void climbOut() { isInHole = false; setY(getY() - getHeight()); // Make sure the Enemy doesn't fall back into the hole. accelerate(); move(); } /** * Try climbing out of a hole. * @return true if the Enemy ends up out of a hole; false if it is still in one. */ public boolean tryClimbOut() { if (isInHole) { if (canClimbOutYet()) climbOut(); else return false; } return true; } /** * Attempt to respawn the Enemy. This will succeed if: * - The Enemy has just been trapped in a hole, and * - The Player is not very close to the respawn point. * If it continues to fail, the Enemy will just climb out even though it's * buried. */ public void tryRespawn(Player p) { if (needsRespawning && !(p.getY() >= initY && p.getY() <= initY + getHeight() && p.getX() >= initX - getWidth() * 2 && p.getX() <= initX + getWidth() * 3)) { needsRespawning = false; x = initX; y = initY; lastClimbOutTime = System.currentTimeMillis(); isInHole = false; } } /** * Mark this Enemy as ready for respawning. */ public void markForRespawn() { needsRespawning = true; } @Override public boolean actorIsOn(Actor a) { return (GamePanel.sorta_equals(a.getY() + a.getHeight(), getY(), a.getMaxVelocity() - 2) && a.getX() + a.getWidth() > getX() && a.getX() < getX() + getWidth()); } @Override public int getMaxVelocity() { return VELOCITY; } }
IceCreamYou/LodeRunner
Enemy.java
1,794
/** * Reverse directions. */
block_comment
en
true