file_id
stringlengths 4
9
| content
stringlengths 146
15.9k
| repo
stringlengths 9
113
| path
stringlengths 6
76
| token_length
int64 34
3.46k
| original_comment
stringlengths 14
2.81k
| comment_type
stringclasses 2
values | detected_lang
stringclasses 1
value | excluded
bool 1
class | file-tokens-Qwen/Qwen2-7B
int64 30
3.35k
| comment-tokens-Qwen/Qwen2-7B
int64 3
624
| file-tokens-bigcode/starcoder2-7b
int64 34
3.46k
| comment-tokens-bigcode/starcoder2-7b
int64 3
696
| file-tokens-google/codegemma-7b
int64 36
3.76k
| comment-tokens-google/codegemma-7b
int64 3
684
| file-tokens-ibm-granite/granite-8b-code-base
int64 34
3.46k
| comment-tokens-ibm-granite/granite-8b-code-base
int64 3
696
| file-tokens-meta-llama/CodeLlama-7b-hf
int64 36
4.12k
| comment-tokens-meta-llama/CodeLlama-7b-hf
int64 3
749
| excluded-based-on-tokenizer-Qwen/Qwen2-7B
bool 2
classes | excluded-based-on-tokenizer-bigcode/starcoder2-7b
bool 2
classes | excluded-based-on-tokenizer-google/codegemma-7b
bool 2
classes | excluded-based-on-tokenizer-ibm-granite/granite-8b-code-base
bool 2
classes | excluded-based-on-tokenizer-meta-llama/CodeLlama-7b-hf
bool 2
classes | include-for-inference
bool 2
classes |
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
60_1 | /*Write a program to find the shortest path between vertices using
bellman-ford algorithm.*/
//bellman ford algorithm for shortest distance from a source node to all the remaining nodes
import java.util.*;
public class BellmanFord {
private static int N;
private static int[][] graph;
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.print("Enter the number of Vertices : ");
N = sc.nextInt();
System.out.println("Enter the Weight Matrix of Graph");
graph = new int[N][N];
for (int i = 0; i < N; i++)
for (int j = 0; j < N; j++)
graph[i][j] = sc.nextInt();
System.out.print("Enter the Source Vertex : ");
int source = sc.nextInt();
bellmanFord(source - 1);
}
public static void bellmanFord(int src) {
int[] dist = new int[N];
Arrays.fill(dist, Integer.MAX_VALUE);
dist[src] = 0;
for (int i = 0; i < N; i++) {
for (int u = 0; u < N; u++) {
for (int v = 0; v < N; v++) {
if (graph[u][v] != 0 && dist[u] != Integer.MAX_VALUE && dist[u] + graph[u][v] < dist[v]) {
dist[v] = dist[u] + graph[u][v];
}
}
}
}
for (int u = 0; u < N; u++) {
for (int v = 0; v < N; v++) {
if (graph[u][v] != 0 && dist[u] != Integer.MAX_VALUE && dist[u] + graph[u][v] < dist[v]) {
System.out.println("Negative weight cycle detected.");
return;
}
}
}
printSolution(dist);
}
public static void printSolution(int[] dist) {
System.out.println("Vertex \t Distance from Source");
for (int i = 0; i < N; i++) {
System.out.println((i + 1) + "\t\t" + dist[i]);
}
}
}
/*output:-
Enter the number of Vertices : 5
Enter the Weight Matrix of Graph
0 6 0 7 0
0 0 5 8 -4
0 0 0 0 0
0 0 -3 0 9
2 0 0 0 0
Enter the Source Vertex : 1
Vertex Distance from Source
1 0
2 6
3 4
4 7
5 2
*/
/*Enter the number of Vertices : 3
Enter the Weight Matrix of Graph
0 10 5
0 0 -8
0 0 0
Enter the Source Vertex : 1
Vertex Distance from Source
1 0
2 10
3 2
*/
/*
Enter the number of Vertices : 3
Enter the Weight Matrix of Graph
0 10 0
0 0 20
0 -30 0
Enter the Source Vertex : 1
Negative weight cycle detected.
*/
| saadhussain01306/computer_net_lab | 3.bellman_ford.java | 777 | //bellman ford algorithm for shortest distance from a source node to all the remaining nodes | line_comment | en | false | 717 | 17 | 777 | 18 | 812 | 17 | 777 | 18 | 856 | 18 | false | false | false | false | false | true |
294_12 | package _2017._09._assignments.projectgo.template.v2;
//imports
import javafx.application.Application;
import javafx.scene.Scene;
import javafx.scene.layout.BorderPane;
import javafx.stage.Stage;
//class defnition f
public class Go extends Application {
// private fields
private BorderPane bp_layout;
private GoCustomControl customControl;
private GoControlPanel controlPanel;
private GoGameLogic gameLogic;
private GoBoard board;
// overridden init method
public void init() {
bp_layout = new BorderPane(); // create layout
board = new GoBoard(); // creates a board
gameLogic = new GoGameLogic(board); // create gameLogic and pass board to gameLogic so gameLogic can call methods from board
customControl = new GoCustomControl(gameLogic); // create customControl and pass gameLogic to customControl so customControl can call methods from gameLogic
controlPanel = new GoControlPanel(gameLogic); // create controlPanel and pass gameLogic to controlPanel so customControl can call methods from gameLogic
bp_layout.setCenter(customControl); // put the customControl in the center of the layout
bp_layout.setLeft(controlPanel); // put the controlPanel in the right of the layout
}
// overridden start method
public void start(Stage primaryStage) {
// set a title, size and the stack pane as the root of the scene graph
primaryStage.setTitle("Go");
primaryStage.setScene(new Scene(bp_layout, 1000, 800));
primaryStage.show();
}
// overridden stop method
public void stop() {
System.out.println("Application closed");
}
// entry point into our program for launching our javafx applicaton
public static void main(String[] args) {
//T1
launch(args);
}
}
| JosephCheevers/GO | Go.java | 469 | // set a title, size and the stack pane as the root of the scene graph | line_comment | en | false | 407 | 17 | 469 | 17 | 464 | 17 | 469 | 17 | 530 | 18 | false | false | false | false | false | true |
909_0 | import java.util.Scanner;
import java.text.DecimalFormat;
/**
* Calculate Pi
* @date 19 August 2014
* @author Nefari0uss
*
* This program will request the approximate number of calculations to run in calculating π.
* The final result will be displayed on the console. Assumption is that the user inputs an int.
*
*
* Uses the Gottfried Leibniz formula for calculation of π:
*
* 1 - 1/3 + 1/5 - 1/7 + 1/9 - ... = π/4
*
* Source: Wikipedia - Leibniz formula for π
**/
public class Pi {
public static void main(String[] args) {
int n = getInput();
double piValue = calculatePi(n);
printResult(piValue);
}
private static double calculatePi(double n) {
double pi = 0;
for (int i = 1; i < n; i++) {
pi += Math.pow(-1,i+1) / (2*i - 1);
}
return 4 * pi;
}
private static int getInput() {
int n = 0;
Scanner input = new Scanner(System.in);
System.out.println("How many calculations should be run for the approximation?");
try {
n = Integer.parseInt(input.nextLine());
} /** Handle input greater than Java's MAX_INT. **/
catch (NumberFormatException e) {
System.out.println("n is too large. Setting n to be the largest possible int value.");
n = Integer.MAX_VALUE;
}
input.close();
return n;
}
private static double calculateError(double piValue) {
return Math.abs(1 - piValue / Math.PI) * 100;
}
private static void printResult(double piValue) {
DecimalFormat df = new DecimalFormat("#.##");
System.out.println("The value of pi is approximately " + piValue + ".");
System.out.println("The calculated value is off by approximately " + df.format(calculateError(piValue)) + "%.");
}
}
| Nefari0uss/calculate-pi | Pi.java | 542 | /**
* Calculate Pi
* @date 19 August 2014
* @author Nefari0uss
*
* This program will request the approximate number of calculations to run in calculating π.
* The final result will be displayed on the console. Assumption is that the user inputs an int.
*
*
* Uses the Gottfried Leibniz formula for calculation of π:
*
* 1 - 1/3 + 1/5 - 1/7 + 1/9 - ... = π/4
*
* Source: Wikipedia - Leibniz formula for π
**/ | block_comment | en | false | 459 | 138 | 542 | 143 | 535 | 137 | 542 | 143 | 602 | 153 | false | false | false | false | false | true |
1566_0 | //2-Given sides of a triangle, check whether the triangle is equilateral, isosceles or scalene. Find it's area
import java.util.Scanner;
public class Triangle {
public static void main(String[] args) {
int a, b, c;
double p, area;
Scanner sc = new Scanner(System.in);
System.out.println("Enter sides of triangle : ");
a = sc.nextInt();
b = sc.nextInt();
c = sc.nextInt();
if((a < b + c) && (b < a + c) && (c < a + b)){
if((a == b) && (b == c))
System.out.println("Given Trangle is Equilateral");
else if ((a == b) || (b == c) || (c == a))
System.out.println("Given Triangle is Isoscleles");
else
System.out.println("Given Triangle is Scalane");
p=(a+b+c)/2;
area = Math.sqrt(p * (p - a) * (p - b) * (p - c));
System.out.println("Area of triangle is = " + area);
}else{
System.out.println("Cannot form a triangle");
}
}
}
| KadeejaSahlaPV/java | 2.java | 293 | //2-Given sides of a triangle, check whether the triangle is equilateral, isosceles or scalene. Find it's area | line_comment | en | false | 264 | 29 | 293 | 30 | 310 | 27 | 293 | 30 | 331 | 33 | false | false | false | false | false | true |
1946_5 | /******************************************************************************
* Compilation: javac UF.java
* Execution: java UF < input.txt
* Dependencies: StdIn.java StdOut.java
* Data files: http://algs4.cs.princeton.edu/15uf/tinyUF.txt
* http://algs4.cs.princeton.edu/15uf/mediumUF.txt
* http://algs4.cs.princeton.edu/15uf/largeUF.txt
*
* Weighted quick-union by rank with path compression by halving.
*
* % java UF < tinyUF.txt
* 4 3
* 3 8
* 6 5
* 9 4
* 2 1
* 5 0
* 7 2
* 6 1
* 2 components
*
******************************************************************************/
import edu.princeton.cs.algs4.MinPQ;
import edu.princeton.cs.algs4.StdIn;
import edu.princeton.cs.algs4.StdOut;
public class UF {
private int[] parent; // parent[i] = parent of i
private byte[] rank; // rank[i] = rank of subtree rooted at i (never more than 31)
private int count; // number of components
/**
* Initializes an empty union–find data structure with {@code n} sites
* {@code 0} through {@code n-1}. Each site is initially in its own
* component.
*
* @param n the number of sites
* @throws IllegalArgumentException if {@code n < 0}
*/
public UF(int n) {
if (n < 0) throw new IllegalArgumentException();
count = n;
parent = new int[n];
rank = new byte[n];
for (int i = 0; i < n; i++) {
parent[i] = i;
rank[i] = 0;
}
}
/**
* Returns the component identifier for the component containing site {@code p}.
*
* @param p the integer representing one site
* @return the component identifier for the component containing site {@code p}
* @throws IndexOutOfBoundsException unless {@code 0 <= p < n}
*/
public int find(int p) {
validate(p);
while (p != parent[p]) {
parent[p] = parent[parent[p]]; // path compression by halving
p = parent[p];
}
return p;
}
/**
* Returns the number of components.
*
* @return the number of components (between {@code 1} and {@code n})
*/
public int count() {
return count;
}
/**
* Returns true if the the two sites are in the same component.
*
* @param p the integer representing one site
* @param q the integer representing the other site
* @return {@code true} if the two sites {@code p} and {@code q} are in the same component;
* {@code false} otherwise
* @throws IndexOutOfBoundsException unless
* both {@code 0 <= p < n} and {@code 0 <= q < n}
*/
public boolean connected(int p, int q) {
return find(p) == find(q);
}
/**
* Merges the component containing site {@code p} with the
* the component containing site {@code q}.
*
* @param p the integer representing one site
* @param q the integer representing the other site
* @throws IndexOutOfBoundsException unless
* both {@code 0 <= p < n} and {@code 0 <= q < n}
*/
public void union(int p, int q) {
int rootP = find(p);
int rootQ = find(q);
if (rootP == rootQ) return;
// make root of smaller rank point to root of larger rank
if (rank[rootP] < rank[rootQ]) parent[rootP] = rootQ;
else if (rank[rootP] > rank[rootQ]) parent[rootQ] = rootP;
else {
parent[rootQ] = rootP;
rank[rootP]++;
}
count--;
}
// validate that p is a valid index
private void validate(int p) {
int n = parent.length;
if (p < 0 || p >= n) {
throw new IndexOutOfBoundsException("index " + p + " is not between 0 and " + (n-1));
}
}
/**
* Reads in a an integer {@code n} and a sequence of pairs of integers
* (between {@code 0} and {@code n-1}) from standard input, where each integer
* in the pair represents some site;
* if the sites are in different components, merge the two components
* and print the pair to standard output.
*
* @param args the command-line arguments
*/
public static void main(String[] args) {
int n = StdIn.readInt();
UF uf = new UF(n);
while (!StdIn.isEmpty()) {
int p = StdIn.readInt();
int q = StdIn.readInt();
if (uf.connected(p, q)) continue;
uf.union(p, q);
StdOut.println(p + " " + q);
}
StdOut.println(uf.count() + " components");
}
}
| dud3/princeton-algs4 | UF.java | 1,263 | /**
* Returns the component identifier for the component containing site {@code p}.
*
* @param p the integer representing one site
* @return the component identifier for the component containing site {@code p}
* @throws IndexOutOfBoundsException unless {@code 0 <= p < n}
*/ | block_comment | en | false | 1,188 | 64 | 1,263 | 63 | 1,367 | 70 | 1,263 | 63 | 1,445 | 73 | false | false | false | false | false | true |
5737_3 | import greenfoot.*; // (World, Actor, GreenfootImage, Greenfoot and MouseInfo)
/**
* Babies do not produce cookies for their player but instead take away
* cookies from the other player.
* every second.
*
* @author Patrick Hu
* @version November 2022
*/
public class Baby extends Building
{
private boolean isDrinkingMilk; // whether the baby was given a milk bottle
private int drinkingCount, drinkingActs;
private GreenfootImage drinkingSprite;
/**
* @param player The player who has purchased a Baby
*/
public Baby(Player player) {
super(player);
animationSize = 11;
scale = 0.5;
isDrinkingMilk = false;
drinkingCount = 0;
drinkingActs = 90;
}
public void act() {
super.act();
if(drinkingCount == 0 && isDrinkingMilk) {
player.getBuildingRows().get(Baby.class).getBuildings().remove(this);
getWorld().removeObject(this);
} else if (drinkingCount <= drinkingActs && isDrinkingMilk) {
Effect.fade(drinkingSprite, drinkingCount, drinkingActs);
} else {
if (actCount == actMark) {
eat();
actMark = getNextActMark(2, 3);
}
}
if(isDrinkingMilk) {
setImage(drinkingSprite);
drinkingCount --;
}
}
/**
* Eats(removes) 5-10 cookies from the other player.
*/
public void eat() {
int amountToEat;
if (Building.LUCKY) {
amountToEat = 10;
}
else {
amountToEat = getRandomNumberInRange(5, 10);
}
CookieWorld cw = (CookieWorld)getWorld();
Player otherPlayer = cw.getOtherPlayer(player);
otherPlayer.changeCookieCount(-amountToEat);
}
/**
* Changes baby's image to it drinking a bottle of milk. This happens when the
* Milk Bottles powerup is activated.
*/
public void drinkMilk() {
drinkingSprite = new GreenfootImage("powerup-icns/baby-drinking-milk.png");
drinkingSprite.scale(50, 50);
setImage(drinkingSprite);
isDrinkingMilk = true;
drinkingCount = 120;
}
}
| edzhuang/cookie-clicker-simulation | Baby.java | 610 | /**
* @param player The player who has purchased a Baby
*/ | block_comment | en | false | 541 | 17 | 610 | 18 | 605 | 18 | 610 | 18 | 688 | 18 | false | false | false | false | false | true |
5838_7 | import java.util.*;
/**
* Implementation of the Farmer Wolf Goat Cabbage problem.
*
* This code was created by Joshua Bates and is his copyright.
*/
public class FWGC implements Problem
{
private boolean[] river=new boolean[4];
private int cost;
/**
* Constructor to create a new FWGC
* Cost is set to 0.
*/
public FWGC()
{
cost=0;
}
//private constructor to create a new state
private FWGC(boolean[] pstate, int oCost)
{
for(int i=0; i< 4; i++)
{
this.river[i]=pstate[i];
}
this.cost=oCost+1;
}
/**
* Checks to see if state is goal state.
* Goal state is everything is across the river.
* @return
*/
@Override
public boolean isGoal()
{
for(int i=0; i<4; i++)
{
if(!river[i])
return false;
}
return true;
}
/**
* Getter method for cost.
* @return
*/
@Override
public int getCost()
{
return cost;
}
//Private method to switch farmer and something else across the river.
private void changeRiver(int i)
{
if(river[0])
{
river[0]=false;
river[i]=false;
}
else
{
river[0]=true;
river[i]=true;
}
}
//Private method to add to array, and change the position
private void newState(ArrayList<FWGC> arr, int position)
{
FWGC state=new FWGC(river, cost);
state.changeRiver(position);
arr.add(state);
}
/**
* Checks valid successors, and returns all possible successors.
* @return
*/
@Override
public ArrayList<FWGC> successors()
{
ArrayList<FWGC> succ=new ArrayList<FWGC>();
if(!river[0])
{
if(!river[1] && !river[2] && !river[3])//everything on bank
{
newState(succ, 2);
}
else if(!river[1] && river[2] && !river[3]) //goat across river, others on bank
{
newState(succ, 3);
newState(succ, 1);
}
else if(!river[1] && !river[2] && river[3]) //goat and wolf on bank, cabbage across river
{
newState(succ, 1);
newState(succ, 2);
}
else if(river[1] && !river[2] && !river[3]) //goat and cabbage on bank, wolf across bank.
{
newState(succ, 3);
newState(succ, 2);
}
else if(river[1] && !river[2] && river[3]) //goat on bank, everything else across
{
newState(succ, 2);
}
}
else
{
if((!river[1] && river[2] && !river[3])||(river[1] && !river[2] && river[3]))
{
newState(succ, 0);
}
else if(!river[1] && river[2] && river[3])
{
newState(succ, 2);
newState(succ, 3);
}
else if(river[1] && !river[2] && !river[3])
{
newState(succ, 2);
newState(succ, 3);
}
}
return succ;
}
/**
* Method for printing out the state.
*
* @return
*/
@Override
public String toString()
{
String str="===============\n";
for(int i=0; i< 4; i++)
{
if(river[i]==false)
{
str+=getPerson(i)+" |RIVER| \n";
}
else
{
str+=" |RIVER| "+getPerson(i)+" \n";
}
}
return str;
}
// Private method used in toString to get F, W, G, or C
private String getPerson(int i)
{
String str="";
if(0==i)
{
str= "F";
}
else if(1==i)
{
str= "W";
}
else if(2==i)
{
str= "G";
}
else if(3==i)
{
str= "C";
}
return str;
}
/**
* Gets heuristic value, which this problem will not have, so the value is
* -1
* @return
*/
@Override
public int heuristicValue()
{
return -1;
}
/**
* Setter for cost
* @param value
*/
@Override
public void setCost(int value)
{
cost=value;
}
/**
* Compares two FWGC classes. If they aren't FWGC, it will return false.
*If they aren't the same state, will also return false
*
* @param state
*/
@Override
public boolean compare( Problem state)
{
boolean isSame;
if(state instanceof FWGC)
{
FWGC comp=(FWGC) state;
int i=0;
isSame=true;//state instanceof FWGC;
while(i<4 && isSame)
{
if(comp.river[i]!=this.river[i])
{
isSame=false;
}
i++;
}
}
else
{
isSame=false;
}
return isSame;
}
}
| BatesJosh/Artficial-Intelligence-Problem-Assignment | FWGC.java | 1,392 | /**
* Checks valid successors, and returns all possible successors.
* @return
*/ | block_comment | en | false | 1,276 | 20 | 1,392 | 21 | 1,561 | 22 | 1,392 | 21 | 1,757 | 25 | false | false | false | false | false | true |
6881_7 | import java.util.ArrayList;
import java.util.List;
// Basic user interface which defines the basic methods required in the system
public interface User {
String getuserName();
String getPassword();
String getContact();
List<Event> getBookedEvents();
List<Booking> getBookings();
boolean isAdmin();
void displayInfo();
}
// implemented Admin class with admin specific entries and methods.
class Admin implements User {
private String userName;
private String password;
private String contactInfo;
private boolean isAdmin = true;
// constructor
public Admin(String userName, String password, String contactInfo) {
this.userName = userName;
this.password = password;
this.contactInfo = contactInfo;
}
public String getuserName() {
return userName;
}
@Override
public String getPassword() {
return password;
}
public String getContact() {
return contactInfo;
}
@Override
public List<Booking> getBookings() {
return null;
}
@Override
public List<Event> getBookedEvents() {
return null;
}
public boolean isAdmin() {
return isAdmin;
}
// boolean method that returns whether the new event is successfully added into the system or not.
public boolean addNewEvent(String eventName, String eventDate, String eventTime, String eventVenue, int avaliableSeats, String eventOrganizer, Event Events[]) {
Event event = new Event(eventName, eventDate, eventTime, eventVenue, avaliableSeats, eventOrganizer);
boolean creation = false;
for (int i = 0; i < Events.length; i++) {
if (Events[i] == null) {
Events[i] = event;
creation = true;
int eveid = Events[i].getEventId();
System.out.println("Event Registered with ID = " + eveid);
break;
} else {
creation = false;
}
}
return creation;
}
// display method which prints all the essential user information
@Override
public void displayInfo() {
System.out.println("User Name: " + userName);
System.out.println("User Password: " + password);
System.out.println("Contact information: " + contactInfo);
System.out.println("is user admin: " + isAdmin + "\n");
}
}
// implemented NormalUser class with specific entries and methods.
class NormalUser implements User {
private String userName;
private String password;
private String contactInfo;
private boolean isAdmin = false;
private List<Event> bookedEvents;
private List<Booking> bookings;
// constructor
public NormalUser(String userName, String password, String contactInfo) {
this.userName = userName;
this.password = password;
this.contactInfo = contactInfo;
bookedEvents = new ArrayList<>();
bookings = new ArrayList<>();
}
@Override
public String getuserName() {
return userName;
}
@Override
public String getPassword() {
return password;
}
@Override
public String getContact() {
return contactInfo;
}
@Override
public boolean isAdmin() {
return isAdmin;
}
@Override
public List<Booking> getBookings() {
return bookings;
}
@Override
public List<Event> getBookedEvents() {
return bookedEvents;
}
// method which prints all the booking details about the bookings made by the user.
public void getAllBookings() {
for (Booking booking : bookings) {
booking.displayBookingDetails();
}
}
// method which prints all the events the user booked in for.
public void getAllBookedEvent() {
for (Event event : bookedEvents) {
event.displayEventDetails();
}
}
// method to add a specific event object which the user booked for.
public void addBookedEvent(Event event) {
bookedEvents.add(event);
}
// method to add the specific booking object associated with a booking
public void addBooking(Booking booking) {
bookings.add(booking);
}
// display method to print all the essential information about the user.
@Override
public void displayInfo() {
System.out.println("User Name: " + userName);
System.out.println("User Password: " + password);
System.out.println("Contact information: " + contactInfo);
System.out.println("is user admin: " + isAdmin + "\n");
}
} | Jainil2004/LocalEventManagementAndBookingSystem | User.java | 1,039 | // method which prints all the booking details about the bookings made by the user.
| line_comment | en | false | 961 | 18 | 1,039 | 19 | 1,185 | 17 | 1,039 | 19 | 1,272 | 19 | false | false | false | false | false | true |
10415_12 | package billingsystem;
import java.util.ArrayList;
import javafx.scene.control.Label;
/**
*
* @author Jason Li
* @version 1.0
* @since 19.12.2016
*
*
*
* The Class Table.
*/
public class Table extends Label implements java.io.Serializable {
/** The tbl name. */
private String tblName;
/** The people. */
private String people;
/** The orders. */
ArrayList<Order> orders = new ArrayList<Order>();
/** The pos X. */
private double posX;
/** The pos Y. */
private double posY;
/**
* Gets the name.
*
* @return the name
*/
public String getName() {
return tblName;
}
/**
* Gets the orders.
*
* @return the orders
*/
public ArrayList<Order> getOrders() {
return orders;
}
/**
* Set new X and Y.
*
* @param x the x-position
* @param y the y-position
*/
public void setXY(double x, double y) {
this.posX = x;
this.posY = y;
}
/**
* Gets the x-position.
*
* @return the x
*/
public double getX() {
return posX;
}
/**
* Gets the y-position.
*
* @return the y
*/
public double getY() {
return posY;
}
/**
* Sets the number of people at the table.
*
* @param people - Number of people
*/
public void setPeople(String people) {
this.people = people;
}
/**
* Gets the number of people at the table.
*
* @return people - Number of people
*/
public String getPeople() {
return people;
}
/**
* Adds the order.
*
* @param order item the order item
*/
public void addOrder(Order orderItem) {
orders.add(orderItem);
}
/**
* Sets the orders.
*
* @param set new orders
*/
public void setOrders(ArrayList<Order> setOrders) {
this.orders = setOrders;
}
/**
* Clear table
*/
public void clear() {
this.people = "";
this.orders.clear();;
}
/**
* Instantiates a new table.
*
* @param tblName the table name
*/
public Table(String tblName) {
this.tblName = tblName;
}
/**
* Instantiates a new table.
*
* @param copyTable - the table to copy
*/
public Table(Table copyTable) {
this.tblName = copyTable.tblName;
this.posX = copyTable.posX;
this.posY = copyTable.posY;
}
}
| kishanrajput23/Java-Projects-Collections | Billing-system/src/billingsystem/Table.java | 732 | /**
* Gets the number of people at the table.
*
* @return people - Number of people
*/ | block_comment | en | false | 615 | 26 | 732 | 25 | 775 | 29 | 732 | 25 | 837 | 30 | false | false | false | false | false | true |
10518_0 | import java.util.ArrayList;
public class Cube extends Traceable {
/* A Cube is cube centered at the origin, extending from -1 to +1 on
* each axis
*
* Note: there is a bug in local_intersect so it sometimes does not work
* correctly, but this should not give you a problem.
*/
public String toString() {
return "Cube \n"+this.transform;
}
@Override
public ArrayList<Intersection> local_intersect(Ray gray) {
var ray = gray.transform(transform.invert());
double[] rets =
check_axis(ray.origin.t[0], ray.direction.t[0]);
double xtmin = rets[0];
double xtmax = rets[1];
rets = check_axis(ray.origin.t[1], ray.direction.t[1]);
if (rets[0] > xtmin)
xtmin = rets[0];
if (rets[1] < xtmax)
xtmax = rets[1];
rets = check_axis(ray.origin.t[2], ray.direction.t[2]);
if (rets[0] > xtmin)
xtmin = rets[0];
if (rets[1] < xtmax)
xtmax = rets[1];
ArrayList<Intersection> ans = new ArrayList<Intersection>();
if (xtmin >= xtmax || xtmax == Double.POSITIVE_INFINITY)
return ans;
ans.add(new Intersection(this, xtmin));
ans.add(new Intersection(this, xtmax));
return ans;
}
private double[] check_axis(double origin, double direction) {
double tmin_numerator = (-1 - origin);
double tmax_numerator = (1 - origin);
double tmin;
double tmax;
//Had an error where Aux could not be resolved to a variable, so I simply replaced Aux.EPSILON with its value 0.0001
if (Math.abs(direction) >= 0.0001) {
tmin = tmin_numerator / direction;
tmax = tmax_numerator / direction;
}
else {
if (tmin_numerator >= 0)
tmin = Double.POSITIVE_INFINITY;
else if (tmin_numerator <=0)
tmin = Double.NEGATIVE_INFINITY;
else tmin = 0;
if (tmax_numerator >= 0)
tmax = Double.POSITIVE_INFINITY;
else if (tmax_numerator <=0)
tmax = Double.NEGATIVE_INFINITY;
else tmax = 0;
}
if (tmin > tmax) {
double temp = tmin;
tmin = tmax;
tmax = temp;
}
return new double[] {tmin, tmax};
}
@Override
public Vector local_normal_at(Point point, Intersection dontUse) {
double[] point_vals = world_to_object(point).getT();
int pos = 0;
double max = -1;
for (int i = 0; i < point_vals.length - 1; i++) {
if (Math.abs(point_vals[i]) > max) {
max = Math.abs(point_vals[i]);
pos = i;
}
}
if (pos == 0) {
return new Vector(point_vals[0],0,0);
} else if (pos == 1) {
return new Vector(0, point_vals[1], 0);
} else {
return new Vector(0, 0, point_vals[2]);
}
}
public static void main(String[] args) {
}
@Override
public boolean includes(Traceable object) {
return this == object;
}
}
| daviddang415/Ray_Tracer | Cube.java | 964 | /* A Cube is cube centered at the origin, extending from -1 to +1 on
* each axis
*
* Note: there is a bug in local_intersect so it sometimes does not work
* correctly, but this should not give you a problem.
*/ | block_comment | en | false | 825 | 61 | 964 | 58 | 964 | 64 | 964 | 58 | 1,184 | 66 | false | false | false | false | false | true |
11161_0 |
import javax.swing.*;
import javax.swing.border.Border;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.FileWriter;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.Iterator;
import java.util.TreeSet;
import java.util.stream.Collectors;
/**
* This class represents a Graphical User Interface (GUI) for the local movie database.
* Users can view, add, and manage movies in the database through this interface.
* The GUI includes options for sorting and filtering movies by different criteria.
*
* @author Asliddin
* @version 6.0
*/
public class GUI extends JFrame {
private Container container = getContentPane();
private JPanel contentPanel;
private static ArrayList<Movie> allMovies = MovieDatabase.allMovies();
private TreeSet<String> directors = MovieDatabase.directors;
/**
* Constructs a new GUI window for the local movie database.
* Initializes the graphical interface, sets its size and title, and adds various components.
* Users can interact with the GUI to view, sort, and filter movies.
*/
GUI() {
this.setVisible(true);
this.setSize(800, 600);
this.setTitle("Local Movie Database");
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
contentPanel = new JPanel(new GridBagLayout());
GridBagConstraints gbc = new GridBagConstraints();
gbc.gridx = 0;
gbc.gridy = 0;
gbc.weightx = 1;
gbc.weighty = 0;
gbc.fill = GridBagConstraints.HORIZONTAL;
gbc.insets = new Insets(10, 10, 10, 10);
JButton addMovie = new JButton("Add Movie");
addMovie.addActionListener((e) -> {
new AddMovie();
});
/**
* Inner class representing a window for adding a new movie to the database.
* Users can input movie details such as title, director, release year, and runtime.
*/
addMovie.setPreferredSize(new Dimension(200, 75));
addMovie.setPreferredSize(new Dimension(130, 50));
JPanel addPanel = new JPanel(new FlowLayout(FlowLayout.LEFT));
addPanel.add(addMovie);
JButton profile = new JButton("Profile");
profile.addActionListener((e) -> {
this.dispose();
new Profile();
});
profile.setPreferredSize(new Dimension(130, 50));
addPanel.add(profile);
String[] str = {"sort by: ", "Title", "Year", "Runtime"};
JComboBox<String> sortBy = new JComboBox<>(str);
sortBy.addActionListener((e)->{
if(sortBy.getSelectedItem().equals("Year")){
Collections.sort(allMovies);
}
else if(sortBy.getSelectedItem().equals("Runtime")){
allMovies.sort((Movie m1, Movie m2)->{
return m2.getRunningTime() - m1.getRunningTime();
});
}
else if(sortBy.getSelectedItem().equals("Title")){
Collections.sort(allMovies, Comparator.comparing(Movie::getTitle));
}
contentPanel.revalidate();
contentPanel.repaint();
this.dispose();
new GUI();
});
Iterator<String> iter = directors.iterator();
String strr[] = new String[directors.size()+2];
strr[0]="Filter By Directors";
strr[1]="All";
int j=2;
while(iter.hasNext()){
strr[j] = iter.next();
j++;
}
JComboBox<String> filter = new JComboBox<>(strr);
filter.addActionListener((e)->{
if(filter.getSelectedItem().equals("All") || filter.getSelectedItem().equals("Filter By Directors")){
allMovies = MovieDatabase.allMovies();
directors = MovieDatabase.directors;
}
else{
allMovies = (ArrayList<Movie>) MovieDatabase.allMovies().stream().filter((ee)->{
return ee.getDirector().equals(filter.getSelectedItem());
}).collect(Collectors.toList());
}
this.dispose();
new GUI();
});
JLabel searchL = new JLabel("search:");
JTextField searchF = new JTextField();
searchF.setPreferredSize(new Dimension(50, 20));
JButton search = new JButton("search");
search.addActionListener(e->{
String txt = searchF.getText();
if(txt.length()==0){
JOptionPane.showMessageDialog(this, "Please fill the blank!");
}else{
Movie movie = MovieDatabase.retrieveMovie(txt);
if(movie==null){
JOptionPane.showMessageDialog(this, "No such movie!");
}else{
String formatted = String.format("Title: %s\n Director: %s\n Year: %d\n Runtime: %d", movie.getTitle(), movie.getDirector(), movie.getReleasedYear(), movie.getRunningTime());
JOptionPane.showMessageDialog(this, formatted);
}
}
});
addPanel.add(sortBy);
addPanel.add(filter);
addPanel.add(searchL);
addPanel.add(searchF);
addPanel.add(search);
container.add(addPanel, BorderLayout.NORTH);
for (int i = 0; i < allMovies.size(); i++) {
String title = allMovies.get(i).getTitle();
String director = allMovies.get(i).getDirector();
int year = allMovies.get(i).getReleasedYear();
int runtime = allMovies.get(i).getRunningTime();
Border insideBorder = BorderFactory.createTitledBorder(title);
JPanel panel = new JPanel();
panel.setLayout(new BorderLayout());
panel.setBorder(insideBorder);
String movieInfo = String.format(
"<strong>Director:</strong> %s, <br><strong>Year:</strong> %d, <br><strong>Runtime:</strong> %d",
director, year, runtime);
JLabel label = new JLabel(
"<html><div style='text-align: left; padding:10px;'>" + movieInfo + "</div></html>");
panel.add(label, BorderLayout.CENTER);
JPanel buttonPanel = new JPanel(new GridLayout(1, 2, 5, 5));
JButton addToWatchlistButton = new JButton("Add to Watchlist");
addToWatchlistButton.addActionListener((e) -> {
User user = Register.getLoggedIn();
ArrayList<Movie> watchlist = MovieDatabase.getUserDB(user);
boolean exists = watchlist.stream().anyMatch((t)->t.getTitle().equals(title));
if(!exists){
try (FileWriter fw = new FileWriter(String.format("DB/UserDB/DB%s.csv", user.getUsername()), true)) {
String movie = String.format("%s, %s, %d, %d\n", title, director, year, runtime);
fw.append(movie);
} catch (Exception ex) {
ex.printStackTrace();
}
}else{
JOptionPane.showMessageDialog(this, "This movie already exists in your watchlist!");
}
});
buttonPanel.add(addToWatchlistButton);
JButton removeButton = new JButton("Remove");
buttonPanel.add(removeButton);
Movie movie = allMovies.get(i);
removeButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
String movieTitle = movie.getTitle();
MovieDatabase.removeMovie(movieTitle);
contentPanel.remove(panel);
contentPanel.revalidate();
contentPanel.repaint();
}
});
panel.add(buttonPanel, BorderLayout.SOUTH);
contentPanel.add(panel, gbc);
gbc.gridy++;
}
JScrollPane scrollPane = new JScrollPane(contentPanel);
scrollPane.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_ALWAYS);
container.add(scrollPane);
}
class AddMovie extends JFrame implements ActionListener {
JButton add = new JButton("add");
JLabel directorLabel = new JLabel("Director : ");
JTextField directorField = new JTextField();
JLabel yearLabel = new JLabel("Release Year: ");
JTextField yearField = new JTextField();
JLabel runtimeLabel = new JLabel("Running time: ");
JTextField runtimeField = new JTextField();
JLabel titleLabel = new JLabel("Title: ");
JTextField titleField = new JTextField();
Container container = getContentPane();
JLabel warning1 = new JLabel("To see the update please click the 'All'");
JLabel warning2 = new JLabel("in filter by director section!!!");
public AddMovie() {
basic();
container.setLayout(null);
setSize();
add.addActionListener(this);
container.add(titleLabel);
container.add(directorLabel);
container.add(yearLabel);
container.add(runtimeLabel);
container.add(titleField);
container.add(directorField);
container.add(yearField);
container.add(runtimeField);
container.add(add);
container.add(warning1);
container.add(warning2);
}
/**
* Performs an action when the add button is clicked in the AddMovie window.
* Validates user input for the new movie and adds it to the database if input is valid.
* Displays error messages for missing or invalid input.
*
* @param e The ActionEvent triggered by clicking the add button.
*/
public void basic() {
this.setVisible(true);
this.setBounds(450, 100, 370, 600);
this.setTitle("Add New Movie");
}
private void setSize() {
titleLabel.setBounds(50, 90, 100, 30);
directorLabel.setBounds(50, 150, 100, 30);
yearLabel.setBounds(50, 220, 150, 30);
runtimeLabel.setBounds(50, 290, 150, 30);
titleField.setBounds(150, 90, 150, 30);
directorField.setBounds(150, 150, 150, 30);
yearField.setBounds(150, 220, 150, 30);
runtimeField.setBounds(150, 290, 150, 30);
add.setBounds(50, 370, 100, 30);
warning1.setFont(new Font("Italic", Font.ITALIC, 15));
warning2.setFont(new Font("Italic", Font.ITALIC, 15));
warning1.setBounds(30, 410, 300, 20);
warning2.setBounds(30, 430, 300, 20);
}
@Override
public void actionPerformed(ActionEvent e) {
if(e.getSource() == add){
if(this.titleField.getText().length()==0 || this.directorField.getText().length()==0 || this.yearField.getText().length()==0 || this.runtimeField.getText().length()==0) {
JOptionPane.showMessageDialog(this, "Please fill all the gaps!");
}
else{
int runtime, year;
try{
runtime = Integer.valueOf(this.runtimeField.getText());
year = Integer.valueOf(this.yearField.getText());
Movie movie = new Movie(this.titleField.getText(), this.directorField.getText(), year, runtime);
MovieDatabase.addMovie(movie);
this.dispose();
}catch(NumberFormatException ee){
JOptionPane.showMessageDialog(this, "Year and runtime should contain only digits!");
}
}
}
}
}
}
| asroilf/MovieDBMS | GUI.java | 2,703 | /**
* This class represents a Graphical User Interface (GUI) for the local movie database.
* Users can view, add, and manage movies in the database through this interface.
* The GUI includes options for sorting and filtering movies by different criteria.
*
* @author Asliddin
* @version 6.0
*/ | block_comment | en | false | 2,362 | 68 | 2,703 | 73 | 2,903 | 71 | 2,703 | 73 | 3,310 | 76 | false | false | false | false | false | true |
12566_1 | //check if a linkedlist is palindrome or not
class LL {
node head;
class node {
int data;
node next;
node(int data) {
this.data = data;
this.next = null;
}
}
/*
* steps:
* 1. find middle of LL
* 2. reverse 2nd half
* 3. check 1st and 2nd half
*/
public void addlast(int data) {
node newnode = new node(data);
if (head == null) {
head = newnode;
}
node curr = head;
while (curr.next != null) {
curr = curr.next;
}
curr.next = newnode;
}
public node reverse(node head) {
node prev = null;
node curr = head;
node next = null;
while (curr != null) {
next = curr.next;
curr.next = prev;
prev = curr;
curr = next;
}
return prev;
}
public node findmiddle(node head) {
node hare = head;
node turtle = head;
while (hare.next.next != null && hare.next != null) {
hare = hare.next.next;
turtle = turtle.next;
}
return turtle;
}
public boolean isPalindrome(node head) {
if (head == null || head.next == null) {
return true;
}
node middle = findmiddle(head);// end of 1st half
node secondstart = reverse(middle.next);
node firststart = head;
while (secondstart != null) {
if (firststart.data != secondstart.data) {
return false;
}
firststart = firststart.next;
secondstart = secondstart.next;
}
return true;
}
}
class sol{
public static void main(String[] args) {
LL list = new LL();
list.addlast(1);
list.addlast(2);
list.addlast(2);
list.addlast(1);
System.out.println("is palindrome"+list.isPalindrome(list.head));
}
} | GAGANDASH002/Java-DSA | q4.java | 510 | /*
* steps:
* 1. find middle of LL
* 2. reverse 2nd half
* 3. check 1st and 2nd half
*/ | block_comment | en | false | 461 | 43 | 510 | 40 | 568 | 45 | 510 | 40 | 601 | 45 | false | false | false | false | false | true |
13150_9 | package LumberYard;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.StandardOpenOption;
import java.time.Instant;
import java.time.ZoneId;
import java.time.format.DateTimeFormatter;
/**
* LumberYard Log class.
*/
public class Log{
private static final DateTimeFormatter TIMESTAMP_FORMATTER = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss +SSS'ms' '['z']'").withZone(ZoneId.systemDefault());
private static final String DEFAULT_DIR = System.getProperty("user.dir")+System.getProperty("file.separator")+"lumberyard";
/**
* Get the default directory used when creating a log without a specified directory.
*
* @return the string
*/
public static String getDefaultDirectory(){
return DEFAULT_DIR;
}
/**
* Convert a throwable into a structured string.
*
* @param e the throwable
* @return the structured string
*/
public static String parseThrowable(Throwable e) {
StringBuilder sb = new StringBuilder();
sb.append(e.getClass().getName()+(e.getMessage()!=null?": "+e.getMessage():""));
for (StackTraceElement element : e.getStackTrace()) {
sb.append("\n\tat ");
sb.append(element.toString());
}
if(e.getCause()!=null){
sb.append("\nCaused by: ");
sb.append(parseThrowable(e.getCause()));
}
return sb.toString();
}
private static Log defaultLog = null;
/**
* Get the default log.
*
* @return the default log
*/
public static Log getDefault(){
if(defaultLog == null){
defaultLog = new Log(Thread.currentThread().getName());
}
return defaultLog;
}
private String name, dir;
private Path path;
/**
* Flag to mirror new log entries to the System.out console after the log file.
*/
public boolean console = true;
/**
* Instantiates a new unnamed Log in the default directory.
*/
public Log(){
this(null);
}
/**
* Instantiates a new Log with a specified name.
*
* @param name the name
*/
public Log(String name){
this(DEFAULT_DIR, name);
}
/**
* Instantiates a new Log with a specified name in a specified directory.
*
* @param dir the dir
* @param name the name
*/
public Log(String dir, String name){
this.name = name;
this.dir = dir;
timestampName();
generatePath();
}
private void generatePath(){
if(name == null){
timestampName();
}
if(dir == null){
dir = getDefaultDirectory();
}
path = Path.of(getDirectory() + System.getProperty("file.separator") + getName() + ".log");
}
/**
* Get the directory of the log.
*
* @return the directory
*/
public String getDirectory(){
return dir;
}
/**
* Get the name of the log.
*
* @return the name
*/
public String getName(){
return name;
}
/**
* Get the full path of the log.
*
* @return the path
*/
public Path getPath(){
return path;
}
private void timestampName(){
DateTimeFormatter stamp = DateTimeFormatter.ofPattern("yyyy-MM-dd_HH-mm-ss").withZone(ZoneId.systemDefault());
name = ((name !=null) ? name + "_" : "") + stamp.format(Instant.now());
}
/**
* Write a categorized message to the log.
*
* @param category the category
* @param message the message
*/
public void write(Category category, String message){
if(category.isEnabled()){
println(category + " | "+ message);
}
}
/**
* Write a throwable to the log.
*
* @param e the throwable
*/
public void write(Throwable e){
if(Category.ERROR.isEnabled()){
println(Category.ERROR +" | "+ parseThrowable(e));
}
}
/**
* Write a blank line to the log.
*/
protected void println(){
try{
Files.write(path, "\n".getBytes(), StandardOpenOption.CREATE, StandardOpenOption.APPEND);
} catch(Exception e){
e.printStackTrace();
}
if(console){
System.out.println();
}
}
/**
* Timestamp and write multiple lines to the log.
*
* @param lines the lines
*/
protected void println(String...lines){
for(String line:lines){
println(line);
}
}
/**
* Timestamp and write a line to the log.
*
* @param line the message
*/
protected void println(String line){
line = TIMESTAMP_FORMATTER.format(Instant.now()) + " | Thread: " +Thread.currentThread().getName()+" | " + line + "\n";
try{
Files.write(path, line.getBytes(), StandardOpenOption.CREATE, StandardOpenOption.APPEND);
} catch(Exception e){
e.printStackTrace();
}
if(console){
System.out.print(line);
}
}
/**
* Make the log the default log.
*/
public void makeDefault(){
defaultLog = this;
}
/**
* Categories of log messages.
*/
public enum Category{
/**
* Info category. Enabled by default.
*/
INFO(),
/**
* Warning category. Enabled by default.
*/
WARNING(),
/**
* Error category. Enabled by default.
*/
ERROR(),
/**
* Debug category. Disabled by default.
*/
DEBUG(false),
/**
* Verbose category. Disabled by default.
*/
VERBOSE(false);
private boolean enabled;
Category(){
this(true);
}
Category(boolean enabled){
this.enabled = enabled;
}
/**
* Enable the category.
*/
public void enable(){
this.enabled = true;
}
/**
* Disable the category.
*/
public void disable(){
this.enabled = false;
}
/**
* Check if the category is enabled.
*
* @return true if the category is enabled.
*/
public boolean isEnabled(){
return enabled;
}
}
}
| YoungGopher/LumberYard | Log.java | 1,600 | /**
* Get the name of the log.
*
* @return the name
*/ | block_comment | en | false | 1,349 | 21 | 1,600 | 20 | 1,669 | 24 | 1,600 | 20 | 1,878 | 24 | false | false | false | false | false | true |
14639_1 | /* Copyright 2010 Brian Mock
*
* This file is part of visint.
*
* visint is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 2 of the License, or
* (at your option) any later version.
*
* visint 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 visint. If not, see <http://www.gnu.org/licenses/>.
*/
import java.util.*;
/**
* This program controls printing debugging output (or not!).
* @author Brian Mock
*/
public class Debug {
public static boolean debug = false;
private static String separator =
"========================================";
public static void error (String s) { if (debug) System.err.println(s); }
public static void println (String s) { if (debug) System.out.println(s); }
public static void print (String s) { if (debug) System.out.print (s); }
public static void printAry(Object[] ary) { println(Arrays.deepToString(ary)); }
public static void printSep() { println(separator); }
}
| wavebeem/visint | Debug.java | 356 | /**
* This program controls printing debugging output (or not!).
* @author Brian Mock
*/ | block_comment | en | false | 317 | 20 | 356 | 23 | 360 | 21 | 356 | 23 | 403 | 22 | false | false | false | false | false | true |
16462_0 | import java.util.ArrayList;
import java.io.*;
public class Driver {
private static ArrayList<Student> studentList;
private static ArrayList<String> schoolList;
public ArrayList<Student> getStudentList() {
return this.studentList;
}
public void setStudentList(ArrayList<Student> studentList) {
this.studentList = studentList;
}
/*
Reads data from the csv file and creates a Student and stores
it in the list.
*/
public static void csvToList(File csvFile) {
try {
studentList = new ArrayList<Student>();
schoolList = new ArrayList<String>();
String row;
BufferedReader csvReader = new BufferedReader(new FileReader(csvFile));
while ((row = csvReader.readLine()) != null) {
String[] rawStudent = row.split(",");
Student student = new Student(Integer.valueOf(rawStudent[0]), rawStudent[1], rawStudent[2]);
studentList.add(student);
if (!schoolList.contains(rawStudent[2])) {
schoolList.add(rawStudent[2]);
}
}
csvReader.close();
} catch (Exception e) {
System.out.println("Error");
}
}
/*
Creates and write to a .txt file.
Tab delimited.
Does this for one school.
*/
public static void tsvForSchool(String school) {
File tsv = new File("data/" + school + ".txt");
String TAB = "\t";
String EOL = "\n";
try {
FileWriter tsvWriter = new FileWriter(tsv);
for (int i = 0; i < studentList.size(); i++) {
StringBuilder sb = new StringBuilder();
if (studentList.get(i).getSchool().equals(school)) {
sb.append(studentList.get(i).getId());
sb.append(TAB);
sb.append(studentList.get(i).getName());
sb.append(TAB);
sb.append(school + EOL);
tsvWriter.write(sb.toString());
}
}
tsvWriter.close();
} catch (IOException e) {
System.out.println("Error");
}
}
public static void main(String[] args) {
File testFile = new File("testFile.csv");
csvToList(testFile);
for (int i = 0; i < schoolList.size(); i++) {
tsvForSchool(schoolList.get(i));
}
}
} | mattspahr/CSV-to-Tab | Driver.java | 630 | /*
Reads data from the csv file and creates a Student and stores
it in the list.
*/ | block_comment | en | false | 545 | 25 | 630 | 25 | 669 | 27 | 630 | 25 | 813 | 30 | false | false | false | false | false | true |
16477_5 | /*
Prompts a frame that asks the user for their personal information and inputs it into a list to be accessed from again
at a later time. Primarily asks for their first and last name, school name, what type of school they are in, and what
quarter or semester they are in currently. Depending on their answers, different choices will show.
@author Nhi Ngo
@version 06/15/2014
*/
import javax.swing.*;
import java.awt.*;
import java.util.*;
import java.awt.event.*;
public class Asking extends Program implements ActionListener{
private JPanel questions;
private JTextPane intro;
private JPanel quarterHS;
private int highS;
private int colle;
private int placeholder;
private JPanel quarterC;
private JPanel overallInfo;
private JPanel userInfo;
private JPanel schoolAsk;
private JPanel empty;
private JPanel overall;
private int quarterNum;
private JPanel info;
private JTextField firstName;
private JTextField lastName;
private JTextField schoolName;
private ArrayList<String> names;
/*Intializes all instance fields*/
public Asking() {
highS = 0;
colle = 0;
placeholder = 0;
questions = new JPanel(new BorderLayout());
overallInfo = new JPanel (new BorderLayout());
userInfo = new JPanel(new GridLayout(1,6));
empty = new JPanel();
schoolAsk = new JPanel (new GridLayout(3,1));
quarterHS = new JPanel(new FlowLayout());
quarterC = new JPanel(new FlowLayout());
overall = new JPanel(new GridLayout(1,1));
info = new JPanel(new BorderLayout());
overall.add(quarterC);
overall.add(quarterHS);
info.add(overall, BorderLayout.NORTH);
overallInfo.add(info, BorderLayout.SOUTH);
names = new ArrayList<String>();
}
/*Adds all components regarding asking the user into the main visual panel for the user to interact and read*/
public JPanel ask() {
questions.add(empty, BorderLayout.CENTER);
intro = introText();
questions.add(intro, BorderLayout.NORTH);
personalInfo();
schoolAsk();
overallInfo.add(userInfo, BorderLayout.NORTH);
overallInfo.add(schoolAsk, BorderLayout.CENTER);
questions.add(overallInfo, BorderLayout.SOUTH);
return questions;
}
/*
*Creates and set a label
*@param name the text that will display on the label
*/
private JLabel label(String name) {
JLabel label = new JLabel(name, JLabel.CENTER);
label.setPreferredSize(new Dimension(80, 15));
return label;
}
/*Creates and set the settings of textfield*/
private JTextField text(){
JTextField text = new JTextField();
text.setPreferredSize(new Dimension(85, 20));
return text;
}
/*Shows the introduction text to the user. Primarily is instructions and information to the user*/
private JTextPane introText() {
JTextPane text = new JTextPane();
text.setEditable(false);
text.setText(" Welcome to Personal Secretary Student Version! Before we start organizing your schedule and\n time, let's set up your profile so you can access it again. All we need is basic information. \n You can edit this information later in the settings option. If you do not wish to answer, feel\n free to leave it blank.");
return text;
}
/*Prompts the user for personal information*/
private void personalInfo() {
JLabel fName = label("First Name");
JLabel lName = label("Last Name");
JLabel sName = label("School Name");
firstName = text();
lastName = text();
schoolName = text();
userInfo.add(fName);
userInfo.add(firstName);
userInfo.add(lName);
userInfo.add(lastName);
userInfo.add(sName);
userInfo.add(schoolName);
}
/*Asks the user about school information and different panels will display according to user's choice*/
private void schoolAsk(){
schoolAsk = new JPanel(new GridLayout(1, 3));
JLabel question = new JLabel ("What school are you in?", JLabel.CENTER);
JRadioButton highSchool = radioButton ("High School");
JRadioButton college = radioButton ("College");
schoolAsk.add(question);
ButtonGroup group = new ButtonGroup();
group.add(highSchool);
group.add(college);
schoolAsk.add(highSchool);
schoolAsk.add(college);
}
/*If the user is in high school, choices of semesters will appear*/
private void highSchool(){
overall.remove(quarterC);
overall.revalidate();
colle += 2;
if (highS == 0) {
JRadioButton firstSem = radioButton("1st Semester");
JRadioButton secondSem = radioButton("2nd Semester");
ButtonGroup group = new ButtonGroup();
group.add(firstSem);
group.add(secondSem);
quarterHS.add(firstSem);
quarterHS.add(secondSem);
}
if(highS == 0 || highS % 2 == 0) {
overall.add(quarterHS);
}
overall.revalidate();
}
/*If user is in college, choices to choose quarters will be visible*/
private void college() {
overall.remove(quarterHS);
overall.revalidate();
highS += 2;
if (colle <= 2) {
JRadioButton fall = radioButton("Fall");
JRadioButton winter = radioButton("Winter");
JRadioButton spring = radioButton("Spring");
JRadioButton summer = radioButton("Summer");
ButtonGroup group = new ButtonGroup();
group.add(fall);
group.add(winter);
group.add(spring);
group.add(summer);
quarterC.add(fall);
quarterC.add(winter);
quarterC.add(spring);
quarterC.add(summer);
}
if(colle == 0 || colle % 2 == 0) {
overall.add(quarterC);
}
overall.revalidate();
}
/*Adds a button of "next" for the user to continue*/
private void next() {
JButton next = button("Continue");
info.add(next, BorderLayout.CENTER);
setNames();
overall.revalidate();
}
/*Add user's info onto arrayList*/
public void setNames() {
names = new ArrayList<String>();
names.add(firstName.getText());
names.add(lastName.getText());
names.add(schoolName.getText());
}
/*
*Creates a radio button
*@param name the text that labels the button
*/
private JRadioButton radioButton(String name){
JRadioButton box = new JRadioButton(name);
box.setSelected(false);
box.addActionListener(this);
return box;
}
/*
*Creates and set the settings for button
*@param name the text that will appear on the button
*/
private JButton button(String name) {
JButton button = new JButton(name);
button.setText(name);
button.setBackground(Color.WHITE);
button.addActionListener(this);
return button;
}
/*Depending on which button user picks, the listener will react differently*/
public void actionPerformed(ActionEvent event) {
if (event.getActionCommand().equals("High School")) {
highSchool();
} else if(event.getActionCommand().equals("College")) {
college();
} else if (event.getActionCommand().equals("Continue")){
questions.setVisible(false);
super.classInfo(names, quarterNum);
} else{
if(event.getActionCommand().equals("Fall")){
quarterNum = 1;
placeholder++;
} else if(event.getActionCommand().equals("Winter")){
quarterNum = 2;
placeholder++;
} else if(event.getActionCommand().equals("Spring")) {
quarterNum = 3;
placeholder++;
} else if(event.getActionCommand().equals("Summer")) {
quarterNum = 4;
placeholder++;
} else if(event.getActionCommand().equals("1st Semester")) {
quarterNum = 5;
placeholder++;
} else if(event.getActionCommand().equals("2nd Semester")) {
quarterNum = 6;
placeholder++;
}
if (placeholder == 1) {
next();
}
}
}
} | rooseveltcs/personal-secretary | Asking.java | 1,925 | /*Shows the introduction text to the user. Primarily is instructions and information to the user*/ | block_comment | en | false | 1,743 | 19 | 1,925 | 20 | 2,098 | 18 | 1,925 | 20 | 2,340 | 20 | false | false | false | false | false | true |
16947_10 | import java.util.*;
public class SRT {
private ArrayList<Process> processes;
private ArrayList<Process> queue;
private Process shortest;
private ArrayList<Process> completed;
private static int QUANTA_MAX = 99;
private static int NUMBER_OF_PROCESSES_TO_MAKE = 30;
private int quanta;
private double totalTurnaroundTime;
private double totalWaitTime;
private double totalResponseTime;
private double processesFinished;
private String out;
public static void main(String[] args) {
ArrayList<Process> processes = new ArrayList<Process>();
for (int i = 1; i <= NUMBER_OF_PROCESSES_TO_MAKE; i++) {
Process process = new Process("P" + i, i);
processes.add(process);
}
Process.sortListByArrivalTime(processes);
SRT srt = new SRT(processes);
String table = "";
for (Process process : srt.getProcesses()) {
table += "[Process: " + String.format("%3s", process.getName()) + ", Arrival time: "
+ String.format("%3d", process.getArrivalTime()) + ", Run time: "
+ String.format("%3d", process.getGivenExecutionTime()) + ", Priority: " + process.getPriority()
+ ", End time: " + String.format("%3d", process.getEndTime()) + ", Time started: "
+ String.format("%3d", process.getStartExecutionTime()) + ", Turnaround time: "
+ String.format("%3d", process.calculateTurnaroundTime()) + ", Wait time: "
+ String.format("%3d", process.calculateWaitTime()) + ", Response time: "
+ String.format("%3d", process.calculateResponseTime()) + "]\n";
}
//System.out.println(table);
}
public SRT(ArrayList<Process> processes) {
this.processes = processes;
this.queue = new ArrayList<Process>();
this.shortest = null;
this.completed = new ArrayList<Process>();
run();
}
public ArrayList<Process> getProcesses() {
return this.completed;
}
private void run() {
quanta = 0;
totalTurnaroundTime = 0;
totalWaitTime = 0;
totalResponseTime = 0;
processesFinished = 0;
out = "";
while (quanta < QUANTA_MAX || !queue.isEmpty()) {
// Check the current time quanta, and add processes that arrive at the current time to the queue.
for (Process process : processes) {
if (process.getArrivalTime() <= quanta) {
queue.add(process);
// processes.remove(process);
}
}
processes.removeAll(queue);
// Preemptive code block.
if (!queue.isEmpty()) {
// Get the process in the queue with the lowest remaining execution time.
shortest = queue.get(0);
for (Process process : queue) {
if (process.getExecutionTimeRemaining() < shortest.getExecutionTimeRemaining()) {
shortest = process;
}
}
queue.remove(shortest);
// If the current shortest process has not started yet, start it.
if (shortest.getStartExecutionTime() < 0 && quanta < QUANTA_MAX) {
shortest.setStartExecutionTime(quanta);
}
// If the process has started
if (shortest.getStartExecutionTime() > -1) {
// Represent it in the timeline
out = out+ "[" + shortest.getName() + "]";
// Decrement the execution time remaining
shortest.decrementExecutionTimeRemaining();
// Move the time splice
quanta++;
// If the shortest process is done (execution time remaining == 0)
if (shortest.getExecutionTimeRemaining() <= 0) {
// Set its end time at the current quanta
shortest.setEndTime(quanta);
// Add the finished process to the completed list.
completed.add(shortest);
processesFinished++;
totalTurnaroundTime += shortest.calculateTurnaroundTime();
totalWaitTime += shortest.calculateWaitTime();
totalResponseTime += shortest.calculateResponseTime();
} else {
// The process is not done, add it back into the queue.
queue.add(shortest);
}
}
} else {
out = out+"[*]";
quanta++;
}
}
}
public String getAverages()
{
String averages = "\n" +"Averages turnaround time: " + totalTurnaroundTime / processesFinished +"\n"
+ "Average wait time: " + totalWaitTime / processesFinished +"\n" +
"Average response time: " + totalResponseTime / processesFinished +"\n"
+ "Throughput: " + processesFinished / quanta + " processes completed per quanta." +"\n";
/*System.out.println("\n");
System.out.println("Average turnaround time: " + totalTurnaroundTime / processesFinished);
System.out.println("Average wait time: " + totalWaitTime / processesFinished);
System.out.println("Average response time: " + totalResponseTime / processesFinished);
System.out.println("Throughput: " + processesFinished / quanta + " processes completed per quanta.");
System.out.println();*/
return averages;
}
public String getOut()
{
out = out +"\n";
return out;
}
} | devstudent123/Scheduling-Algorithms | SRT.java | 1,363 | // If the shortest process is done (execution time remaining == 0)
| line_comment | en | false | 1,199 | 16 | 1,363 | 16 | 1,383 | 15 | 1,363 | 16 | 1,787 | 16 | false | false | false | false | false | true |
18261_5 | public class oop {
public static void main(String[] args) {
Pen p1= new Pen();// create a pen obj called p1
p1.size=5;
System.out.println("Pen Size: "+p1.size);
p1.color="Yellow";
System.out.println("Pen Color: "+p1.color);
p1.setColor("Red"); //using setter function instead of direct assignment
System.out.println("New Pen Color after using Setter Function :"+p1.getcolor());
p1.setSize(8);//Using getter functions in place of accessing member variable directly
System.out.println("Updated pen size:"+p1.getsize());
BankAccount myAcc= new BankAccount();
//myAcc is an object of the type "BankAccount" and it has two instance variables
myAcc.usearname="Subhajyoti";
//myAcc.passwors="<PASSWORD>"; Not allowed to access the password directly from
//outside of this object, hence we need a method for setting it
myAcc.setpassword("<PASSWORD>");
}
}
//Getter and Setters
//Get:to return value
//Set:To change or assign or modify values
//this:this keyword is used to refer to current object
class BankAccount{
public String usearname;
private String passwors;
public void setpassword(String pwd){
passwors =pwd ;
}
}
class Pen{
String color;
int size;
String getcolor(){
return this.color;
}
int getsize(){
return this.size;
}
void setColor(String newcolor){
color= newcolor;
}
void setSize(int newsize){
size= newsize;
}
}
// access modifier
// acc mode | with in class| outside package | outside package by sub class | outside package
// private | y | n | n | n
// default | y | y | n | n
// protected | y | y | y | n
// public | y | y | y | y | tanXnyx/java_dsa | oop.java | 511 | //outside of this object, hence we need a method for setting it
| line_comment | en | false | 468 | 15 | 511 | 15 | 541 | 15 | 511 | 15 | 579 | 16 | false | false | false | false | false | true |
19027_11 | /*
Copyright (C) 2004 Geoffrey Alan Washburn
This program is free software; you can redistribute it and/or
modify it under the terms of the GNU General Public License
as published by the Free Software Foundation; either version 2
of the License, or (at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program; if not, write to the Free Software
Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307,
USA.
*/
import java.util.Iterator;
/**
* An abstract class for representing mazes, and the operations a {@link Client}
* in the {@link Maze} may wish to perform..
* @author Geoffrey Washburn <<a href="mailto:[email protected]">[email protected]</a>>
* @version $Id: Maze.java 343 2004-01-24 03:43:45Z geoffw $
*/
public abstract class Maze {
/* Maze Information ****************************************************/
/**
* Obtain a {@link Point} describing the size of the {@link Maze}.
* @return A {@link Point} where the method <code>getX</code> returns the maximum X
* coordintate, and the method <code>getY</code> returns the maximum Y coordinate.
*/
public abstract Point getSize();
/**
* Check whether a {@link Point} is within the bounds of the {@link Maze}.
* @return <code>true</code> if the point lies within the {@link Maze}, <code>false</code> otherwise.
*/
public abstract boolean checkBounds(Point point);
/**
* Obtain the {@link Cell} corresponding to a given {@link Point} in the {@link Maze}.
* @param point Location in the {@link Maze}.
* @return A {@link Cell} describing that location.
*/
public abstract Cell getCell(Point point);
/* Client functionality ************************************************/
/**
* Add a {@link Client} at random location in the {@link Maze}.
* @param client {@link Client} to be added to the {@link Maze}.
*/
public abstract void addClient(Client client);
/**
* Create a new {@link Projectile} from the specified {@link Client}
* @param client {@link Client} that is firing.
* @return <code>false</code> on failure, <code>true</code> on success. */
public abstract boolean clientFire(Client client);
/**
* Remove the specified {@link Client} from the {@link Maze}
* @param client {@link Client} to be removed.
*/
public abstract void removeClient(Client client);
/**
* Find out where a specified {@link Client} is located
* in the {@link Maze}.
* @param client The {@link Client} being located.
* @return A {@link Point} describing the location of the client. */
public abstract Point getClientPoint(Client client);
/**
* Find out the cardinal direction a {@link Client} is facing.
* @param client The {@link Client} being queried.
* @return The orientation of the specific {@link Client} as a {@link Direction}.
*/
public abstract Direction getClientOrientation(Client client);
/**
* Attempt to move a {@link Client} in the {@link Maze} forward.
* @param client {@link Client} to move.
* @return <code>true</code> if successful, <code>false</code> if failure.
*/
public abstract boolean moveClientForward(Client client);
/** Attempt to move a {@link Client} in the {@link Maze} backward.
* @param client {@link Client} to move.
* @return <code>true</code> if successful, false if failure.
*/
public abstract boolean moveClientBackward(Client client);
/**
* Obtain an {@link Iterator} over all {@link Client}s in the {@link Maze}
* @return {@link Iterator} over clients in the {@link Maze}.
*/
public abstract Iterator getClients();
/**
* Add a remote client to the maze in a given location with a given orientation
* @param client Client to be added to the maze
* @param point The point at which the remote client will spawn
* @param dir The starting orientation of the client
*/
public abstract void addRemoteClient(Client client, Point point, Direction dir);
public abstract void addRemoteClientScore(Client client, Point point, Direction dir, int score);
public abstract void missiletick();
/* Maze Listeners ******************************************************/
/**
* Register an object that wishes to be notified when the maze changes
* @param ml An object implementing the {@link MazeListener} interface.
* */
public abstract void addMazeListener(MazeListener ml);
/** Remove an object from the notification queue
* @param ml An object implementing the {@link MazeListener} interface.
*/
public abstract void removeMazeListener(MazeListener ml);
}
| sangaani/Lab2 | Maze.java | 1,225 | /**
* Find out the cardinal direction a {@link Client} is facing.
* @param client The {@link Client} being queried.
* @return The orientation of the specific {@link Client} as a {@link Direction}.
*/ | block_comment | en | false | 1,175 | 51 | 1,228 | 51 | 1,281 | 55 | 1,225 | 51 | 1,426 | 57 | false | false | false | false | false | true |
20117_71 | /* */ import javafx.event.ActionEvent;
/* */ import javafx.geometry.Pos;
/* */ import javafx.scene.Node;
/* */ import javafx.scene.Parent;
/* */ import javafx.scene.Scene;
/* */ import javafx.scene.control.Button;
/* */ import javafx.scene.control.Label;
/* */ import javafx.scene.layout.VBox;
/* */ import javafx.stage.Stage;
/* */
/* */ public class score
/* */ {//This class shows the final score, high score, and keeps track of the overall rounds and winning streaks
/* */ public static int p1streak;
/* */ public static int p2streak;
/* */ public static int p1rounds;
/* */ public static int p2rounds;
/* */ public static int temp;
/* */ public static int temp1;
/* 19 */ public static int highscore = 0;
/* 20 */ public static int games = 0;
/* */ public static void update(int w) { //This method updates the score by tracking how many rounds each player has won, and the high score
/* 22 */ games++;
/* 23 */ if (games == 3) {
/* 24 */ if (w == 1) {
/* 25 */ p1streak++;
/* 26 */ temp++;
/* 27 */ if (temp > highscore) {
/* 28 */ highscore = temp;
/* */ }
/* */ }
/* 31 */ if (w == 2) {
/* 32 */ p2streak++;
/* 33 */ temp1++;
/* 34 */ if (temp1 > highscore) {
/* 35 */ highscore = temp1;
/* */ }
/* */ }
/* 38 */ if (p1streak > p2streak) {
/* 39 */ p1rounds++;
/* */ }
/* 41 */ if (p2streak > p1streak) {
/* 42 */ p2rounds++;
/* */ }
/* */
/* 45 */ games = 0;
/* 46 */ p1streak = 0;
/* 47 */ p2streak = 0;
/* */ }
/* 49 */ if (w == 1) {
/* 50 */ p1streak++;
/* 51 */ temp++;
/* 52 */ if (temp > highscore) {
/* 53 */ highscore = temp;
/* */ }
/* 55 */ health.updateHealth(1);
/* */ }
/* 57 */ if (w == 2) {
/* 58 */ p2streak++;
/* 59 */ temp1++;
/* 60 */ if (temp1 > highscore) {
/* 61 */ highscore = temp1;
/* */ }
/* 63 */ health.updateHealth(2);
/* */ }
/* */ }
/* */
/* */
/* */
/* */ public static void showScore() {//This class shows the final window with the overall streaks and how many rounds have been won by each player
/* 70 */ Stage window = new Stage();
/* 71 */ window.setTitle("Score");
/* */
/* 73 */ Label p1score = new Label("Player one's streak: " + p1streak);
/* 74 */ Label p2score = new Label("Player two's streak: " + p2streak);
/* 75 */ Label p1Rounds = new Label("Player one's rounds: " + p1rounds);
/* 76 */ Label p2Rounds = new Label("Player two's rounds: " + p2rounds);
/* */
/* 78 */ Button exit = new Button("Exit");
/* 79 */ exit.setOnAction(e -> window.close());
/* */
/* */
/* */
/* 83 */ VBox layout = new VBox(10.0D);
/* 84 */ layout.getChildren().addAll((Object[])new Node[] { (Node)p1score, (Node)p2score, (Node)p1Rounds, (Node)p2Rounds, (Node)exit });
/* 85 */ layout.setAlignment(Pos.CENTER);
/* 86 */ Scene scene = new Scene((Parent)layout, 300.0D, 300.0D);
/* 87 */ scene.getStylesheets().add("game.css");
/* 88 */ window.setScene(scene);
/* 89 */ window.show();
/* */ }
/* */ public static void showHighScore() {//THis opens a window that shows the highest score, being the largest amount of rounds won
/* 92 */ Stage window = new Stage();
/* 93 */ window.setTitle("High Score");
/* */
/* 95 */ Label p1score = new Label("Highest winning streak: " + highscore);
/* */
/* 97 */ Button exit = new Button("exit");
/* 98 */ exit.setOnAction(e -> window.close());
/* */
/* */
/* */
/* 102 */ VBox layout = new VBox(10.0);
/* 103 */ layout.getChildren().addAll((Object[])new Node[] { (Node)p1score, (Node)exit });
/* 104 */ layout.setAlignment(Pos.CENTER);
/* 105 */ Scene scene = new Scene((Parent)layout, 300.0D, 300.0D);
/* 106 */ scene.getStylesheets().add("game.css");
/* 107 */ window.setScene(scene);
/* 108 */ window.show();
/* */ }
/* */ }
| KavitaDoobay/RockPaperScissors | score.java | 1,498 | //This class shows the final window with the overall streaks and how many rounds have been won by each player | line_comment | en | false | 1,381 | 22 | 1,498 | 23 | 1,466 | 21 | 1,498 | 23 | 1,541 | 23 | false | false | false | false | false | true |
20619_9 | /**
* Models a simple Car for the game Racer.
*
* @author Joe Finney ([email protected])
*/
public class Car
{
public static String CAR_COLOUR = "#FF0000";
public static String WHEEL_COLOUR = "#404040";
private Rectangle[] parts = new Rectangle[7];
private double xPosition;
private double yPosition;
private GameArena arena;
private double xSpeed;
private double ySpeed;
/**
* Creates a new Car, at the given location.
*
* @param x The x position on the screen of the centre of the car.
* @param y The y position on the screen of the centre of the car.
* @param a The GameArena upon which to draw this car.
*/
public Car(double x, double y, GameArena a)
{
parts[0] = new Rectangle(10, 20, 10, 20, WHEEL_COLOUR);
parts[1] = new Rectangle(10, 80, 10, 20, WHEEL_COLOUR);
parts[2] = new Rectangle(50, 20, 10, 20, WHEEL_COLOUR);
parts[3] = new Rectangle(50, 80, 10, 20, WHEEL_COLOUR);
parts[4] = new Rectangle(30, 50, 40, 70, CAR_COLOUR);
parts[5] = new Rectangle(15, 18, 5, 5, "WHITE");
parts[6] = new Rectangle(45, 18, 5, 5, "WHITE");
arena = a;
this.setXPosition(x);
this.setYPosition(y);
for (int i=0; i < parts.length; i++)
arena.addRectangle(parts[i]);
}
/**
* Changes the position of this car to the given location
*
* @param x The new x positition of this car on the screen.
*/
public void setXPosition(double x)
{
double dx = x - xPosition;
for (int i=0; i < parts.length; i++)
parts[i].setXPosition(parts[i].getXPosition() + dx);
xPosition = x;
}
/**
* Changes the position of this car to the given location
*
* @param y The new y positition of this car on the screen.
*/
public void setYPosition(double y)
{
double dy = y - yPosition;
for (int i=0; i < parts.length; i++)
parts[i].setYPosition(parts[i].getYPosition() + dy);
yPosition = y;
}
/**
* Determines the position of this car on the screen
*
* @return The x position of the centre of this car on the screen.
*/
public double getXPosition()
{
return xPosition;
}
/**
* Determines the position of this car on the screen
*
* @return The y co-ordinate of the centre of this car on the screen.
*/
public double getYPosition()
{
return yPosition;
}
/**
* Sets the speed of this car in the X axis - i.e. the number of pixels it moves in the X axis every time move() is called.
*
* @param s The new speed of this car in the x axis
*/
public void setXSpeed(double s)
{
xSpeed = s;
}
/**
* Sets the speed of this car in the Y axis - i.e. the number of pixels it moves in the Y axis every time move() is called.
*
* @param s The new speed of this car in the y axis
*/
public void setYSpeed(double s)
{
ySpeed = s;
}
/**
* Updates the position of this car by a small amount, depending upon its speed.
* see setXSpeed() and setYSpeed() methods.
*/
public void move()
{
this.setXPosition(xPosition + xSpeed);
this.setYPosition(yPosition + ySpeed);
}
/**
* Determines if this car is touching the given RoadSegment.
*
* @param s The segment of road to test against.
* @return true of this car is touching the given road segment, false otherwise.
*/
public boolean isTouching(RoadSegment s)
{
Rectangle[] roadParts = s.getParts();
for (int i=0; i < parts.length; i++)
for (int j=0; j < roadParts.length; j++)
if(parts[i].isTouching(roadParts[j]))
return true;
return false;
}
}
| finneyj/Racer | Car.java | 1,126 | /**
* Determines if this car is touching the given RoadSegment.
*
* @param s The segment of road to test against.
* @return true of this car is touching the given road segment, false otherwise.
*/ | block_comment | en | false | 1,061 | 49 | 1,126 | 51 | 1,199 | 54 | 1,126 | 51 | 1,305 | 59 | false | false | false | false | false | true |
21019_2 | import java.util.*;
public class Hotel {
public static void main(String[] args) {
// ["+1A", "+3E", "-1A", "+4F", "+1A", "-3E"]
String[] books1 = { "+1A", "+3E", "-1A", "+4F", "+1A", "-3E" };
String[] books2 = {"+1A","+3F","+2B"};
String[] books3 = {"+1E", "-1E", "+1E", "-1E", "+1E", "-1E", "+1E", "-1E","+2A", "-2A", "+2A", "-2A", "+2A", "-2A", "+2A",
"-2A","+2B", "-2B", "+2B", "-2B", "+2B", "-2B", "+2B", "-2B"};
System.out.println(solution(books1));
System.out.println(solution(books2));
System.out.println(solution(books3));
}
static class Room implements Comparable<Room>{
public String no;
public int book;
public Room(String no) {
this.no = no;
}
@Override
// The compareTo method is a little bit differet from my orignal solution.
// I use all the time to figure why my code give a null pointer exception.
// Hence, I don't have time to check the result of my compareTo.
// The compareTo method in my solution will give an opposite result of this one.
public int compareTo(Room o) {
if (this.book < o.book) {
return -1;
} else if (this.book > o.book) {
return 1;
} else {
return -this.no.compareTo(o.no);
}
}
}
private static String solution(String[] A) {
Room[] res = new Room[260];
for(int i = 0 ; i < res.length; i++) {
char[] ch = new char[2];
char f = (char)(i/26 + '0');
char n = (char)(i%26 + 'A');
ch[0] = f;
ch[1] = n;
res[i] = new Room(new String(ch));
}
for(String str : A) {
if(str.charAt(0) == '+') {
int floor = str.charAt(1) - '0';
int cell = (str.charAt(2) - 'A');
int id = floor * 26 + cell;
res[id].book += 1; // This line give a nullPointerException
}
}
Arrays.sort(res);
return res[res.length - 1].no;
}
}
| ruoyangqiu/Leetcode | Hotel.java | 701 | // I use all the time to figure why my code give a null pointer exception. | line_comment | en | false | 615 | 17 | 701 | 17 | 703 | 17 | 701 | 17 | 828 | 17 | false | false | false | false | false | true |
22558_12 | package posix;
/** Read and write memory reachable through a C ptr. Memory access is
bounds checked to keep it within the size of region addressed by
the C ptr. Only classes within the posix package can create CPtr objects,
and the use of this class is completely safe at present. This is
because we know the size of, for instance, shared memory segments or
memory allocated with C malloc. At some future date, we may need the
ability to dereference arbitrary C pointers - those dereferences will
be unsafe.
<p>
We have not yet implemented the floating and 64-bit types for get/set
due to a lack of need.
@author <a href="mailto:[email protected]">Stuart D. Gathman</a>
Copyright (C) 1998 Business Management Systems, Inc. <br>
<p>
This code is distributed under the
<a href="http://www.gnu.org/copyleft/lgpl.html">
GNU Library General Public License </a>
<p>
This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Library General Public
License as published by the Free Software Foundation; either
version 2 of the License, or (at your option) any later version.
<p>
This library is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
Library General Public License for more details.
<p>
You should have received a copy of the GNU Library General Public
License along with this library; if not, write to the
Free Software Foundation, Inc., 59 Temple Place - Suite 330,
Boston, MA 02111-1307, USA.
*/
public class CPtr {
long addr;
int size;
/** A null CPtr value. */
static final long NULL = getNULL();
CPtr() { }
CPtr(long addr,int size) {
this.addr = addr;
this.size = size;
}
private static final long getNULL() {
System.loadLibrary("posix");
return init();
}
private static native long init();
/** Type codes for <code>alignOf()</code> and <code>sizeOf()</code>. */
public static final int
CBYTE_TYPE = 0,
CSHORT_TYPE = 1,
CINT_TYPE = 2,
CLONG_TYPE = 3,
CFLT_TYPE = 4,
CDBL_TYPE = 5,
CPTR_TYPE = 6;
/** Get the alignment of a C type. Can be used to compute C struct
offsets in a mostly system independent manner.
*/
public static native int alignOf(int type);
/** Get the size of a C type. Can be used to compute C struct
offsets in a mostly system independent manner.
*/
public static native int sizeOf(int type);
/** Compute the offsets of a C struct one member at a time. This
is supposed to reflect what a C compiler would do. I can't think
of a better way to track C data structs with code that doesn't get
recompiled. A config file could do it, but would be even
more work. Some C compilers will do surprising things - like
padding structs that contain only 'char' members. They do this to
avoid cache misses at the beginning of the struct - or to make struct
pointers uniform on word addressable machines (e.g. PDP20).
You can work around this for now with the
<code>addMember</code> method - provided you can figure out <u>when</u>
to do so. Please report any problems you encounter - we can add
additional native methods, e.g. 'structAlign' to return minimum
struct alignment.
*/
public static class Struct {
private int offset = 0;
private int align = 0; // maximum alignment in struct
/** Initialize with the offset (within a CPtr) of the C struct.
*/
public Struct(int offset) { this.offset = offset; }
/** Return the offset of the next member. */
public final int offsetOf(int type) {
return offsetOf(type,1);
}
/** Return the offset of the next array member. */
public final int offsetOf(int type,int len) {
return addMember(len * sizeOf(type),alignOf(type) - 1);
}
/** Add a member by size and alignment mask. Return the member
offset.
*/
public final int addMember(int size,int mask) {
int pos = (offset + mask) & ~mask; // align for this member
offset = pos + size;
if (mask > align) align = mask;
return pos;
}
/** Return the offset of a nested struct. The members must have
already been added to the nested struct so that it will have
the proper size and alignment.
*/
public final int offsetOf(Struct s,int cnt) {
return addMember(cnt * s.size(),s.align);
}
/** Return total struct size including padding to reflect
maximum alignment. */
public final int size() {
return (offset + align) & ~align;
}
}
/** Copy bytes out of C memory into a Java byte array. */
public native void copyOut(int off,byte[] ba,int pos,int cnt);
/** Copy a Java byte array into C memory. */
public native void copyIn(int off,byte[] ba,int pos,int cnt);
public native byte getByte(int off);
public native void setByte(int off,byte val);
public native short getShort(int off);
public native void setShort(int off,short val);
public native int getInt(int off);
public native void setInt(int off,int val);
public native short getCShort(int off,int idx);
public native void setCShort(int off,int idx,short val);
public native int getCInt(int off,int idx);
public native void setCInt(int off,int idx,int val);
public short getCShort(int off) { return getCShort(off,0); }
public void setCShort(int off,short val ) { setCShort(off,0,val); }
public int getCInt(int off) { return getCInt(off,0); }
public void setCInt(int off,int val) { setCInt(off,0,val); }
}
| delonnewman/java-posix | CPtr.java | 1,503 | /** Return the offset of a nested struct. The members must have
already been added to the nested struct so that it will have
the proper size and alignment.
*/ | block_comment | en | false | 1,414 | 36 | 1,503 | 37 | 1,592 | 38 | 1,503 | 37 | 1,698 | 39 | false | false | false | false | false | true |
24100_9 | /**
* @author Alena Fisher
*/
import java.util.ArrayList;
public class Coach {
// Creating instance variables
private String name;
private String title;
private String department;
private String officeLocation;
private String phoneNumber;
private String email;
public Coach(String name, String title, String department, String officeLocation, String phoneNumber, String email) {
/**
* This method receives 'name', 'title', 'department', 'officeLocation', 'phoneNumber', and 'email' as explicit parameters and assigns them to the instance variables
*/
this.name = name;
this.title = title;
this.department = department;
this.officeLocation = officeLocation;
this.phoneNumber = phoneNumber;
this.email = email;
}
public String getCoachName() {
/**
* This method returns the coach's name
*/
return name;
}
public String getOfficeLocation() {
/**
* This method returns the coach's office location
*/
return officeLocation;
}
public String getTitle() {
/**
* This method returns the coach's title
*/
return title;
}
public String getDepartment() {
/**
* This method returns the coach's department
*/
return department;
}
public String getPhoneNumber() {
/**
* This method returns the coach's phone number
*/
return phoneNumber;
}
public String getEmail() {
/**
* This method returns the coach's email address
*/
return email;
}
public void setCoachName(String name) {
/**
* This method receives 'name' as an explicit parameter and assigns it to the instance variable
*/
this.name = name;
}
public void setOfficeLocation(String officeLocation) {
/**
* This method receives 'officeLocation' as an explicit parameter and assigns it to the instance variable
*/
this.officeLocation = officeLocation;
}
public void setTitle(String title) {
/**
* This method receives 'title' as an explicit parameter and assigns it to the instance variable
*/
this.title = title;
}
public void setDepartment(String department) {
/**
* This method receives 'department' as an explicit parameter and assigns it to the instance variable
*/
this.department = department;
}
public void setPhoneNumber(String phoneNumber) {
/**
* This method receives 'phoneNumber' as an explicit parameter and assigns it to the instance variable
*/
this.phoneNumber = phoneNumber;
}
public void setEmail(String email) {
/**
* This method receives 'email' as an explicit parameter and assigns it to the instance variable
*/
this.email = email;
}
}
| AlenaFisher/CS234 | S3/Coach.java | 606 | /**
* This method receives 'name' as an explicit parameter and assigns it to the instance variable
*/ | block_comment | en | false | 576 | 23 | 606 | 22 | 727 | 25 | 606 | 22 | 777 | 27 | false | false | false | false | false | true |
24927_5 | // 1 dist, 1 exe build in the package
ReleaseTemplate.release("community") {
distribution("standard").from {
exe = Launch4jExeTemplate.exe {
from = "/release/standard/exe"
}
companionFiles = "/release/standard/companion"
}
}
// or could we do dist ?
ReleaseTemplate.release("community") {
dist {
exe = Launch4jExeTemplate.exe {
from = "/release/standard/exe"
}
companionFiles = "/release/standard/companion"
}
}
// or with a distribution template, could be shortened still more
ReleaseTemplate.release("community") {
distribution("standard").from {
template = Launch4jDistributionTemplate.dist {
resourcesDir = "/release/standard"
}
}
}
// or better yet?
ReleaseTemplate.release("community") {
dist(Launch4jDistributionTemplate){
resourcesDir = "/release/community/gui"
}
}
// or better yet?
// we can translate the release name from either camel case or snake case.
// The distribution will assume we are using the default distribution (for this release name) if none
// is provided we can either create or retrieve it as necessary.
task communityRelease {
dist(Launch4jDistributionTemplate){
resourcesDir = "/release/community/gui"
}
}
// accessors
releases.community.distributions.community.resourcesDir
releases.community.distributions.community.exeTask
releases.community.distributions.community.distributionBuildTask
releases.community.distributions.community.distributionAssembleTask
// 1 dist, 2 exe builds in the package
// N.B. would require that the names of the outputs from the exe tasks MUST be different!
ReleaseTemplate.release("community") {
dist {
template = Launch4jDistributionTemplate.dist {
exe("gui") {
resourcesDir = "/release/community/gui"
custom {
headerType = "gui"
}
}
exe("console") {
resourcesDir = "/release/community/console"
custom {
headerType = "console"
}
}
}
}
}
// or this! We could define some kind of an interface
// that would require either a no-args constructor
// or a constructor(Project).
ReleaseTemplate.release("community") {
dist(Launch4jDistributionTemplate){
exe("gui") {
resourcesDir = "/release/community/gui"
config {
headerType = "gui"
}
}
exe("console") {
resourcesDir = "/release/community/console"
config {
headerType = "console"
}
}
}
}
// or, considering launch4j.properties...
task communityRelease(type: ReleaseTemplateTask) {
dist(Launch4jDistributionTemplate){
exe("gui") {
resourcesDir = "/release/community/shared"
config("/release/shared/launch4j.properties") {
myCustomProperty = "someCustomValue"
dependsOn someCustomJarTask
copyConfigurable = someCustomJarTask.outputs.files
}
}
exe("console") {
resourcesDir = "/release/community/shared"
}
}
}
// 2 dist, 1 exe in each package
ReleaseTemplate.release("allEditions") {
distribution("community").from {
template = Launch4jDistributionTemplate.dist {
resourcesDir = "/editions/community"
}
}
distribution("ultimate").from {
template = Launch4jDistributionTemplate.dist {
resourcesDir = "/editions/ultimate"
}
}
}
// 2 dist, 2 exe builds in each package
ReleaseTemplate.release("community") {
dist("community", Launch4jDistributionTemplate){
exe("gui") {
resourcesDir = "/release/community/gui" // copies exe build info and companions
custom {
headerType = "gui"
}
}
exe("console") {
resourcesDir = "/release/community/console"
custom {
headerType = "console"
}
}
}
dist("ultimate", Launch4jDistributionTemplate){
exe("gui") {
resourcesDir = "/release/ultimate/gui"
custom {
headerType = "gui"
}
}
exe("console") {
resourcesDir = "/release/ultimate/console"
custom {
headerType = "console"
}
}
}
}
// and considering breaking the whole thing down into more manageable pieces
task communityDistribution(type: Launch4jDistributionTemplateTask) {
exe("gui", Launch4jExeTemplate) {
resourcesDir = "/release/community/shared"
config("/release/shared/launch4j.properties") {
myCustomProperty = "someCustomValue"
dependsOn someCustomJarTask
copyConfigurable = someCustomJarTask.outputs.files
}
}
exe("console", Launch4jExeTemplate) {
resourcesDir = "/release/community/shared"
}
}
// and breaking the exe build out of the distribution...
task communityDisributionGuiExe(type: Launch4jExeTemplateTask) {
resourcesDir = "/release/community/shared"
config {
myCustomProperty = "someCustomValue"
dependsOn someCustomJarTask
copyConfigurable = someCustomJarTask.outputs.files
}
}
| alessandroscarlatti/launch4j-gradle-plugin | syntax-demo.java | 1,337 | // we can translate the release name from either camel case or snake case. | line_comment | en | false | 1,167 | 15 | 1,337 | 15 | 1,312 | 15 | 1,337 | 15 | 1,569 | 17 | false | false | false | false | false | true |
25044_13 |
import java.util.Random;
/**
* A Deck of 52 Cards which can be dealt and shuffled
*
* Some functions could be made much faster with some extra memory.
* I invite anyone to do so ;-)
*
* <P>Source Code: <A HREF="http://www.cs.ualberta.ca/~davidson/poker/src/poker/Deck.java">Deck.java</A><P>
*
* @author Aaron Davidson
* @version 1.0.1
*/
public class Deck {
public static final int NUM_CARDS = 52;
private Card[] gCards = new Card[NUM_CARDS];
private char position;
private Random r = new Random();
/**
* Constructor.
*/
public Deck() {
position = 0;
for (int i=0;i<NUM_CARDS;i++) {
gCards[i] = new Card(i);
}
}
/**
* Constructor w/ shuffle seed.
* @param seed the seed to use in randomly shuffling the deck.
*/
public Deck(long seed) {
this();
if (seed == 0) seed = System.currentTimeMillis();
r.setSeed(seed);
}
/**
* Places all cards back into the deck.
* Note: Does not sort the deck.
*/
public void reset() { position = 0; }
/**
* Shuffles the cards in the deck.
*/
public void shuffle() {
Card tempCard;
int i,j;
for (i=0; i<NUM_CARDS; i++) {
j = i + randInt(NUM_CARDS-i);
tempCard = gCards[j];
gCards[j] = gCards[i];
gCards[i] = tempCard;
}
position = 0;
}
/**
* Obtain the next card in the deck.
* If no cards remain, a null card is returned
* @return the card dealt
*/
public Card deal() {
return (position < NUM_CARDS ? gCards[position++] : null);
}
/**
* Find position of Card in Deck.
*/
public int findCard(Card c) {
int i = position;
int n = c.getIndex();
while (i < NUM_CARDS && n != gCards[i].getIndex())
i++;
return (i < NUM_CARDS ? i : -1);
}
private int findDiscard(Card c) {
int i = 0;
int n = c.getIndex();
while (i < position && n != gCards[i].getIndex())
i++;
return (n == gCards[i].getIndex() ? i : -1);
}
/**
* Remove all cards in the given hand from the Deck.
*/
public void extractHand(Hand h) {
for (int i=1;i<=h.size();i++)
this.extractCard(h.getCard(i));
}
/**
* Remove a card from within the deck.
* @param c the card to remove.
*/
public void extractCard(Card c) {
int i = findCard(c);
if (i != -1) {
Card t = gCards[i];
gCards[i] = gCards[position];
gCards[position] = t;
position++;
} else {
System.err.println("*** ERROR: could not find card " + c);
}
}
/**
* Remove and return a randomly selected card from within the deck.
*/
public Card extractRandomCard() {
int pos = position+randInt(NUM_CARDS-position);
Card c = gCards[pos];
gCards[pos] = gCards[position];
gCards[position] = c;
position++;
return c;
}
/**
* Return a randomly selected card from within the deck without removing it.
*/
public Card pickRandomCard() {
return gCards[position+randInt(NUM_CARDS-position)];
}
/**
* Place a card back into the deck.
* @param c the card to insert.
*/
public void replaceCard(Card c) {
int i = findDiscard(c);
if (i != -1) {
position--;
Card t = gCards[i];
gCards[i] = gCards[position];
gCards[position] = t;
}
}
/**
* Obtain the position of the top card.
* (the number of cards dealt from the deck)
* @return the top card index
*/
public int getTopCardIndex() {
return position;
}
/**
* Obtain the number of cards left in the deck
*/
public int cardsLeft() {
return NUM_CARDS-position;
}
/**
* Obtain the card at a specific index in the deck.
* Does not matter if card has been dealt or not.
* If i < topCardIndex it has been dealt.
* @param i the index into the deck (0..51)
* @return the card at position i
*/
public Card getCard(int i) {
return gCards[i];
}
public String toString() {
StringBuffer s = new StringBuffer();
s.append("* ");
for (int i=0;i<position;i++)
s.append(gCards[i].toString()+" ");
s.append("\n* ");
for (int i=position;i<NUM_CARDS;i++)
s.append(gCards[i].toString()+" ");
return s.toString();
}
private int randInt(int range) {
return (int)(r.nextDouble()*range);
}
}
| lukassaul/kelly-poker | Deck.java | 1,429 | /**
* Obtain the number of cards left in the deck
*/ | block_comment | en | false | 1,190 | 15 | 1,433 | 15 | 1,510 | 17 | 1,429 | 14 | 1,725 | 19 | false | false | false | false | false | true |
25245_0 | //write a program to calculate the area of square & rectangle overloading the area method.
class p6
{
void area(int l)
{
System.out.println("Area of square=> "+(l*l));
}
void area(int l,int b)
{
System.out.println("Area of Rectangle=> "+(l*b));
}
public static void main(String []args)
{
p6 one=new p6();
one.area(6);
one.area(8,8);
}
}
| Rutvik5o/Practice-Programming | p6.java | 128 | //write a program to calculate the area of square & rectangle overloading the area method.
| line_comment | en | false | 109 | 19 | 128 | 19 | 151 | 17 | 128 | 19 | 155 | 18 | false | false | false | false | false | true |
25670_6 | /*
* class Customer defines a registered customer. It keeps track of the customer's name and address.
* A unique id is generated when when a new customer is created.
*
* Implement the Comparable interface and compare two customers based on name
*/
public class Customer implements Comparable<Customer>
{
private String id;
private String name;
private String shippingAddress;
Cart cart;
/** Main constructor that creates a customer with their specified id, name and address.
*
* @param id - is the string id of the customer.
* @param name - is the string name of the customer.
* @param address - is the address of the customer in a string.
*/
public Customer(String id, String name, String address)
{
this.id = id;
this.name = name;
this.shippingAddress = address;
cart = new Cart(id);
}
/** Constructor for customer.
* @param id - is the assigned id to a customer.
*/
public Customer(String id)
{
this.id = id;
this.name = "";
this.shippingAddress = "";
}
/** Constructor that creates a customer with their specified id, name, address and cart.
*
* @param id - is the string id of the customer.
* @param name - is the string name of the customer.
* @param address - is the address of the customer in a string.
* @param cart - is the cart assigned to the customer
*/
public Customer(String id, String name, String address, Cart cart)
{
this.id = id;
this.name = name;
this.shippingAddress = address;
this.cart = cart;
}
/** Gets the id of the customer.
* @return the id of the customer.
*/
public String getId()
{
return id;
}
/*
* Set the id for the customer.
*/
public void setId(String id)
{
this.id = id;
}
/** Gets the name of the customer.
* @return the name of the customer.
*/
public String getName()
{
return name;
}
/*
* Set the name of the customer.
*/
public void setName(String name)
{
this.name = name;
}
/** Gets the shipping address of the customer.
* @return the shipping address of the customer.
*/
public String getShippingAddress()
{
return shippingAddress;
}
/*
* Set the shipping address of the customer.
*/
public void setShippingAddress(String shippingAddress)
{
this.shippingAddress = shippingAddress;
}
/** Gets the cart that belongs to the customer.
* @return the customer's cart.
*/
public Cart getCustCart()
{
return cart;
}
/*
* Gives a string representation of the customer object.
* Prints the name, id and shipping address of the customer as a formatted string.
*/
public void print()
{
System.out.printf("\nName: %-20s ID: %3s Address: %-35s", name, id, shippingAddress);
}
/*
* Two customers are equal if they have the same product Id.
* This method is inherited from superclass Object and overridden here
*/
public boolean equals(Object other)
{
Customer otherC = (Customer) other;
return this.id.equals(otherC.id);
}
//compareTo method (comparable interface) for SORTCUSTS action
public int compareTo(Customer otherCust) {
return this.getName().compareTo(otherCust.getName());
}
}
| jenniferchung14/E-Commerce-System-Simulator | Customer.java | 912 | /** Gets the name of the customer.
* @return the name of the customer.
*/ | block_comment | en | false | 785 | 20 | 912 | 22 | 980 | 22 | 912 | 22 | 1,059 | 23 | false | false | false | false | false | true |
26033_2 | import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.Statement;
import java.text.SimpleDateFormat;
import java.time.LocalDate;
import java.time.temporal.TemporalField;
import java.util.concurrent.Exchanger;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
public class ForumDB {
private Connection connection;
private int id = 0;
/*
* Constructor for the ForumDB class
*
* @return a new forumdb object
*/
public ForumDB() {
try {
Class.forName("org.sqlite.JDBC");
connection = DriverManager.getConnection("JDBC:sqlite:forum.db");
} catch (Exception e) {
e.printStackTrace();
}
}
/*
* Prints all the users from the database
*/
public void printUsers() {
try {
var s = connection.createStatement();
System.out.println("Current users:");
var rs = s.executeQuery("select name from Users;");
while (rs.next()) {
System.out.println(rs.getString("name"));
}
s.close();
} catch (Exception e) {
e.printStackTrace();
}
}
/*
* Adds a new subforum to the forum
*
* @param name the name of the subforum to be added
*/
public void addSubforum(String name) {
try {
var ps = connection.prepareStatement("INSERT INTO Subforum (name) VALUES (?);");
ps.setString(1, name);
ps.executeUpdate();
ps.close();
} catch (Exception e) {
e.printStackTrace();
}
}
/*
* Adds a new post to the subforum
*
* @param subforum_id id of the subforum where post is to be added
* @param post_title heading of the post to be added
* @param post_body body, the text of the forum post to be added
* @param post_date the purported date when the post was posted
* @param userid the id of the user who posted the post
*/
public void addPostToSubforum(int subforum_id, String post_title, String post_body, String post_date,
int userid)
{
try {
String post_text = post_title.toUpperCase() + "\n\n" + post_body;
var ps = connection.prepareStatement("INSERT INTO Posts (userid, subforumid, time, text) VALUES (?, ?, ?, ?);");
ps.setInt(1, userid);
ps.setInt(2, subforum_id);
ps.setString(3, post_date);
ps.setString(4, post_text);
ps.executeUpdate();
ps.close();
} catch (Exception e) {
e.printStackTrace();
}
}
/*
* Censors a subforum post based on id
*
* @param postID the id of the post to be censored.
*/
public void censorPost (int postID) {
try {
var ps = connection.prepareStatement("UPDATE Posts SET body = '[CENSORED]' WHERE id = ?;");
ps.setInt(1, postID);
ps.executeUpdate();
ps.close();
} catch (Exception e) {
e.printStackTrace();
}
}
/*
* Sets the body of the post to a specified string.
*
* @param postID id of the post to be altered
* @param body the text string that the body of the post is going to be replaced with
*/
public void setPostBody (int postID, String body) {
try {
var ps = connection.prepareStatement("UPDATE Posts SET text = ? WHERE id = ?;");
ps.setString(1, body);
ps.setInt(2, postID);
ps.executeUpdate();
ps.close();
} catch (Exception e) {
e.printStackTrace();
}
}
/*
* Adds a user to the list of moderators based on the id
*
* @param userID id of the user to be promoted to the moderator status
*/
public void appointModerator(int userID) {
try {
var ps = connection.prepareStatement("INSERT INTO ModeratorList (userid) SELECT Users.id FROM Users WHERE Users.id = ?;");
ps.setInt(1, userID);
ps.executeUpdate();
} catch (Exception e) {
e.printStackTrace();
}
}
/*
* Gets the name of the user with the specified id
*
* @param userid id of the user to get the username of
* @return the name of the user
*/
public String getUserName(int userid) {
try {
var ps = connection.prepareStatement("select name from Users where id = ?;");
ps.setInt(1, userid);
var rs = ps.executeQuery();
rs.next();
System.out.println(rs.getString("name"));
String name = rs.getString("name");
ps.close();
return name;
} catch (Exception e) {
e.printStackTrace();
return e.getStackTrace().toString();
}
}
/*
* set
*/
public void setUserName(int userid, String name) {
try {
var ps = connection.prepareStatement("UPDATE Users SET name=? where id = ?;");
ps.setString(1, name);
ps.setInt(2, userid);
ps.executeUpdate();
ps.close();
} catch (Exception e) {
e.printStackTrace();
}
}
public Post createPost(String title, String body, Date date, int authorId) {
int postID = -1; //is supposed to be a post containing [ERROR]
try {
var ps = connection.prepareStatement("INSERT INTO Posts (title, body, userid, date) VALUES (?, ?, ?, ?) RETURNING id ;");
ps.setString(1, title);
ps.setString(2, body);
ps.setInt(3, authorId);
ps.setString(4, new SimpleDateFormat("yyyy-MM-dd").format(Calendar.getInstance().getTime()));
var rs = ps.executeQuery();
postID = rs.getInt("id");
rs.close();
ps.close();
return new Post(postID, this);
} catch (Exception e) {
e.printStackTrace();
return new Post(postID, this);
}
}
public String getPostTitle(int id) {
try {
var ps = connection.prepareStatement("SELECT title FROM Posts WHERE id = ?;");
ps.setInt(1, id);
ResultSet rs = ps.executeQuery();
String title = rs.getString("title");
ps.close();
rs.close();
return title;
} catch (Exception e) {
e.printStackTrace();
return "[ERROR]" + e.getStackTrace();
}
}
public String getPostBody(int postId) {
try {
var ps = connection.prepareStatement("SELECT body FROM Posts WHERE id = ?;");
ps.setInt(1, postId);
ResultSet rs = ps.executeQuery();
String body = rs.getString("body");
ps.close();
rs.close();
return body;
} catch (Exception e) {
e.printStackTrace();
return "[ERROR]" + e.getStackTrace();
}
}
public String getPostDate(int id) {
try {
var ps = connection.prepareStatement("SELECT date FROM Posts WHERE id = ?;");
ps.setInt(1, id);
ResultSet rs = ps.executeQuery();
String date = rs.getString("date");
ps.close();
rs.close();
return date;
} catch (Exception e) {
e.printStackTrace();
return new Date().toString();
}
}
public String getPostAuthor(int postId) {
try {
var ps = connection.prepareStatement("SELECT name FROM Users, Posts WHERE Posts.userid = Users.id AND Posts.id = ?;");
ps.setInt(1, postId);
ResultSet rs = ps.executeQuery();
String name = rs.getString("name");
ps.close();
rs.close();
return name;
} catch (Exception e) {
e.printStackTrace();
return "[ERROR]";
}
}
public Subforum[] getSubforums() {
List<Subforum> subforums = new ArrayList<Subforum>();
try {
var s = connection.createStatement();
var rs = s.executeQuery("SELECT id FROM Subforum;");
while (rs.next()) {
subforums.add(new Subforum(rs.getInt("id"), this));
}
s.close();
rs.close();
} catch (Exception e) {
e.printStackTrace();
}
return subforums.toArray(new Subforum[0]);
}
public String getSubforumTitle(int id) {
try {
var ps = connection.prepareStatement("SELECT name FROM Subforum WHERE id = ?;");
ps.setInt(1, id);
ResultSet rs = ps.executeQuery();
String title = rs.getString("name");
ps.close();
rs.close();
return title;
} catch (Exception e) {
e.printStackTrace();
return "[ERROR]" + e.getStackTrace();
}
}
public Post[] getSubforumPosts(int subforum_id) {
List<Post> posts = new ArrayList<Post>();
try {
var ps = connection.prepareStatement("SELECT id FROM Posts WHERE subforumid = ?;");
ps.setInt(1, subforum_id);
var rs = ps.executeQuery();
while (rs.next()) {
posts.add(new Post(rs.getInt("id"), this));
}
ps.close();
rs.close();
} catch (Exception e) {
e.printStackTrace();
}
return posts.toArray(new Post[0]);
}
public void postPostToSubforum(int subforum_id, int post_id) {
try {
var ps = connection.prepareStatement("UPDATE Posts SET subforumid = ? WHERE id = ?;");
ps.setInt(1, subforum_id);
ps.setInt(2, post_id);
ps.executeUpdate();
ps.close();
} catch (Exception e) {
e.printStackTrace();
}
}
public void removePostFromSubforum(int post_id) {
try {
var ps = connection.prepareStatement("UPDATE Posts SET subforumid = NULL WHERE id = ?;");
ps.setInt(1, post_id);
ps.executeUpdate();
ps.close();
} catch (Exception e) {
e.printStackTrace();
}
}
private boolean isUserAdmin(int userid) {
boolean result = false;
try {
var ps = connection.prepareStatement("SELECT * FROM AdminList WHERE userid = ?;");
ps.setInt(1, userid);
ResultSet rs = ps.executeQuery();
if(rs.isBeforeFirst()) { // it returned something
result = true;
}
ps.close();
rs.close();
} catch (Exception e) {
e.printStackTrace();
}
return result;
}
private boolean isUserModerator(int userid) {
boolean result = false;
try {
var ps = connection.prepareStatement("SELECT * FROM ModeratorList WHERE userid = ?;");
ps.setInt(1, userid);
ResultSet rs = ps.executeQuery();
if(rs.isBeforeFirst()) { // it returned something
result = true;
}
ps.close();
rs.close();
} catch (Exception e) {
e.printStackTrace();
}
return result;
}
public User getUser(int userid) {
try {
if(getUserName(userid).equals("null")) {
return null;
}
else if (isUserAdmin(userid)) {
return new Admin(userid, this);
}
else if (isUserModerator(userid)) {
return new Moderator(userid, this);
}
else
{
return new User(userid, this);
}
} catch (Exception e) {
e.printStackTrace();
return null;
}
}
}
| c00291296/java-forum | ForumDB.java | 2,715 | /*
* Adds a new subforum to the forum
*
* @param name the name of the subforum to be added
*/ | block_comment | en | false | 2,458 | 32 | 2,715 | 29 | 3,029 | 34 | 2,715 | 29 | 3,268 | 35 | false | false | false | false | false | true |
27718_2 | // https://www.hackerearth.com/practice/data-structures/disjoint-data-strutures/basics-of-disjoint-data-structures/practice-problems/algorithm/marriage-problem/editorial/
/* package whatever; // don't place package name! */
import java.util.*;
import java.lang.*;
import java.io.*;
/* Name of the class has to be "Main" only if the class is public. */
class Ideone
{
int parent[], women[], men[], size[];
public void union(int a, int b) {
int u = find(a);
int v = find(b);
if (u == v) return;
if (size[u] > size[v]) {
parent[v] = u;
women[u] += women[v];
men[u] += men[v];
size[u] += size[v];
} else {
parent[u] = v;
women[v] += women[u];
men[v] += men[u];
size[v] += size[u];
}
}
public int find(int a) {
while (parent[a] != a) {
a = parent[a];
}
return a;
}
public static void main (String[] args) throws java.lang.Exception
{
Scanner sc = new Scanner(System.in);
int x = sc.nextInt(), y = sc.nextInt(), q1 = sc.nextInt();
parent = new int[x+y]; men = new int[x+y]; women = new int[x+y]; size = new int[x+y];
for (int i = 0; i < x+y; i++) {
parent[i] = i;
size[i] = 1;
women[i] = 0;
men[i] = 0;
if (i < x) men[i] = 1;
else women[i] = 1;
}
while(q1--) {
a = sc.nextInt(); b = sc.nextInt();
union(a, b);
}
int q2 = sc.nextInt();
while(q2--) {
a = sc.nextInt()+x; b = sc.nextInt()+x;
union(a, b);
}
int q3 = sc.nextInt();
while(q3--) {
a = sc.nextInt(); b = sc.nextInt()+x;
union(a, b);
}
HashMap<Integer, LinkedList<Integer>> cc = new HashMap<Integer, LinkedList<Integer>>();
int ans = 0;
for (for int i = 0; i < x; i++) {
ans += (y - women[find(i)]);
}
System.out.println(ans);
}
}
| maiquynhtruong/algorithms-and-problems | marriage-problem.java | 699 | /* Name of the class has to be "Main" only if the class is public. */ | block_comment | en | false | 561 | 19 | 699 | 19 | 692 | 19 | 699 | 19 | 807 | 19 | false | false | false | false | false | true |
29683_0 | public class House implements Cloneable, Comparable<House> {
private int id;
private double area;
private java.util.Date whenBuilt;
public House(int id, double area) {
this.id = id;
this.area = area;
whenBuilt = new java.util.Date();
}
public int getId() {
return id;
}
public double getArea() {
return area;
}
public java.util.Date getWhenBuilt() {
return whenBuilt;
}
@Override /** Override the protected clone method defined in
the Object class, and strengthen its accessibility */
public Object clone() {
try {
return super.clone();
}
catch (CloneNotSupportedException ex) {
return null;
}
}
@Override // Implement the compareTo method defined in Comparable
public int compareTo(House o) {
if (area > o.area)
return 1;
else if (area < o.area)
return -1;
else
return 0;
}
}
| rdejong/LiangJava | House.java | 234 | /** Override the protected clone method defined in
the Object class, and strengthen its accessibility */ | block_comment | en | false | 223 | 19 | 234 | 20 | 276 | 20 | 234 | 20 | 297 | 23 | false | false | false | false | false | 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 | 644 | 23 | 677 | 22 | 734 | 26 | 677 | 22 | 842 | 27 | false | false | false | false | false | 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 | 1,606 | 49 | 1,583 | 46 | 1,724 | 51 | 1,583 | 46 | 1,985 | 52 | false | false | false | false | false | 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 | 330 | 73 | 393 | 73 | 403 | 80 | 393 | 73 | 459 | 85 | false | false | false | false | false | 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 | 659 | 24 | 727 | 22 | 782 | 24 | 727 | 22 | 868 | 26 | false | false | false | false | false | true |
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 | 645 | 23 | 702 | 24 | 738 | 24 | 702 | 24 | 791 | 25 | false | false | false | false | false | true |
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 | 337 | 17 | 376 | 17 | 395 | 17 | 376 | 17 | 406 | 20 | false | false | false | false | false | 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 | 414 | 17 | 480 | 17 | 521 | 17 | 480 | 17 | 556 | 17 | false | false | false | false | false | true |
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 | 1,545 | 38 | 1,579 | 36 | 1,817 | 43 | 1,579 | 36 | 1,937 | 44 | false | false | false | false | false | true |
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 | 617 | 26 | 753 | 28 | 797 | 28 | 753 | 28 | 889 | 28 | false | false | false | false | false | 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 | 1,905 | 33 | 2,210 | 33 | 2,223 | 36 | 2,210 | 33 | 2,552 | 39 | false | false | false | false | false | 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 | 1,188 | 34 | 1,253 | 34 | 1,323 | 37 | 1,253 | 34 | 1,496 | 39 | false | false | false | false | false | 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 | 349 | 30 | 362 | 29 | 400 | 32 | 362 | 29 | 439 | 34 | false | false | false | false | false | 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 | 106 | 19 | 114 | 19 | 142 | 20 | 114 | 19 | 156 | 20 | false | false | false | false | false | true |
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 | 162 | 38 | 170 | 37 | 191 | 40 | 170 | 37 | 203 | 41 | false | false | false | false | false | 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 | 574 | 274 | 646 | 283 | 685 | 302 | 646 | 283 | 740 | 316 | true | true | true | true | true | 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 | 98 | 17 | 111 | 17 | 116 | 17 | 111 | 17 | 117 | 17 | false | false | false | false | false | 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 | 687 | 44 | 806 | 49 | 757 | 49 | 806 | 49 | 883 | 51 | false | false | false | false | false | true |
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 | 57 | 30 | 65 | 34 | 61 | 32 | 65 | 34 | 73 | 38 | false | false | false | false | false | 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 | 1,212 | 36 | 1,356 | 36 | 1,386 | 37 | 1,356 | 36 | 1,560 | 38 | false | false | false | false | false | 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 | 248 | 35 | 300 | 36 | 320 | 36 | 300 | 36 | 342 | 37 | false | false | false | false | false | true |
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 | 701 | 18 | 744 | 19 | 810 | 19 | 744 | 19 | 851 | 20 | false | false | false | false | false | true |
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 | 2,364 | 73 | 2,409 | 69 | 2,812 | 79 | 2,409 | 69 | 3,032 | 81 | false | false | false | false | false | 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 | 557 | 17 | 586 | 17 | 659 | 17 | 586 | 17 | 703 | 18 | false | false | false | false | false | 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 | 1,930 | 23 | 2,131 | 20 | 2,321 | 24 | 2,131 | 20 | 2,522 | 25 | false | false | false | false | false | 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 | 1,163 | 22 | 1,240 | 21 | 1,388 | 23 | 1,240 | 21 | 1,476 | 23 | false | false | false | false | false | 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 | 571 | 54 | 609 | 59 | 740 | 60 | 609 | 59 | 799 | 63 | false | false | false | false | false | true |
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 | 1,292 | 19 | 1,453 | 21 | 1,625 | 20 | 1,453 | 21 | 1,826 | 22 | false | false | false | false | false | 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 | 183 | 31 | 200 | 32 | 218 | 32 | 200 | 32 | 240 | 36 | false | false | false | false | false | 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 | 362 | 32 | 392 | 35 | 423 | 37 | 392 | 35 | 446 | 37 | false | false | false | false | false | true |
63425_0 |
import java.util.stream.Stream;
import java.math.*;
/**
* Implements tail-call using Java 8 Stream.
*
* @author adavis
*/
@FunctionalInterface
public interface Tail<T> {
Tail<T> apply();
default boolean isDone() {
return false;
}
default T result() {
throw new UnsupportedOperationException("Not done yet.");
}
default T invoke() {
return Stream.iterate(this, Tail::apply)
.filter(Tail::isDone)
.findFirst()
.get()
.result();
}
static <T> Tail<T> done(final T value) {
return new Tail<T>() {
@Override
public T result() {
return value;
}
@Override
public boolean isDone() {
return true;
}
@Override
public Tail<T> apply() {
throw new UnsupportedOperationException("Not supported.");
}
};
}
static BigInteger streamFactorial(int n) {
return streamFactorial(BigInteger.ONE, n).invoke();
}
static Tail<BigInteger> streamFactorial(BigInteger x, int n) {
return () -> {
switch (n) {
case 1:
return Tail.done(x);
default:
return streamFactorial(x.multiply(BigInteger.valueOf(n)), n - 1);
}
};
}
static BigInteger stackFactorial(int n) {
return stackFactorial(BigInteger.ONE, n);
}
static BigInteger stackFactorial(BigInteger x, int n) {
if (n==1) return x;
else return stackFactorial(x.multiply(BigInteger.valueOf(n)), n - 1);
}
public static void main(String...args) {
long start = System.currentTimeMillis();
final int num = 55555;
System.out.println("calculating " + num + "!");
try {
stackFactorial(num);
System.out.println("stack: " + (System.currentTimeMillis() - start));
} catch (StackOverflowError e) {
System.err.println(e);
}
streamFactorial(num);
System.out.println("stream: " + (System.currentTimeMillis() - start) + "ms");
}
}
| adamldavis/hellojava8 | Tail.java | 518 | /**
* Implements tail-call using Java 8 Stream.
*
* @author adavis
*/ | block_comment | en | false | 471 | 20 | 518 | 23 | 603 | 24 | 518 | 23 | 654 | 26 | false | false | false | false | false | true |
63894_3 | /**
*LSArray.java - Reads in Load Shedding Data from file to a binary search tree
*Provides method to search through it
*@ThaddeusOwl, 01-03-2020
*Use Tree(int,string) if you want to change the dataset length or input file
*else use Tree() for default settings
*/
import java.io.File;
import java.io.FileNotFoundException;
import java.util.Scanner;
public class Tree{
BinarySearchTree<Data> bst;
String fileName="Load_Shedding_All_Areas_Schedule_and_Map.clean.final.txt";
int n=2976;
/**reads in default file with default dataset lenth into bst */
public Tree() throws FileNotFoundException{
bst = new BinarySearchTree<Data>();
Scanner file=new Scanner(new File(fileName));
for(int i=0; i<n; i++){
String line = file.nextLine();
String[] lineSplit = line.split(" ", 2);
bst.insert(new Data(lineSplit[0],lineSplit[1]));
}
}
/**reads in specified dataset length of specified file into bst */
public Tree(int a, String b) throws FileNotFoundException{
this.n=a;
if(b.equals("default")){
}else{this.fileName=b;}
bst = new BinarySearchTree<Data>();
Scanner file=new Scanner(new File(fileName));
for(int i=0; i<n; i++){
String line = file.nextLine();
String[] lineSplit = line.split(" ", 2);
bst.insert(new Data(lineSplit[0],lineSplit[1]));
}
}
/**Searches for the given parameter's match in the tree and outputs the corresponding area*/
public String search(String details){
Data a = new Data(details);
BinaryTreeNode<Data> b = bst.find(a);
if(b!=null){
return b.data.getAreas();
}else{return "Areas not found";}
}
/**prints all details/parameters with their corresponding areas */
public void allAreas(){
bst.inOrder();
}
/**Returns number of operations counted when inserting */
public int getInsertOpCount(){
return bst.insertOpCount;
}
/** Returns operations counted when searching*/
public int getSearchOpCount(){
return bst.searchOpCount;
}
}
| ThaddeusOwl/loadshedding_program | src/Tree.java | 578 | /**Searches for the given parameter's match in the tree and outputs the corresponding area*/ | block_comment | en | false | 485 | 18 | 578 | 19 | 594 | 19 | 578 | 19 | 658 | 19 | false | false | false | false | false | true |
64856_0 | import java.util.Calendar;
import java.util.Set;
/**
* A class to represent meetings
*
* Meetings have unique IDs, scheduled date and a list of participating contacts
*
* @auhor PiJ Team
*/
public interface Meeting {
/**
* Returns the id of the meeting.
*
* @return the id of the meeting.
*/
int getId();
/**
* Return the date of the meeting.
*
* @return the date of the meeting.
*/
Calendar getDate();
/**
* Return the details of people that attended the meeting.
*
* The list contains a minimum of one contact (if there were
* just two people: the user and the contact) and may contain an
* arbitrary number of them.
*
* @return the details of people that attended the meeting.
*/
Set<Contact> getContacts();
}
| cgroc/cw-cm | Meeting.java | 226 | /**
* A class to represent meetings
*
* Meetings have unique IDs, scheduled date and a list of participating contacts
*
* @auhor PiJ Team
*/ | block_comment | en | false | 184 | 34 | 226 | 41 | 219 | 37 | 226 | 41 | 227 | 41 | false | false | false | false | false | true |
65516_1 |
/**
* This Pit class is use MouseAdapter to
* identify each pit on the board to keep track of each pit when mouse is pressed
*
*/
import java.util.*;
import java.awt.event.MouseAdapter;
public class Pit extends MouseAdapter {
private int identify;
/**
* @param identify This is the identify parameter
*/
public Pit(int identify) {
super();
this.identify = identify;
}
/**
* @return This will return the identify
*/
public int getMouseListenerID() {
return identify;
}
}
| MarkSaweres/ManclaMakers | Pit.java | 134 | /**
* @param identify This is the identify parameter
*/ | block_comment | en | false | 118 | 14 | 134 | 13 | 142 | 15 | 134 | 13 | 150 | 15 | false | false | false | false | false | true |
65999_2 | package org.fleen.maximilian;
import java.util.ArrayList;
import java.util.List;
import org.fleen.geom_2D.DYard;
/*
* A polygonal shape pierced by 1..n polygonal shapes (holes)
* It can come in several varieties. Specifics are denoted by tag.
* ie :
* "bagel" : a polygon pierced by 1 similar polygon creating a bagel-like shape with a uniform wraparound shape
* "sponge" " a polygon pierced in such a way, by 1 or more polygons, as to create a pretty irregular space
*
*/
public class MYard extends MShape{
private static final long serialVersionUID=-726090849488448340L;
/*
* ################################
* CONSTRUCTORS
* ################################
*/
/*
* the first polygon is the outer edge, the rest are holes
* There is only ever at most just 1 yard in a jig-generated geometry
* system, so we assign the chorus index automatically.
* We use our reserved chorus index for yards
*/
public MYard(List<MPolygon> mpolygons,int chorusindex,List<String> tags){
super(MYARDCHORUSINDEX,tags);
//create a new list to decouple param, for safety
this.mpolygons=new ArrayList<MPolygon>(mpolygons);}
public MYard(MPolygon outer,List<MPolygon> inner,int chorusindex,List<String> tags){
super(MYARDCHORUSINDEX,tags);
this.mpolygons=new ArrayList<MPolygon>(inner.size()+1);
this.mpolygons.add(outer);
this.mpolygons.addAll(inner);}
/*
* ################################
* GEOMETRY
* ################################
*/
public List<MPolygon> mpolygons;
public DYard getDYard(){
DYard y=new DYard(mpolygons.size());
for(MPolygon p:mpolygons)
y.add(p.dpolygon);
return y;}
/*
* ++++++++++++++++++++++++++++++++
* DETAIL SIZE
* smallest distance between component polygons
* ++++++++++++++++++++++++++++++++
*/
Double detailsize=null;
public double getDetailSize(){
if(detailsize==null)initDetailSize();
return detailsize;}
private void initDetailSize(){
double smallest=Double.MAX_VALUE,test;
for(MPolygon p0:mpolygons){
for(MPolygon p1:mpolygons){
if(p0!=p1){
test=p0.getDistance(p1);
if(test<smallest)
smallest=test;}}}
detailsize=smallest;}
/*
* ++++++++++++++++++++++++++++++++
* DISTORTION LEVEL
* the distortion level of this yard's most distorted component polygon
* ++++++++++++++++++++++++++++++++
*/
Double distortionlevel=null;
public double getDistortionLevel(){
if(distortionlevel==null)
initDistortionLevel();
return distortionlevel;}
private void initDistortionLevel(){
double largest=Double.MIN_VALUE,test;
for(MPolygon p:mpolygons){
test=p.getDistortionLevel();
if(test>largest)
largest=test;}
distortionlevel=largest;}
/*
* ################################
* CHORUS INDEX
* ################################
*/
public static final int MYARDCHORUSINDEX=Integer.MAX_VALUE;
}
| johnalexandergreene/Maximilian | MYard.java | 840 | /*
* the first polygon is the outer edge, the rest are holes
* There is only ever at most just 1 yard in a jig-generated geometry
* system, so we assign the chorus index automatically.
* We use our reserved chorus index for yards
*/ | block_comment | en | false | 754 | 61 | 841 | 66 | 908 | 66 | 840 | 66 | 1,060 | 69 | false | false | false | false | false | true |
66194_10 | import java.util.*;
class Student{
protected int rollNo;
protected float percentage;
Student(){
rollNo = 0;
percentage=0.0f;
}
// SUPER CLASS CONSTRUCTOR (CHAINED IN THE TWO SUB-CLASSES)
Student(int rollNo, float percentage){
this.rollNo=rollNo;
this.percentage=percentage;
}
public void show(){
// System.out.println("Student class show() method called");
System.out.println("Roll No : "+this.rollNo);
System.out.println("Percentage : "+this.percentage);
}
}
class CollegeStudent extends Student{
protected int semester;
CollegeStudent(){
super();
semester = 1;//DEFAULT INITIALISATION
}
CollegeStudent(int rollNo, float percentage, int semester){
super(rollNo, percentage);//CALL TO CONSTRUCTOR OF SUPER CLASS
this.semester=semester;
}
public void show(){
super.show();//CALL TO THE SHOW OF SUPER CLASS
// System.out.println("CollegeStudent class show() method called");
System.out.println("Semester : "+this.semester);
}
}
class SchoolStudent extends Student{
protected int className;
SchoolStudent(){
super();
className = 1; //DEFAULT INITIALISATION
}
SchoolStudent(int rollNo, float percentage,int className){
super(rollNo, percentage);//CALL TO CONSTRUCTOR OF SUPER CLASS
this.className=className;
}
//OVER RIDDEN METHOD
public void show(){
super.show();//CALL TO THE SHOW OF SUPER CLASS
System.out.println("Class : "+this.className);
}
}
class Demo{
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
//creating an array of student because the super can hold the ref variable of the sub class (UPCASTING)
Student students[] = new Student[5];
//TO ENTER THE OBJ AND THEIR DETAILS INTO AN ARRAY
for(int i=0; i<students.length; i++){
if(i < 2){
System.out.println("\nEnter details for College Students : ");
System.out.print("Enter Roll No : ");
int rollNo = sc.nextInt();
System.out.print("Enter Percentage : ");
float percentage = sc.nextFloat();
System.out.print("Enter Semester : ");
int semester = sc.nextInt();
Student cs = new CollegeStudent(rollNo,percentage,semester);
students[i]=cs;
}
else{
System.out.println("\nEnter details for School Students : ");
System.out.print("Enter Roll No : ");
int rollNo = sc.nextInt();
System.out.print("Enter Percentage : ");
float percentage = sc.nextFloat();
System.out.print("Enter Class : ");
int className = sc.nextInt();
Student ss = new SchoolStudent(rollNo,percentage,className);
students[i]=ss;
}
}
System.out.println("\n\n\nTO PRINT THE DETAILS OF ARRAY \n");
for(int i=0; i<students.length; i++){
if(i < 2){
System.out.println("Details for College Students : ");
students[i].show();
}
else{
System.out.println("Details for College Students : ");
students[i].show();
}
}
//TO SEARCH THE ROLL NO IN THE ARRAY
System.out.println("\n\n\nSEARCHING ROLL NO IN ARRAY =>\n");
System.out.println("Enter Roll no to search : ");
int roll = sc.nextInt();
for(int i=0; i<students.length; i++){
if(students[i].rollNo == roll){
System.out.println("Details for Roll No "+roll+" : ");
students[i].show();
}
else
continue;
}
//TO FIND THE NO OF STUDENTS WITH GRADE A (GRADE > 75)
int studentCount=0;
for(int i=0; i<students.length; i++){
if(students[i].percentage > 75){
studentCount++;
}
else
continue;
}
System.out.println("\n\nNumber of Students with grade A : "+studentCount);
}
} | Anushree-Gawali/CORE-JAVA | Assignment5/Demo.java | 1,015 | //creating an array of student because the super can hold the ref variable of the sub class (UPCASTING)
| line_comment | en | false | 900 | 24 | 1,015 | 24 | 1,177 | 23 | 1,015 | 24 | 1,344 | 25 | false | false | false | false | false | true |
66213_11 | package math_genealogy;
import com.vaticle.typeql.lang.query.TypeQLDelete;
import mjson.Json;
import java.io.IOException;
import java.nio.file.Files;
import java.util.*;
import java.nio.file.Path;
import java.nio.file.Paths;
import static mjson.Json.read;
import com.vaticle.typedb.client.api.TypeDBClient;
import com.vaticle.typedb.client.api.TypeDBSession;
import com.vaticle.typedb.client.api.TypeDBTransaction;
import com.vaticle.typedb.client.TypeDB;
import com.vaticle.typeql.lang.TypeQL;
import static com.vaticle.typeql.lang.TypeQL.*;
import com.vaticle.typeql.lang.query.TypeQLInsert;
class DataMigrator
{
public static int sz=0;
public static int getId(Json file, int idx)
{
return file.at("nodes").at(idx).at("id").asInteger();
}
public static String getName(Json file, int idx)
{
return file.at("nodes").at(idx).at("name").asString();
}
public static String getSchool(Json file, int idx)
{
return file.at("nodes").at(idx).at("school").asString();
}
public static int getYear(Json file, int idx)
{
if (!file.at("nodes").at(idx).at("year").isNull())
return file.at("nodes").at(idx).at("year").asInteger();
else
return 0;
}
public static String getSpeciality(Json file, int idx)
{
if (!file.at("nodes").at(idx).at("subject").isNull())
{
return file.at("nodes").at(idx).at("subject").asString();
}
else return "Unknown";
}
public static List getAdvisors(Json file, int idx)
{
List<Object> ls = file.at("nodes").at(idx).at("advisors").asList();
return ls;
}
public static void instantiateMathematicians(TypeDBSession session, Json file)
{
for (int z = 0; z < sz; z++)
{
try (TypeDBTransaction writeTransaction = session.transaction(TypeDBTransaction.Type.WRITE)) {
// Insert a person using a WRITE transaction
TypeQLInsert insertQuery = TypeQL.insert
(var("x").isa("mathematician")
.has("id", getId(file, z))
.has("name", getName(file, z))
.has("year_of_degree", getYear(file, z))
);
writeTransaction.query().insert(insertQuery);
// to persist changes, a write-transaction must always be committed (closed)
writeTransaction.commit();
}
}
}
public static void instantiateSchools(TypeDBSession session, Json file)
{
Set<String> school_set = new HashSet<String>();
for (int z = 0; z < sz; z++) {
try (TypeDBTransaction writeTransaction = session.transaction(TypeDBTransaction.Type.WRITE)) {
// Insert a person using a WRITE transaction
String school = getSchool(file, z);
if (!school_set.contains(school)) {
school_set.add(school);
TypeQLInsert insertQuery = TypeQL.insert
(var("x").isa("school")
.has("name", school)
);
writeTransaction.query().insert(insertQuery);
writeTransaction.commit();
}
}
}
}
public static void instantiateSpecialities(TypeDBSession session, Json file)
{
Set<String> speciality_set = new HashSet<String>();
for (int z = 0; z < sz; z++) {
try (TypeDBTransaction writeTransaction = session.transaction(TypeDBTransaction.Type.WRITE)) {
// Insert a person using a WRITE transaction
String speciality = getSpeciality(file, z);
if (!speciality_set.contains(speciality)) {
speciality_set.add(speciality);
TypeQLInsert insertQuery = TypeQL.insert
(var("x").isa("speciality")
.has("name", speciality)
);
writeTransaction.query().insert(insertQuery);
writeTransaction.commit();
}
}
}
}
public static void instantiateRelationships(TypeDBSession session, Json file)
{
Set<ArrayList<String>> offerSet = new HashSet<>();
for (int z = 0; z < sz; z++) {
int m_id = getId(file, z);
String school = getSchool(file, z);
//add studentship relationship
try (TypeDBTransaction writeTransaction = session.transaction(TypeDBTransaction.Type.WRITE)) {
TypeQLInsert insertQuery = TypeQL.match(
var("m1").isa("mathematician").has("id", m_id),
var("s").isa("school").has("name", school)
).insert(
var("new-studentship").rel("student", "m1").rel("school", "s").isa("studentship")
);
writeTransaction.query().insert(insertQuery);
writeTransaction.commit();
}
//offer relationship
String speciality = getSpeciality(file, z);
try (TypeDBTransaction writeTransaction = session.transaction(TypeDBTransaction.Type.WRITE)) {
ArrayList<String> a = new ArrayList<>();
a.add(school);
a.add("mathematics");
a.add(speciality);
if (!offerSet.contains(a)) {
TypeQLInsert insertQuery = TypeQL.match(
var("s").isa("school").has("name", school),
var("s2").isa("subject").has("name", "mathematics"),
var("s3").isa("speciality").has("name", speciality)
).insert(
var("new-offer").rel("school", "s").rel("subject", "s2").rel("speciality", "s3").isa("offer")
);
offerSet.add(a);
writeTransaction.query().insert(insertQuery);
writeTransaction.commit();
System.out.println("Offer Relationship added\n" + " school: " + school + " speciality = " + speciality);
System.out.println("size = " + offerSet.size());
}
}
//add mastery relationship
try (TypeDBTransaction writeTransaction = session.transaction(TypeDBTransaction.Type.WRITE)) {
TypeQLInsert insertQuery = TypeQL.match(
var("m").isa("mathematician").has("id", m_id),
var("s").isa("speciality").has("name", speciality)
).insert(
var("new-mastery").rel("master", "m").rel("speciality", "s").isa("mastery")
);
writeTransaction.query().insert(insertQuery);
writeTransaction.commit();
}
List advisor_list = getAdvisors(file, z);
int len = advisor_list.size();
//add research relationship
for (int j = 0; j < len; j++) {
java.lang.Long a_id = (java.lang.Long) advisor_list.get(j);
//research relationship
try (TypeDBTransaction writeTransaction = session.transaction(TypeDBTransaction.Type.WRITE)) {
TypeQLInsert insertQuery = TypeQL.match(
var("m1").isa("mathematician").has("id", m_id),
var("m2").isa("mathematician").has("id", a_id),
var("s").isa("school").has("name", school)
).insert(
var("new-research").rel("advisor", "m2").rel("advisee", "m1").rel("school", "s").isa("research")
);
writeTransaction.query().insert(insertQuery);
writeTransaction.commit();
}
}
}
}
public static void instantiateSubjects(TypeDBSession session, Json file)
{
try (TypeDBTransaction writeTransaction = session.transaction(TypeDBTransaction.Type.WRITE)) {
// Insert a person using a WRITE transaction
TypeQLInsert insertQuery = TypeQL.insert
(var("x").isa("subject")
.has("name", "mathematics")
);
writeTransaction.query().insert(insertQuery);
writeTransaction.commit();
}
}
private static void defineSchema(String databaseName, String schemaFileName, TypeDBClient client) {
try (TypeDBSession session = client.session(databaseName, TypeDBSession.Type.SCHEMA)) {
try (TypeDBTransaction transaction = session.transaction(TypeDBTransaction.Type.WRITE)) {
String typeQLSchemaQuery = Files.readString(Paths.get(schemaFileName));
System.out.println("Defining schema...");
transaction.query().define(TypeQL.parseQuery(typeQLSchemaQuery).asDefine());
transaction.commit();
} catch (IOException e) {
throw new RuntimeException(e);
}
}
}
public static void main(String[] args)
{
Path filePath=Paths.get("datalite.json");
TypeDBClient client = TypeDB.coreClient("localhost:1729");
String contents="";
try {
contents = Files.readString(filePath);
}
catch(IOException e)
{
System.out.println("IO Exception in file: "+e.getMessage());
e.printStackTrace();
}
Json file=read(contents);
List mylist=file.at("nodes").asList();
sz=mylist.size();
System.out.println("Size = "+sz);
String dbName="onboarding";
String schemaFileName="schema.tql";
if (client.databases().contains(dbName))
{
client.databases().get(dbName).delete();
}
client.databases().create(dbName);
defineSchema(dbName, schemaFileName, client);
try (TypeDBSession session = client.session(dbName, TypeDBSession.Type.DATA)) {
//first purge existing data
try (TypeDBTransaction writeTransaction = session.transaction(TypeDBTransaction.Type.WRITE)) {
TypeQLDelete query = TypeQL.match(
var("p").isa("thing")
).delete(var("p").isa("thing"));
writeTransaction.query().delete(query);
// to persist changes, a write-transaction must always be committed (closed)
writeTransaction.commit();
}
instantiateMathematicians(session, file);
instantiateSchools(session, file);
instantiateSubjects(session, file);
instantiateSpecialities(session, file);
instantiateRelationships(session, file);
}
client.close();
}
}
| shiladitya-mukherjee/math-genealogy-typedb | DataMigrator.java | 2,474 | // to persist changes, a write-transaction must always be committed (closed) | line_comment | en | false | 2,203 | 16 | 2,474 | 16 | 2,667 | 16 | 2,474 | 16 | 2,851 | 16 | false | false | false | false | false | true |
71718_9 | import org.json.simple.JSONArray;
import org.json.simple.JSONObject;
import org.json.simple.parser.JSONParser;
import org.json.simple.parser.ParseException;
import java.io.FileReader;
import java.io.IOException;
import java.time.Instant;
import java.util.ArrayList;
/**
* The DataLoader class provides methods to load the data from the Cards,Users, and trades JSON files.
*/
public class DataLoader {
private static final String CARDS_FILE_PATH = "json/cards.json";
private static final String USERS_FILE_PATH = "json/users.json";
private static final String TRADES_FILE_PATH = "json/trades.json";
/**
* Loads cards from the Card.JSON file.
*
* @return an ArrayList of Card objects.
*/
public static ArrayList<Card> loadCards() {
ArrayList<Card> cards = new ArrayList<>();
JSONParser parser = new JSONParser();
try (FileReader reader = new FileReader(CARDS_FILE_PATH)) {
JSONArray cardsArray = (JSONArray) parser.parse(reader);
for (Object obj : cardsArray) {
JSONObject cardObject = (JSONObject) obj;
cards.add(parseCard(cardObject));
}
} catch (IOException | ParseException e) {
e.printStackTrace();
}
return cards;
}
/**
* Loads users from the Users.JSON file.
*
* @return an ArrayList of User objects.
*/
public static ArrayList<User> loadUsers() {
ArrayList<User> users = new ArrayList<>();
JSONParser parser = new JSONParser();
try (FileReader reader = new FileReader(USERS_FILE_PATH)) {
JSONArray usersArray = (JSONArray) parser.parse(reader);
for (Object obj : usersArray) {
JSONObject userObject = (JSONObject) obj;
users.add(parseUser(userObject));
}
} catch (IOException | ParseException e) {
e.printStackTrace();
}
return users;
}
/**
* Loads trades from the trades.JSON file.
*
* @return an ArrayList of Trade objects.
*/
public static ArrayList<Trade> loadTrades() {
ArrayList<Trade> trades = new ArrayList<>();
JSONParser parser = new JSONParser();
try (FileReader reader = new FileReader(TRADES_FILE_PATH)) {
JSONArray tradesArray = (JSONArray) parser.parse(reader);
for (Object obj : tradesArray) {
JSONObject tradeObject = (JSONObject) obj;
trades.add(parseTrade(tradeObject));
}
} catch (IOException | ParseException e) {
e.printStackTrace();
}
return trades;
}
/**
* Parses a JSONObject into a Card object.
*
* @param cardObject the JSONObject to parse.
* @return a Card object.
*/
private static Card parseCard(JSONObject cardObject) {
int id = getIntValue(cardObject, "id");
String name = getStringValue(cardObject, "name");
String type = getStringValue(cardObject, "type");
String rarity = getStringValue(cardObject, "rarity");
int pack = getIntValue(cardObject, "pack");
int hp = getIntValue(cardObject, "hp");
double value = getDoubleValue(cardObject, "value");
int evoStage = getIntValue(cardObject, "evoStage");
ArrayList<Integer> familyCards = getIntegerList(cardObject, "family");
ArrayList<String> attacks = getStringList(cardObject, "attacks");
return new Card(id, name, type, rarity, pack, hp, value, evoStage, familyCards, attacks);
}
/**
* Gets an integer value from a JSONObject.
*
* @param jsonObject the JSONObject.
* @param key the key of the value.
* @return the integer value.
*/
private static int getIntValue(JSONObject jsonObject, String key) {
Object value = jsonObject.get(key);
if (value instanceof Long) {
return ((Long) value).intValue();
}
return 0;
}
/**
* Gets a double value from a JSONObject.
*
* @param jsonObject the JSONObject.
* @param key value of the double.
* @return the double value.
*/
private static double getDoubleValue(JSONObject jsonObject, String key) {
Object value = jsonObject.get(key);
if (value instanceof Long) {
return ((Long) value).doubleValue();
} else if (value instanceof Double) {
return (Double) value;
}
return 0.0;
}
/**
* Gets a string value from a JSONObject.
*
* @param jsonObject the JSONObject.
* @param key the key of the value.
* @return the string value.
*/
private static String getStringValue(JSONObject jsonObject, String key) {
Object value = jsonObject.get(key);
return value != null ? value.toString() : "";
}
/**
* Gets an ArrayList of integers from a JSONObject.
*
* @param jsonObject the JSONObject.
* @param key the key of the value.
* @return an ArrayList of integers.
*/
private static ArrayList<Integer> getIntegerList(JSONObject jsonObject, String key) {
ArrayList<Integer> list = new ArrayList<>();
Object value = jsonObject.get(key);
if (value instanceof JSONArray) {
JSONArray jsonArray = (JSONArray) value;
for (Object obj : jsonArray) {
if (obj instanceof Long) {
list.add(((Long) obj).intValue());
}
}
} else if (value instanceof Long) {
list.add(((Long) value).intValue());
}
return list;
}
/**
* Gets an ArrayList of strings from a JSONObject.
*
* @param jsonObject the JSONObject.
* @param key the key of the value.
* @return an ArrayList of strings.
*/
private static ArrayList<String> getStringList(JSONObject jsonObject, String key) {
ArrayList<String> list = new ArrayList<>();
Object value = jsonObject.get(key);
if (value instanceof JSONArray) {
JSONArray jsonArray = (JSONArray) value;
for (Object obj : jsonArray) {
if (obj instanceof String) {
list.add((String) obj);
}
}
} else if (value instanceof String) {
list.add((String) value);
}
return list;
}
/**
* Parses a JSONObject into a User object.
*
* @param userObject the JSONObject to parse.
* @return a User object.
*/
private static User parseUser(JSONObject userObject) {
String userName = getStringValue(userObject, "userName");
String uniqueIdentifier = getStringValue(userObject, "uniqueIdentifier");
String password = getStringValue(userObject, "password");
String firstName = getStringValue(userObject, "firstName");
String lastName = getStringValue(userObject, "lastName");
String email = getStringValue(userObject, "email");
double currency = getDoubleValue(userObject, "currency");
ArrayList<Integer> favoriteCardsTemp = getIntegerList(userObject, "favoriteCards");
ArrayList<Card> favoriteCards = new ArrayList<>();
CardList masterList = CardList.getInstance();
for (Integer temp : favoriteCardsTemp) {
favoriteCards.add(masterList.searchById(temp));
}
ArrayList<Integer> ownedCardsTemp = getIntegerList(userObject, "ownedCards");
ArrayList<Card> ownedCards = new ArrayList<>();
for (Integer temp : ownedCardsTemp) {
ownedCards.add(masterList.searchById(temp));
}
Instant lastClaimedCurrencyTime = Instant.parse(getStringValue(userObject, "lastClaimedCurrencyTime"));
User user = new User(userName, password, firstName, lastName, email, favoriteCards, currency, ownedCards);
user.setLastClaimedCurrencyTime(lastClaimedCurrencyTime);
return user;
}
/**
* Parses a JSONObject into a Trade object.
*
* @param tradeObject the JSONObject to parse.
* @return a Trade object.
*/
private static Trade parseTrade(JSONObject tradeObject) {
UserList userList = UserList.getInstance();
CardList masterList = CardList.getInstance();
String receiverUserName = getStringValue(tradeObject, "receiverUserName");
User receiver = userList.searchByUserName(receiverUserName);
String senderUserName = getStringValue(tradeObject, "senderUserName");
User sender = userList.searchByUserName(senderUserName);
ArrayList<Integer> cardsIds = getIntegerList(tradeObject, "cardsOffered");
ArrayList<Card> cardsOffered = new ArrayList<Card>();
for (int num : cardsIds) {
cardsOffered.add(masterList.searchById(num));
}
int cardRequested = getIntValue(tradeObject, "cardsRequested");
Card realCard = masterList.searchById(cardRequested);
boolean isFairTrade = (Boolean) tradeObject.get("isFairTrade");
boolean awaitingResponse = (Boolean) tradeObject.get("awaitingResponse");
boolean wasAccepted = (Boolean) tradeObject.get("wasAccepted");
String comment = getStringValue(tradeObject, "comment");
Trade trade = new Trade(sender, receiver, cardsOffered, realCard, isFairTrade, awaitingResponse, wasAccepted, comment);
if (sender != null)
sender.addReceivingTrade(trade);
if (receiver != null)
receiver.addReceivingTrade(trade);
return trade;
}
}
| CSVrajTPatel/PokeBros | DataLoader.java | 2,147 | /**
* Gets an ArrayList of strings from a JSONObject.
*
* @param jsonObject the JSONObject.
* @param key the key of the value.
* @return an ArrayList of strings.
*/ | block_comment | en | false | 1,961 | 45 | 2,147 | 44 | 2,336 | 51 | 2,147 | 44 | 2,590 | 55 | false | false | false | false | false | true |
71786_9 | /*********************************************************************
* Indirect priority queue.
*
* The priority queue maintains its own copy of the priorities,
* unlike the one in Algorithms in Java.
*
* This code is from "Algorithms in Java, Third Edition,
* by Robert Sedgewick, Addison-Wesley, 2003.
*********************************************************************/
public class IndexPQ {
private int N; // number of elements on PQ
private int[] pq; // binary heap
private int[] qp; //
private double[] priority; // priority values
public IndexPQ(int NMAX) {
pq = new int[NMAX + 1];
qp = new int[NMAX + 1];
priority = new double[NMAX + 1];
N = 0;
}
public boolean isEmpty() { return N == 0; }
// insert element k with given priority
public void insert(int k, double value) {
N++;
qp[k] = N;
pq[N] = k;
priority[k] = value;
fixUp(pq, N);
}
// delete and return the minimum element
public int delMin() {
exch(pq[1], pq[N]);
fixDown(pq, 1, --N);
return pq[N+1];
}
// change the priority of element k to specified value
public void change(int k, double value) {
priority[k] = value;
fixUp(pq, qp[k]);
fixDown(pq, qp[k], N);
}
/**************************************************************
* General helper functions
**************************************************************/
private boolean greater(int i, int j) {
return priority[i] > priority[j];
}
private void exch(int i, int j) {
int t = qp[i]; qp[i] = qp[j]; qp[j] = t;
pq[qp[i]] = i; pq[qp[j]] = j;
}
/**************************************************************
* Heap helper functions
**************************************************************/
private void fixUp(int[] a, int k) {
while (k > 1 && greater(a[k/2], a[k])) {
exch(a[k], a[k/2]);
k = k/2;
}
}
private void fixDown(int[] a, int k, int N) {
int j;
while (2*k <= N) {
j = 2*k;
if (j < N && greater(a[j], a[j+1])) j++;
if (!greater(a[k], a[j])) break;
exch(a[k], a[j]);
k = j;
}
}
}
| SalmonRanjay/Bison-Maps | IndexPQ.java | 636 | /**************************************************************
* Heap helper functions
**************************************************************/ | block_comment | en | false | 583 | 11 | 636 | 11 | 741 | 20 | 636 | 11 | 801 | 25 | false | false | false | false | false | true |
72279_1 | public class Alien extends Monster{
// The Alien, moves in leftwards, until it cannot go any further,
// then it will turn 90 degrees to the left and continue.
private int counter;
public Alien(GameState game, int x, int y){
super(game, x, y);
counter=0;
}
public void tick(){
// counter=0 left, counter=1 down, counter=2 right, counter=3 up
switch(counter){
case 0:
if(this.canMoveLeft()){
moveLeft();
break;
}
counter=(counter+1)%4;
case 1:
if(this.canMoveDown()){
moveDown();
break;
}
counter=(counter+1)%4;
case 2:
if(this.canMoveRight()){
moveRight();
break;
}
counter=(counter+1)%4;
case 3:
if(this.canMoveUp()){
moveUp();
break;
}
counter=(counter+1)%4;
default:
break;
}
}
@Override
public void drawSelf(){
String sprite = new String("\uD83D\uDC7D");
int x = this.getX();
int y = this.getY();
GameState game = this.getGame();
game.drawSpriteAt(x, y, sprite);
}
@Override
public void onPlayerColision(Player p){
int x = this.getX();
int y = this.getY();
GameState game = this.getGame();
if(p.occupiesPosition(x, y)){
System.out.println("Captured by Aliens! Game Over...");
game.stop();
}
}
} | TriptSharma/JavaGame | Alien.java | 391 | // then it will turn 90 degrees to the left and continue. | line_comment | en | false | 365 | 15 | 391 | 15 | 440 | 15 | 391 | 15 | 479 | 15 | false | false | false | false | false | true |
72454_1 | /**
* @author Grace Bero
* Creates a spell class that can be used to create spells
*/
public class Spell {
protected String spellName;
protected int damage;
protected int staminaCost;
protected String keyAssociation;
/**
* Constructor for Attacks Class
* @param s, string for spell name
* @param d, int for damage
* @param m, int for mana cost
* @param k, string for key association
*/
public Spell(String s, int d, int st, String k) {
spellName = s;
damage = d;
staminaCost = st;
keyAssociation = k;
}
/**
* Mutators for spell name, damage, and mana cost
* @param spell, string for spell name
* @param dmg, int for damage
* @param stam, int for stamina cost
* @param key, string for key association
*/
public void setSpellName(String s) {
spellName = s;
}
public void setDamage(int d) {
damage = d;
}
public void setStamina(int st) {
staminaCost = st;
}
/**
* Accessors for spell name, damage, and mana cost
* @return spellName, damage, manaCost, keyAssociation
*/
public String getSpellName() {
return spellName;
}
public int getDamage() {
return damage;
}
public int getStaminaCost() {
return staminaCost;
}
/**
* toString method for Attacks class
* @return String representation of Attack
*/
public String toString() {
String spellString = spellName + ", " + damage + " dmg, " + staminaCost + " stamina";
return spellString;
}
/**
* Testing printing out spells
*/
public static void main(String[] args) {
Spell fireball = new Spell("Fireball", 20, 4, "f");
Spell lightning = new Spell("Lightning", 10, 2, "l");
Spell ice = new Spell("Ice", 15, 3, "i");
Spell heal = new Spell("Heal", -20, 4, "h");
System.out.println(fireball);
System.out.println(lightning);
System.out.println(ice);
System.out.println(heal);
}
}
| graceb620/Adventure_Game2.0 | src/Spell.java | 559 | /**
* Constructor for Attacks Class
* @param s, string for spell name
* @param d, int for damage
* @param m, int for mana cost
* @param k, string for key association
*/ | block_comment | en | false | 527 | 53 | 559 | 50 | 591 | 54 | 559 | 50 | 655 | 57 | false | false | false | false | false | true |
72473_9 | import sun.reflect.generics.reflectiveObjects.NotImplementedException;
/**
* Created by sebastian on 28/03/15.
*
* Enum class containing enums that are used for consistency throughout the project.
*/
public class Enums {
/**
* Enumeration pertaining to statistics
*/
public enum Stats {
/**
* The number of matches
*/
matches,
/**
* The emotion
*/
emotion
}
/**
* Enumeration pertaining to features
*/
public enum Features {
/**
* If the object of a pattern is an NP; else it is whole sub-clause, i.e. S.
*/
isNP,
/**
* If the regular order of subject := emotion holder and object := cause is reversed, e.g. for "scare".
*/
orderIsReversed
}
/**
* Enumeration containing Plutchik's eight emotions that are used.
*/
public enum Emotions {
anger, anticipation, disgust, fear, joy, sadness, surprise, trust
}
/**
* Enumeration for the two association metrics that are used.
*/
public enum Metric {
pmi, chi_square
}
/**
* Enumeration containing the two ngrams that are used.
*/
public enum Ngram {
unigram, bigram
}
/**
* Enumeration containing the different sources the ngrams can come from.
*/
public enum NgramSource {
np_cause, s_cause, s_cause_subj_pred, s_cause_pred_dobj, emotion_holder
}
/**
* Enumeration containing the different possible sentiments.
*/
public enum Sentiment {
positive, negative, neutral
}
/**
* Enumeration containing the possible degrees of overlap with the NRC Emotion-Association Lexicon (EmoLex).
*/
public enum NRCOverlap {
FALSE, TRUE, NA
}
/**
* Converts an emotion enum to its corresponding sentiment.
* @param emotion the emotion enum
* @return the corresponding sentiment
*/
public static Sentiment emotionToSentiment(Emotions emotion) {
switch (emotion) {
case anger:
case disgust:
case fear:
case sadness:
return Sentiment.negative;
case joy:
case trust:
return Sentiment.positive;
case anticipation:
case surprise:
return Sentiment.neutral;
default:
throw new NotImplementedException();
}
}
}
| sebastianruder/emotion_proposition_store | src/Enums.java | 553 | /**
* Enumeration containing the two ngrams that are used.
*/ | block_comment | en | false | 528 | 15 | 553 | 15 | 602 | 17 | 553 | 15 | 709 | 20 | false | false | false | false | false | true |
72784_1 | /*
* Qno1:(Test-Drive: Body Mass Index Calculator) Obesity causes significant
increases in illnesses such as diabetes and heart disease. To determine
whether a person is overweight or obese, you can use a measure called the
body mass index (BMI). The United States Department of Health and Human
Services provides a BMI calculator at:
http://www.nhlbi.nih.gov/guidelines/obesity/BMI/bmicalc.htm
Use it to calculate your own BMI. A forthcoming exercise will ask you to
program your own BMI calculator. To prepare for this, use the web to research
the formulas for calculating BMI.
*/
import java.util.Scanner;
public class BMI {
public static void main(String args[]) {
Scanner input = new Scanner(System.in);
System.out.println("----------------------------------------------------------\n");
System.out.println("Enter The weight:");
double weight = input.nextDouble();
System.out.println("----------------------------------------------------------\n");
System.out.println("Enter The height:");
double height = input.nextDouble();
// The formula for BMI is weight in kilograms divided by height in meters squared
double Body_Mass_index = weight / (height * height);
System.out.println("----------------------------------------------------------\n");
System.out.println("The Body Mass Index is " + Body_Mass_index);
// Categorizing the BMI
if (Body_Mass_index < 18.5) {
System.out.println("You are Underweight.");
} else if (Body_Mass_index >= 18.5 && Body_Mass_index <= 24.9) {
System.out.println("You have Normal weight.");
} else if (Body_Mass_index >= 25 && Body_Mass_index <= 29.9) {
System.out.println("You are Overweight.");
} else {
System.out.println("You are Obese.");
}
khan khan = new khan();
khan.printStart();
}
} | Yousaf-Maaz/Java-Programmming | BMI.java | 485 | // The formula for BMI is weight in kilograms divided by height in meters squared | line_comment | en | false | 413 | 15 | 485 | 19 | 481 | 15 | 485 | 19 | 541 | 19 | false | false | false | false | false | true |
73245_1 | package controllers;
import java.sql.SQLException;
import java.util.List;
import java.util.Map;
import models.Building;
import models.Experiment;
import models.Room;
import models.User;
import play.Logger;
import play.Routes;
import play.data.Form;
import play.data.validation.Constraints;
import play.i18n.Messages;
import play.mvc.Controller;
import play.mvc.Result;
import views.html.index;
import views.html.admin.lab;
import static play.data.Form.form;
/**
* Login and Logout.
* User: yesnault
*/
public class Admin extends Controller {
/**
* Displays the admin mainview
*
* @return
*/
public static Result admin() {
// try {
return ok(views.html.admin.admin.render());
// } catch (SQLException e) {
// return badRequest(e.toString());
// }
}
/**
* Displays the user_edit view
* @TODO wieso gibts hier den fehler von eclipse?
* @return
*
* G
*/
public static Result user_edit(Long id) throws SQLException {
Form<User> editForm = form(User.class);
return ok(views.html.admin.user_edit.render(User.byId(id)));
}
/**
* Displays the admin user view
*
* @return
*/
public static Result astudies() {
return ok(views.html.admin.studies.render());
}
/**
* Displays the admin studies
*
* @return
*/
public static Result auser() {
return ok(views.html.admin.user.render());
}
/**
* Displays the admin edit page
*
* @return
*/
public static Result edit() {
return ok(views.html.admin.edit_admin.render());
}
/**
* Displays the admin lab
*
* @return
*/
public static Result lab() {
try {
return ok(views.html.admin.lab.render(Building.all(),Room.all(),Building.count()));
} catch (SQLException e) {
// TODO Auto-generated catch block
return badRequest(e.toString());
}
}
/**
*Gets the coordinates from client (admin) for a new room
*
*@return
*/
public static Result save(){
final Map<String, String[]> values = request().body().asFormUrlEncoded();
final String name = values.get("name")[0];
final String description = values.get("desc")[0];
// Float ist zu klein, schneidet die Hälfte ab!!!
final double lat = Double.parseDouble(values.get("lat")[0]);
final double lng = Double.parseDouble(values.get("lng")[0]);
String created = "Lat: "+lat;
// zeigt in der console an ob der server es bekommen hat
Logger.info(created);
try {
long newId = Building.add(name, description, lat, lng);
return ok(String.valueOf(newId));
// return ok("Neues Gebäude'"+name+"' wurde erfolgreich angelegt!");
} catch (SQLException e) {
// TODO Auto-generated catch block
return badRequest(e.toString());
}
}
public static Result saveuser(){
final Map<String, String[]> values = request().body().asFormUrlEncoded();
final String name = values.get("buildingName")[0];
final String description = values.get("pac-input")[0];
// Float ist zu klein, schneidet die Hälfte ab!!!
final double lat = Double.parseDouble(values.get("latFld")[0]);
final double lng = Double.parseDouble(values.get("lngFld")[0]);
String created = "Lat: "+lat;
// zeigt in der console an ob der server es bekommen hat
Logger.info(created);
try {
Building.add(name, description, lat, lng);
return ok(lab.render(Building.all(),Room.all(),Building.count()));
} catch (SQLException e) {
// TODO Auto-generated catch block
return badRequest(e.toString());
}
}
public static Result saveEditBuilding(){
final Map<String, String[]> values = request().body().asFormUrlEncoded();
final Long id = Long.parseLong(values.get("id")[0]);
final String name = values.get("name")[0];
final String description = values.get("desc")[0];
// Float ist zu klein, schneidet die Hälfte ab!!!
final double lat = Double.parseDouble(values.get("lat")[0]);
final double lng = Double.parseDouble(values.get("lng")[0]);
// zeigt in der console an ob der server es bekommen hat
Logger.info("Building with ID: "+id +" will be updated with 'Name:' "+
name+", 'Description:' "+description+", 'Lat:' "+lat+", 'Lng:' "+lng);
try {
Building.update(id, name, description, lat, lng);
return ok("Änderungen gespeichert!");
} catch (Exception e) {
// TODO Auto-generated catch block
return badRequest(e.toString());
}
}
public static Result deleteBuilding(){
final Map<String, String[]> values = request().body().asFormUrlEncoded();
final Long idToDelete = Long.parseLong(values.get("id")[0]);
final String nameToDelete = values.get("name")[0];
Boolean hasRoomsInUse = null;
try {
hasRoomsInUse = Building.checkRoomsUsedInSession(idToDelete);
} catch (SQLException e1) {
// TODO Auto-generated catch block
return badRequest("ERROR CHECKING IF ROOMS IN USE:\n"+e1.toString());
}
if(!hasRoomsInUse){
try{
Building.delete(idToDelete);
return ok("Das Gebäude "+nameToDelete+" wurde ins Archiv verschoben!\n"
+ "Es können nun keine Studien mehr in ihm stattfinden.");
} catch (SQLException e){
return badRequest("BUILDING TO ARCHIVE ERROR! "+e.toString());
}
}
else if(hasRoomsInUse)
return badRequest("In diesem Gebäude finden noch Studien statt, deren Sessions noch nicht abgelaufen sind!");
else{
return badRequest("BOOLEAN CHECKING IF ROOMS IN USE == NULL: 'SOMETHING WENT VERY WRONG' ");
}
}
public static Result saveNewRoom(){
final Map<String, String[]> values = request().body().asFormUrlEncoded();
final String name = values.get("roomName")[0];
final String description = values.get("roomDescription")[0];
final Long building_id = Long.parseLong(values.get("building_id")[0]);
String created = name+" ; "+building_id+" ; "+description;
// zeigt in der console an ob der server es bekommen hat
Logger.info(created);
try {
long newId = Room.add(name, description, building_id);
return ok(String.valueOf(newId));
} catch (SQLException e) {
// TODO Auto-generated catch block
return badRequest("Fehler beim Anlegen des Raumes:\n"+ e.toString());
}
}
public static Result saveEditRoom(){
final Map<String, String[]> values = request().body().asFormUrlEncoded();
final Long id = Long.parseLong(values.get("id")[0]);
final String name = values.get("name")[0];
final String description = values.get("desc")[0];
try {
Room.update(id, name, description);
return ok("Die Änderungen wurden gespeichert!");
} catch (SQLException e) {
// TODO Auto-generated catch block
return badRequest(e.toString());
}
}
public static Result deleteRoom(){
final Map<String, String[]> values = request().body().asFormUrlEncoded();
final Long idToDelete = Long.parseLong(values.get("id")[0]);
final String nameToDelete = values.get("name")[0];
Boolean roomInUse = null ;
try {
roomInUse = Room.checkRoomInUse(idToDelete);
if(roomInUse)
return badRequest("In diesem Raum finden noch Studien statt, deren Sessions noch nicht abgelaufen sind!");
else{
Room.delete(idToDelete);
return ok("Der Raum "+nameToDelete+" wurde ins Archiv verschoben.\n"
+ "In ihm können keine weiteren Studien mehr stattfinden");
}
} catch (SQLException e) {
return badRequest(e.toString());
}
}
/**
* Displays the admin lmap
*
* @return
*/
public static Result mapTest() {
return ok(views.html.admin.mapTest.render());
}
/**
* Displays konto config
*
* @return
*/
public static Result konto() {
return ok(views.html.admin.konto.render());
}
} | dan91/PlayStartApp | app/controllers/Admin.java | 2,244 | /**
* Displays the admin mainview
*
* @return
*/ | block_comment | en | false | 1,969 | 18 | 2,244 | 16 | 2,404 | 20 | 2,244 | 16 | 2,755 | 21 | false | false | false | false | false | true |
73768_6 | /** A class that creates an Odometer object to track fuel and mileage for a car.
* Class contains instance variables to track the miles driven and the fuel
* efficiency in miles per gallon. Class includes mutator methods to reset the
* odometer to 0 miles, to set the fuel efficiency and to accept miles driven
* for a trip and add it to odometer total. Class includes an accessor method
* that returns the number of gallons of gas the car has consumed since the
* odometer was last reset. See test program "OdometerTest.java" that creates
* several trips with different fuel efficiencies.
*/
package odometertest;
import java.util.Scanner;
/**
*
* @author k8port
*/
public class Odometer {
// class variable
private double miles; // the miles driven in a trip
private double mpg; // the fuel efficiency of the vehicle in miles per gallon
// constructors
/** No argument constructor sets miles driven to 0 and fuel efficiency to
* average combined fuel efficiency for 2014 vehicles.
*/
public Odometer() {
miles = 0;
mpg = 29.5;
}
// mutator and accessor methods
/** No argument method to reset the odometer to 0.
*
*/
public void resetZero() {miles = 0;};
/** Method that allows user to set the fuel efficiency of a vehicle.
* Uses Scanner to get input from user instead of argument.
*/
public void setMPG() {
Scanner scan = new Scanner(System.in);
System.out.println("Set the fuel efficiency of your vehicle.");
System.out.println("What is the combined (city/highway) fuel efficiency of the car?");
mpg = scan.nextDouble();
while (mpg < 10 || mpg > 150) {
System.out.println("Error entering fuel efficiency. Please reenter.");
mpg = scan.nextDouble();
}
}
/** Method that allows user to input miles driven for a trip and adds it to
* the odometer total. Also tells user how much gas was used for these miles.
*/
public void acceptMiles() {
double trip;
Scanner scan = new Scanner(System.in);
System.out.println("How many miles were driven on this trip?");
trip = scan.nextDouble();
while (trip < 0) {
System.out.println("You must enter a positive number or 0 if no trip was taken.");
trip = scan.nextDouble();
}
miles += trip;
}
/** Method that allows user to request price of gas based on current odometer
* reading.
* @return the number of gallons of gas used since odometer was last set
*/
public double getGallons() {return miles/mpg;}
// other methods
/** Method to test equality of Odometer objects.
* @param other the other Odometer
* @return true if objects are the same
*/
public boolean equals(Odometer other) {
return (mpg == other.mpg && miles == other.miles);
}
/** Method that returns String representation of Odometer object.
* @return String representing Odometer object.
*/
@Override
public String toString() {
return miles + " miles driven at " + mpg + " miles per gallon.";
}
}
| k8port/Java | Odometer.java | 806 | /** No argument constructor sets miles driven to 0 and fuel efficiency to
* average combined fuel efficiency for 2014 vehicles.
*/ | block_comment | en | false | 746 | 32 | 806 | 32 | 827 | 34 | 806 | 32 | 880 | 34 | false | false | false | false | false | true |
73824_0 | /**
* All Gold has a value and can be picked up to acquire that value.
*/
public class Gold extends Pickup {
public static final String TITLE = "Gold";
public static final String NAME = "gold";
public static final String DEFAULT_IMAGE_PATH = "coin.png";
@Override
public String title() {
return TITLE;
}
@Override
public String name() {
return NAME;
}
@Override
public String defaultImagePath() {
return DEFAULT_IMAGE_PATH;
}
private int value;
public Gold(int x, int y) {
super(x, y);
value = 0;
}
public Gold(int x, int y, int val) {
super(x, y);
value = val;
}
public int getValue() {
return value;
}
}
| IceCreamYou/LodeRunner | Gold.java | 217 | /**
* All Gold has a value and can be picked up to acquire that value.
*/ | block_comment | en | false | 166 | 18 | 217 | 20 | 220 | 20 | 217 | 20 | 241 | 21 | false | false | false | false | false | true |
74006_7 | /*
* Written by Ed Hong UWT Feb. 19, 2003.
* Modified by Donald Chinn May 14, 2003.
* Modified by Donald Chinn December 11, 2003.
* Modified by Donald Chinn February 28, 2004. */
/**
* Class that represents an edge in a graph.
* An object (usually some sort of data) can be associated with the edge.
*
* A label (also represented by an object (e.g., a string) can also be
* associated with an edge. This could be useful, for example, if you
* need to mark an edge as being visited in some graph traversal.
*
* @author edhong
* @version 0.0
*/
public class Edge {
/** the first endpoint of the edge */
private Vertex v1;
/** the second endpoint of the edge */
private Vertex v2;
private Object data; // an object associated with this edge
private Object name; // a name associated with this edge
/**
* Constructor that allows data and a name to be associated
* with the edge.
* @param v the first endpoint of this edge
* @param w the second endpoint of this edge
* @param data data to be associated with this edge
* @param name a name to be associated with this edge
*/
public Edge (Vertex v, Vertex w, Object data, Object name) {
this.data = data;
this.name = name;
this.v1 = v;
this.v2 = w;
}
/**
* Return the first endpoint of this edge.
* @return the first endpoint of this edge
*/
public Vertex getFirstEndpoint() {
return this.v1;
}
/**
* Return the second endpoint of this edge.
* @return the second endpoint of this edge
*/
public Vertex getSecondEndpoint() {
return this.v2;
}
/**
* Return the data associated with this edge.
* @return the data of this edge
*/
public Object getData() {
return this.data;
}
/**
* Set the data associated with this edge.
* @param data the data of this edge
*/
public void setData(Object data) {
this.data = data;
}
/**
* Return the name associated with this edge.
* @return the name of this edge
*/
public Object getName() {
return this.name;
}
}
| iceColdChris/KruskalsAlgorithm | Edge.java | 581 | /**
* Return the first endpoint of this edge.
* @return the first endpoint of this edge
*/ | block_comment | en | false | 565 | 25 | 581 | 24 | 668 | 28 | 581 | 24 | 693 | 29 | false | false | false | false | false | true |
74939_2 | package chickenfactory;
import java.util.*;
public class Menu {
//*NOTE: NO SETTER METHOD
//INSTANCE VARIABLES OF ARRAYLISTS OF DIFFERENT MENU
private ArrayList<Food> regularMenu = new ArrayList<Food>();
private ArrayList<Food> limitedMenu = new ArrayList<Food>();
private ArrayList<Food> specialMenu = new ArrayList<Food>();
//ADDS THE FOOD OBJECTS TO THE DIFFERENT MENU ACCORDING TO THE PRICE OF THE ITEM
public void add(Food items) {
if(items.getPrice()<100) {
regularMenu.add(items);
}else if (items.getPrice()>100 && items.getPrice()<1000) {
limitedMenu.add(items);
}else if (items.getPrice()>1000) {
specialMenu.add(items);
}
}
//Gives me the price of the item the user chose
public double itemPriceRegular(int index1) {
return regularMenu.get(index1).getPrice();
}
public double itemPriceLimited(int index2) {
return limitedMenu.get(index2).getPrice();
}
public double itemPriceSpecial(int index3) {
return specialMenu.get(index3).getPrice();
}
//GETTER METHOD
//--> prints out the menu so the customer is able to order from it
public void getRegular() {
System.out.println(regularMenu);
}
public void getLimited() {
System.out.println(limitedMenu);
}
public void getSpecial() {
System.out.println(specialMenu);
}
//--> Get's the size of the menu. Helps solve index out of bound issues
public int getRegularMenuSize() {
return regularMenu.size();
}
public int getLimitedMenuSize() {
return limitedMenu.size();
}
public int getSpecialMenuSize() {
return specialMenu.size();
}
}
| cattiskatt/chickenfactory2.0 | Menu.java | 494 | //ADDS THE FOOD OBJECTS TO THE DIFFERENT MENU ACCORDING TO THE PRICE OF THE ITEM | line_comment | en | false | 405 | 22 | 494 | 23 | 482 | 19 | 494 | 23 | 567 | 31 | false | false | false | false | false | true |
75134_4 |
// 1 * 4 <-- encodings of various directions around a cell
// 2
//
// +--+--+ +--+--+
// | | |11 12| 11 12 a maze and its representation
// +--+ + +--+ +
// | | |11 06| 11 06
// +--+--+ +--+--+
//
// 16 16 16 16 initial maze contents returned by constructor
// 16 15 15 16
// 16 15 15 16
// 16 16 16 16
//
/*============================================================*/
import java.util.Random;
import java.util.*;
public class Maze {
private int[][] m; // maze representation
private boolean[][] marked; // have we visited this cell yet
private int rows; // number of rows in the maze
private int cols; // number of columns in the maze
private final static byte[] TWO = { 1, 2, 4, 8, 16};
private final static byte[] DX = { 0,+1, 0,-1};
private final static byte[] DY = {-1, 0,+1, 0};
private boolean done; // used in finding a single solution.
private long count; // used in finding the number of solutions.
private Random r; // for generating random integers.
public int getRows() { return( rows ); }
public int getCols() { return( cols ); }
public Maze ( int nr, int nc, int seed ) {
r = new Random( seed );
rows = nr; cols = nc;
m = new int[nr+2][nc+2];
for (int r=1; r<=nr; ++r ) {
for (int c=1; c<=nc; ++c ) {
m[r][c] = 15;
}
}
for (int r=0; r<nr+2; ++r ) {
m[r][0] = m[r][nc+1] = 16;
}
for (int c=0; c<nc+2; ++c ) {
m[0][c] = m[nr+1][c] = 16;
}
Create( nr/2+1, nc/2+1, 0 );
}
// Wall in direction p?
public boolean ok ( int x, int y, int p ) {
return( (m[x][y] & TWO[p]) == TWO[p] );
}
private boolean downWall( int x, int y, int p ) {
if (ok(x,y,p) && m[x+DX[p]][y+DY[p]] != 16) {
m[x][y] ^= TWO[p];
m[x+DX[p]][y+DY[p]] ^= TWO[p^2];
return true;
}
return false;
}
private void knockDown( int count ) {
// Caution: make sure there are at least count walls!
for (int i=0; i<count; ++i) {
int x = 1+r.nextInt(rows);
int y = 1+r.nextInt(cols);
if (!downWall( x, y, r.nextInt(4))) --i;
}
}
private void Create ( int x, int y, int val ) {
int[] perm = randPerm( 4 );
m[x][y] ^= val;
for (int i=0; i<4; ++i) {
int p = perm[i];
if (m[x+DX[p]][y+DY[p]] == 15) {
m[x][y] ^= TWO[p];
Create( x+DX[p], y+DY[p], TWO[p^2] );
}
}
}
private int[] randPerm( int n ) {
// This algorithm should look familiar!
int[] perm = new int[n];
for (int k=0; k<n; ++k) perm[k] = k;
for (int k=n; k>0; --k) {
int rand = r.nextInt(k);
int t = perm[rand]; perm[rand] = perm[k-1]; perm[k-1] = t;
}
return( perm );
}
public String toString() {
StringBuilder sb = new StringBuilder();
for (int i = 1; i <= rows; i++) {
for (int j = 1; j <= cols; j++) {
String out = m[i][j] > 9 ? (m[i][j] + " ") : (m[i][j] + " ");
sb.append(out);
}
sb.append(System.getProperty("line.separator"));
}
return sb.toString();
}
private void back(int x, int y) {
if (x > rows || y > cols || x < 1 || y < 1) return;
m[x][y] += 16;
if (x == rows && y == cols) {
count++;
m[x][y] -= 16;
return;
}
for (int i = 0; i < 4; i++) {
if (((m[x][y] & TWO[i]) == 0) && m[x + DX[i]][y + DY[i]] < 16) {
back(x + DX[i], y + DY[i]);
}
}
m[x][y] -= 16;
}
public void solveMaze() {
int x = 1;
int y = 1;
solve(x, y);
}
public boolean solve(int x, int y) {
m[x][y] += 16;
if (x == rows && y == cols) {
toString();
m[x][y] -= 16;
return true;
}
for (int i = 0; i < 4; i++) {
if (((m[x][y] & TWO[i]) == 0) && m[x + DX[i]][y + DY[i]] < 16) {
boolean done = solve(x + DX[i], y + DY[i]);
if (done) {
m[x][y] -= 16;
return true;
}
}
}
m[x][y] -= 16;
return false;
}
public long numSolutions() {
int x = 1;
int y = 1;
back(x, y);
return count;
}
public static void main ( String[] args ) {
int row = Integer.parseInt( args[0] );
int col = Integer.parseInt( args[1] );
Maze maz = new Maze( row, col, 9998 );
System.out.print( maz );
maz.solveMaze();
System.out.println( "Solutions = "+maz.numSolutions() );
maz.knockDown( (row+col)/4 );
maz.solveMaze();
System.out.print( maz );
System.out.println( "Solutions = "+maz.numSolutions() );
maz = new Maze( row, col, 9999 ); // creates the same maze anew.
maz.solveMaze();
System.out.print( maz );
}
}
| john-curry/226a5 | Maze.java | 1,782 | // | | |11 12| 11 12 a maze and its representation | line_comment | en | false | 1,666 | 27 | 1,782 | 26 | 1,894 | 25 | 1,782 | 26 | 2,022 | 26 | false | false | false | false | false | true |
81556_27 | /*
* Conditions Of Use
*
* This software was developed by employees of the National Institute of
* Standards and Technology (NIST), an agency of the Federal Government.
* Pursuant to title 15 Untied States Code Section 105, works of NIST
* employees are not subject to copyright protection in the United States
* and are considered to be in the public domain. As a result, a formal
* license is not needed to use the software.
*
* This software is provided by NIST as a service and is expressly
* provided "AS IS." NIST MAKES NO WARRANTY OF ANY KIND, EXPRESS, IMPLIED
* OR STATUTORY, INCLUDING, WITHOUT LIMITATION, THE IMPLIED WARRANTY OF
* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE, NON-INFRINGEMENT
* AND DATA ACCURACY. NIST does not warrant or make any representations
* regarding the use of the software or the results thereof, including but
* not limited to the correctness, accuracy, reliability or usefulness of
* the software.
*
* Permission to use this software is contingent upon your acceptance
* of the terms of this agreement
*
* .
*
*/
/***************************************************************************
* Product of NIST/ITL Advanced Networking Technologies Division(ANTD). *
**************************************************************************/
package gov.nist.core;
import java.net.*;
/*
* IPv6 Support added by Emil Ivov ([email protected])<br/>
* Network Research Team (http://www-r2.u-strasbg.fr))<br/>
* Louis Pasteur University - Strasbourg - France<br/>
*
* Frank Feif reported a bug.
*
*
*/
/**
* Stores hostname.
* @version 1.2
*
* @author M. Ranganathan
* @author Emil Ivov <[email protected]> IPV6 Support. <br/>
*
*
*
* Marc Bednarek <[email protected]> (Bugfixes).<br/>
*
*/
public class Host extends GenericObject {
/**
* Determines whether or not we should tolerate and strip address scope
* zones from IPv6 addresses. Address scope zones are sometimes returned
* at the end of IPv6 addresses generated by InetAddress.getHostAddress().
* They are however not part of the SIP semantics so basically this method
* determines whether or not the parser should be stripping them (as
* opposed simply being blunt and throwing an exception).
*/
private static boolean stripAddressScopeZones = false;
private static final long serialVersionUID = -7233564517978323344L;
protected static final int HOSTNAME = 1;
protected static final int IPV4ADDRESS = 2;
protected static final int IPV6ADDRESS = 3;
static {
stripAddressScopeZones = Boolean.getBoolean("gov.nist.core.STRIP_ADDR_SCOPES");
}
/** hostName field
*/
protected String hostname;
/** address field
*/
protected int addressType;
private InetAddress inetAddress;
/** default constructor
*/
public Host() {
addressType = HOSTNAME;
}
/** Constructor given host name or IP address.
*/
public Host(String hostName) throws IllegalArgumentException {
if (hostName == null)
throw new IllegalArgumentException("null host name");
setHost(hostName, IPV4ADDRESS);
}
/** constructor
* @param name String to set
* @param addrType int to set
*/
public Host(String name, int addrType) {
setHost(name, addrType);
}
/**
* Return the host name in encoded form.
* @return String
*/
public String encode() {
return encode(new StringBuilder()).toString();
}
public StringBuilder encode(StringBuilder buffer) {
if (addressType == IPV6ADDRESS && !isIPv6Reference(hostname)) {
buffer.append('[').append(hostname).append(']');
} else {
buffer.append(hostname);
}
return buffer;
}
/**
* Compare for equality of hosts.
* Host names are compared by textual equality. No dns lookup
* is performed.
* @param obj Object to set
* @return boolean
*/
public boolean equals(Object obj) {
if ( obj == null ) return false;
if (!this.getClass().equals(obj.getClass())) {
return false;
}
Host otherHost = (Host) obj;
return otherHost.hostname.equals(hostname);
}
/** get the HostName field
* @return String
*/
public String getHostname() {
return hostname;
}
/** get the Address field
* @return String
*/
public String getAddress() {
return hostname;
}
/**
* Convenience function to get the raw IP destination address
* of a SIP message as a String.
* @return String
*/
public String getIpAddress() {
String rawIpAddress = null;
if (hostname == null)
return null;
if (addressType == HOSTNAME) {
try {
if (inetAddress == null)
inetAddress = InetAddress.getByName(hostname);
rawIpAddress = inetAddress.getHostAddress();
} catch (UnknownHostException ex) {
dbgPrint("Could not resolve hostname " + ex);
}
} else {
if (addressType == IPV6ADDRESS){
try {
String ipv6FullForm = getInetAddress().toString();
int slashIndex = ipv6FullForm.indexOf("/");
if (slashIndex != -1) {
ipv6FullForm = ipv6FullForm.substring(++slashIndex, ipv6FullForm.length());
}
if (hostname.startsWith("[")) {
rawIpAddress = '[' + ipv6FullForm + ']';
} else {
rawIpAddress = ipv6FullForm;
}
} catch (UnknownHostException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
} else {
rawIpAddress = hostname;
}
}
return rawIpAddress;
}
/**
* Set the hostname member.
* @param h String to set
*/
public void setHostname(String h) {
setHost(h, HOSTNAME);
}
/** Set the IP Address.
*@param address is the address string to set.
*/
public void setHostAddress(String address) {
setHost(address, IPV4ADDRESS);
}
/**
* Sets the host address or name of this object.
*
* @param host that host address/name value
* @param type determines whether host is an address or a host name
*/
private void setHost(String host, int type){
//set inetAddress to null so that it would be reinited
//upon next call to getInetAddress()
inetAddress = null;
if (isIPv6Address(host))
addressType = IPV6ADDRESS;
else
addressType = type;
// Null check bug fix sent in by [email protected]
if (host != null){
hostname = host.trim();
//if this is an FQDN, make it lowercase to simplify processing
if(addressType == HOSTNAME)
hostname = hostname.toLowerCase();
//remove address scope zones if this is an IPv6 address as they
//are not allowed by the RFC
int zoneStart = -1;
if(addressType == IPV6ADDRESS
&& stripAddressScopeZones
&& (zoneStart = hostname.indexOf('%'))!= -1){
hostname = hostname.substring(0, zoneStart);
//if the above was an IPv6 literal, then we would need to
//restore the closing bracket
if( hostname.startsWith("[") && !hostname.endsWith("]"))
hostname += ']';
}
}
}
/**
* Set the address member
* @param address address String to set
*/
public void setAddress(String address) {
this.setHostAddress(address);
}
/** Return true if the address is a DNS host name
* (and not an IPV4 address)
*@return true if the hostname is a DNS name
*/
public boolean isHostname() {
return addressType == HOSTNAME;
}
/** Return true if the address is a DNS host name
* (and not an IPV4 address)
*@return true if the hostname is host address.
*/
public boolean isIPAddress() {
return addressType != HOSTNAME;
}
/** Get the inet address from this host.
* Caches the inet address returned from dns lookup to avoid
* lookup delays.
*
*@throws UnkownHostexception when the host name cannot be resolved.
*/
public InetAddress getInetAddress() throws java.net.UnknownHostException {
if (hostname == null)
return null;
if (inetAddress != null)
return inetAddress;
inetAddress = InetAddress.getByName(hostname);
return inetAddress;
}
//----- IPv6
/**
* Verifies whether the <code>address</code> could
* be an IPv6 address
*/
private boolean isIPv6Address(String address) {
return (address != null && address.indexOf(':') != -1);
}
/**
* Verifies whether the ipv6reference, i.e. whether it enclosed in
* square brackets
*/
public static boolean isIPv6Reference(String address) {
return address.charAt(0) == '['
&& address.charAt(address.length() - 1) == ']';
}
@Override
public int hashCode() {
return this.getHostname().hashCode();
}
}
| RestComm/jain-sip | src/gov/nist/core/Host.java | 2,173 | /**
* Set the address member
* @param address address String to set
*/ | block_comment | en | false | 2,059 | 20 | 2,173 | 18 | 2,360 | 21 | 2,173 | 18 | 2,678 | 21 | false | false | false | false | false | true |
82336_9 | package edu.mills.cs64.final_project;
import java.io.File;
import java.io.FileNotFoundException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Hashtable;
import java.util.List;
import java.util.Scanner;
/**
* A representation of an academic course. Course information
* can be loaded from a file through the method {@link #loadCourses(String)}.
* After this method has been called, courses can be retrieved
* through the method {@link #getCourse(String)}.
*
* @author B0048993
* @version 28 April 2016
*/
public class Course
{
private String department;
private int number;
private String name;
private int credits;
private CoreRequirement[] requirementsMet;
private static Hashtable<String, Course> courses;
private static final String COURSES_FILE = "courses.txt";
private static Hashtable<CoreRequirement, List<Course>> coursesMeetingRequirements;
/**
* Constructs a new Course with the given information.
*
*
* @param department the department
* @param number the course number
* @param name the course name
* @param credits the number of credits
* @param requirementsMet the list of requirements met
*/
private Course(String department, int number, String name, int credits,
CoreRequirement[] requirementsMet) {
this.department = department;
this.number = number;
this.name = name;
this.credits = credits;
this.requirementsMet = requirementsMet;
}
/**
* Loads course information from the specified file, after
* which the information can be retrieved by calling
* {@link #getCourse(String)}.
* <p>
* The file should consist of records in the following
* format:
* <pre>
* DEPARTMENT NUMBER
* NAME
* CREDITS
* REQUIREMENTS MET (comma-separated list)
* </pre>
* Here is a sample file:
* <pre>
* CS 64
* Computer Concepts and Intermediate Programming
* 4
* QL
* ARTH 18
* Introduction to Western Art
* 3
* CA, CIE, IP
* </pre>
* All courses in the file must meet at least one requirement.
* <p>
* Results are undefined if the file is not in the proper format.
* (In other words, there is no error checking and recovery.)
*
* @param filename the name of the file with course information
* @throws FileNotFoundException if the file cannot be found
*/
public static void loadCourses(String filename) throws FileNotFoundException
{
courses = new Hashtable<String, Course>();
coursesMeetingRequirements = new Hashtable<CoreRequirement, List<Course>>();
List<Course> courseList;
File inputFile = new File(COURSES_FILE);
Scanner scanner = new Scanner(inputFile);
while (scanner.hasNextLine()) {
String[] splitLine1 = scanner.nextLine().split(" ");
String department = splitLine1[0];
int number = Integer.parseInt(splitLine1[1]);
String name = scanner.nextLine();
int credits = Integer.parseInt(scanner.nextLine());
String[] splitLine4 = scanner.nextLine().split(", ");
CoreRequirement[] requirementsMet = new CoreRequirement[splitLine4.length];
for (int i = 0; i < requirementsMet.length; i++)
{
requirementsMet[i] = CoreRequirement.valueOf(splitLine4[i]);
}
Course course = new Course(department, number, name, credits, requirementsMet);
courses.put(course.getShortName(), course);
for (CoreRequirement cr : requirementsMet) {
if (coursesMeetingRequirements.containsKey(cr)) {
courseList = coursesMeetingRequirements.get(cr);
courseList.add(course);
}
else {
courseList = new ArrayList<Course>();
courseList.add(course);
}
coursesMeetingRequirements.put(cr, courseList);
}
}
scanner.close();
}
/**
* Gets a course that was previously loaded through a call
* to {@link #loadCourses(String)}.
*
* @param shortName the short name of the course, as would be
* returned by {@link #getShortName()}
* @return the course, or null if it cannot be found
* @throws IllegalStateException if courses have not yet been
* loaded
*/
public static Course getCourse(String shortName)
throws IllegalStateException
{
try {
Course course = courses.get(shortName);
if (course != null) {
return course;
} else {
return null;
}
} catch (IllegalStateException e) {
System.err.println(e.toString());
return null;
}
}
/**
* Gets a list of courses that meets the provided
* Core Requirement.
*
* @param the core requirement
* @return list of courses that meet CoreRequirement
*/
public static List<Course> getCoursesMeetingRequirements(CoreRequirement cr) {
if (cr != null) {
return coursesMeetingRequirements.get(cr);
}
return null;
}
/**
* Gets a short version of the name of this course.
* This consists of the department and the number, e.g.,
* "CS 64".
*
* @return a short version of the name of this course
*/
public String getShortName()
{
return department + " " + number;
}
/**
* Gets the department of this course.
*
* @return the department
*/
public String getDepartment() {
return department;
}
/**
* Gets the number of this course.
*
* @return the number
*/
public int getNumber() {
return number;
}
/**
* Gets the name of this course.
*
* @return the name
*/
public String getName() {
return name;
}
/**
* Gets the number of credits for this course.
*
* @return the number of credits
*/
public int getCredits() {
return credits;
}
/**
* Gets the core requirements met by this course.
*
* @return the requirements met by this course
*/
public CoreRequirement[] getRequirementsMet() {
return requirementsMet;
}
/**
* Gets the hashtable with a core requirement as the key
* and a list of courses as values.
*
* @return the courses that meet each core requirement
*/
public Hashtable<CoreRequirement, List<Course>> getcoursesMeetingRequirements() {
return coursesMeetingRequirements;
}
/**
* Overrides the toString method.
*
* @return a string representation of the course
* department, number, name and credits.
*/
@Override
public String toString()
{
return department + " " + number + ": " + name + "(" + credits + ")";
}
}
| kcutler/Student-Record-System | Course.java | 1,692 | /**
* Gets the number of credits for this course.
*
* @return the number of credits
*/ | block_comment | en | false | 1,551 | 27 | 1,692 | 24 | 1,880 | 31 | 1,692 | 24 | 2,218 | 35 | false | false | false | false | false | true |
82751_2 | package ast;
import java.util.*;
import visitor.*;
/**
* The AST Abstract class is the Abstract Syntax Tree representation;
* each node contains<ol><li> references to its kids, <li>its unique node number
* used for printing/debugging, <li>its decoration used for constraining
* and code generation, and <li>a label for code generation</ol>
* The AST is built by the Parser
*/
public abstract class AST {
protected ArrayList<AST> kids;
protected int nodeNum;
protected AST decoration;
protected String label = ""; // label for generated code of tree
static int NodeCount = 0;
public AST() {
kids = new ArrayList<AST>();
NodeCount++;
nodeNum = NodeCount;
}
public void setDecoration(AST t) {
decoration = t;
}
public AST getDecoration() {
return decoration;
}
public int getNodeNum() {
return nodeNum;
}
/**
* get the AST corresponding to the kid
* @param i is the number of the needed kid; it starts with kid number one
* @return the AST for the indicated kid
*/
public AST getKid(int i) {
if ( (i <= 0) || (i > kidCount())) {
return null;
}
return kids.get(i - 1);
}
/**
* @return the number of kids at this node
*/
public int kidCount() {
return kids.size();
}
public ArrayList<AST> getKids() {
return kids;
}
/**
* accept the visitor for this node - this method must be defined in each of
* the subclasses of AST
* @param v is the ASTVisitor visiting this node (currently, a printer,
* constrainer and code generator)
* @return the desired Object, as determined by the visitor
*/
public abstract Object accept(ASTVisitor v);
public AST addKid(AST kid) {
kids.add(kid);
return this;
}
public void setLabel(String label) {
this.label = label;
}
public String getLabel() {
return label;
}
}
| bestkao/Compiler | src/ast/AST.java | 514 | /**
* get the AST corresponding to the kid
* @param i is the number of the needed kid; it starts with kid number one
* @return the AST for the indicated kid
*/ | block_comment | en | false | 471 | 43 | 514 | 44 | 538 | 44 | 514 | 44 | 594 | 46 | false | false | false | false | false | true |
84567_5 | // License: GPL. Copyright 2007 by Immanuel Scholz and others
//Licence: GPL
// Note: The name of the main class will be the name of the application menu on OS X.
// so instead of exposing "org.openstreetmap.josm.gui.MainApplication" to the
// user, we subclass it with a nicer name "JOSM".
// An alternative would be to set the name in the plist file---but JOSM usually
// is not delivered as an OS X Application Bundle, so we have no plist file.
import org.openstreetmap.josm.gui.MainApplication;
public class JOSM extends MainApplication {}
| Firefishy/josm | src/JOSM.java | 157 | // An alternative would be to set the name in the plist file---but JOSM usually | line_comment | en | false | 145 | 20 | 157 | 20 | 151 | 20 | 157 | 20 | 167 | 21 | false | false | false | false | false | true |
85961_1 | /*
* Copyright Dept. of Mathematics & Computer Science Univ. Paris-Descartes
*
* This software is governed by the CeCILL license under French law and
* abiding by the rules of distribution of free software. You can use,
* modify and/ or redistribute the software under the terms of the CeCILL
* license as circulated by CEA, CNRS and INRIA at the following URL
* "http://www.cecill.info".
*
* As a counterpart to the access to the source code and rights to copy,
* modify and redistribute granted by the license, users are provided only
* with a limited warranty and the software's author, the holder of the
* economic rights, and the successive licensors have only limited
* liability.
*
* In this respect, the user's attention is drawn to the risks associated
* with loading, using, modifying and/or developing or reproducing the
* software by the user in light of its specific status of free software,
* that may mean that it is complicated to manipulate, and that also
* therefore means that it is reserved for developers and experienced
* professionals having in-depth computer knowledge. Users are therefore
* encouraged to load and test the software's suitability as regards their
* requirements in conditions enabling the security of their systems and/or
* data to be ensured and, more generally, to use and operate it in the
* same conditions as regards security.
*
* The fact that you are presently reading this means that you have had
* knowledge of the CeCILL license and that you accept its terms.
*/
package pddl4j.exp;
/**
* This interface is implements by all expression that can be used in the PDDL
* language in the initial state description.
*
* @author Damien Pellier
* @version 1.0
*/
public interface InitEl extends Exp {
}
| gerryai/PDDL4J | src/pddl4j/exp/InitEl.java | 454 | /**
* This interface is implements by all expression that can be used in the PDDL
* language in the initial state description.
*
* @author Damien Pellier
* @version 1.0
*/ | block_comment | en | false | 406 | 44 | 454 | 48 | 431 | 47 | 454 | 48 | 466 | 49 | false | false | false | false | false | true |
86471_2 | package Vdb;
/*
* Copyright (c) 2000, 2013, Oracle and/or its affiliates. All rights reserved.
*/
/*
* Author: Henk Vandenbergh.
*/
import java.util.*;
/**
* This class stores all Work() instances and with that can keep track of which
* SD is used where.
*
* We could maintain individual lists, but it seems easier to just always
* recreate whatever we need from one central Work list when needed.
* The information is not asked for often enough to warrant worrying about
* performance.
*
* During report creation AllWork has information about ALL runs, during a real
* run however it knows only about what is CURRENTLY running by calling
* clearWork() at appropriate times.
*/
public class AllWork
{
private final static String c =
"Copyright (c) 2000, 2013, Oracle and/or its affiliates. All rights reserved.";
private static Vector <Work> work_list = new Vector(8, 0);
public static void addWork(Work work)
{
common.where();
work_list.add(work);
}
public static void clearWork()
{
common.where();
work_list.removeAllElements();
}
/**
* Return SDs used anywhere
*/
public static String[] obsolete_getRealUsedSdNames()
{
HashMap map = new HashMap(16);
for (int i = 0; i < work_list.size(); i++)
{
Work work = (Work) work_list.elementAt(i);
for (int j = 0; j < work.wgs_for_slave.size(); j++)
{
WG_entry wg = (WG_entry) work.wgs_for_slave.get(j);
String[] names = wg.getRealSdNames();
for (int k = 0; k < names.length; k++)
map.put(names[k], null);
}
}
return (String[]) map.keySet().toArray(new String[0]);
}
/**
* Return SDs used in a host
*/
public static String[] obsolete_getRealHostSdList(Host host)
{
HashMap <String, Object> map = new HashMap(16);
for (int i = 0; i < work_list.size(); i++)
{
Work work = (Work) work_list.elementAt(i);
if (Host.findHost(work.host_label) != host)
continue;
for (int j = 0; j < work.wgs_for_slave.size(); j++)
{
WG_entry wg = (WG_entry) work.wgs_for_slave.get(j);
String[] names = wg.getRealSdNames();
for (int k = 0; k < names.length; k++)
map.put(names[k], null);
}
}
return (String[]) map.keySet().toArray(new String[0]);
}
/**
* Return SDs used in a slave
*/
public static String[] obsolete_getSlaveSdList(Slave slave)
{
HashMap map = new HashMap(16);
for (int i = 0; i < work_list.size(); i++)
{
Work work = (Work) work_list.elementAt(i);
if (work.slave_label.equals(slave.getLabel()))
continue;
for (int j = 0; j < work.wgs_for_slave.size(); j++)
{
WG_entry wg = (WG_entry) work.wgs_for_slave.get(j);
map.put(wg.sd_used.sd_name, null);
}
}
return (String[]) map.keySet().toArray(new String[0]);
}
/**
* Return SDs used for this RD_entry
*/
public static String[] obsolete_getRdSdList(RD_entry rd)
{
HashMap map = new HashMap(16);
for (Work work : work_list)
{
if (work.rd != rd)
continue;
for (WG_entry wg : work.wgs_for_slave)
{
for (String name : wg.getRealSdNames())
map.put(name, null);
}
}
return (String[]) map.keySet().toArray(new String[0]);
}
/**
* Return SDs used in a host for this RD_entry
*/
public static String[] obsolete_getHostRdSdList(Host host, RD_entry rd)
{
HashMap map = new HashMap(16);
for (int i = 0; i < work_list.size(); i++)
{
Work work = (Work) work_list.elementAt(i);
if (work.rd != rd)
continue;
if (Host.findHost(work.slave_label) != host)
continue;
for (int j = 0; j < work.wgs_for_slave.size(); j++)
{
WG_entry wg = (WG_entry) work.wgs_for_slave.get(j);
map.put(wg.sd_used.sd_name, null);
}
}
return (String[]) map.keySet().toArray(new String[0]);
}
/**
* Return SDs used in a slave for this RD_entry
*/
public static String[] obsolete_getSlaveRdSdList(Slave slave, RD_entry rd)
{
HashMap map = new HashMap(16);
for (int i = 0; i < work_list.size(); i++)
{
Work work = (Work) work_list.elementAt(i);
if (work.rd != rd)
continue;
if (work.slave_label.equals(slave.getLabel()))
continue;
for (int j = 0; j < work.wgs_for_slave.size(); j++)
{
WG_entry wg = (WG_entry) work.wgs_for_slave.get(j);
map.put(wg.sd_used.sd_name, null);
}
}
return (String[]) map.keySet().toArray(new String[0]);
}
}
| itfanr/vdbench | Vdb/AllWork.java | 1,431 | /**
* This class stores all Work() instances and with that can keep track of which
* SD is used where.
*
* We could maintain individual lists, but it seems easier to just always
* recreate whatever we need from one central Work list when needed.
* The information is not asked for often enough to warrant worrying about
* performance.
*
* During report creation AllWork has information about ALL runs, during a real
* run however it knows only about what is CURRENTLY running by calling
* clearWork() at appropriate times.
*/ | block_comment | en | false | 1,258 | 111 | 1,431 | 120 | 1,543 | 118 | 1,431 | 120 | 1,689 | 123 | false | false | false | false | false | true |
86932_0 | /**
* Interface that presents the two methods that each class animal has to do
*/
public interface Animal {
void eat();
void watch();
}
| ilan15/OOP-Observer-Design-Patern | Animal.java | 34 | /**
* Interface that presents the two methods that each class animal has to do
*/ | block_comment | en | false | 30 | 17 | 34 | 18 | 36 | 18 | 34 | 18 | 36 | 18 | false | false | false | false | false | true |
87159_3 |
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.Statement;
import javax.swing.JOptionPane;
/*
* 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 SAMYAK & ATISHAY
*/
public class PNR extends javax.swing.JFrame {
/**
* Creates new form PNR
*/
public PNR(String un) {
initComponents();
jLabel2.setText(""+un);
}
/**
* 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() {
PNR = new javax.swing.JTextField();
jLabel1 = new javax.swing.JLabel();
jScrollPane1 = new javax.swing.JScrollPane();
TA1 = new javax.swing.JTextArea();
jButton1 = new javax.swing.JButton();
jLabel2 = new javax.swing.JLabel();
jLabel3 = new javax.swing.JLabel();
jLabel4 = new javax.swing.JLabel();
setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
getContentPane().setLayout(new org.netbeans.lib.awtextra.AbsoluteLayout());
getContentPane().add(PNR, new org.netbeans.lib.awtextra.AbsoluteConstraints(280, 40, 870, 67));
jLabel1.setFont(new java.awt.Font("Times New Roman", 1, 24)); // NOI18N
jLabel1.setForeground(new java.awt.Color(255, 204, 204));
jLabel1.setText("ENTER PNR NO.");
getContentPane().add(jLabel1, new org.netbeans.lib.awtextra.AbsoluteConstraints(50, 40, 220, 60));
TA1.setColumns(20);
TA1.setFont(new java.awt.Font("Bell MT", 1, 30)); // NOI18N
TA1.setRows(5);
jScrollPane1.setViewportView(TA1);
getContentPane().add(jScrollPane1, new org.netbeans.lib.awtextra.AbsoluteConstraints(30, 250, 1200, 420));
jButton1.setFont(new java.awt.Font("Times New Roman", 1, 24)); // NOI18N
jButton1.setText("SHOW STATUS");
jButton1.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jButton1ActionPerformed(evt);
}
});
getContentPane().add(jButton1, new org.netbeans.lib.awtextra.AbsoluteConstraints(370, 120, 580, 50));
jLabel2.setVisible(false);
getContentPane().add(jLabel2, new org.netbeans.lib.awtextra.AbsoluteConstraints(30, 120, 190, 30));
jLabel3.setFont(new java.awt.Font("Times New Roman", 1, 24)); // NOI18N
jLabel3.setForeground(new java.awt.Color(255, 204, 204));
jLabel3.setText("<<back to home");
jLabel3.addMouseListener(new java.awt.event.MouseAdapter() {
public void mouseClicked(java.awt.event.MouseEvent evt) {
jLabel3MouseClicked(evt);
}
});
getContentPane().add(jLabel3, new org.netbeans.lib.awtextra.AbsoluteConstraints(50, 130, 260, 50));
jLabel4.setIcon(new javax.swing.ImageIcon(getClass().getResource("/images/train_railway_snow_forest_119261_1440x900.jpg"))); // NOI18N
jLabel4.setText("jLabel4");
getContentPane().add(jLabel4, new org.netbeans.lib.awtextra.AbsoluteConstraints(0, 0, 1280, 690));
pack();
}// </editor-fold>//GEN-END:initComponents
int b;
private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton1ActionPerformed
b=Integer.parseInt(PNR.getText());
try
{
Class.forName("java.sql.Driver");
Connection con= DriverManager.getConnection("jdbc:mysql://localhost:3306/irctc?zeroDateTimeBehavior=convertToNull","root","123456");
Statement stmt=con.createStatement();
String sql="select * from BOOK_TICKET where PNR="+b+" && username='"+ jLabel2.getText()+"'";
System.out.println(sql);
ResultSet rs= stmt.executeQuery(sql);
while(rs.next())
{
int pnr = rs.getInt("PNR");
String src=rs.getString("SRC");
String dst=rs.getString("DST");
String doj=rs.getString("DOJ");
int np = rs.getInt("NOP");
String train =rs.getString("TRAIN");
String ts =rs.getString("ticket_status");
TA1.append(" YOUR TICKET INFO " + "\n" +"USER ID: "+jLabel2.getText()+ "\n" +"PNR NO: "+ pnr + "\n" +"NUMBER OF PASSENGERS: " +np+"\n"+ "SOURCE STATION: "+src+"\n"+ "DESTINATION STATION: "+dst+"\n"+ "TRAIN NAME: " +train+"\n"+"TICKET STATUS: " + ts+ "\n"+"DATE OF JOURNEY: "+doj);
}
}
catch(Exception ex)
{
JOptionPane.showMessageDialog(null,ex.getMessage());
}
}//GEN-LAST:event_jButton1ActionPerformed
private void jLabel3MouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_jLabel3MouseClicked
HOME L=new HOME(jLabel2.getText());
L.setVisible(true);this.dispose();
}//GEN-LAST:event_jLabel3MouseClicked
/**
* @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 ("Nimbus".equals(info.getName())) {
javax.swing.UIManager.setLookAndFeel(info.getClassName());
break;
}
}
} catch (ClassNotFoundException ex) {
java.util.logging.Logger.getLogger(PNR.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (InstantiationException ex) {
java.util.logging.Logger.getLogger(PNR.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (IllegalAccessException ex) {
java.util.logging.Logger.getLogger(PNR.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (javax.swing.UnsupportedLookAndFeelException ex) {
java.util.logging.Logger.getLogger(PNR.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
}
//</editor-fold>
/* Create and display the form */
java.awt.EventQueue.invokeLater(new Runnable() {
public void run() {
new PNR(null).setVisible(true);
}
});
}
// Variables declaration - do not modify//GEN-BEGIN:variables
private javax.swing.JTextField PNR;
private javax.swing.JTextArea TA1;
private javax.swing.JButton jButton1;
private javax.swing.JLabel jLabel1;
private javax.swing.JLabel jLabel2;
private javax.swing.JLabel jLabel3;
private javax.swing.JLabel jLabel4;
private javax.swing.JScrollPane jScrollPane1;
// End of variables declaration//GEN-END:variables
}
| Sam9685/IRCTC- | src/PNR.java | 2,028 | /**
* 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.
*/ | block_comment | en | false | 1,659 | 44 | 2,028 | 43 | 2,085 | 47 | 2,028 | 43 | 2,464 | 50 | false | false | false | false | false | true |
87460_13 | import java.util.*;
class Risk {
public static void main(String[] args) {
ArrayList<Integer> troopNumbersMaster = new ArrayList<Integer>();
System.out.println("Simulating a Risk turn with the following setup:");
System.out.println();
System.out.println("The first value is the attacking country, the rest of the");
System.out.println("values are the chain of defending countries");
/**
* Edit the numbers below here for attacking a defending troop setups and the
* number of trials to run
*/
// The attacking Troop
troopNumbersMaster.add(45);
// The defending Troops
troopNumbersMaster.add(1);
troopNumbersMaster.add(1);
troopNumbersMaster.add(7);
troopNumbersMaster.add(1);
troopNumbersMaster.add(7);
troopNumbersMaster.add(7);
troopNumbersMaster.add(7);
troopNumbersMaster.add(1);
troopNumbersMaster.add(1);
troopNumbersMaster.add(1);
troopNumbersMaster.add(1);
// The number of trials
int totalReps = 100000;
/**
* Do not edit below here
*/
System.out.println(troopNumbersMaster);
System.out.println();
Integer[] copyDeep = new Integer[troopNumbersMaster.size()];
copyDeep = troopNumbersMaster.toArray(copyDeep);
int winCount = 0;
for (int i = 0; i < totalReps; i++) {
ArrayList<Integer> troopNumbers = new ArrayList<Integer>(Arrays.asList(copyDeep));
// the starting index for the attackers
int attackingIndex = 0;
// Have the attacking index attack the next square until depleted
while (attackingIndex < troopNumbers.size() - 1 && troopNumbers.get(attackingIndex) > 1) {
// System.out.println("Attacking Index " + attackingIndex);
// System.out.println(troopNumbers);
int attacking = troopNumbers.get(attackingIndex);
int defending = troopNumbers.get(attackingIndex + 1);
int[] res = simulateBattle(new int[] { attacking, defending });
if (res[0] > 1) {
// the attacker won, needs to leave one behind
// System.out.println("attacker Won");
troopNumbers.set(attackingIndex, 1);
troopNumbers.set(attackingIndex + 1, res[0] - 1);
attackingIndex++;
} else {
// the defender won
// System.out.println("defender Won");
troopNumbers.set(attackingIndex, 1);
troopNumbers.set(attackingIndex + 1, res[1]);
}
}
// simulation is finisished, attacker won if they made it to the last index
if (attackingIndex == troopNumbers.size() - 1) {
winCount++;
}
}
double percentWon = (double) winCount / (double) totalReps;
System.out.println("Result: ");
System.out.printf("Win percent: %.2f %n", percentWon * 100);
}
public static int[] simulateBattle(int[] input) {
int attacking = input[0];
int defending = input[1];
// System.out.println("Battling " + attacking + " vs " + defending);
while (attacking > 1 && defending > 0) {
// System.out.println("Attacking: " + attacking);
// System.out.println("Defending: " + defending);
int[] attackingRolls = new int[Math.min(attacking - 1, 3)];
int[] defendingRolls = new int[Math.min(defending, 2)];
for (int i = 0; i < attackingRolls.length; i++) {
attackingRolls[i] = (int) (Math.random() * 6) + 1;
}
for (int i = 0; i < defendingRolls.length; i++) {
defendingRolls[i] = (int) (Math.random() * 6) + 1;
}
Arrays.sort(attackingRolls);
Arrays.sort(defendingRolls);
attackingRolls = reverseArray(attackingRolls);
defendingRolls = reverseArray(defendingRolls);
// System.out.println("attacking Rolls:");
// System.out.println(Arrays.toString(attackingRolls));
// System.out.println("defending Rolls:");
// System.out.println(Arrays.toString(defendingRolls));
for (int i = 0; i < Math.min(attackingRolls.length, defendingRolls.length); i++) {
if (attackingRolls[i] > defendingRolls[i]) {
defending--;
// System.out.println("minus one defending");
} else {
attacking--;
// System.out.println("minus one attacking");
}
}
}
int[] result = new int[] { attacking, defending };
return result;
}
public static int[] reverseArray(int[] validData) {
for (int i = 0; i < validData.length / 2; i++) {
int temp = validData[i];
validData[i] = validData[validData.length - i - 1];
validData[validData.length - i - 1] = temp;
}
return validData;
}
} | tshibley/Risk-Model | Risk.java | 1,330 | // simulation is finisished, attacker won if they made it to the last index | line_comment | en | false | 1,146 | 17 | 1,332 | 17 | 1,361 | 16 | 1,330 | 17 | 1,525 | 18 | false | false | false | false | false | true |
87775_4 | import javax.crypto.Cipher;
import javax.crypto.spec.SecretKeySpec;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.Socket;
import java.security.Key;
import java.util.Base64;
import java.util.Scanner;
/**
* This is the backdoor client
* Use ip = 127.0.0.1 and port = 9999 by default
* @author salah3x
*/
public class Client {
public static void main(String[] args) throws Exception {
//Server ip
String host = "127.0.0.1";
//Port to listen to
int port = 9999;
if (args.length == 2) {
host = args[0];
port = Integer.valueOf(args[1]);
}
//The signal to let the client know that the request is finished
//there will be no data to wait for(needed by the client to stop reading from output stream)
String endSignal = "%**%";
//The encryption key used to encrypt an decrypt communication
//Symmetric encryption is used
String encryptionKey = "sixteen byte key";
//Encryption algorithm
String algorithm = "AES";
//A helper class used to encrypt and decrypt Strings
CryptoHelper cryptoHelper = new CryptoHelper(encryptionKey, algorithm);
//Starting the server
Socket socket = new Socket(host, port);
//Used to red user input
Scanner scanner = new Scanner(System.in);
//Used to write data to socket's output stream
PrintWriter printWriter = new PrintWriter(socket.getOutputStream());
//Used to read data from socket's input stream
BufferedReader br = new BufferedReader(new InputStreamReader(socket.getInputStream()));
//Check if we are/still connected to server
while (!socket.isClosed()) {
try {
//Getting user input
System.err.print("[remote shell] $ ");
String cmd = scanner.nextLine();
//Encrypting and sending command
printWriter.println(cryptoHelper.encrypt(cmd));
printWriter.flush();
if (cmd.equals("exit"))
break;
//Reading, decrypting and printing output to console
String line;
while ((line = cryptoHelper.decrypt(br.readLine())) != null) {
//Until there is no data to read
if (line.endsWith(endSignal))
break;
System.out.println(line);
}
} catch (Exception e) {
e.printStackTrace();
br.close();
printWriter.close();
socket.close();
}
}
}
/**
* This helper class deals with Cipher class and byte arrays in order
* to provide an abstraction to use encryption on strings
*/
static class CryptoHelper {
private Cipher cipher;
private Key key;
CryptoHelper(String key, String algo) throws Exception {
this.key = new SecretKeySpec(key.getBytes(), algo);
this.cipher = Cipher.getInstance(algo);
}
String encrypt(String plaintext) throws Exception {
if (plaintext == null)
return null;
cipher.init(Cipher.ENCRYPT_MODE, key);
byte[] encrypted = cipher.doFinal(plaintext.getBytes());
return Base64.getEncoder().encodeToString(encrypted);
}
String decrypt(String encrypted) throws Exception {
if (encrypted == null)
return null;
cipher.init(Cipher.DECRYPT_MODE, key);
byte[] decorded = Base64.getDecoder().decode(encrypted);
byte[] decrypted = cipher.doFinal(decorded);
return new String(decrypted);
}
}
} | salah3x/backdoor | src/Client.java | 895 | //there will be no data to wait for(needed by the client to stop reading from output stream) | line_comment | en | false | 782 | 21 | 895 | 21 | 897 | 21 | 895 | 21 | 1,148 | 22 | false | false | false | false | false | true |
87874_0 | import java.util.ArrayList;
import java.util.List;
/**
* This class contains utility methods for performing various tasks.
* @author Matteo Loporchio
*/
public final class Utility {
/**
* This function chops a list into sublists of a given length.
* @param l the list to be divided
* @param k the number of elements in each sublist
* @return a list containing all the sublists
*/
public static <T> List<List<T>> split(List<T> l, int k) {
List<List<T>> parts = new ArrayList<List<T>>();
for (int i = 0; i < l.size(); i += k) {
parts.add(l.subList(i, Math.min(l.size(), i + k)));
}
return parts;
}
}
| mloporchio/BTXA | Utility.java | 200 | /**
* This class contains utility methods for performing various tasks.
* @author Matteo Loporchio
*/ | block_comment | en | false | 172 | 25 | 200 | 28 | 208 | 25 | 200 | 28 | 216 | 28 | false | false | false | false | false | true |
88453_3 | /* SWEN20003 Object Oriented Software Development
* RPG Game Engine
* Author: James Stone 761353 stone1
*/
import org.newdawn.slick.Image;
import org.newdawn.slick.geom.Vector2f;
abstract public class Item {
private Image image;
private Vector2f position;
/**
* Generates an item, called by subclasses as abstract class
* @param image an image representing the item
* @param position the start position of the item in the world
*/
Item(Image image, Vector2f position) {
this.image = image;
this.position = position;
}
/**
* What happens when an item is picked up
* @param playerStats the stats to modify
*/
public abstract void onPickup(Stats playerStats);
/**
* Renders an item to the screen
* @param camera the camera
*/
public void render(Camera camera) {
if (onScreen(camera)) {
image.drawCentered((int) position.getX(), (int) position.getY());
}
}
/**
* Renders an item to the statusPanel
* @param camera the camera
* @param position where in the status panel to place it
*/
public void render(Camera camera, Vector2f position) {
image.draw((int) position.getX(), (int) position.getY());
}
private boolean onScreen(Camera cam) {
return cam.getMinX() <= position.getX() && position.getX() <= cam.getMaxX() &&
cam.getMinY() <= position.getY() && position.getY() <= cam.getMaxY();
}
/**
* Returns true if a point is within a certain distance of the item
* @param point the point
* @param distance the distance (px)
* @return true if a point is within a certain distance of the item
*/
public boolean near(Vector2f point, float distance) {
return position.distance(point) < distance;
}
}
| jamesmstone/Object-Oriented-Software-Development-Project | src/Item.java | 462 | /**
* Renders an item to the screen
* @param camera the camera
*/ | block_comment | en | false | 436 | 20 | 462 | 19 | 500 | 22 | 462 | 19 | 532 | 22 | false | false | false | false | false | true |
89133_1 |
import java.util.*;
public class Malady extends OntClass {
Set<Symptom> symptoms;
private Set<Symptom> inheritedSymptoms;
private double priorProbability;
public String treatment;
public Malady() {}
public Malady(String line) {
super(line);
symptoms = new HashSet<Symptom>();
String[] csvComponents = line.split(",");
this.className = csvComponents[0];
inheritedSymptoms = null;
if (csvComponents.length >= 3)
priorProbability = Double.parseDouble(csvComponents[2]);
else
priorProbability = 0.0;
if (csvComponents.length >= 4) {
String[] treatments = Arrays.copyOfRange(csvComponents, 3, csvComponents.length);
treatment = "";
for (String t : treatments) {
treatment += t + ",";
}
treatment = treatment.substring(0, treatment.length() - 1);
} else
treatment = null;
}
public static Malady fromSymptomLine(String[] symptomLine) {
Malady m = new Malady(symptomLine[1]);
m.priorProbability = 1.0; // placeholder for now
return m;
}
void addSymptom(Symptom s) {
symptoms.add(s);
}
double getPriorProb() {
return priorProbability;
}
public Set<Symptom> getSymptons() {
return symptoms;
}
public void addSympton(Symptom s) {
symptoms.add(s);
}
public String getTreatments() {
String treatments = "";
String emergency = null;
Set<OntClass> current = new HashSet<OntClass>();
current.add(this);
while (true) {
Set<OntClass> next = new HashSet<OntClass>();
for (OntClass classObj : current) {
Malady malady = (Malady)classObj;
if (malady.treatment != null && !"".equals(malady.treatment)) {
if (malady.treatment.contains("Call 911 immediately.")) {
emergency = malady.treatment;
} else
treatments += " " + malady.treatment + ",";
}
next.addAll(malady.getParents());
}
// root's only parent is itself, so if next==current we have
// reached the root node
if (next.equals(current)) {
break;
}
current = next;
}
if (treatments.length() > 0 && treatments.charAt(treatments.length() - 1) == ',')
treatments = treatments.substring(0, treatments.length() - 1);
return emergency == null ? treatments : emergency + " In the meantime: " + treatments;
}
Set<Symptom> inheritedSymptoms() {
if (inheritedSymptoms == null) {
inheritedSymptoms = new HashSet<Symptom>();
Set<OntClass> current = new HashSet<OntClass>();
current.addAll(this.getParents());
while (true) {
Set<OntClass> next = new HashSet<OntClass>();
for (OntClass classObj : current) {
Malady malady = (Malady)classObj;
inheritedSymptoms.addAll(malady.getSymptons());
next.addAll(malady.getParents());
}
// root's only parent is itself, so if next==current we have
// reached the root node
if (next.equals(current)) {
break;
}
current = next;
}
}
return inheritedSymptoms;
}
} | rush8192/bmi210-project | src/Malady.java | 842 | // root's only parent is itself, so if next==current we have | line_comment | en | false | 772 | 15 | 842 | 15 | 883 | 16 | 842 | 15 | 1,020 | 16 | false | false | false | false | false | true |
89534_42 | import java.util.List;
import java.util.Iterator;
import java.lang.NullPointerException;
import java.util.ArrayList;
import java.util.Random;
/** @file Cpu.java
@brief Automatic player.
*/
/**
@class Cpu
@brief Automatic player with knowledge of previous games.
*/
public class Cpu{
private Knowledge _knowledge; ///< Knwoledge of winner sequencies
private Chess _chess; ///< Reference to global chess object
private int _profundity; ///< Profunidty level for search the possibilities movements tree.
private PieceColor _color; ///< Color of the CPU player
/** @brief Default CPU constructor
@pre chess is not null, profundity > 0 and color is not null
@param knowledge Reference to the knowledge
@param chess Reference to the Chess
*/
public Cpu(Knowledge knowledge,Chess chess,int profundity,PieceColor color){
if(chess==null)throw new NullPointerException("chess given argument cannot be null");
else if(color==null)throw new NullPointerException("color given argument cannot be null");
else if(profundity<=0)throw new IllegalArgumentException("profunidty argument cannot be less or equal to zero");
else{
_knowledge=knowledge;
_chess=chess;
_profundity=profundity;
_color=color;
}
}
/** @brief Makes a movement
@pre --
@return Returns a pair which indicates the origin position and final position of the pice movmement choose.
*/
public Pair<Position,Position> doMovement(){
if(_knowledge!=null){ //If we have knowledge
Pair<Position,Position> movement = _knowledge.buscarConeixament(_chess,_color);
if(movement!=null){ //If we find knowledge saved we choose the movement to do from the knowledge
return movement;
}
else return minMax();//If we dont find any stored movement we choose from the minmax algorithm
}
else return minMax();//If we dont have knowledge we choose from the minmax
}
/** @biref Returns the optimal movement to do.
@pre Cpu can do a movement
@return Returns the optimal movement to do inside the decision tree with profundity @c _profunidty.
*/
private Pair<Position,Position> minMax(){
Pair<Position,Position> movement = new Pair<Position,Position>(null,null);
i_minMax(0,0,0,movement,Integer.MIN_VALUE,Integer.MAX_VALUE,_chess);
return movement;
}
/** @brief Immersion function for minMaxAlgorsim
@pre --
@return Returns the puntuation choosen for the @p playerType of this @p profundity.
*/
private int i_minMax(Integer score,int profundity,int playerType,Pair<Position,Position> movement,int biggestAnterior,int smallerAnterior,Chess tauler){
if(profundity==_profundity)return score;
else if(playerType==0){ //Turn of the cpu player (we will maximize score here)
Integer max = Integer.MIN_VALUE;
List<Pair<Position,Position>> equealMovementsFirstLevel = new ArrayList<Pair<Position,Position>>();//list to save movements with same puntuation at profunity 1
List<Pair<Position,Piece>> pieces,piecesContrincant;
if(_color==PieceColor.White)pieces=tauler.pListWhite();
else pieces=tauler.pListBlack();
Boolean follow = true;
Iterator<Pair<Position,Piece>> itPieces = pieces.iterator();
while(itPieces.hasNext() && follow){//for each peice
Pair<Position,Piece> piece = itPieces.next();
List<Pair<Position,Integer>> destinyWithScores= tauler.allPiecesDestiniesWithValues(piece.first);//take all possibles movements for this piece which the socre asssociated at this movement
Iterator<Pair<Position,Integer>> itMoviments = destinyWithScores.iterator();
while(itMoviments.hasNext() && follow){//for each movement
Chess taulerCopia = (Chess)tauler.clone();//We copy the chess and we will work with that copy for not affecting next movements
Pair<Position,Integer> pieceMovement = itMoviments.next();
Integer result=pieceMovement.second + score;//add actul + score for actual movement into result
Pair<List<MoveAction>,List<Position>> check= taulerCopia.checkMovement(piece.first,pieceMovement.first);//necessary for the chess class, it needs to know the pieces which will die and(list of positions), the list of moveAction is for Console/Visual game class
List<MoveAction> actions = taulerCopia.applyMovement(piece.first,pieceMovement.first,check.second,false);//we apply this movement with the returnend parameters on the checkMovement
if(_color==PieceColor.White)piecesContrincant=taulerCopia.pListBlack();//take contrincant pieces
else piecesContrincant=taulerCopia.pListWhite();
if(!taulerCopia.isCheck(piecesContrincant)){//we look if this movement will cause check if it does we omit it
actions.forEach((action)->{
if(action==MoveAction.Promote){//if this movement cause a promotion we choose the biggest puntuation piece to promote
List<PieceType> typePieces = taulerCopia.typeList();
Iterator<PieceType> itTypePieces = typePieces.iterator();
PieceType piecetype = itTypePieces.next();
while(itTypePieces.hasNext()){
PieceType nextPieceType = itTypePieces.next();
if(nextPieceType.ptValue()>piecetype.ptValue())piecetype=nextPieceType;
}
taulerCopia.promotePiece(pieceMovement.first,piecetype);
}
});
result = i_minMax(result,profundity+1,1,movement,biggestAnterior,smallerAnterior,taulerCopia); //recursive call minMax with playerType = 1 to make the optimal simulation for the other plyer
if(result>=max){
if(profundity==0 && result > max){
equealMovementsFirstLevel.clear();
equealMovementsFirstLevel.add(new Pair<Position,Position>( (Position) piece.first.clone(),(Position) pieceMovement.first.clone()));
}
else if(profundity==0 && result==max)equealMovementsFirstLevel.add(new Pair<Position,Position>((Position) piece.first.clone(),(Position) pieceMovement.first.clone()));
if(result>biggestAnterior)biggestAnterior=result;
max=result;
}
/*If the new biggest is bigger than smallest on
the anterior node (because anterior will choose the samllest)
we dont have to continue inspecinting this branch so we cut it.
*/
if(smallerAnterior<biggestAnterior){follow=false;}
}
}
}
if(profundity==0){/*At first level for CPU player we need to choose the movement if there's more than one with same puntuation we will choose one random. With that we cant be sure that cpu vs cpu
will not always choose same movements */
Random rand = new Random();
int n = rand.nextInt(equealMovementsFirstLevel.size());
Pair<Position,Position> choosed = equealMovementsFirstLevel.get(n);
movement.first = choosed.first;
movement.second = choosed.second;
}
if(max==Integer.MIN_VALUE)return -100+score;//if the max == MIN_VALUE it means that all movements possibles of CPU puts himself in check(loose game) so we return a value of -100(king value) + preuvious score
else return max;//else we return the max value possible
}
else{ /*Here we will choose the lowest because we want to minamize our negative score
the socre here will be negative because the positive for the other player is negative for the cpu*/
//codi del contrincant
Integer min = Integer.MAX_VALUE;
List<Pair<Position,Piece>> pieces,piecesContrincant;
if(_color==PieceColor.Black)pieces=tauler.pListWhite();//peçes del contrincant
else pieces=tauler.pListBlack();
Boolean follow = true;
Iterator<Pair<Position,Piece>> itPieces = pieces.iterator();
while(itPieces.hasNext() && follow){//FOR EACH PIECE
Pair<Position,Piece> piece = itPieces.next();
List<Pair<Position,Integer>> destinyWithScores=tauler.allPiecesDestiniesWithValues(piece.first);
Iterator<Pair<Position,Integer>> itMoviments = destinyWithScores.iterator();
while(itMoviments.hasNext() && follow){//FOR EACH MOVEMENT
Chess taulerCopia = (Chess)tauler.clone();//We copy the chess and we will work with that copy for not affecting next movements
Pair<Position,Integer> pieceMovement = itMoviments.next();
Integer result= -pieceMovement.second + score;
Pair<List<MoveAction>,List<Position>> check= taulerCopia.checkMovement(piece.first,pieceMovement.first);
List<MoveAction> actions=taulerCopia.applyMovement(piece.first,pieceMovement.first,check.second,false);
if(_color==PieceColor.Black)piecesContrincant=taulerCopia.pListBlack();//take contrincant pieces
else piecesContrincant=taulerCopia.pListWhite();
if(!taulerCopia.isCheck(piecesContrincant)){//we look if this movement will cause check if it does we omit it
actions.forEach((action)->{
if(action==MoveAction.Promote){//if this movement cause a promotion we choose the biggest puntuation piece to promote
List<PieceType> typePieces = taulerCopia.typeList();
Iterator<PieceType> itTypePieces = typePieces.iterator();
PieceType piecetype = itTypePieces.next();
while(itTypePieces.hasNext()){
PieceType nextPieceType = itTypePieces.next();
if(nextPieceType.ptValue()>piecetype.ptValue())piecetype=nextPieceType;
}
taulerCopia.promotePiece(pieceMovement.first,piecetype);
}
});
result = i_minMax(result,profundity+1,0,movement,biggestAnterior,smallerAnterior,taulerCopia);//recrusive call
if(result<=min){//if the result is less than the actual min we update it
if(result<smallerAnterior)smallerAnterior=result;//if its smaller than the anteirorSmaller we also updatate this one
min=result;
}
/*If the new smallest is smaller than biggest on
the anterior node (because anterior will choose the bigger)
we dont have to continue inspecinting this branch so we cut it.
*/
if(biggestAnterior>smallerAnterior){follow=false;}
}
}
}
if(min==Integer.MAX_VALUE)return 100+score;//if contricant cant choose any movement then it means that all of his movements put himself into check so he cant do anythink (he loose)
else return min;//else we return the minimum value possible
}
}
} | udg-propro-spring-2020/projecte-2020-a3 | src/Cpu.java | 2,655 | //if its smaller than the anteirorSmaller we also updatate this one | line_comment | en | false | 2,458 | 18 | 2,655 | 18 | 2,716 | 17 | 2,655 | 18 | 3,218 | 18 | false | false | false | false | false | true |
89581_4 | package charactercreator;
import java.io.Serializable;
/*
* This class defines Skill objects, which allow the character to interact with the game world in a wide variety of ways. They represent the
* crystallization of some type of knowledge and/or training the character has practiced (or is naturally gifted at.)
*/
public class Skill extends Thing implements Serializable {
protected String[] classes; // a list of classes that could use each feature
protected String[] tags; // a list of tag words assoiated with this feature -- included for future versions.
protected String relevantAbilityScore = "Strength"; // Which ability score will be used when calculating ability bonus values.
protected boolean isProficient = false; // Whether or not the character is proficient with this skill, and will receive their Proficiency Bonus when using it.
protected int miscBonus = 0; // Any additional bonuses the character has to this skill.
//Constructor to be used when reading in data from skills.json
public Skill(String idIn, String nameIn, String descriptionIn, String[] classesIn,
String relevantAbilityScoreIn, String[] tagsIn) {
super(idIn, nameIn, descriptionIn);
this.classes = classesIn;
this.relevantAbilityScore = relevantAbilityScoreIn;
this.tags = tagsIn;
this.isProficient = false;
this.miscBonus = 0;
} // end constructor method
// Setters and getters.
// For associated tags
public String[] getTags() {
return this.tags;
}
public void setTags(String[] newTagsIn) {
this.tags = newTagsIn;
}
// For associated classTypes
public String[] getClasses() {
return this.classes;
}
public void setClasses(String[] newClassesIn) {
this.classes = newClassesIn;
}
// For relevant ability score.
public void setRelevantAbilityScore(String relevantAbilityScoreIn) {
this.relevantAbilityScore = relevantAbilityScoreIn;
}
public String getRelevantAbilityScore() {
return this.relevantAbilityScore;
}
// For isProficient.
public void setIsProficient(boolean isProficientIn) {
this.isProficient = isProficientIn;
} // shouldn't this be in character.java?
public boolean getIsProficient() {
return this.isProficient;
} // shouldn't this be in character.java?
// For miscellaneous bonus.
public void setMiscBonus(int miscBonusIn) {
this.miscBonus = miscBonusIn;
}
public int getMiscBonus() {
return this.miscBonus;
}
}
| Ian-RSager/CMSC495 | src/Skill.java | 603 | // Whether or not the character is proficient with this skill, and will receive their Proficiency Bonus when using it. | line_comment | en | false | 563 | 23 | 603 | 25 | 638 | 22 | 603 | 25 | 730 | 27 | false | false | false | false | false | true |
91144_1 | import java.util.Stack;
/*************************************************************************
* Compilation: javac Graph.java
* Execution: java Graph input.txt
* Dependencies: Bag.java In.java StdOut.java
* Data files: http://algs4.cs.princeton.edu/41undirected/tinyG.txt
*
* A graph, implemented using an array of sets.
* Parallel edges and self-loops allowed.
*
* % java Graph tinyG.txt
* 13 vertices, 13 edges
* 0: 6 2 1 5
* 1: 0
* 2: 0
* 3: 5 4
* 4: 5 6 3
* 5: 3 4 0
* 6: 0 4
* 7: 8
* 8: 7
* 9: 11 10 12
* 10: 9
* 11: 9 12
* 12: 11 9
*
* % java Graph mediumG.txt
* 250 vertices, 1273 edges
* 0: 225 222 211 209 204 202 191 176 163 160 149 114 97 80 68 59 58 49 44 24 15
* 1: 220 203 200 194 189 164 150 130 107 72
* 2: 141 110 108 86 79 51 42 18 14
* ...
*
*************************************************************************/
/**
* The <tt>Graph</tt> class represents an undirected graph of vertices named 0
* through <em>V</em> - 1. It supports the following two primary operations: add
* an edge to the graph, iterate over all of the vertices adjacent to a vertex.
* It also provides methods for returning the number of vertices <em>V</em> and
* the number of edges <em>E</em>. Parallel edges and self-loops are permitted.
* <p>
* This implementation uses an adjacency-lists representation, which is a
* vertex-indexed array of {@link Bag} objects. All operations take constant
* time (in the worst case) except iterating over the vertices adjacent to a
* given vertex, which takes time proportional to the number of such vertices.
* <p>
* For additional documentation, see
* <a href="http://algs4.cs.princeton.edu/41undirected">Section 4.1</a> of
* <i>Algorithms, 4th Edition</i> by Robert Sedgewick and Kevin Wayne.
*
* @author Robert Sedgewick
* @author Kevin Wayne
*/
public class Graph {
private final int V;
private int E;
private Bag<Integer>[] adj;
private Mark[] marked;
private boolean isCycle = false;
private enum Mark {
WHITE, GRAY, BLACK
};
/**
* Initializes an empty graph with <tt>V</tt> vertices and 0 edges. param V
* the number of vertices
*
* @throws java.lang.IllegalArgumentException
* if <tt>V</tt> < 0
*/
public Graph(int V) {
if (V < 0)
throw new IllegalArgumentException("Number of vertices must be nonnegative");
this.V = V;
this.E = 0;
adj = (Bag<Integer>[]) new Bag[V];
marked = new Mark[V];
for (int v = 0; v < V; v++) {
adj[v] = new Bag<Integer>();
marked[v] = Mark.WHITE;
}
}
/**
* Initializes a graph from an input stream. The format is the number of
* vertices <em>V</em>, followed by the number of edges <em>E</em>, followed
* by <em>E</em> pairs of vertices, with each entry separated by whitespace.
*
* @param in
* the input stream
* @throws java.lang.IndexOutOfBoundsException
* if the endpoints of any edge are not in prescribed range
* @throws java.lang.IllegalArgumentException
* if the number of vertices or edges is negative
*/
public Graph(In in) {
this(in.readInt());
int E = in.readInt();
if (E < 0)
throw new IllegalArgumentException("Number of edges must be nonnegative");
for (int i = 0; i < E; i++) {
int v = in.readInt();
int w = in.readInt();
addEdge(v, w);
}
}
/**
* Initializes a new graph that is a deep copy of <tt>G</tt>.
*
* @param G
* the graph to copy
*/
public Graph(Graph G) {
this(G.V());
this.E = G.E();
for (int v = 0; v < G.V(); v++) {
// reverse so that adjacency list is in same order as original
Stack<Integer> reverse = new Stack<Integer>();
for (int w : G.adj[v]) {
reverse.push(w);
}
for (int w : reverse) {
adj[v].add(w);
}
}
}
/**
* Returns the number of vertices in the graph.
*
* @return the number of vertices in the graph
*/
public int V() {
return V;
}
/**
* Returns the number of edges in the graph.
*
* @return the number of edges in the graph
*/
public int E() {
return E;
}
/**
* Adds the undirected edge v-w to the graph.
*
* @param v
* one vertex in the edge
* @param w
* the other vertex in the edge
* @throws java.lang.IndexOutOfBoundsException
* unless both 0 <= v < V and 0 <= w < V
*/
public void addEdge(int v, int w) {
if (v < 0 || v >= V)
throw new IndexOutOfBoundsException();
if (w < 0 || w >= V)
throw new IndexOutOfBoundsException();
E++;
adj[v].add(w);
// for an undirected edges uncomment below
// for directed edges leave the line below commented
// adj[w].add(v);
}
private void dfs(int v) {
System.out.println("visiting:" + v);
marked[v] = Mark.GRAY;
for (int w : adj[v]) {
if (marked[w] == Mark.WHITE)
dfs(w);
}
marked[v] = Mark.BLACK;
}
private void dfs2(int v) {
System.out.println("visiting:" + v);
marked[v] = Mark.GRAY;
for (int w : adj[v]) {
if (marked[w] == Mark.GRAY) {
isCycle = true;
}
if (marked[w] == Mark.WHITE)
dfs2(w);
}
marked[v] = Mark.BLACK;
}
private void cycle(int v) {
while(notVisited()!=-1){
dfs2(notVisited());
}
if(isCycle) System.out.println("There is a cylce");
else System.out.println("there is no cycle");
}
// function returns -1 if there are no more unvisited nodes
private int notVisited() {
for (int i = 0; i < V - 1; i++) {
if (marked[i] == Mark.WHITE)
return i;
}
return -1;
}
private void connectedComponents(int v) {
int count = 0;
// while unvisited nodes
while (notVisited() != -1) {
System.out.println("\nComponent " + count);
dfs(notVisited());
count++;
}
System.out.println("There are " + count + " components");
}
/**
* Returns the vertices adjacent to vertex <tt>v</tt>.
*
* @return the vertices adjacent to vertex <tt>v</tt> as an Iterable
* @param v
* the vertex
* @throws java.lang.IndexOutOfBoundsException
* unless 0 <= v < V
*/
public Iterable<Integer> adj(int v) {
if (v < 0 || v >= V)
throw new IndexOutOfBoundsException();
return adj[v];
}
/**
* Returns a string representation of the graph. This method takes time
* proportional to <em>E</em> + <em>V</em>.
*
* @return the number of vertices <em>V</em>, followed by the number of
* edges <em>E</em>, followed by the <em>V</em> adjacency lists
*/
public String toString() {
StringBuilder s = new StringBuilder();
String NEWLINE = System.getProperty("line.separator");
s.append(V + " vertices, " + E + " edges " + NEWLINE);
for (int v = 0; v < V; v++) {
s.append(v + ": ");
for (int w : adj[v]) {
s.append(w + " ");
}
s.append(NEWLINE);
}
return s.toString();
}
/**
* Unit tests the <tt>Graph</tt> data type.
*/
public void makeSet(int x){
KrusNode node = new KrusNode();
}
public static void main(String[] args) {
In in = new In(args[0]);
Graph G = new Graph(in);
StdOut.println(G);
// System.out.println("\n");
// G.connectedComponents(0);
G.cycle(0);
}
}
| sirjudge/Graph | Graph.java | 2,486 | /**
* The <tt>Graph</tt> class represents an undirected graph of vertices named 0
* through <em>V</em> - 1. It supports the following two primary operations: add
* an edge to the graph, iterate over all of the vertices adjacent to a vertex.
* It also provides methods for returning the number of vertices <em>V</em> and
* the number of edges <em>E</em>. Parallel edges and self-loops are permitted.
* <p>
* This implementation uses an adjacency-lists representation, which is a
* vertex-indexed array of {@link Bag} objects. All operations take constant
* time (in the worst case) except iterating over the vertices adjacent to a
* given vertex, which takes time proportional to the number of such vertices.
* <p>
* For additional documentation, see
* <a href="http://algs4.cs.princeton.edu/41undirected">Section 4.1</a> of
* <i>Algorithms, 4th Edition</i> by Robert Sedgewick and Kevin Wayne.
*
* @author Robert Sedgewick
* @author Kevin Wayne
*/ | block_comment | en | false | 2,236 | 248 | 2,481 | 270 | 2,528 | 251 | 2,486 | 270 | 2,834 | 271 | true | true | true | true | true | false |
91201_0 | import java.awt.Point;
public class King extends Piece{
/**
* Constructor
*
*@param p - initial starting position of king
*
**/
public King(Point p, boolean isWhite){
super(p, isWhite);
}
/**
* makeMove
* makes sure move is legal and moves king
*
* @param p - point you want to move king to
*/
public void makeMove(Point p){
int x = (int)(p.getX());
int y = (int)(p.getY());
if(Math.abs(x-getX()) <= 1 && Math.abs(y-getY()) <= 1){
move(p);
}else{
return;
}
}
} | The-Pheonix21/Chess-1 | King.java | 191 | /**
* Constructor
*
*@param p - initial starting position of king
*
**/ | block_comment | en | false | 160 | 24 | 191 | 26 | 197 | 26 | 191 | 26 | 221 | 29 | false | false | false | false | false | true |
92245_1 | package scheduler;
import java.io.FileNotFoundException;
import java.util.HashMap;
import parser.VTParser;
import time.Time;
import time.TimeException;
/**
* ScheduleMaker generates a list of schedules
* can only be called in a static way
*
* @author Phillip Ngo
*/
public class ScheduleMaker {
private LinkedList<Schedule> schedules;
private HashMap<String, LinkedList<VTCourse>> listings;
private HashMap<String, LinkedList<VTCourse>> pass;
private HashMap<String, LinkedList<VTCourse>> fail;
private LinkedList<VTCourse> crnCourses;
/**
* Constructor creates all schedule combinations and compiles data
* @param term the term to parse
* @param subjects subjects of the classes. index corresponds to numbers, types, and profs
* @param numbers numbers of the classes. index corresponds to subjects, types, and profs
* @param types types of the classes. index corresponds to subjects, numbers, and profs
* @param start start time restriction
* @param end end time restriction
* @param freeDays free days restriction
* @param crns the crns to add
* @param profs the prof preferences of the classes. index corresponds to subjetcs, numbers, and types
* @throws Exception
*/
public ScheduleMaker(String term, LinkedList<String> subjects, LinkedList<String> numbers, LinkedList<String> types,
String start, String end, String[] freeDays, LinkedList<String> crns, LinkedList<String> profs) throws Exception {
listings = new HashMap<>();
pass = new HashMap<>();
fail = new HashMap<>();
crnCourses = new LinkedList<>();
schedules = generateSchedule(term, subjects, numbers, types, start, end, freeDays, crns, profs);
}
/**
* List of possible schedules
* @return schedules
*/
public LinkedList<Schedule> getSchedules() {
return schedules;
}
/**
* Listings found for the classes inputted
* @return listings
*/
public HashMap<String, LinkedList<VTCourse>> getListings() {
return listings;
}
/**
* The listings of specific crns
* @return crnCourses
*/
public LinkedList<VTCourse> getCrns() {
return crnCourses;
}
/**
* The classes that failed the restrictions sorted by course numbers
* @return fail
*/
public HashMap<String, LinkedList<VTCourse>> getFailed() {
return fail;
}
/**
* The classes that passed the restrictions sorted by course numbers
* @return pass
*/
public HashMap<String, LinkedList<VTCourse>> getPassed() {
return pass;
}
/**
* Generates all possible schedules with the given parameter
*
* @param term the term value
* @param subjects array of subjects where the indices correspond to the indices of numbers
* @param numbers array of numbers where the indices correspond to the indices of subjects
* @param types array of class types where the indices correspond
* @param onlineAllowed array of booleans noting whether online for a class is allowed
* @param start the earliest time allowed
* @param end the latest time allowed
* @param freeDay freeDay if there is one
* @param crns any specific crns
* @return the LinkedList of all the schedules
* @throws Exception
*/
private LinkedList<Schedule> generateSchedule(String term, LinkedList<String> subjects, LinkedList<String> numbers, LinkedList<String> types,
String start, String end, String[] freeDays, LinkedList<String> crns, LinkedList<String> profs) throws Exception {
LinkedList<Schedule> schedules = new LinkedList<>();
LinkedList<LinkedList<VTCourse>> classes = new LinkedList<>();
HashMap<String, HashMap<String, LinkedList<VTCourse>>> map = null;
VTParser parser = null;
try {
//throw new FileNotFoundException(); //debugging
map = VTParser.parseTermFile(term);
}
catch (FileNotFoundException e) {
parser = new VTParser(term);
}
for (int i = 0; i < subjects.size(); i++) {
LinkedList<VTCourse> curr = null;
String type = types.get(i);
String subj = subjects.get(i);
String num = numbers.get(i);
try {
if (map != null) {
LinkedList<VTCourse> find = map.get(subj).get(num);
listings.put(type + subj + " " + num, find.createCopy());
curr = find.createCopy();
}
else {
LinkedList<VTCourse> find = parser.parseCourse(subj, num);
listings.put(type + subj + " " + num, find);
curr = find.createCopy();
}
}
catch (Exception e) {
throw new Exception(subj + " " + num + " does not exist on the timetable");
}
LinkedList<VTCourse> failed = new LinkedList<>();
for (VTCourse c : curr) {
if (!checkRestrictions(c, start, end, type, freeDays, profs.get(i))) {
curr.remove(c);
if (!c.getClassType().equals(type)) {
listings.get(type + subj + " " + num).remove(c);
}
else {
failed.add(c);
}
}
}
pass.put(types.get(i) + subjects.get(i) + " " + numbers.get(i), curr);
fail.put(types.get(i) + subjects.get(i) + " " + numbers.get(i), failed);
classes.add(curr);
}
if (crns.size() != 0) {
for (String crn : crns) {
LinkedList<VTCourse> curr = new LinkedList<>();
outerloop:
for (String subj : map.keySet()) {
HashMap<String, LinkedList<VTCourse>> subject = map.get(subj);
for (String numb : subject.keySet()) {
LinkedList<VTCourse> list = subject.get(numb);
for (VTCourse c : list) {
if (crn.equals(c.getCRN())) {
curr.add(c);
crnCourses.add(c);
for (VTCourse c2 : list) {
if (!c2.getClassType().equals(c.getClassType())) {
list.remove(c2);
}
}
listings.put(c.getClassType() + subj + " " + numb, list);
break outerloop;
}
}
}
}
classes.add(curr);
}
}
try {
createSchedules(classes, new Schedule(), 0, schedules);
} catch (Exception e) {}
return schedules;
}
/**
* Creates all valid schedules
*
* @param classListings A list holding a list for each class
* @param schedule the schedule to add to schedules
* @param classIndex current index in classListings
* @param schedules the list of possible schedules
* @throws Exception
*/
private void createSchedules(LinkedList<LinkedList<VTCourse>> classListings, Schedule schedule,
int classIndex, LinkedList<Schedule> schedules) throws Exception {
for (VTCourse course : classListings.get(classIndex)) {
Schedule copy = schedule;
if (classIndex == classListings.size() - 1) {
copy = schedule.createCopy();
}
try {
copy.add(course);
}
catch (TimeException e) {
continue;
}
if (classIndex == classListings.size() - 1) {
if (schedules.size() >= 201) {
throw new Exception("Too Many Schedules");
}
schedules.add(copy);
}
else {
createSchedules(classListings, copy, classIndex + 1, schedules);
schedule.remove(course);
}
}
}
/**
* Checks if a course meets the given restrictions
*
* @param course the class to check
* @param start the start time restriction
* @param end the end time restriction
* @param freeDay the free day restriction
* @return true if the course meets the restrictions
* @throws TimeException
*/
private boolean checkRestrictions(VTCourse course, String start, String end, String type, String[] freeDays,
String prof) throws TimeException {
Time time = course.getTimeSlot();
if (!type.equals("A") && !type.equals(course.getClassType())) {
return false;
}
if (!prof.equals("A") && !(prof).equals(course.getProf().replace("-", " "))) {
return false;
}
if (time == null) {
return true;
}
int startTime = Time.timeNumber(start);
int endTime = Time.timeNumber(end);
if (freeDays != null) {
for (String d : freeDays) {
for (String d2 : course.getDays()) {
if (d.equals(d2)) {
return false;
}
}
}
}
if (time.getStartNum() < startTime || time.getEndNum() > endTime) {
return false;
}
time = course.getAdditionalTime();
if (time == null) {
return true;
}
startTime = Time.timeNumber(start);
endTime = Time.timeNumber(end);
if (freeDays != null) {
for (String d : freeDays) {
for (String d2 : course.getAdditionalDays()) {
if (d.equals(d2)) {
return false;
}
}
}
}
if (time.getStartNum() < startTime || time.getEndNum() > endTime) {
return false;
}
return true;
}
}
| stephentuso/pScheduler | src/scheduler/ScheduleMaker.java | 2,252 | /**
* Constructor creates all schedule combinations and compiles data
* @param term the term to parse
* @param subjects subjects of the classes. index corresponds to numbers, types, and profs
* @param numbers numbers of the classes. index corresponds to subjects, types, and profs
* @param types types of the classes. index corresponds to subjects, numbers, and profs
* @param start start time restriction
* @param end end time restriction
* @param freeDays free days restriction
* @param crns the crns to add
* @param profs the prof preferences of the classes. index corresponds to subjetcs, numbers, and types
* @throws Exception
*/ | block_comment | en | false | 2,109 | 159 | 2,252 | 147 | 2,572 | 170 | 2,252 | 147 | 2,815 | 175 | false | false | false | false | false | true |
92468_1 | import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
/*****************************************************************
* The panel is used to create the layout of the game.
* @author William Minshew, Jeffrey Siebach, and Michael Howard
******************************************************************/
public class Panel extends JPanel
{
/******************************************************************
* Creates a panel with a Panel2() and a BattlePanel1()
******************************************************************/
public Panel()
{
Labels x = new Labels();
Scoreboard y = new Scoreboard();
BattlePanel1 bp = new BattlePanel1(x, y);
setLayout(new BorderLayout());
add(new Panel2(bp, x, y), BorderLayout.LINE_START);
add(bp, BorderLayout.CENTER);
}
}
| snickelfritz/chinpokomon | Panel.java | 173 | /******************************************************************
* Creates a panel with a Panel2() and a BattlePanel1()
******************************************************************/ | block_comment | en | false | 156 | 22 | 173 | 21 | 197 | 29 | 173 | 21 | 222 | 33 | false | false | false | false | false | true |
94696_2 | /*
* 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 net.candhcapital.Graphing;
import java.awt.Color;
import java.awt.Rectangle;
import java.text.DecimalFormat;
/**
*
* @author Corporate
*/
public class Block {
/**
* Need to know if red for different brightener.
*/
private boolean red;
/**
* The start time.
*/
private ZonedStockDateTime beginning;
/**
* The value of our block.
*/
private double value;
/**
* The color of the block (based on candles).
*/
private final Color blockColor;
/**
* The rectangle we are going to draw.
*/
private Rectangle block;
/**
* Needs a way to see if we can graph this.
*/
private boolean gotBlock = false;
/**
* A formatted string with our volume.
*/
private final String formattedValue;
/**
* The Candle UP color.
*/
private static final Color CANDLEUPCOLOR = new Color(0, 153, 0);
/**
* The Candle NEUTRAL color.
*/
private static final Color CANDLENEUTRALCOLOR = new Color(255, 255, 0);
/**
* The Candle DOWN color.
*/
private static final Color CANDLEDOWNCOLOR = new Color(204, 0, 0);
/**
* Takes a block and sets the color.
* @param start the time this block starts at.
* @param pDifference the difference of the last volume and first.
* @param pColor a double so we know what color to make this block.
*/
public Block(final ZonedStockDateTime start,
final double pvalue, final double pColor) {
beginning = start;
DecimalFormat formatter = new DecimalFormat("#,###");
formattedValue = "Volume: " + formatter.format(pvalue) + "M";
value = pvalue;
if (pColor > 0) {
blockColor = CANDLEUPCOLOR;
} else if (pColor == 0) {
blockColor = CANDLENEUTRALCOLOR;
} else {
blockColor = CANDLEDOWNCOLOR;
red = true;
}
}
/**
* Once we know the dimensions of the window we can calculate the location
* of the rectangle we are going to draw.
* @param start The start time of our window.
* @param pixelWeight The number of seconds per pixel.
* @param candleWidth The width of our candles.
* @param bottom The lowy value.
* @param top The highy value.
* @param pixelHeight The number of pixels of our graph.
*/
public final void setRectangles(final ZonedStockDateTime start,
final double pixelWeight, final int candleWidth,
final double bottom, final double top, final int pixelHeight,
final int topMargin) {
int x1 = (int)
Math.round(start.getMarketSecondsUntil(beginning)
/ pixelWeight);
ZonedStockDateTime end = beginning.getCopy();
end.addSeconds(candleWidth);
int x2 = (int)
Math.round(start.getMarketSecondsUntil(end) / pixelWeight) - 1;
double valueHeight = top - bottom;
int y1 = (int) Math.round(pixelHeight
- (pixelHeight / valueHeight * (0 - bottom))) + topMargin;
int y2 = (int) Math.round(pixelHeight
- (pixelHeight / valueHeight * (value - bottom))) + topMargin;
if (y1 - y2 >= 0) {
block = new Rectangle(x1, y2, x2 - x1, y1 - y2);
} else {
block = new Rectangle(x1, y1, x2 - x1, y2 - y1);
}
gotBlock = true;
}
/**
* public block's start X value.
* @return **the x-value to start at**
*/
public final int getX() {
if (gotBlock) {
return (int) block.getX();
} else {
return -1;
}
}
/**
* public block's start Y value.
* @return **the y-value to start at**
*/
public final int getY() {
if (gotBlock) {
return (int) block.getY();
} else {
return -1;
}
}
/**
* public block's width.
* @return **the width of our block**
*/
public final int getWidth() {
if (gotBlock) {
return (int) block.getWidth();
} else {
return -1;
}
}
/**
* public block's height.
* @return **the height of our block**
*/
public final int getHeight() {
if (gotBlock) {
return (int) block.getHeight();
} else {
return -1;
}
}
/**
* Gets the color of our block.
* @return **the color of our block**
*/
public final Color getColor() {
return blockColor;
}
/**
* Checks to see if our candle should be red.
* @return true for red.
*/
public final boolean isRed() {
return red;
}
/**
* Checks to see if the mouse is in that block.
* @param x **The x-value our mouse is currently at**
* @return **True if the mouse is contained**
*/
public final boolean matchMouseX(final int x) {
return (x >= getX() && x <= getX() + getWidth());
}
/**
* simple toString() function.
* @return **The value formatted with commas**
*/
@Override
public final String toString() {
return formattedValue;
}
public final double getValue() {
return value;
}
}
| BenAychh/java-graphing | Block.java | 1,389 | /**
* Need to know if red for different brightener.
*/ | block_comment | en | false | 1,309 | 15 | 1,389 | 15 | 1,534 | 17 | 1,389 | 15 | 1,654 | 18 | false | false | false | false | false | true |
95473_12 | // public class myProgram1{
// public static void main(String[] args) {
// System.out.println("Hello, World!");
// int age= 47;
// System.out.println("my age is "+ age );
// }
// }
// Lab1a.java
// This short class has several bugs for practice.
// Authors: Carol Zander, Rob Nash, Clark Olson, you
public class Lab1a {
public static void main(String[] args) {
compareNumbers();
calculateDist();
}
public static void compareNumbers() { //space after public
int firstNum = 5;
int secondNum = 2; //do we need to define second num?
System.out.println( "Sum is: "+ firstNum + secondNum ); //missing parenthesis close after : and secondNum hasn't been initialized above
System.out.println( "Difference is: " + (firstNum - secondNum));//add ) to complete expression
System.out.println( "Product is: " + firstNum * secondNum ); //typo nuM
}
public static void calculateDist() {//need to shorten name to calculateDist
int velocity = 10; //miles-per-hour
int time = 2, //hoursint
distance = velocity * time;//missing semicolon and from the new line System.out.println
System.out.println( "Total distance is: " + distance); //typo distAnce and missing +
}
} | impeterbol/CSS142 | Lab1a.java | 343 | //missing parenthesis close after : and secondNum hasn't been initialized above | line_comment | en | false | 322 | 14 | 343 | 15 | 357 | 15 | 343 | 15 | 375 | 17 | false | false | false | false | false | true |